@payloadcms/drizzle 4.0.0-internal.934870d → 4.0.0-internal.952ed66
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/count.d.ts.map +1 -1
- package/dist/count.js +25 -3
- package/dist/count.js.map +1 -1
- package/dist/countGlobalVersions.js +8 -3
- package/dist/countGlobalVersions.js.map +1 -1
- package/dist/countVersions.d.ts.map +1 -1
- package/dist/countVersions.js +29 -4
- package/dist/countVersions.js.map +1 -1
- package/dist/createGlobalVersion.d.ts.map +1 -1
- package/dist/createGlobalVersion.js +17 -2
- package/dist/createGlobalVersion.js.map +1 -1
- package/dist/createVersion.d.ts.map +1 -1
- package/dist/createVersion.js +12 -1
- package/dist/createVersion.js.map +1 -1
- package/dist/deleteBranchGlobal.d.ts +10 -0
- package/dist/deleteBranchGlobal.d.ts.map +1 -0
- package/dist/deleteBranchGlobal.js +27 -0
- package/dist/deleteBranchGlobal.js.map +1 -0
- package/dist/deleteOne.d.ts.map +1 -1
- package/dist/deleteOne.js +25 -1
- package/dist/deleteOne.js.map +1 -1
- package/dist/exports/postgres.d.ts +1 -1
- package/dist/exports/postgres.d.ts.map +1 -1
- package/dist/exports/postgres.js +1 -1
- package/dist/exports/postgres.js.map +1 -1
- package/dist/exports/sqlite.d.ts +1 -1
- package/dist/exports/sqlite.d.ts.map +1 -1
- package/dist/exports/sqlite.js +1 -1
- package/dist/exports/sqlite.js.map +1 -1
- package/dist/find/buildFindManyArgs.d.ts +3 -2
- package/dist/find/buildFindManyArgs.d.ts.map +1 -1
- package/dist/find/buildFindManyArgs.js +2 -1
- package/dist/find/buildFindManyArgs.js.map +1 -1
- package/dist/find/buildPolymorphicJoinQuery.d.ts +5 -3
- package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -1
- package/dist/find/buildPolymorphicJoinQuery.js +43 -15
- package/dist/find/buildPolymorphicJoinQuery.js.map +1 -1
- package/dist/find/buildPolymorphicJoinWhere.js +1 -1
- package/dist/find/buildPolymorphicJoinWhere.js.map +1 -1
- package/dist/find/createPolymorphicJoinWherePlan.d.ts +2 -1
- package/dist/find/createPolymorphicJoinWherePlan.d.ts.map +1 -1
- package/dist/find/createPolymorphicJoinWherePlan.js +14 -5
- package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -1
- package/dist/find/findMany.d.ts +6 -1
- package/dist/find/findMany.d.ts.map +1 -1
- package/dist/find/findMany.js +16 -3
- package/dist/find/findMany.js.map +1 -1
- package/dist/find/traverseFields.d.ts +3 -2
- package/dist/find/traverseFields.d.ts.map +1 -1
- package/dist/find/traverseFields.js +64 -8
- package/dist/find/traverseFields.js.map +1 -1
- package/dist/find.d.ts.map +1 -1
- package/dist/find.js +32 -4
- package/dist/find.js.map +1 -1
- package/dist/findDistinct.d.ts.map +1 -1
- package/dist/findDistinct.js +104 -8
- package/dist/findDistinct.js.map +1 -1
- package/dist/findGlobal.d.ts.map +1 -1
- package/dist/findGlobal.js +24 -5
- package/dist/findGlobal.js.map +1 -1
- package/dist/findGlobalVersions.js +8 -3
- package/dist/findGlobalVersions.js.map +1 -1
- package/dist/findOne.d.ts +1 -1
- package/dist/findOne.d.ts.map +1 -1
- package/dist/findOne.js +30 -3
- package/dist/findOne.js.map +1 -1
- package/dist/findVersions.d.ts.map +1 -1
- package/dist/findVersions.js +32 -5
- package/dist/findVersions.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/postgres/insert.d.ts.map +1 -1
- package/dist/postgres/insert.js +4 -2
- package/dist/postgres/insert.js.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
- package/dist/postgres/requireDrizzleKit.d.ts +4 -0
- package/dist/postgres/requireDrizzleKit.d.ts.map +1 -1
- package/dist/postgres/requireDrizzleKit.js +16 -10
- package/dist/postgres/requireDrizzleKit.js.map +1 -1
- package/dist/postgres/types.d.ts +4 -0
- package/dist/postgres/types.d.ts.map +1 -1
- package/dist/postgres/types.js.map +1 -1
- package/dist/queries/buildAndOrConditions.d.ts +3 -2
- package/dist/queries/buildAndOrConditions.d.ts.map +1 -1
- package/dist/queries/buildAndOrConditions.js +2 -1
- package/dist/queries/buildAndOrConditions.js.map +1 -1
- package/dist/queries/buildBranchVisibility.d.ts +11 -0
- package/dist/queries/buildBranchVisibility.d.ts.map +1 -0
- package/dist/queries/buildBranchVisibility.js +48 -0
- package/dist/queries/buildBranchVisibility.js.map +1 -0
- package/dist/queries/buildOrderBy.d.ts +3 -2
- package/dist/queries/buildOrderBy.d.ts.map +1 -1
- package/dist/queries/buildOrderBy.js +2 -1
- package/dist/queries/buildOrderBy.js.map +1 -1
- package/dist/queries/buildQuery.d.ts +3 -2
- package/dist/queries/buildQuery.d.ts.map +1 -1
- package/dist/queries/buildQuery.js +4 -2
- package/dist/queries/buildQuery.js.map +1 -1
- package/dist/queries/getTableColumnFromPath.d.ts +3 -2
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +167 -29
- package/dist/queries/getTableColumnFromPath.js.map +1 -1
- package/dist/queries/parseParams.d.ts +3 -2
- package/dist/queries/parseParams.d.ts.map +1 -1
- package/dist/queries/parseParams.js +4 -1
- package/dist/queries/parseParams.js.map +1 -1
- package/dist/queryDrafts.d.ts.map +1 -1
- package/dist/queryDrafts.js +27 -5
- package/dist/queryDrafts.js.map +1 -1
- package/dist/schema/build.d.ts.map +1 -1
- package/dist/schema/build.js +28 -20
- package/dist/schema/build.js.map +1 -1
- package/dist/sqlite/createRequireDrizzleKit.d.ts +6 -0
- package/dist/sqlite/createRequireDrizzleKit.d.ts.map +1 -0
- package/dist/sqlite/createRequireDrizzleKit.js +15 -0
- package/dist/sqlite/createRequireDrizzleKit.js.map +1 -0
- package/dist/sqlite/execute.js.map +1 -1
- package/dist/sqlite/insert.d.ts.map +1 -1
- package/dist/sqlite/insert.js +5 -3
- package/dist/sqlite/insert.js.map +1 -1
- package/dist/sqlite/types.d.ts +4 -0
- package/dist/sqlite/types.d.ts.map +1 -1
- package/dist/sqlite/types.js.map +1 -1
- package/dist/transactions/beginTransaction.d.ts.map +1 -1
- package/dist/transactions/beginTransaction.js +13 -5
- package/dist/transactions/beginTransaction.js.map +1 -1
- package/dist/transactions/commitTransaction.d.ts.map +1 -1
- package/dist/transactions/commitTransaction.js +2 -5
- package/dist/transactions/commitTransaction.js.map +1 -1
- package/dist/transform/read/traverseFields.js.map +1 -1
- package/dist/transform/write/array.d.ts +3 -2
- package/dist/transform/write/array.d.ts.map +1 -1
- package/dist/transform/write/array.js +2 -1
- package/dist/transform/write/array.js.map +1 -1
- package/dist/transform/write/blocks.d.ts +3 -2
- package/dist/transform/write/blocks.d.ts.map +1 -1
- package/dist/transform/write/blocks.js +2 -1
- package/dist/transform/write/blocks.js.map +1 -1
- package/dist/transform/write/index.d.ts.map +1 -1
- package/dist/transform/write/index.js +2 -0
- package/dist/transform/write/index.js.map +1 -1
- package/dist/transform/write/traverseFields.d.ts +2 -1
- package/dist/transform/write/traverseFields.d.ts.map +1 -1
- package/dist/transform/write/traverseFields.js +43 -7
- package/dist/transform/write/traverseFields.js.map +1 -1
- package/dist/transform/write/types.d.ts +7 -0
- package/dist/transform/write/types.d.ts.map +1 -1
- package/dist/transform/write/types.js.map +1 -1
- package/dist/types.d.ts +3 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/updateGlobal.d.ts +5 -1
- package/dist/updateGlobal.d.ts.map +1 -1
- package/dist/updateGlobal.js +96 -4
- package/dist/updateGlobal.js.map +1 -1
- package/dist/updateOne.d.ts.map +1 -1
- package/dist/updateOne.js +54 -5
- package/dist/updateOne.js.map +1 -1
- package/dist/upsertBranchGlobalChange.d.ts +3 -0
- package/dist/upsertBranchGlobalChange.d.ts.map +1 -0
- package/dist/upsertBranchGlobalChange.js +35 -0
- package/dist/upsertBranchGlobalChange.js.map +1 -0
- package/dist/upsertRow/deleteExistingRowsByPath.d.ts.map +1 -1
- package/dist/upsertRow/deleteExistingRowsByPath.js +17 -12
- package/dist/upsertRow/deleteExistingRowsByPath.js.map +1 -1
- package/dist/upsertRow/index.d.ts +1 -1
- package/dist/upsertRow/index.d.ts.map +1 -1
- package/dist/upsertRow/index.js +132 -42
- package/dist/upsertRow/index.js.map +1 -1
- package/dist/upsertRow/types.d.ts +3 -0
- package/dist/upsertRow/types.d.ts.map +1 -1
- package/dist/upsertRow/types.js.map +1 -1
- package/dist/utilities/blocksToJsonMigrator.d.ts.map +1 -1
- package/dist/utilities/blocksToJsonMigrator.js +7 -18
- package/dist/utilities/blocksToJsonMigrator.js.map +1 -1
- package/dist/utilities/buildCreateMigration.js +1 -1
- package/dist/utilities/buildCreateMigration.js.map +1 -1
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js +1 -1
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js.map +1 -1
- package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.js +7 -12
- package/dist/utilities/createSchemaGenerator.js.map +1 -1
- package/dist/utilities/executeSchemaHooks.js +1 -1
- package/dist/utilities/executeSchemaHooks.js.map +1 -1
- package/dist/utilities/formatGeneratedFile.d.ts +10 -0
- package/dist/utilities/formatGeneratedFile.d.ts.map +1 -0
- package/dist/utilities/formatGeneratedFile.js +58 -0
- package/dist/utilities/formatGeneratedFile.js.map +1 -0
- package/dist/utilities/getTransaction.js.map +1 -1
- package/dist/utilities/pushDevSchema.js +1 -1
- package/dist/utilities/pushDevSchema.js.map +1 -1
- package/package.json +17 -19
- package/dist/sqlite/requireDrizzleKit.d.ts +0 -3
- package/dist/sqlite/requireDrizzleKit.d.ts.map +0 -1
- package/dist/sqlite/requireDrizzleKit.js +0 -12
- package/dist/sqlite/requireDrizzleKit.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/upsertRow/types.ts"],"sourcesContent":["import type { SQL } from 'drizzle-orm'\nimport type { FlattenedField, JoinQuery, PayloadRequest, SelectType } from 'payload'\n\nimport type { DrizzleAdapter, DrizzleTransaction, GenericColumn } from '../types.js'\n\ntype BaseArgs = {\n adapter: DrizzleAdapter\n /**\n * Collection slug for error reporting\n */\n collectionSlug?: string\n data: Record<string, unknown>\n db: DrizzleAdapter['drizzle'] | DrizzleTransaction\n fields: FlattenedField[]\n /**\n * Collection slug for error reporting\n */\n globalSlug?: string\n /**\n * When true, skips reading the data back from the database and returns the input data\n * @default false\n */\n ignoreResult?: 'idOnly' | boolean\n joinQuery?: JoinQuery\n path?: string\n req?: Partial<PayloadRequest>\n tableName: string\n}\n\ntype CreateArgs = {\n customID?: number | string\n id?: never\n joinQuery?: never\n operation: 'create'\n select?: SelectType\n upsertTarget?: never\n where?: never\n} & BaseArgs\n\ntype UpdateArgs = {\n customID?: never\n id?: number | string\n joinQuery?: JoinQuery\n operation: 'update'\n select?: SelectType\n upsertTarget?: GenericColumn\n where?: SQL<unknown>\n} & BaseArgs\n\nexport type Args = CreateArgs | UpdateArgs\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/upsertRow/types.ts"],"sourcesContent":["import type { SQL } from 'drizzle-orm'\nimport type { FlattenedField, JoinQuery, PayloadRequest, SelectType } from 'payload'\n\nimport type { DrizzleAdapter, DrizzleTransaction, GenericColumn } from '../types.js'\n\ntype BaseArgs = {\n adapter: DrizzleAdapter\n /**\n * Collection slug for error reporting\n */\n collectionSlug?: string\n data: Record<string, unknown>\n db: DrizzleAdapter['drizzle'] | DrizzleTransaction\n fields: FlattenedField[]\n /**\n * Collection slug for error reporting\n */\n globalSlug?: string\n /**\n * When true, skips reading the data back from the database and returns the input data\n * @default false\n */\n ignoreResult?: 'idOnly' | boolean\n joinQuery?: JoinQuery\n path?: string\n req?: Partial<PayloadRequest>\n tableName: string\n}\n\ntype CreateArgs = {\n customID?: number | string\n id?: never\n joinQuery?: never\n operation: 'create'\n select?: SelectType\n upsertConflictData?: never\n upsertTarget?: never\n where?: never\n} & BaseArgs\n\ntype UpdateArgs = {\n customID?: never\n id?: number | string\n joinQuery?: JoinQuery\n operation: 'update'\n select?: SelectType\n /** Data applied only when an insert conflicts with an existing upsert target. */\n upsertConflictData?: Record<string, unknown>\n upsertTarget?: GenericColumn\n where?: SQL<unknown>\n} & BaseArgs\n\nexport type Args = CreateArgs | UpdateArgs\n"],"names":[],"mappings":"AAoDA,WAA0C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"blocksToJsonMigrator.d.ts","sourceRoot":"","sources":["../../src/utilities/blocksToJsonMigrator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EAExB,OAAO,EAGR,MAAM,SAAS,CAAA;AAchB,OAAO,KAAK,EAGV,oBAAoB,EACpB,cAAc,EACf,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"blocksToJsonMigrator.d.ts","sourceRoot":"","sources":["../../src/utilities/blocksToJsonMigrator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EAExB,OAAO,EAGR,MAAM,SAAS,CAAA;AAchB,OAAO,KAAK,EAGV,oBAAoB,EACpB,cAAc,EACf,MAAM,aAAa,CAAA;AAkrBpB,eAAO,MAAM,0BAA0B,oDAIpC;IACD,OAAO,EAAE,cAAc,CAAA;IACvB,aAAa,EAAE,MAAM,CAAA;IACrB,kBAAkB,EAAE,CAAC,IAAI,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,EAAE,CAAA;KAAE,KAAK,MAAM,CAAA;CACnF,KAAG,oBAEH,CAAA;AAED,eAAO,MAAM,uBAAuB,YAAa,OAAO,KAAG,oBAQ1D,CAAA;AAED,eAAO,MAAM,2CAA2C,qBAErD;IACD,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,wBAoCH,CAAA"}
|
|
@@ -3,6 +3,7 @@ import path from 'path';
|
|
|
3
3
|
import { APIError, buildVersionCollectionFields, buildVersionGlobalFields, dynamicImport } from 'payload';
|
|
4
4
|
import { findConfig } from 'payload/node';
|
|
5
5
|
import { fieldShouldBeLocalized } from 'payload/shared';
|
|
6
|
+
import { formatGeneratedFile } from './formatGeneratedFile.js';
|
|
6
7
|
import { getTransaction } from './getTransaction.js';
|
|
7
8
|
const DEFAULT_BATCH_SIZE = 100;
|
|
8
9
|
const TEMP_FOLDER_NAME = '.payload-blocks-migration';
|
|
@@ -425,7 +426,7 @@ class BlocksToJsonMigratorImpl {
|
|
|
425
426
|
this.adapter.payload.logger.info(`Collected total of ${totalCollected} entities across ${batchIndex} batches`);
|
|
426
427
|
}
|
|
427
428
|
async getMigrationStatements() {
|
|
428
|
-
const { generateDrizzleJson, generateMigration } = this.adapter.requireDrizzleKit();
|
|
429
|
+
const { generateDrizzleJson, generateMigration } = await this.adapter.requireDrizzleKit();
|
|
429
430
|
const drizzleJsonBefore = await generateDrizzleJson(this.adapter.schema);
|
|
430
431
|
this.adapter.blocksAsJSON = true;
|
|
431
432
|
this.resetSchema();
|
|
@@ -520,23 +521,11 @@ class BlocksToJsonMigratorImpl {
|
|
|
520
521
|
const printer = ts.createPrinter({
|
|
521
522
|
newLine: ts.NewLineKind.LineFeed
|
|
522
523
|
});
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
const config = configPath ? await prettier.resolveConfig(configPath) : {};
|
|
529
|
-
output = await prettier.format(output, {
|
|
530
|
-
...config,
|
|
531
|
-
parser: 'typescript'
|
|
532
|
-
});
|
|
533
|
-
} catch (err) {
|
|
534
|
-
this.adapter.payload.logger.error({
|
|
535
|
-
err,
|
|
536
|
-
msg: 'Could not format payload config with Prettier'
|
|
537
|
-
});
|
|
538
|
-
}
|
|
539
|
-
writeFileSync(configPath, output, 'utf-8');
|
|
524
|
+
writeFileSync(configPath, printer.printFile(result.transformed[0]), 'utf-8');
|
|
525
|
+
await formatGeneratedFile({
|
|
526
|
+
filePath: configPath,
|
|
527
|
+
logger: this.adapter.payload.logger
|
|
528
|
+
});
|
|
540
529
|
this.adapter.payload.logger.info(`Updated ${configPath} with blocksAsJSON: true`);
|
|
541
530
|
}
|
|
542
531
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/blocksToJsonMigrator.ts"],"sourcesContent":["import type {\n DynamicMigrationTemplate,\n FlattenedField,\n Payload,\n PayloadRequest,\n SanitizedConfig,\n} from 'payload'\nimport type tsTypes from 'typescript'\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'\nimport path from 'path'\nimport {\n APIError,\n buildVersionCollectionFields,\n buildVersionGlobalFields,\n dynamicImport,\n} from 'payload'\nimport { findConfig } from 'payload/node'\nimport { fieldShouldBeLocalized } from 'payload/shared'\n\nimport type {\n BlocksToJsonBlockToMigrate,\n BlocksToJsonEntityToMigrate,\n BlocksToJsonMigrator,\n DrizzleAdapter,\n} from '../types.js'\n\nimport { getTransaction } from './getTransaction.js'\n\nconst DEFAULT_BATCH_SIZE = 100\nconst TEMP_FOLDER_NAME = '.payload-blocks-migration'\n\nconst writeEntitiesToTempFile = (\n entities: BlocksToJsonEntityToMigrate[],\n tempFolderPath: string,\n batchIndex: number,\n): void => {\n const filePath = path.join(tempFolderPath, `entities-batch-${batchIndex}.json`)\n writeFileSync(filePath, JSON.stringify(entities, null, 2), 'utf-8')\n}\n\nconst acceptDrizzlePrompts = async <T>(\n callPrompt: () => Promise<T> | T,\n {\n silenceLogs = false,\n }: {\n silenceLogs?: boolean\n } = {},\n): Promise<T> => {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const write = process.stdout.write\n\n if (silenceLogs) {\n process.stdout.write = () => true\n }\n\n const promise = callPrompt()\n\n const interval = setInterval(\n () =>\n process.stdin.emit('keypress', '\\n', {\n name: 'return',\n ctrl: false,\n }),\n 25,\n )\n\n const res = await promise\n\n if (silenceLogs) {\n process.stdout.write = write\n }\n\n clearInterval(interval)\n\n return res\n}\n\nconst entityHasBlocksField = (entity: { flattenedFields: FlattenedField[] }): boolean => {\n for (const field of entity.flattenedFields) {\n if (field.type === 'blocks') {\n return true\n }\n\n if (\n 'flattenedFields' in field &&\n entityHasBlocksField({ flattenedFields: field.flattenedFields })\n ) {\n return true\n }\n }\n\n return false\n}\n\nconst collectBlocksToMigrate = ({\n config,\n data,\n fields,\n parentAccessor,\n parentIsLocalized,\n}: {\n config: SanitizedConfig\n data: any\n fields: FlattenedField[]\n parentAccessor: (number | string)[]\n parentIsLocalized: boolean\n}): BlocksToJsonBlockToMigrate[] => {\n const result: BlocksToJsonBlockToMigrate[] = []\n\n for (const field of fields) {\n switch (field.type) {\n case 'array': {\n const arrayData = data[field.name]\n\n if (!Array.isArray(arrayData)) {\n continue\n }\n\n if (config.localization && fieldShouldBeLocalized({ field, parentIsLocalized })) {\n result.push(\n ...collectBlocksToMigrate({\n config,\n data: arrayData,\n fields: config.localization.localeCodes.map((code) => ({\n ...field,\n name: code,\n localized: false,\n })),\n parentAccessor: [...parentAccessor, field.name],\n parentIsLocalized: true,\n }),\n )\n\n continue\n }\n\n for (const [index, row] of arrayData.entries()) {\n result.push(\n ...collectBlocksToMigrate({\n config,\n data: row,\n fields: field.flattenedFields,\n parentAccessor: [...parentAccessor, field.name, index],\n parentIsLocalized,\n }),\n )\n }\n break\n }\n case 'blocks': {\n result.push({\n data: data[field.name],\n fieldAccessor: [...parentAccessor, field.name],\n })\n break\n }\n case 'group':\n case 'tab': {\n if (config.localization && fieldShouldBeLocalized({ field, parentIsLocalized })) {\n result.push(\n ...collectBlocksToMigrate({\n config,\n data: data[field.name],\n fields: config.localization.localeCodes.map((code) => ({\n ...field,\n name: code,\n localized: false,\n })),\n parentAccessor: [...parentAccessor, field.name],\n parentIsLocalized: true,\n }),\n )\n\n continue\n }\n\n result.push(\n ...collectBlocksToMigrate({\n config,\n data: data[field.name],\n fields: field.flattenedFields,\n parentAccessor: [...parentAccessor, field.name],\n parentIsLocalized,\n }),\n )\n break\n }\n default: {\n continue\n }\n }\n }\n\n return result\n}\n\nclass BlocksToJsonMigratorImpl implements BlocksToJsonMigrator {\n private readonly batchSize: number\n private tempFolderPath: string\n\n constructor(\n private readonly adapter: DrizzleAdapter,\n private readonly sanitizeStatements: (args: {\n sqlExecute: string\n statements: string[]\n }) => string,\n private readonly executeMethod: string,\n batchSize?: number,\n ) {\n this.batchSize = batchSize || DEFAULT_BATCH_SIZE\n this.tempFolderPath = path.resolve(this.adapter.migrationDir, TEMP_FOLDER_NAME)\n }\n\n private ensureTempFolder(): void {\n if (!existsSync(this.tempFolderPath)) {\n mkdirSync(this.tempFolderPath, { recursive: true })\n }\n }\n\n private *fetchEntitiesFromJsonBatches(): IterableIterator<BlocksToJsonEntityToMigrate[]> {\n if (!existsSync(this.tempFolderPath)) {\n return\n }\n\n const files = readdirSync(this.tempFolderPath)\n .filter((file) => file.startsWith('entities-batch-') && file.endsWith('.json'))\n .sort((a, b) => {\n const aNum = parseInt(a.match(/\\d+/)?.[0] || '0', 10)\n const bNum = parseInt(b.match(/\\d+/)?.[0] || '0', 10)\n return aNum - bNum\n })\n\n for (const file of files) {\n const filePath = path.join(this.tempFolderPath, file)\n const fileContent = readFileSync(filePath, 'utf-8')\n const batchEntities = JSON.parse(fileContent) as BlocksToJsonEntityToMigrate[]\n yield batchEntities\n }\n }\n\n private async migrateEntities(\n entities: BlocksToJsonEntityToMigrate[],\n req: PayloadRequest,\n ): Promise<void> {\n this.adapter.blocksAsJSON = true\n this.resetSchema()\n await this.adapter.init()\n await this.adapter.connect()\n\n await this.syncTransactionDrizzleInstance(req)\n\n const totalEntities = entities.length\n let processed = 0\n\n for (const entity of entities) {\n switch (entity.type) {\n case 'collection': {\n await this.adapter.updateOne({\n collection: entity.slug,\n data: entity.originalData,\n joins: false,\n req,\n where: {\n id: {\n equals: entity.id,\n },\n },\n })\n break\n }\n case 'collectionVersion': {\n await this.adapter.updateVersion({\n id: entity.id,\n collection: entity.slug,\n req,\n versionData: entity.originalData as any,\n })\n\n break\n }\n case 'global': {\n await this.adapter.updateGlobal({\n slug: entity.slug,\n data: entity.originalData,\n req,\n })\n break\n }\n case 'globalVersion': {\n await this.adapter.updateGlobalVersion({\n id: entity.id,\n global: entity.slug,\n req,\n versionData: entity.originalData as any,\n })\n break\n }\n }\n\n processed++\n if (processed % this.batchSize === 0 || processed === totalEntities) {\n this.adapter.payload.logger.info(\n `Migrated ${processed}/${totalEntities} entities (${Math.round((processed / totalEntities) * 100)}%)`,\n )\n }\n }\n }\n\n private resetSchema() {\n this.adapter.schema = {}\n this.adapter.tables = {}\n this.adapter.indexes = new Set()\n this.adapter.foreignKeys = new Set()\n this.adapter.relations = {}\n this.adapter.rawTables = {}\n this.adapter.rawRelations = {}\n this.adapter.tableNameMap = new Map()\n this.adapter.enums = {}\n }\n\n private async syncTransactionDrizzleInstance(req: PayloadRequest) {\n const tsx = (await getTransaction(this.adapter, req)) as any\n\n tsx._ = this.adapter.drizzle._\n tsx.schema = this.adapter.drizzle._\n tsx.session.schema = (this.adapter.drizzle as any).session.schema\n }\n\n cleanupTempFolder(): void {\n rmSync(this.tempFolderPath, { force: true, recursive: true })\n\n this.adapter.payload.logger.info(`Cleaned up temp folder at ${this.tempFolderPath}`)\n }\n\n async collectAndSaveEntitiesToBatches(\n req: PayloadRequest,\n options?: {\n batchSize?: number\n },\n ): Promise<void> {\n const batchSize = options?.batchSize ?? this.batchSize\n\n this.cleanupTempFolder()\n this.ensureTempFolder()\n\n this.adapter.blocksAsJSON = false\n this.resetSchema()\n await this.adapter.init()\n await this.adapter.connect()\n\n // Count total entities to migrate\n let totalExpected = 0\n for (const collection of this.adapter.payload.config.collections.filter(entityHasBlocksField)) {\n const { totalDocs } = await this.adapter.count({ collection: collection.slug })\n totalExpected += totalDocs\n\n if (collection.versions) {\n const { totalDocs: totalVersions } = await this.adapter.countVersions({\n collection: collection.slug,\n })\n totalExpected += totalVersions\n }\n }\n\n for (const globalConfig of this.adapter.payload.config.globals.filter(entityHasBlocksField)) {\n totalExpected += 1 // Global itself\n\n if (globalConfig.versions) {\n const { totalDocs: totalGlobalVersions } = await this.adapter.countGlobalVersions({\n global: globalConfig.slug,\n })\n totalExpected += totalGlobalVersions\n }\n }\n\n this.adapter.payload.logger.info(\n `Found ${totalExpected} total entities to collect and save to batches`,\n )\n\n let batchIndex = 0\n let currentBatch: BlocksToJsonEntityToMigrate[] = []\n let totalCollected = 0\n\n const flushBatch = () => {\n if (currentBatch.length > 0) {\n writeEntitiesToTempFile(currentBatch, this.tempFolderPath, batchIndex)\n const percentage =\n totalExpected > 0 ? Math.round((totalCollected / totalExpected) * 100) : 0\n this.adapter.payload.logger.info(\n `Saved batch ${batchIndex} with ${currentBatch.length} entities (${totalCollected}/${totalExpected} - ${percentage}%)`,\n )\n batchIndex++\n currentBatch = []\n }\n }\n\n const addEntity = (entity: BlocksToJsonEntityToMigrate) => {\n currentBatch.push(entity)\n totalCollected++\n if (currentBatch.length >= batchSize) {\n flushBatch()\n }\n }\n\n for (const collection of this.adapter.payload.config.collections.filter(entityHasBlocksField)) {\n let page = 1\n let hasMore = true\n\n while (hasMore) {\n const { docs, hasNextPage } = await this.adapter.find({\n collection: collection.slug,\n limit: batchSize,\n page,\n })\n\n for (const doc of docs) {\n const entity: BlocksToJsonEntityToMigrate = {\n id: doc.id,\n slug: collection.slug,\n type: 'collection',\n blocks: collectBlocksToMigrate({\n config: this.adapter.payload.config,\n data: doc,\n fields: collection.flattenedFields,\n parentAccessor: [],\n parentIsLocalized: false,\n }),\n originalData: doc,\n }\n\n addEntity(entity)\n }\n\n this.adapter.payload.logger.info(\n `Collected ${docs.length} entries from ${collection.slug} (page ${page})`,\n )\n\n hasMore = hasNextPage\n page++\n }\n\n if (collection.versions) {\n let versionPage = 1\n let hasMoreVersions = true\n\n while (hasMoreVersions) {\n const { docs: versionDocs, hasNextPage: hasNextVersionPage } =\n await this.adapter.findVersions({\n collection: collection.slug,\n limit: batchSize,\n page: versionPage,\n })\n\n for (const versionDoc of versionDocs) {\n const entity: BlocksToJsonEntityToMigrate = {\n id: versionDoc.id,\n slug: collection.slug,\n type: 'collectionVersion',\n blocks: collectBlocksToMigrate({\n config: this.adapter.payload.config,\n data: versionDoc,\n fields: buildVersionCollectionFields(this.adapter.payload.config, collection, true),\n parentAccessor: [],\n parentIsLocalized: false,\n }),\n originalData: versionDoc,\n }\n\n addEntity(entity)\n }\n\n this.adapter.payload.logger.info(\n `Collected ${versionDocs.length} versions from ${collection.slug} (page ${versionPage})`,\n )\n\n hasMoreVersions = hasNextVersionPage\n versionPage++\n }\n }\n }\n\n for (const globalConfig of this.adapter.payload.config.globals.filter(entityHasBlocksField)) {\n const globalDoc = await this.adapter.findGlobal({ slug: globalConfig.slug })\n\n const entity: BlocksToJsonEntityToMigrate = {\n slug: globalConfig.slug,\n type: 'global',\n blocks: collectBlocksToMigrate({\n config: this.adapter.payload.config,\n data: globalDoc,\n fields: globalConfig.flattenedFields,\n parentAccessor: [],\n parentIsLocalized: false,\n }),\n originalData: globalDoc,\n }\n\n addEntity(entity)\n this.adapter.payload.logger.info(`Collected global ${globalConfig.slug}`)\n\n if (globalConfig.versions) {\n let globalVersionPage = 1\n let hasMoreGlobalVersions = true\n\n while (hasMoreGlobalVersions) {\n const { docs: globalVersionDocs, hasNextPage: hasNextGlobalVersionPage } =\n await this.adapter.findGlobalVersions({\n global: globalConfig.slug,\n limit: batchSize,\n page: globalVersionPage,\n })\n\n for (const globalVersionDoc of globalVersionDocs) {\n const entity: BlocksToJsonEntityToMigrate = {\n id: globalVersionDoc.id,\n slug: globalConfig.slug,\n type: 'globalVersion',\n blocks: collectBlocksToMigrate({\n config: this.adapter.payload.config,\n data: globalVersionDoc,\n fields: buildVersionGlobalFields(this.adapter.payload.config, globalConfig, true),\n parentAccessor: [],\n parentIsLocalized: false,\n }),\n originalData: globalVersionDoc,\n }\n\n addEntity(entity)\n }\n\n this.adapter.payload.logger.info(\n `Collected ${globalVersionDocs.length} versions from global ${globalConfig.slug} (page ${globalVersionPage})`,\n )\n\n hasMoreGlobalVersions = hasNextGlobalVersionPage\n globalVersionPage++\n }\n }\n }\n\n flushBatch()\n\n this.adapter.payload.logger.info(\n `Collected total of ${totalCollected} entities across ${batchIndex} batches`,\n )\n }\n\n async getMigrationStatements(): Promise<{\n statements: string\n writeDrizzleSnapshot(filePath: string): void\n }> {\n const { generateDrizzleJson, generateMigration } = this.adapter.requireDrizzleKit()\n\n const drizzleJsonBefore = await generateDrizzleJson(this.adapter.schema)\n this.adapter.blocksAsJSON = true\n this.resetSchema()\n\n await this.adapter.init()\n const drizzleJsonAfter = await generateDrizzleJson(this.adapter.schema)\n this.adapter.blocksAsJSON = false\n this.resetSchema()\n await this.adapter.init()\n\n const statements = await acceptDrizzlePrompts(\n () => generateMigration(drizzleJsonBefore, drizzleJsonAfter),\n {\n silenceLogs: true,\n },\n )\n\n const sqlExecute = `await db.${this.executeMethod}(` + 'sql`'\n\n return {\n statements: this.sanitizeStatements({\n sqlExecute,\n statements,\n }),\n writeDrizzleSnapshot(filePath) {\n writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n },\n }\n }\n\n async migrateEntitiesFromTempFolder(\n req: PayloadRequest,\n options?: {\n clearBatches?: boolean\n },\n ): Promise<void> {\n const clearBatches = options?.clearBatches ?? true\n\n let totalEntities = 0\n let hasEntities = false\n\n for (const entities of this.fetchEntitiesFromJsonBatches()) {\n hasEntities = true\n totalEntities += entities.length\n\n this.adapter.payload.logger.info(\n `Migrating batch with ${entities.length} entities (total: ${totalEntities})`,\n )\n\n await this.migrateEntities(entities, req)\n }\n\n if (!hasEntities) {\n this.adapter.payload.logger.warn('No entities found in temp folder to migrate')\n return\n }\n\n this.adapter.payload.logger.info(\n `Completed migration of ${totalEntities} entities from temp folder`,\n )\n\n if (clearBatches) {\n this.cleanupTempFolder()\n } else {\n this.adapter.payload.logger.info(\n `Temp folder preserved at ${this.tempFolderPath} (clearBatches: false)`,\n )\n }\n }\n\n setTempFolder(tempFolderPath: string): void {\n this.tempFolderPath = tempFolderPath\n }\n\n async updatePayloadConfigFile(): Promise<void> {\n let configPath: string\n\n try {\n configPath = findConfig()\n } catch {\n this.adapter.payload.logger.info(\n 'updatePayloadConfigFile failed - could not find the payload config. Please set the blocksAsJSON DB adapter property manually to \"true\"',\n )\n return\n }\n\n const configFile = readFileSync(configPath, 'utf-8')\n\n const ts = await dynamicImport<typeof tsTypes>('typescript')\n\n const source = ts.createSourceFile(configPath, configFile, ts.ScriptTarget.ESNext)\n\n let hadChanges = false\n\n const result = ts.transform(source, [\n (ctx) => (sourceFile) => {\n const factory = ctx.factory\n\n const visit: tsTypes.Visitor = (node) => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'db' &&\n ts.isCallExpression(node.initializer) &&\n node.initializer.arguments.length > 0 &&\n ts.isObjectLiteralExpression(node.initializer.arguments[0])\n ) {\n const call = node.initializer\n const obj = node.initializer.arguments[0]\n\n const filteredProps = obj.properties.filter((prop) => {\n if (!ts.isPropertyAssignment(prop)) {\n return true\n }\n\n return !(ts.isIdentifier(prop.name) && prop.name.text === 'blocksAsJSON')\n })\n\n const newProperty = factory.createPropertyAssignment(\n 'blocksAsJSON',\n factory.createTrue(),\n )\n hadChanges = true\n const newObject = factory.updateObjectLiteralExpression(obj, [\n ...filteredProps,\n newProperty,\n ])\n\n const newCall = factory.updateCallExpression(\n call,\n call.expression,\n call.typeArguments,\n [newObject],\n )\n\n return factory.updatePropertyAssignment(node, node.name, newCall)\n }\n\n return ts.visitEachChild(node, visit, ctx)\n }\n\n return ts.visitNode(sourceFile, visit) as tsTypes.SourceFile\n },\n ])\n\n if (!hadChanges) {\n this.adapter.payload.logger.info(\n 'No changes made to payload config. Set blocksAsJSON to true manually.',\n )\n return\n }\n\n const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed })\n let output = printer.printFile(result.transformed[0])\n\n try {\n // eslint-disable-next-line @typescript-eslint/consistent-type-imports\n const prettier = await dynamicImport<typeof import('prettier')>('prettier')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n output = await prettier.format(output, { ...config, parser: 'typescript' })\n } catch (err) {\n this.adapter.payload.logger.error({\n err,\n msg: 'Could not format payload config with Prettier',\n })\n }\n\n writeFileSync(configPath, output, 'utf-8')\n this.adapter.payload.logger.info(`Updated ${configPath} with blocksAsJSON: true`)\n }\n}\n\nexport const createBlocksToJsonMigrator = ({\n adapter,\n executeMethod,\n sanitizeStatements,\n}: {\n adapter: DrizzleAdapter\n executeMethod: string\n sanitizeStatements: (args: { sqlExecute: string; statements: string[] }) => string\n}): BlocksToJsonMigrator => {\n return new BlocksToJsonMigratorImpl(adapter, sanitizeStatements, executeMethod)\n}\n\nexport const getBlocksToJsonMigrator = (payload: Payload): BlocksToJsonMigrator => {\n const migrator = (payload.db as DrizzleAdapter).blocksToJsonMigrator\n\n if (!migrator) {\n throw new APIError(`blocksToJsonMigrator is not defined for ${payload.db.packageName}`)\n }\n\n return migrator\n}\n\nexport const buildDynamicPredefinedBlocksToJsonMigration = ({\n packageName,\n}: {\n packageName: string\n}): DynamicMigrationTemplate => {\n return async ({ filePath, payload }) => {\n const migrator = getBlocksToJsonMigrator(payload)\n\n const migrationStatements = await migrator.getMigrationStatements()\n\n migrationStatements.writeDrizzleSnapshot(filePath)\n\n await migrator.updatePayloadConfigFile()\n const upSQL = `\nconst migrator = getBlocksToJsonMigrator(payload)\nmigrator.setTempFolder(TEMP_FOLDER)\nawait migrator.collectAndSaveEntitiesToBatches(req, { batchSize: BATCH_SIZE })\n\n${migrationStatements.statements}\npayload.logger.info(\"Executed blocks to JSON migration statements.\")\n\nawait migrator.migrateEntitiesFromTempFolder(req, { clearBatches: true })\n `\n\n return {\n imports: `\nimport { getBlocksToJsonMigrator } from '${packageName}/migration-utils'\nimport { fileURLToPath } from 'url'\nimport path from 'path'\n\nconst filename = fileURLToPath(import.meta.url)\nconst dirname = path.dirname(filename)\n\n// Configure migration options (optional)\nconst BATCH_SIZE = 100 // Number of entities to process per batch\nconst TEMP_FOLDER = path.resolve(dirname, '${TEMP_FOLDER_NAME}') // Folder path to store migration batch\n`,\n upSQL,\n }\n }\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","rmSync","writeFileSync","path","APIError","buildVersionCollectionFields","buildVersionGlobalFields","dynamicImport","findConfig","fieldShouldBeLocalized","getTransaction","DEFAULT_BATCH_SIZE","TEMP_FOLDER_NAME","writeEntitiesToTempFile","entities","tempFolderPath","batchIndex","filePath","join","JSON","stringify","acceptDrizzlePrompts","callPrompt","silenceLogs","write","process","stdout","promise","interval","setInterval","stdin","emit","name","ctrl","res","clearInterval","entityHasBlocksField","entity","field","flattenedFields","type","collectBlocksToMigrate","config","data","fields","parentAccessor","parentIsLocalized","result","arrayData","Array","isArray","localization","push","localeCodes","map","code","localized","index","row","entries","fieldAccessor","BlocksToJsonMigratorImpl","batchSize","adapter","sanitizeStatements","executeMethod","resolve","migrationDir","ensureTempFolder","recursive","fetchEntitiesFromJsonBatches","files","filter","file","startsWith","endsWith","sort","a","b","aNum","parseInt","match","bNum","fileContent","batchEntities","parse","migrateEntities","req","blocksAsJSON","resetSchema","init","connect","syncTransactionDrizzleInstance","totalEntities","length","processed","updateOne","collection","slug","originalData","joins","where","id","equals","updateVersion","versionData","updateGlobal","updateGlobalVersion","global","payload","logger","info","Math","round","schema","tables","indexes","Set","foreignKeys","relations","rawTables","rawRelations","tableNameMap","Map","enums","tsx","_","drizzle","session","cleanupTempFolder","force","collectAndSaveEntitiesToBatches","options","totalExpected","collections","totalDocs","count","versions","totalVersions","countVersions","globalConfig","globals","totalGlobalVersions","countGlobalVersions","currentBatch","totalCollected","flushBatch","percentage","addEntity","page","hasMore","docs","hasNextPage","find","limit","doc","blocks","versionPage","hasMoreVersions","versionDocs","hasNextVersionPage","findVersions","versionDoc","globalDoc","findGlobal","globalVersionPage","hasMoreGlobalVersions","globalVersionDocs","hasNextGlobalVersionPage","findGlobalVersions","globalVersionDoc","getMigrationStatements","generateDrizzleJson","generateMigration","requireDrizzleKit","drizzleJsonBefore","drizzleJsonAfter","statements","sqlExecute","writeDrizzleSnapshot","migrateEntitiesFromTempFolder","clearBatches","hasEntities","warn","setTempFolder","updatePayloadConfigFile","configPath","configFile","ts","source","createSourceFile","ScriptTarget","ESNext","hadChanges","transform","ctx","sourceFile","factory","visit","node","isPropertyAssignment","isIdentifier","text","isCallExpression","initializer","arguments","isObjectLiteralExpression","call","obj","filteredProps","properties","prop","newProperty","createPropertyAssignment","createTrue","newObject","updateObjectLiteralExpression","newCall","updateCallExpression","expression","typeArguments","updatePropertyAssignment","visitEachChild","visitNode","printer","createPrinter","newLine","NewLineKind","LineFeed","output","printFile","transformed","prettier","resolveConfigFile","resolveConfig","format","parser","err","error","msg","createBlocksToJsonMigrator","getBlocksToJsonMigrator","migrator","db","blocksToJsonMigrator","packageName","buildDynamicPredefinedBlocksToJsonMigration","migrationStatements","upSQL","imports"],"mappings":"AASA,SAASA,UAAU,EAAEC,SAAS,EAAEC,WAAW,EAAEC,YAAY,EAAEC,MAAM,EAAEC,aAAa,QAAQ,KAAI;AAC5F,OAAOC,UAAU,OAAM;AACvB,SACEC,QAAQ,EACRC,4BAA4B,EAC5BC,wBAAwB,EACxBC,aAAa,QACR,UAAS;AAChB,SAASC,UAAU,QAAQ,eAAc;AACzC,SAASC,sBAAsB,QAAQ,iBAAgB;AASvD,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,MAAMC,qBAAqB;AAC3B,MAAMC,mBAAmB;AAEzB,MAAMC,0BAA0B,CAC9BC,UACAC,gBACAC;IAEA,MAAMC,WAAWd,KAAKe,IAAI,CAACH,gBAAgB,CAAC,eAAe,EAAEC,WAAW,KAAK,CAAC;IAC9Ed,cAAce,UAAUE,KAAKC,SAAS,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,0BAA0B,CAACpI;IACtC,MAAMqI,WAAW,AAACrI,QAAQsI,EAAE,CAAoBC,oBAAoB;IAEpE,IAAI,CAACF,UAAU;QACb,MAAM,IAAI9O,SAAS,CAAC,wCAAwC,EAAEyG,QAAQsI,EAAE,CAACE,WAAW,EAAE;IACxF;IAEA,OAAOH;AACT,EAAC;AAED,OAAO,MAAMI,8CAA8C,CAAC,EAC1DD,WAAW,EAGZ;IACC,OAAO,OAAO,EAAEpO,QAAQ,EAAE4F,OAAO,EAAE;QACjC,MAAMqI,WAAWD,wBAAwBpI;QAEzC,MAAM0I,sBAAsB,MAAML,SAASvE,sBAAsB;QAEjE4E,oBAAoBpE,oBAAoB,CAAClK;QAEzC,MAAMiO,SAASzD,uBAAuB;QACtC,MAAM+D,QAAQ,CAAC;;;;;AAKnB,EAAED,oBAAoBtE,UAAU,CAAC;;;;EAI/B,CAAC;QAEC,OAAO;YACLwE,SAAS,CAAC;yCACyB,EAAEJ,YAAY;;;;;;;;;2CASZ,EAAEzO,iBAAiB;AAC9D,CAAC;YACK4O;QACF;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/blocksToJsonMigrator.ts"],"sourcesContent":["import type {\n DynamicMigrationTemplate,\n FlattenedField,\n Payload,\n PayloadRequest,\n SanitizedConfig,\n} from 'payload'\nimport type tsTypes from 'typescript'\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'\nimport path from 'path'\nimport {\n APIError,\n buildVersionCollectionFields,\n buildVersionGlobalFields,\n dynamicImport,\n} from 'payload'\nimport { findConfig } from 'payload/node'\nimport { fieldShouldBeLocalized } from 'payload/shared'\n\nimport type {\n BlocksToJsonBlockToMigrate,\n BlocksToJsonEntityToMigrate,\n BlocksToJsonMigrator,\n DrizzleAdapter,\n} from '../types.js'\n\nimport { formatGeneratedFile } from './formatGeneratedFile.js'\nimport { getTransaction } from './getTransaction.js'\n\nconst DEFAULT_BATCH_SIZE = 100\nconst TEMP_FOLDER_NAME = '.payload-blocks-migration'\n\nconst writeEntitiesToTempFile = (\n entities: BlocksToJsonEntityToMigrate[],\n tempFolderPath: string,\n batchIndex: number,\n): void => {\n const filePath = path.join(tempFolderPath, `entities-batch-${batchIndex}.json`)\n writeFileSync(filePath, JSON.stringify(entities, null, 2), 'utf-8')\n}\n\nconst acceptDrizzlePrompts = async <T>(\n callPrompt: () => Promise<T> | T,\n {\n silenceLogs = false,\n }: {\n silenceLogs?: boolean\n } = {},\n): Promise<T> => {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const write = process.stdout.write\n\n if (silenceLogs) {\n process.stdout.write = () => true\n }\n\n const promise = callPrompt()\n\n const interval = setInterval(\n () =>\n process.stdin.emit('keypress', '\\n', {\n name: 'return',\n ctrl: false,\n }),\n 25,\n )\n\n const res = await promise\n\n if (silenceLogs) {\n process.stdout.write = write\n }\n\n clearInterval(interval)\n\n return res\n}\n\nconst entityHasBlocksField = (entity: { flattenedFields: FlattenedField[] }): boolean => {\n for (const field of entity.flattenedFields) {\n if (field.type === 'blocks') {\n return true\n }\n\n if (\n 'flattenedFields' in field &&\n entityHasBlocksField({ flattenedFields: field.flattenedFields })\n ) {\n return true\n }\n }\n\n return false\n}\n\nconst collectBlocksToMigrate = ({\n config,\n data,\n fields,\n parentAccessor,\n parentIsLocalized,\n}: {\n config: SanitizedConfig\n data: any\n fields: FlattenedField[]\n parentAccessor: (number | string)[]\n parentIsLocalized: boolean\n}): BlocksToJsonBlockToMigrate[] => {\n const result: BlocksToJsonBlockToMigrate[] = []\n\n for (const field of fields) {\n switch (field.type) {\n case 'array': {\n const arrayData = data[field.name]\n\n if (!Array.isArray(arrayData)) {\n continue\n }\n\n if (config.localization && fieldShouldBeLocalized({ field, parentIsLocalized })) {\n result.push(\n ...collectBlocksToMigrate({\n config,\n data: arrayData,\n fields: config.localization.localeCodes.map((code) => ({\n ...field,\n name: code,\n localized: false,\n })),\n parentAccessor: [...parentAccessor, field.name],\n parentIsLocalized: true,\n }),\n )\n\n continue\n }\n\n for (const [index, row] of arrayData.entries()) {\n result.push(\n ...collectBlocksToMigrate({\n config,\n data: row,\n fields: field.flattenedFields,\n parentAccessor: [...parentAccessor, field.name, index],\n parentIsLocalized,\n }),\n )\n }\n break\n }\n case 'blocks': {\n result.push({\n data: data[field.name],\n fieldAccessor: [...parentAccessor, field.name],\n })\n break\n }\n case 'group':\n case 'tab': {\n if (config.localization && fieldShouldBeLocalized({ field, parentIsLocalized })) {\n result.push(\n ...collectBlocksToMigrate({\n config,\n data: data[field.name],\n fields: config.localization.localeCodes.map((code) => ({\n ...field,\n name: code,\n localized: false,\n })),\n parentAccessor: [...parentAccessor, field.name],\n parentIsLocalized: true,\n }),\n )\n\n continue\n }\n\n result.push(\n ...collectBlocksToMigrate({\n config,\n data: data[field.name],\n fields: field.flattenedFields,\n parentAccessor: [...parentAccessor, field.name],\n parentIsLocalized,\n }),\n )\n break\n }\n default: {\n continue\n }\n }\n }\n\n return result\n}\n\nclass BlocksToJsonMigratorImpl implements BlocksToJsonMigrator {\n private readonly batchSize: number\n private tempFolderPath: string\n\n constructor(\n private readonly adapter: DrizzleAdapter,\n private readonly sanitizeStatements: (args: {\n sqlExecute: string\n statements: string[]\n }) => string,\n private readonly executeMethod: string,\n batchSize?: number,\n ) {\n this.batchSize = batchSize || DEFAULT_BATCH_SIZE\n this.tempFolderPath = path.resolve(this.adapter.migrationDir, TEMP_FOLDER_NAME)\n }\n\n private ensureTempFolder(): void {\n if (!existsSync(this.tempFolderPath)) {\n mkdirSync(this.tempFolderPath, { recursive: true })\n }\n }\n\n private *fetchEntitiesFromJsonBatches(): IterableIterator<BlocksToJsonEntityToMigrate[]> {\n if (!existsSync(this.tempFolderPath)) {\n return\n }\n\n const files = readdirSync(this.tempFolderPath)\n .filter((file) => file.startsWith('entities-batch-') && file.endsWith('.json'))\n .sort((a, b) => {\n const aNum = parseInt(a.match(/\\d+/)?.[0] || '0', 10)\n const bNum = parseInt(b.match(/\\d+/)?.[0] || '0', 10)\n return aNum - bNum\n })\n\n for (const file of files) {\n const filePath = path.join(this.tempFolderPath, file)\n const fileContent = readFileSync(filePath, 'utf-8')\n const batchEntities = JSON.parse(fileContent) as BlocksToJsonEntityToMigrate[]\n yield batchEntities\n }\n }\n\n private async migrateEntities(\n entities: BlocksToJsonEntityToMigrate[],\n req: PayloadRequest,\n ): Promise<void> {\n this.adapter.blocksAsJSON = true\n this.resetSchema()\n await this.adapter.init()\n await this.adapter.connect()\n\n await this.syncTransactionDrizzleInstance(req)\n\n const totalEntities = entities.length\n let processed = 0\n\n for (const entity of entities) {\n switch (entity.type) {\n case 'collection': {\n await this.adapter.updateOne({\n collection: entity.slug,\n data: entity.originalData,\n joins: false,\n req,\n where: {\n id: {\n equals: entity.id,\n },\n },\n })\n break\n }\n case 'collectionVersion': {\n await this.adapter.updateVersion({\n id: entity.id,\n collection: entity.slug,\n req,\n versionData: entity.originalData as any,\n })\n\n break\n }\n case 'global': {\n await this.adapter.updateGlobal({\n slug: entity.slug,\n data: entity.originalData,\n req,\n })\n break\n }\n case 'globalVersion': {\n await this.adapter.updateGlobalVersion({\n id: entity.id,\n global: entity.slug,\n req,\n versionData: entity.originalData as any,\n })\n break\n }\n }\n\n processed++\n if (processed % this.batchSize === 0 || processed === totalEntities) {\n this.adapter.payload.logger.info(\n `Migrated ${processed}/${totalEntities} entities (${Math.round((processed / totalEntities) * 100)}%)`,\n )\n }\n }\n }\n\n private resetSchema() {\n this.adapter.schema = {}\n this.adapter.tables = {}\n this.adapter.indexes = new Set()\n this.adapter.foreignKeys = new Set()\n this.adapter.relations = {}\n this.adapter.rawTables = {}\n this.adapter.rawRelations = {}\n this.adapter.tableNameMap = new Map()\n this.adapter.enums = {}\n }\n\n private async syncTransactionDrizzleInstance(req: PayloadRequest) {\n const tsx = (await getTransaction(this.adapter, req)) as any\n\n tsx._ = this.adapter.drizzle._\n tsx.schema = this.adapter.drizzle._\n tsx.session.schema = (this.adapter.drizzle as any).session.schema\n }\n\n cleanupTempFolder(): void {\n rmSync(this.tempFolderPath, { force: true, recursive: true })\n\n this.adapter.payload.logger.info(`Cleaned up temp folder at ${this.tempFolderPath}`)\n }\n\n async collectAndSaveEntitiesToBatches(\n req: PayloadRequest,\n options?: {\n batchSize?: number\n },\n ): Promise<void> {\n const batchSize = options?.batchSize ?? this.batchSize\n\n this.cleanupTempFolder()\n this.ensureTempFolder()\n\n this.adapter.blocksAsJSON = false\n this.resetSchema()\n await this.adapter.init()\n await this.adapter.connect()\n\n // Count total entities to migrate\n let totalExpected = 0\n for (const collection of this.adapter.payload.config.collections.filter(entityHasBlocksField)) {\n const { totalDocs } = await this.adapter.count({ collection: collection.slug })\n totalExpected += totalDocs\n\n if (collection.versions) {\n const { totalDocs: totalVersions } = await this.adapter.countVersions({\n collection: collection.slug,\n })\n totalExpected += totalVersions\n }\n }\n\n for (const globalConfig of this.adapter.payload.config.globals.filter(entityHasBlocksField)) {\n totalExpected += 1 // Global itself\n\n if (globalConfig.versions) {\n const { totalDocs: totalGlobalVersions } = await this.adapter.countGlobalVersions({\n global: globalConfig.slug,\n })\n totalExpected += totalGlobalVersions\n }\n }\n\n this.adapter.payload.logger.info(\n `Found ${totalExpected} total entities to collect and save to batches`,\n )\n\n let batchIndex = 0\n let currentBatch: BlocksToJsonEntityToMigrate[] = []\n let totalCollected = 0\n\n const flushBatch = () => {\n if (currentBatch.length > 0) {\n writeEntitiesToTempFile(currentBatch, this.tempFolderPath, batchIndex)\n const percentage =\n totalExpected > 0 ? Math.round((totalCollected / totalExpected) * 100) : 0\n this.adapter.payload.logger.info(\n `Saved batch ${batchIndex} with ${currentBatch.length} entities (${totalCollected}/${totalExpected} - ${percentage}%)`,\n )\n batchIndex++\n currentBatch = []\n }\n }\n\n const addEntity = (entity: BlocksToJsonEntityToMigrate) => {\n currentBatch.push(entity)\n totalCollected++\n if (currentBatch.length >= batchSize) {\n flushBatch()\n }\n }\n\n for (const collection of this.adapter.payload.config.collections.filter(entityHasBlocksField)) {\n let page = 1\n let hasMore = true\n\n while (hasMore) {\n const { docs, hasNextPage } = await this.adapter.find({\n collection: collection.slug,\n limit: batchSize,\n page,\n })\n\n for (const doc of docs) {\n const entity: BlocksToJsonEntityToMigrate = {\n id: doc.id,\n slug: collection.slug,\n type: 'collection',\n blocks: collectBlocksToMigrate({\n config: this.adapter.payload.config,\n data: doc,\n fields: collection.flattenedFields,\n parentAccessor: [],\n parentIsLocalized: false,\n }),\n originalData: doc,\n }\n\n addEntity(entity)\n }\n\n this.adapter.payload.logger.info(\n `Collected ${docs.length} entries from ${collection.slug} (page ${page})`,\n )\n\n hasMore = hasNextPage\n page++\n }\n\n if (collection.versions) {\n let versionPage = 1\n let hasMoreVersions = true\n\n while (hasMoreVersions) {\n const { docs: versionDocs, hasNextPage: hasNextVersionPage } =\n await this.adapter.findVersions({\n collection: collection.slug,\n limit: batchSize,\n page: versionPage,\n })\n\n for (const versionDoc of versionDocs) {\n const entity: BlocksToJsonEntityToMigrate = {\n id: versionDoc.id,\n slug: collection.slug,\n type: 'collectionVersion',\n blocks: collectBlocksToMigrate({\n config: this.adapter.payload.config,\n data: versionDoc,\n fields: buildVersionCollectionFields(this.adapter.payload.config, collection, true),\n parentAccessor: [],\n parentIsLocalized: false,\n }),\n originalData: versionDoc,\n }\n\n addEntity(entity)\n }\n\n this.adapter.payload.logger.info(\n `Collected ${versionDocs.length} versions from ${collection.slug} (page ${versionPage})`,\n )\n\n hasMoreVersions = hasNextVersionPage\n versionPage++\n }\n }\n }\n\n for (const globalConfig of this.adapter.payload.config.globals.filter(entityHasBlocksField)) {\n const globalDoc = await this.adapter.findGlobal({ slug: globalConfig.slug })\n\n const entity: BlocksToJsonEntityToMigrate = {\n slug: globalConfig.slug,\n type: 'global',\n blocks: collectBlocksToMigrate({\n config: this.adapter.payload.config,\n data: globalDoc,\n fields: globalConfig.flattenedFields,\n parentAccessor: [],\n parentIsLocalized: false,\n }),\n originalData: globalDoc,\n }\n\n addEntity(entity)\n this.adapter.payload.logger.info(`Collected global ${globalConfig.slug}`)\n\n if (globalConfig.versions) {\n let globalVersionPage = 1\n let hasMoreGlobalVersions = true\n\n while (hasMoreGlobalVersions) {\n const { docs: globalVersionDocs, hasNextPage: hasNextGlobalVersionPage } =\n await this.adapter.findGlobalVersions({\n global: globalConfig.slug,\n limit: batchSize,\n page: globalVersionPage,\n })\n\n for (const globalVersionDoc of globalVersionDocs) {\n const entity: BlocksToJsonEntityToMigrate = {\n id: globalVersionDoc.id,\n slug: globalConfig.slug,\n type: 'globalVersion',\n blocks: collectBlocksToMigrate({\n config: this.adapter.payload.config,\n data: globalVersionDoc,\n fields: buildVersionGlobalFields(this.adapter.payload.config, globalConfig, true),\n parentAccessor: [],\n parentIsLocalized: false,\n }),\n originalData: globalVersionDoc,\n }\n\n addEntity(entity)\n }\n\n this.adapter.payload.logger.info(\n `Collected ${globalVersionDocs.length} versions from global ${globalConfig.slug} (page ${globalVersionPage})`,\n )\n\n hasMoreGlobalVersions = hasNextGlobalVersionPage\n globalVersionPage++\n }\n }\n }\n\n flushBatch()\n\n this.adapter.payload.logger.info(\n `Collected total of ${totalCollected} entities across ${batchIndex} batches`,\n )\n }\n\n async getMigrationStatements(): Promise<{\n statements: string\n writeDrizzleSnapshot(filePath: string): void\n }> {\n const { generateDrizzleJson, generateMigration } = await this.adapter.requireDrizzleKit()\n\n const drizzleJsonBefore = await generateDrizzleJson(this.adapter.schema)\n this.adapter.blocksAsJSON = true\n this.resetSchema()\n\n await this.adapter.init()\n const drizzleJsonAfter = await generateDrizzleJson(this.adapter.schema)\n this.adapter.blocksAsJSON = false\n this.resetSchema()\n await this.adapter.init()\n\n const statements = await acceptDrizzlePrompts(\n () => generateMigration(drizzleJsonBefore, drizzleJsonAfter),\n {\n silenceLogs: true,\n },\n )\n\n const sqlExecute = `await db.${this.executeMethod}(` + 'sql`'\n\n return {\n statements: this.sanitizeStatements({\n sqlExecute,\n statements,\n }),\n writeDrizzleSnapshot(filePath) {\n writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n },\n }\n }\n\n async migrateEntitiesFromTempFolder(\n req: PayloadRequest,\n options?: {\n clearBatches?: boolean\n },\n ): Promise<void> {\n const clearBatches = options?.clearBatches ?? true\n\n let totalEntities = 0\n let hasEntities = false\n\n for (const entities of this.fetchEntitiesFromJsonBatches()) {\n hasEntities = true\n totalEntities += entities.length\n\n this.adapter.payload.logger.info(\n `Migrating batch with ${entities.length} entities (total: ${totalEntities})`,\n )\n\n await this.migrateEntities(entities, req)\n }\n\n if (!hasEntities) {\n this.adapter.payload.logger.warn('No entities found in temp folder to migrate')\n return\n }\n\n this.adapter.payload.logger.info(\n `Completed migration of ${totalEntities} entities from temp folder`,\n )\n\n if (clearBatches) {\n this.cleanupTempFolder()\n } else {\n this.adapter.payload.logger.info(\n `Temp folder preserved at ${this.tempFolderPath} (clearBatches: false)`,\n )\n }\n }\n\n setTempFolder(tempFolderPath: string): void {\n this.tempFolderPath = tempFolderPath\n }\n\n async updatePayloadConfigFile(): Promise<void> {\n let configPath: string\n\n try {\n configPath = findConfig()\n } catch {\n this.adapter.payload.logger.info(\n 'updatePayloadConfigFile failed - could not find the payload config. Please set the blocksAsJSON DB adapter property manually to \"true\"',\n )\n return\n }\n\n const configFile = readFileSync(configPath, 'utf-8')\n\n const ts = await dynamicImport<typeof tsTypes>('typescript')\n\n const source = ts.createSourceFile(configPath, configFile, ts.ScriptTarget.ESNext)\n\n let hadChanges = false\n\n const result = ts.transform(source, [\n (ctx) => (sourceFile) => {\n const factory = ctx.factory\n\n const visit: tsTypes.Visitor = (node) => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'db' &&\n ts.isCallExpression(node.initializer) &&\n node.initializer.arguments.length > 0 &&\n ts.isObjectLiteralExpression(node.initializer.arguments[0])\n ) {\n const call = node.initializer\n const obj = node.initializer.arguments[0]\n\n const filteredProps = obj.properties.filter((prop) => {\n if (!ts.isPropertyAssignment(prop)) {\n return true\n }\n\n return !(ts.isIdentifier(prop.name) && prop.name.text === 'blocksAsJSON')\n })\n\n const newProperty = factory.createPropertyAssignment(\n 'blocksAsJSON',\n factory.createTrue(),\n )\n hadChanges = true\n const newObject = factory.updateObjectLiteralExpression(obj, [\n ...filteredProps,\n newProperty,\n ])\n\n const newCall = factory.updateCallExpression(\n call,\n call.expression,\n call.typeArguments,\n [newObject],\n )\n\n return factory.updatePropertyAssignment(node, node.name, newCall)\n }\n\n return ts.visitEachChild(node, visit, ctx)\n }\n\n return ts.visitNode(sourceFile, visit) as tsTypes.SourceFile\n },\n ])\n\n if (!hadChanges) {\n this.adapter.payload.logger.info(\n 'No changes made to payload config. Set blocksAsJSON to true manually.',\n )\n return\n }\n\n const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed })\n writeFileSync(configPath, printer.printFile(result.transformed[0]), 'utf-8')\n await formatGeneratedFile({ filePath: configPath, logger: this.adapter.payload.logger })\n\n this.adapter.payload.logger.info(`Updated ${configPath} with blocksAsJSON: true`)\n }\n}\n\nexport const createBlocksToJsonMigrator = ({\n adapter,\n executeMethod,\n sanitizeStatements,\n}: {\n adapter: DrizzleAdapter\n executeMethod: string\n sanitizeStatements: (args: { sqlExecute: string; statements: string[] }) => string\n}): BlocksToJsonMigrator => {\n return new BlocksToJsonMigratorImpl(adapter, sanitizeStatements, executeMethod)\n}\n\nexport const getBlocksToJsonMigrator = (payload: Payload): BlocksToJsonMigrator => {\n const migrator = (payload.db as DrizzleAdapter).blocksToJsonMigrator\n\n if (!migrator) {\n throw new APIError(`blocksToJsonMigrator is not defined for ${payload.db.packageName}`)\n }\n\n return migrator\n}\n\nexport const buildDynamicPredefinedBlocksToJsonMigration = ({\n packageName,\n}: {\n packageName: string\n}): DynamicMigrationTemplate => {\n return async ({ filePath, payload }) => {\n const migrator = getBlocksToJsonMigrator(payload)\n\n const migrationStatements = await migrator.getMigrationStatements()\n\n migrationStatements.writeDrizzleSnapshot(filePath)\n\n await migrator.updatePayloadConfigFile()\n const upSQL = `\nconst migrator = getBlocksToJsonMigrator(payload)\nmigrator.setTempFolder(TEMP_FOLDER)\nawait migrator.collectAndSaveEntitiesToBatches(req, { batchSize: BATCH_SIZE })\n\n${migrationStatements.statements}\npayload.logger.info(\"Executed blocks to JSON migration statements.\")\n\nawait migrator.migrateEntitiesFromTempFolder(req, { clearBatches: true })\n `\n\n return {\n imports: `\nimport { getBlocksToJsonMigrator } from '${packageName}/migration-utils'\nimport { fileURLToPath } from 'url'\nimport path from 'path'\n\nconst filename = fileURLToPath(import.meta.url)\nconst dirname = path.dirname(filename)\n\n// Configure migration options (optional)\nconst BATCH_SIZE = 100 // Number of entities to process per batch\nconst TEMP_FOLDER = path.resolve(dirname, '${TEMP_FOLDER_NAME}') // Folder path to store migration batch\n`,\n upSQL,\n }\n }\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","rmSync","writeFileSync","path","APIError","buildVersionCollectionFields","buildVersionGlobalFields","dynamicImport","findConfig","fieldShouldBeLocalized","formatGeneratedFile","getTransaction","DEFAULT_BATCH_SIZE","TEMP_FOLDER_NAME","writeEntitiesToTempFile","entities","tempFolderPath","batchIndex","filePath","join","JSON","stringify","acceptDrizzlePrompts","callPrompt","silenceLogs","write","process","stdout","promise","interval","setInterval","stdin","emit","name","ctrl","res","clearInterval","entityHasBlocksField","entity","field","flattenedFields","type","collectBlocksToMigrate","config","data","fields","parentAccessor","parentIsLocalized","result","arrayData","Array","isArray","localization","push","localeCodes","map","code","localized","index","row","entries","fieldAccessor","BlocksToJsonMigratorImpl","batchSize","adapter","sanitizeStatements","executeMethod","resolve","migrationDir","ensureTempFolder","recursive","fetchEntitiesFromJsonBatches","files","filter","file","startsWith","endsWith","sort","a","b","aNum","parseInt","match","bNum","fileContent","batchEntities","parse","migrateEntities","req","blocksAsJSON","resetSchema","init","connect","syncTransactionDrizzleInstance","totalEntities","length","processed","updateOne","collection","slug","originalData","joins","where","id","equals","updateVersion","versionData","updateGlobal","updateGlobalVersion","global","payload","logger","info","Math","round","schema","tables","indexes","Set","foreignKeys","relations","rawTables","rawRelations","tableNameMap","Map","enums","tsx","_","drizzle","session","cleanupTempFolder","force","collectAndSaveEntitiesToBatches","options","totalExpected","collections","totalDocs","count","versions","totalVersions","countVersions","globalConfig","globals","totalGlobalVersions","countGlobalVersions","currentBatch","totalCollected","flushBatch","percentage","addEntity","page","hasMore","docs","hasNextPage","find","limit","doc","blocks","versionPage","hasMoreVersions","versionDocs","hasNextVersionPage","findVersions","versionDoc","globalDoc","findGlobal","globalVersionPage","hasMoreGlobalVersions","globalVersionDocs","hasNextGlobalVersionPage","findGlobalVersions","globalVersionDoc","getMigrationStatements","generateDrizzleJson","generateMigration","requireDrizzleKit","drizzleJsonBefore","drizzleJsonAfter","statements","sqlExecute","writeDrizzleSnapshot","migrateEntitiesFromTempFolder","clearBatches","hasEntities","warn","setTempFolder","updatePayloadConfigFile","configPath","configFile","ts","source","createSourceFile","ScriptTarget","ESNext","hadChanges","transform","ctx","sourceFile","factory","visit","node","isPropertyAssignment","isIdentifier","text","isCallExpression","initializer","arguments","isObjectLiteralExpression","call","obj","filteredProps","properties","prop","newProperty","createPropertyAssignment","createTrue","newObject","updateObjectLiteralExpression","newCall","updateCallExpression","expression","typeArguments","updatePropertyAssignment","visitEachChild","visitNode","printer","createPrinter","newLine","NewLineKind","LineFeed","printFile","transformed","createBlocksToJsonMigrator","getBlocksToJsonMigrator","migrator","db","blocksToJsonMigrator","packageName","buildDynamicPredefinedBlocksToJsonMigration","migrationStatements","upSQL","imports"],"mappings":"AASA,SAASA,UAAU,EAAEC,SAAS,EAAEC,WAAW,EAAEC,YAAY,EAAEC,MAAM,EAAEC,aAAa,QAAQ,KAAI;AAC5F,OAAOC,UAAU,OAAM;AACvB,SACEC,QAAQ,EACRC,4BAA4B,EAC5BC,wBAAwB,EACxBC,aAAa,QACR,UAAS;AAChB,SAASC,UAAU,QAAQ,eAAc;AACzC,SAASC,sBAAsB,QAAQ,iBA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0B,CAAC3H;IACtC,MAAM4H,WAAW,AAAC5H,QAAQ6H,EAAE,CAAoBC,oBAAoB;IAEpE,IAAI,CAACF,UAAU;QACb,MAAM,IAAItO,SAAS,CAAC,wCAAwC,EAAE0G,QAAQ6H,EAAE,CAACE,WAAW,EAAE;IACxF;IAEA,OAAOH;AACT,EAAC;AAED,OAAO,MAAMI,8CAA8C,CAAC,EAC1DD,WAAW,EAGZ;IACC,OAAO,OAAO,EAAE3N,QAAQ,EAAE4F,OAAO,EAAE;QACjC,MAAM4H,WAAWD,wBAAwB3H;QAEzC,MAAMiI,sBAAsB,MAAML,SAAS9D,sBAAsB;QAEjEmE,oBAAoB3D,oBAAoB,CAAClK;QAEzC,MAAMwN,SAAShD,uBAAuB;QACtC,MAAMsD,QAAQ,CAAC;;;;;AAKnB,EAAED,oBAAoB7D,UAAU,CAAC;;;;EAI/B,CAAC;QAEC,OAAO;YACL+D,SAAS,CAAC;yCACyB,EAAEJ,YAAY;;;;;;;;;2CASZ,EAAEhO,iBAAiB;AAC9D,CAAC;YACKmO;QACF;IACF;AACF,EAAC"}
|
|
@@ -10,7 +10,7 @@ export const buildCreateMigration = ({ executeMethod, filename, sanitizeStatemen
|
|
|
10
10
|
if (!fs.existsSync(dir)) {
|
|
11
11
|
fs.mkdirSync(dir);
|
|
12
12
|
}
|
|
13
|
-
const { generateDrizzleJson, generateMigration, upSnapshot } = this.requireDrizzleKit();
|
|
13
|
+
const { generateDrizzleJson, generateMigration, upSnapshot } = await this.requireDrizzleKit();
|
|
14
14
|
const drizzleJsonAfter = await generateDrizzleJson(this.schema);
|
|
15
15
|
const [yyymmdd, hhmmss] = new Date().toISOString().split('T');
|
|
16
16
|
const formattedDate = yyymmdd.replace(/\D/g, '');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/buildCreateMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport prompts from 'prompts'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nexport const buildCreateMigration = ({\n executeMethod,\n filename,\n sanitizeStatements,\n}: {\n executeMethod: string\n filename: string\n sanitizeStatements: (args: { sqlExecute: string; statements: string[] }) => string\n}): CreateMigration => {\n const dirname = path.dirname(filename)\n return async function createMigration(\n this: DrizzleAdapter,\n { file, forceAcceptWarning, migrationName, payload, shouldPrompt = true, skipEmpty },\n ) {\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n\n const { generateDrizzleJson, generateMigration, upSnapshot } = this.requireDrizzleKit()\n\n const drizzleJsonAfter = await generateDrizzleJson(this.schema)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n imports = predefinedMigration.imports\n downSQL = predefinedMigration.downSQL\n upSQL = predefinedMigration.upSQL\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n if (typeof predefinedMigration.dynamic === 'function') {\n const dynamicResult = await predefinedMigration.dynamic({ filePath, payload })\n\n if (dynamicResult.upSQL) {\n upSQL = dynamicResult.upSQL\n }\n\n if (dynamicResult.downSQL) {\n downSQL = dynamicResult.downSQL\n }\n\n if (dynamicResult.imports) {\n imports = dynamicResult.imports\n }\n }\n\n let drizzleJsonBefore = this.defaultDrizzleSnapshot as DrizzleSnapshotJSON\n\n if (this.schemaName) {\n drizzleJsonBefore.schemas = {\n [this.schemaName]: this.schemaName,\n }\n }\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'))\n\n if (upSnapshot && drizzleJsonBefore.version < drizzleJsonAfter.version) {\n drizzleJsonBefore = upSnapshot(drizzleJsonBefore)\n }\n }\n\n payload.logger.info('Starting migration: generating UP statements...')\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n\n payload.logger.info('Migration UP complete. Generating DOWN statements...')\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n\n payload.logger.info('Migration DOWN statements generation complete.')\n\n const sqlExecute = `await db.${executeMethod}(` + 'sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsUp })\n }\n if (sqlStatementsDown?.length) {\n downSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsDown })\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n if (skipEmpty || !shouldPrompt) {\n return { created: false }\n }\n\n const { confirm: shouldCreateBlankMigration } = await prompts({\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n })\n\n if (!shouldCreateBlankMigration) {\n return { created: false }\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n const data = getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n packageName: payload.db.packageName,\n upSQL: upSQL || ` // Migration code`,\n })\n\n const fullPath = `${filePath}.ts`\n\n // write migration\n fs.writeFileSync(fullPath, data)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${fullPath}` })\n\n return { created: true, path: fullPath }\n }\n}\n"],"names":["fs","path","getPredefinedMigration","writeMigrationIndex","prompts","getMigrationTemplate","buildCreateMigration","executeMethod","filename","sanitizeStatements","dirname","createMigration","file","forceAcceptWarning","migrationName","payload","shouldPrompt","skipEmpty","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","upSnapshot","requireDrizzleKit","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","predefinedMigration","timestamp","name","slice","join","fileName","filePath","dynamic","dynamicResult","drizzleJsonBefore","defaultDrizzleSnapshot","schemaName","schemas","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","version","logger","info","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","statements","created","confirm","shouldCreateBlankMigration","type","initial","message","writeFileSync","stringify","data","packageName","fullPath","migrationsDir","msg"],"mappings":"AAGA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,EAAEC,mBAAmB,QAAQ,UAAS;AACrE,OAAOC,aAAa,UAAS;AAI7B,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,aAAa,EACbC,QAAQ,EACRC,kBAAkB,EAKnB;IACC,MAAMC,UAAUT,KAAKS,OAAO,CAACF;IAC7B,OAAO,eAAeG,gBAEpB,EAAEC,IAAI,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,OAAO,EAAEC,eAAe,IAAI,EAAEC,SAAS,EAAE;QAEpF,MAAMC,MAAMH,QAAQI,EAAE,CAACC,YAAY;QACnC,IAAI,CAACpB,GAAGqB,UAAU,CAACH,MAAM;YACvBlB,GAAGsB,SAAS,CAACJ;QACf;QAEA,MAAM,EAAEK,mBAAmB,EAAEC,iBAAiB,EAAEC,UAAU,EAAE,GAAG,IAAI,CAACC,iBAAiB;
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/buildCreateMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport prompts from 'prompts'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nexport const buildCreateMigration = ({\n executeMethod,\n filename,\n sanitizeStatements,\n}: {\n executeMethod: string\n filename: string\n sanitizeStatements: (args: { sqlExecute: string; statements: string[] }) => string\n}): CreateMigration => {\n const dirname = path.dirname(filename)\n return async function createMigration(\n this: DrizzleAdapter,\n { file, forceAcceptWarning, migrationName, payload, shouldPrompt = true, skipEmpty },\n ) {\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n\n const { generateDrizzleJson, generateMigration, upSnapshot } = await this.requireDrizzleKit()\n\n const drizzleJsonAfter = await generateDrizzleJson(this.schema)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n imports = predefinedMigration.imports\n downSQL = predefinedMigration.downSQL\n upSQL = predefinedMigration.upSQL\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n if (typeof predefinedMigration.dynamic === 'function') {\n const dynamicResult = await predefinedMigration.dynamic({ filePath, payload })\n\n if (dynamicResult.upSQL) {\n upSQL = dynamicResult.upSQL\n }\n\n if (dynamicResult.downSQL) {\n downSQL = dynamicResult.downSQL\n }\n\n if (dynamicResult.imports) {\n imports = dynamicResult.imports\n }\n }\n\n let drizzleJsonBefore = this.defaultDrizzleSnapshot as DrizzleSnapshotJSON\n\n if (this.schemaName) {\n drizzleJsonBefore.schemas = {\n [this.schemaName]: this.schemaName,\n }\n }\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'))\n\n if (upSnapshot && drizzleJsonBefore.version < drizzleJsonAfter.version) {\n drizzleJsonBefore = upSnapshot(drizzleJsonBefore)\n }\n }\n\n payload.logger.info('Starting migration: generating UP statements...')\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n\n payload.logger.info('Migration UP complete. Generating DOWN statements...')\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n\n payload.logger.info('Migration DOWN statements generation complete.')\n\n const sqlExecute = `await db.${executeMethod}(` + 'sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsUp })\n }\n if (sqlStatementsDown?.length) {\n downSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsDown })\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n if (skipEmpty || !shouldPrompt) {\n return { created: false }\n }\n\n const { confirm: shouldCreateBlankMigration } = await prompts({\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n })\n\n if (!shouldCreateBlankMigration) {\n return { created: false }\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n const data = getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n packageName: payload.db.packageName,\n upSQL: upSQL || ` // Migration code`,\n })\n\n const fullPath = `${filePath}.ts`\n\n // write migration\n fs.writeFileSync(fullPath, data)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${fullPath}` })\n\n return { created: true, path: fullPath }\n }\n}\n"],"names":["fs","path","getPredefinedMigration","writeMigrationIndex","prompts","getMigrationTemplate","buildCreateMigration","executeMethod","filename","sanitizeStatements","dirname","createMigration","file","forceAcceptWarning","migrationName","payload","shouldPrompt","skipEmpty","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","upSnapshot","requireDrizzleKit","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","predefinedMigration","timestamp","name","slice","join","fileName","filePath","dynamic","dynamicResult","drizzleJsonBefore","defaultDrizzleSnapshot","schemaName","schemas","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","version","logger","info","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","statements","created","confirm","shouldCreateBlankMigration","type","initial","message","writeFileSync","stringify","data","packageName","fullPath","migrationsDir","msg"],"mappings":"AAGA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,EAAEC,mBAAmB,QAAQ,UAAS;AACrE,OAAOC,aAAa,UAAS;AAI7B,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,aAAa,EACbC,QAAQ,EACRC,kBAAkB,EAKnB;IACC,MAAMC,UAAUT,KAAKS,OAAO,CAACF;IAC7B,OAAO,eAAeG,gBAEpB,EAAEC,IAAI,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,OAAO,EAAEC,eAAe,IAAI,EAAEC,SAAS,EAAE;QAEpF,MAAMC,MAAMH,QAAQI,EAAE,CAACC,YAAY;QACnC,IAAI,CAACpB,GAAGqB,UAAU,CAACH,MAAM;YACvBlB,GAAGsB,SAAS,CAACJ;QACf;QAEA,M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AE,GAAG,MAAMpE,QAAQ;oBAC5DsC,MAAM;oBACN+B,MAAM;oBACNC,SAAS;oBACTC,SAAS;gBACX;gBAEA,IAAI,CAACH,4BAA4B;oBAC/B,OAAO;wBAAEF,SAAS;oBAAM;gBAC1B;YACF;YAEA,eAAe;YACftE,GAAG4E,aAAa,CAAC,GAAG9B,SAAS,KAAK,CAAC,EAAEa,KAAKkB,SAAS,CAAClD,kBAAkB,MAAM;QAC9E;QAEA,MAAMmD,OAAOzE,qBAAqB;YAChCiC,SAASA,WAAW,CAAC,mBAAmB,CAAC;YACzCD;YACA0C,aAAahE,QAAQI,EAAE,CAAC4D,WAAW;YACnCxC,OAAOA,SAAS,CAAC,mBAAmB,CAAC;QACvC;QAEA,MAAMyC,WAAW,GAAGlC,SAAS,GAAG,CAAC;QAEjC,kBAAkB;QAClB9C,GAAG4E,aAAa,CAACI,UAAUF;QAE3B3E,oBAAoB;YAAE8E,eAAelE,QAAQI,EAAE,CAACC,YAAY;QAAC;QAE7DL,QAAQgD,MAAM,CAACC,IAAI,CAAC;YAAEkB,KAAK,CAAC,qBAAqB,EAAEF,UAAU;QAAC;QAE9D,OAAO;YAAEV,SAAS;YAAMrE,MAAM+E;QAAS;IACzC;AACF,EAAC"}
|
|
@@ -39,7 +39,7 @@ import { findSizesToVariantsFieldCollision, getSizesToVariantsRenames } from './
|
|
|
39
39
|
if (!latestSnapshotFile) {
|
|
40
40
|
return undefined;
|
|
41
41
|
}
|
|
42
|
-
const { generateDrizzleJson, upSnapshot } = adapter.requireDrizzleKit();
|
|
42
|
+
const { generateDrizzleJson, upSnapshot } = await adapter.requireDrizzleKit();
|
|
43
43
|
const currentVersion = (await generateDrizzleJson(adapter.schema)).version;
|
|
44
44
|
const snapshot = JSON.parse(readFileSync(`${dir}/${latestSnapshotFile}`, 'utf8'));
|
|
45
45
|
return upSnapshot && snapshot.version < currentVersion ? upSnapshot(snapshot) : snapshot;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/buildDynamicPredefinedSizesToVariantsMigration.ts"],"sourcesContent":["import type { DynamicMigrationTemplate } from 'payload'\n\nimport { randomUUID } from 'crypto'\nimport { readdirSync, readFileSync, writeFileSync } from 'fs'\n\nimport type { DrizzleAdapter } from '../types.js'\nimport type { SizesToVariantsTableRenames } from './getSizesToVariantsRenames.js'\n\nimport {\n findSizesToVariantsFieldCollision,\n getSizesToVariantsRenames,\n} from './getSizesToVariantsRenames.js'\n\ntype SnapshotIndex = {\n columns: ({ expression: string } | string)[]\n name: string\n}\n\ntype SnapshotTable = {\n columns: Record<string, { name: string }>\n indexes?: Record<string, SnapshotIndex>\n name: string\n}\n\ntype Snapshot = {\n id?: string\n prevId?: string\n tables: Record<string, SnapshotTable>\n version: string\n}\n\n/**\n * Builds the `sizes-to-variants` predefined migration for a SQL adapter. The migration renames\n * columns rather than letting drizzle-kit diff the schema (which would drop and re-add them,\n * losing every stored image size).\n *\n * It also writes a schema snapshot: the project's previous snapshot with only these renames\n * applied. The next generated migration then diffs from the renamed columns instead of dropping\n * them, and still picks up every other schema change the upgrade brings. Without a previous\n * snapshot (a project that has only ever used `push`) there's nothing to update, so none is written.\n */\nexport const buildDynamicPredefinedSizesToVariantsMigration = ({\n packageName,\n}: {\n packageName: string\n}): DynamicMigrationTemplate => {\n return async ({ filePath, payload }) => {\n const adapter = payload.db as unknown as DrizzleAdapter\n const previousSnapshot = await readLatestSnapshot({ adapter })\n\n if (previousSnapshot) {\n const renamedSnapshot = applySizesToVariantsRenames({\n plan: getSizesToVariantsRenames({ adapter, direction: 'up' }),\n snapshot: previousSnapshot,\n })\n\n writeFileSync(`${filePath}.json`, JSON.stringify(renamedSnapshot, null, 2))\n }\n\n return {\n downSQL: ` await migrateSizesToVariants({ db, direction: 'down', payload })`,\n imports: `import { migrateSizesToVariants } from '${packageName}/migration-utils'`,\n upSQL: ` await migrateSizesToVariants({ db, payload })`,\n }\n }\n}\n\n/** The latest snapshot in the migrations directory, upgraded to drizzle-kit's current format. */\nasync function readLatestSnapshot({\n adapter,\n}: {\n adapter: DrizzleAdapter\n}): Promise<Snapshot | undefined> {\n const dir = adapter.migrationDir\n const latestSnapshotFile = readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()[0]\n\n if (!latestSnapshotFile) {\n return undefined\n }\n\n const { generateDrizzleJson, upSnapshot } = adapter.requireDrizzleKit()\n const currentVersion = (await generateDrizzleJson(adapter.schema)).version\n const snapshot = JSON.parse(readFileSync(`${dir}/${latestSnapshotFile}`, 'utf8')) as Snapshot\n\n return upSnapshot && snapshot.version < currentVersion ? upSnapshot(snapshot) : snapshot\n}\n\nfunction applySizesToVariantsRenames({\n plan,\n snapshot,\n}: {\n plan: SizesToVariantsTableRenames[]\n snapshot: Snapshot\n}): Snapshot {\n const renamed: Snapshot = structuredClone(snapshot)\n\n for (const { columns, indexes, tableName } of plan) {\n const table = Object.values(renamed.tables).find(({ name }) => name === tableName)\n\n if (!table) {\n continue\n }\n\n const existingColumns = new Set(Object.values(table.columns).map(({ name }) => name))\n\n for (const { from, to } of columns) {\n if (existingColumns.has(from) && existingColumns.has(to)) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before creating this migration.`,\n )\n }\n }\n\n const fieldCollision = findSizesToVariantsFieldCollision({ columns, existingColumns })\n\n if (fieldCollision) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both the \"${fieldCollision.from}\" and \"${fieldCollision.to}\" fields. Move or rename the existing destination data before creating this migration.`,\n )\n }\n\n for (const { from, to } of columns) {\n const column = table.columns[from]\n\n if (column) {\n if (table.columns[to]) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before creating this migration.`,\n )\n }\n\n delete table.columns[from]\n table.columns[to] = { ...column, name: to }\n }\n }\n\n for (const [key, index] of Object.entries(table.indexes ?? {})) {\n const indexColumns = index.columns.map((column) => {\n const name = typeof column === 'string' ? column : column.expression\n const renamedName = columns.find(({ from }) => from === name)?.to ?? name\n\n return typeof column === 'string' ? renamedName : { ...column, expression: renamedName }\n })\n const indexColumnNames = indexColumns.map((column) =>\n typeof column === 'string' ? column : column.expression,\n )\n const target = indexes.find(\n (planned) => planned.columns.join(',') === indexColumnNames.join(','),\n )\n\n if (!target) {\n continue\n }\n\n if (key !== target.to && table.indexes?.[target.to]) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both indexes \"${key}\" and \"${target.to}\". Move or rename the existing destination index before creating this migration.`,\n )\n }\n\n delete table.indexes[key]\n table.indexes[target.to] = { ...index, name: target.to, columns: indexColumns }\n }\n }\n\n renamed.prevId = snapshot.id\n renamed.id = randomUUID()\n\n return renamed\n}\n"],"names":["randomUUID","readdirSync","readFileSync","writeFileSync","findSizesToVariantsFieldCollision","getSizesToVariantsRenames","buildDynamicPredefinedSizesToVariantsMigration","packageName","filePath","payload","adapter","db","previousSnapshot","readLatestSnapshot","renamedSnapshot","applySizesToVariantsRenames","plan","direction","snapshot","JSON","stringify","downSQL","imports","upSQL","dir","migrationDir","latestSnapshotFile","filter","file","endsWith","sort","reverse","undefined","generateDrizzleJson","upSnapshot","requireDrizzleKit","currentVersion","schema","version","parse","renamed","structuredClone","columns","indexes","tableName","table","Object","values","tables","find","name","existingColumns","Set","map","from","to","has","Error","fieldCollision","column","key","index","entries","indexColumns","expression","renamedName","indexColumnNames","target","planned","join","prevId","id"],"mappings":"AAEA,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AAK7D,SACEC,iCAAiC,EACjCC,yBAAyB,QACpB,iCAAgC;AAoBvC;;;;;;;;;CASC,GACD,OAAO,MAAMC,iDAAiD,CAAC,EAC7DC,WAAW,EAGZ;IACC,OAAO,OAAO,EAAEC,QAAQ,EA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F,OAAO,IAAI,CAAC,GAAI;YAC9D,MAAMoB,eAAeF,MAAMnB,OAAO,CAACW,GAAG,CAAC,CAACM;gBACtC,MAAMT,OAAO,OAAOS,WAAW,WAAWA,SAASA,OAAOK,UAAU;gBACpE,MAAMC,cAAcvB,QAAQO,IAAI,CAAC,CAAC,EAAEK,IAAI,EAAE,GAAKA,SAASJ,OAAOK,MAAML;gBAErE,OAAO,OAAOS,WAAW,WAAWM,cAAc;oBAAE,GAAGN,MAAM;oBAAEK,YAAYC;gBAAY;YACzF;YACA,MAAMC,mBAAmBH,aAAaV,GAAG,CAAC,CAACM,SACzC,OAAOA,WAAW,WAAWA,SAASA,OAAOK,UAAU;YAEzD,MAAMG,SAASxB,QAAQM,IAAI,CACzB,CAACmB,UAAYA,QAAQ1B,OAAO,CAAC2B,IAAI,CAAC,SAASH,iBAAiBG,IAAI,CAAC;YAGnE,IAAI,CAACF,QAAQ;gBACX;YACF;YAEA,IAAIP,QAAQO,OAAOZ,EAAE,IAAIV,MAAMF,OAAO,EAAE,CAACwB,OAAOZ,EAAE,CAAC,EAAE;gBACnD,MAAM,IAAIE,MACR,CAAC,sEAAsE,EAAEb,UAAU,yBAAyB,EAAEgB,IAAI,OAAO,EAAEO,OAAOZ,EAAE,CAAC,gFAAgF,CAAC;YAE1N;YAEA,OAAOV,MAAMF,OAAO,CAACiB,IAAI;YACzBf,MAAMF,OAAO,CAACwB,OAAOZ,EAAE,CAAC,GAAG;gBAAE,GAAGM,KAAK;gBAAEX,MAAMiB,OAAOZ,EAAE;gBAAEb,SAASqB;YAAa;QAChF;IACF;IAEAvB,QAAQ8B,MAAM,GAAGpD,SAASqD,EAAE;IAC5B/B,QAAQ+B,EAAE,GAAGvE;IAEb,OAAOwC;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/buildDynamicPredefinedSizesToVariantsMigration.ts"],"sourcesContent":["import type { DynamicMigrationTemplate } from 'payload'\n\nimport { randomUUID } from 'crypto'\nimport { readdirSync, readFileSync, writeFileSync } from 'fs'\n\nimport type { DrizzleAdapter } from '../types.js'\nimport type { SizesToVariantsTableRenames } from './getSizesToVariantsRenames.js'\n\nimport {\n findSizesToVariantsFieldCollision,\n getSizesToVariantsRenames,\n} from './getSizesToVariantsRenames.js'\n\ntype SnapshotIndex = {\n columns: ({ expression: string } | string)[]\n name: string\n}\n\ntype SnapshotTable = {\n columns: Record<string, { name: string }>\n indexes?: Record<string, SnapshotIndex>\n name: string\n}\n\ntype Snapshot = {\n id?: string\n prevId?: string\n tables: Record<string, SnapshotTable>\n version: string\n}\n\n/**\n * Builds the `sizes-to-variants` predefined migration for a SQL adapter. The migration renames\n * columns rather than letting drizzle-kit diff the schema (which would drop and re-add them,\n * losing every stored image size).\n *\n * It also writes a schema snapshot: the project's previous snapshot with only these renames\n * applied. The next generated migration then diffs from the renamed columns instead of dropping\n * them, and still picks up every other schema change the upgrade brings. Without a previous\n * snapshot (a project that has only ever used `push`) there's nothing to update, so none is written.\n */\nexport const buildDynamicPredefinedSizesToVariantsMigration = ({\n packageName,\n}: {\n packageName: string\n}): DynamicMigrationTemplate => {\n return async ({ filePath, payload }) => {\n const adapter = payload.db as unknown as DrizzleAdapter\n const previousSnapshot = await readLatestSnapshot({ adapter })\n\n if (previousSnapshot) {\n const renamedSnapshot = applySizesToVariantsRenames({\n plan: getSizesToVariantsRenames({ adapter, direction: 'up' }),\n snapshot: previousSnapshot,\n })\n\n writeFileSync(`${filePath}.json`, JSON.stringify(renamedSnapshot, null, 2))\n }\n\n return {\n downSQL: ` await migrateSizesToVariants({ db, direction: 'down', payload })`,\n imports: `import { migrateSizesToVariants } from '${packageName}/migration-utils'`,\n upSQL: ` await migrateSizesToVariants({ db, payload })`,\n }\n }\n}\n\n/** The latest snapshot in the migrations directory, upgraded to drizzle-kit's current format. */\nasync function readLatestSnapshot({\n adapter,\n}: {\n adapter: DrizzleAdapter\n}): Promise<Snapshot | undefined> {\n const dir = adapter.migrationDir\n const latestSnapshotFile = readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()[0]\n\n if (!latestSnapshotFile) {\n return undefined\n }\n\n const { generateDrizzleJson, upSnapshot } = await adapter.requireDrizzleKit()\n const currentVersion = (await generateDrizzleJson(adapter.schema)).version\n const snapshot = JSON.parse(readFileSync(`${dir}/${latestSnapshotFile}`, 'utf8')) as Snapshot\n\n return upSnapshot && snapshot.version < currentVersion ? upSnapshot(snapshot) : snapshot\n}\n\nfunction applySizesToVariantsRenames({\n plan,\n snapshot,\n}: {\n plan: SizesToVariantsTableRenames[]\n snapshot: Snapshot\n}): Snapshot {\n const renamed: Snapshot = structuredClone(snapshot)\n\n for (const { columns, indexes, tableName } of plan) {\n const table = Object.values(renamed.tables).find(({ name }) => name === tableName)\n\n if (!table) {\n continue\n }\n\n const existingColumns = new Set(Object.values(table.columns).map(({ name }) => name))\n\n for (const { from, to } of columns) {\n if (existingColumns.has(from) && existingColumns.has(to)) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before creating this migration.`,\n )\n }\n }\n\n const fieldCollision = findSizesToVariantsFieldCollision({ columns, existingColumns })\n\n if (fieldCollision) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both the \"${fieldCollision.from}\" and \"${fieldCollision.to}\" fields. Move or rename the existing destination data before creating this migration.`,\n )\n }\n\n for (const { from, to } of columns) {\n const column = table.columns[from]\n\n if (column) {\n if (table.columns[to]) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before creating this migration.`,\n )\n }\n\n delete table.columns[from]\n table.columns[to] = { ...column, name: to }\n }\n }\n\n for (const [key, index] of Object.entries(table.indexes ?? {})) {\n const indexColumns = index.columns.map((column) => {\n const name = typeof column === 'string' ? column : column.expression\n const renamedName = columns.find(({ from }) => from === name)?.to ?? name\n\n return typeof column === 'string' ? renamedName : { ...column, expression: renamedName }\n })\n const indexColumnNames = indexColumns.map((column) =>\n typeof column === 'string' ? column : column.expression,\n )\n const target = indexes.find(\n (planned) => planned.columns.join(',') === indexColumnNames.join(','),\n )\n\n if (!target) {\n continue\n }\n\n if (key !== target.to && table.indexes?.[target.to]) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both indexes \"${key}\" and \"${target.to}\". Move or rename the existing destination index before creating this migration.`,\n )\n }\n\n delete table.indexes[key]\n table.indexes[target.to] = { ...index, name: target.to, columns: indexColumns }\n }\n }\n\n renamed.prevId = snapshot.id\n renamed.id = randomUUID()\n\n return renamed\n}\n"],"names":["randomUUID","readdirSync","readFileSync","writeFileSync","findSizesToVariantsFieldCollision","getSizesToVariantsRenames","buildDynamicPredefinedSizesToVariantsMigration","packageName","filePath","payload","adapter","db","previousSnapshot","readLatestSnapshot","renamedSnapshot","applySizesToVariantsRenames","plan","direction","snapshot","JSON","stringify","downSQL","imports","upSQL","dir","migrationDir","latestSnapshotFile","filter","file","endsWith","sort","reverse","undefined","generateDrizzleJson","upSnapshot","requireDrizzleKit","currentVersion","schema","version","parse","renamed","structuredClone","columns","indexes","tableName","table","Object","values","tables","find","name","existingColumns","Set","map","from","to","has","Error","fieldCollision","column","key","index","entries","indexColumns","expression","renamedName","indexColumnNames","target","planned","join","prevId","id"],"mappings":"AAEA,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AAK7D,SACEC,iCAAiC,EACjCC,yBAAyB,QACpB,iCAAgC;AAoBvC;;;;;;;;;CASC,GACD,OAAO,MAAMC,iDAAiD,CAAC,EAC7DC,WAAW,EAGZ;IACC,OAAO,OAAO,EAAEC,QAAQ,EAAEC,OAAO,EAAE;QACjC,MAAMC,UAAUD,QAAQE,EAAE;QAC1B,MAAMC,mBAAmB,MAAMC,mBAAmB;YAAEH;QAAQ;QAE5D,IAAIE,kBAAk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AAW,WAAWA,SAASA,OAAOK,UAAU;gBACpE,MAAMC,cAAcvB,QAAQO,IAAI,CAAC,CAAC,EAAEK,IAAI,EAAE,GAAKA,SAASJ,OAAOK,MAAML;gBAErE,OAAO,OAAOS,WAAW,WAAWM,cAAc;oBAAE,GAAGN,MAAM;oBAAEK,YAAYC;gBAAY;YACzF;YACA,MAAMC,mBAAmBH,aAAaV,GAAG,CAAC,CAACM,SACzC,OAAOA,WAAW,WAAWA,SAASA,OAAOK,UAAU;YAEzD,MAAMG,SAASxB,QAAQM,IAAI,CACzB,CAACmB,UAAYA,QAAQ1B,OAAO,CAAC2B,IAAI,CAAC,SAASH,iBAAiBG,IAAI,CAAC;YAGnE,IAAI,CAACF,QAAQ;gBACX;YACF;YAEA,IAAIP,QAAQO,OAAOZ,EAAE,IAAIV,MAAMF,OAAO,EAAE,CAACwB,OAAOZ,EAAE,CAAC,EAAE;gBACnD,MAAM,IAAIE,MACR,CAAC,sEAAsE,EAAEb,UAAU,yBAAyB,EAAEgB,IAAI,OAAO,EAAEO,OAAOZ,EAAE,CAAC,gFAAgF,CAAC;YAE1N;YAEA,OAAOV,MAAMF,OAAO,CAACiB,IAAI;YACzBf,MAAMF,OAAO,CAACwB,OAAOZ,EAAE,CAAC,GAAG;gBAAE,GAAGM,KAAK;gBAAEX,MAAMiB,OAAOZ,EAAE;gBAAEb,SAASqB;YAAa;QAChF;IACF;IAEAvB,QAAQ8B,MAAM,GAAGpD,SAASqD,EAAE;IAC5B/B,QAAQ+B,EAAE,GAAGvE;IAEb,OAAOwC;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAoCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,cA4SH,CAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync } from 'fs';
|
|
2
2
|
import { writeFile } from 'fs/promises';
|
|
3
3
|
import path from 'path';
|
|
4
|
+
import { formatGeneratedFile } from './formatGeneratedFile.js';
|
|
4
5
|
/**
|
|
5
6
|
* @example
|
|
6
7
|
* console.log(sanitizeObjectKey("oneTwo")); // oneTwo
|
|
@@ -215,7 +216,7 @@ declare module '${this.packageName}' {
|
|
|
215
216
|
*/
|
|
216
217
|
`;
|
|
217
218
|
const importTypes = `import type {} from '${this.packageName}'`;
|
|
218
|
-
|
|
219
|
+
const code = [
|
|
219
220
|
warning,
|
|
220
221
|
importTypes,
|
|
221
222
|
...importDeclarationsSanitized,
|
|
@@ -235,19 +236,13 @@ declare module '${this.packageName}' {
|
|
|
235
236
|
outputFile = path.resolve(cwd, 'payload-generated-schema.ts');
|
|
236
237
|
}
|
|
237
238
|
}
|
|
239
|
+
await writeFile(outputFile, code, 'utf-8');
|
|
238
240
|
if (prettify) {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
code = await prettier.format(code, {
|
|
244
|
-
...config,
|
|
245
|
-
parser: 'typescript'
|
|
246
|
-
});
|
|
247
|
-
} catch {
|
|
248
|
-
/* empty */ }
|
|
241
|
+
await formatGeneratedFile({
|
|
242
|
+
filePath: outputFile,
|
|
243
|
+
logger: this.payload.logger
|
|
244
|
+
});
|
|
249
245
|
}
|
|
250
|
-
await writeFile(outputFile, code, 'utf-8');
|
|
251
246
|
if (log) {
|
|
252
247
|
this.payload.logger.info(`Written ${outputFile}`);
|
|
253
248
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n }\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n\n return { outputFile }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAAC,CAAC;IACnC;IAEA,OAAO,GAAGD,QAAQ,CAAC,EAAEJ,KAAK;AAC5B;AAEA,OAAO,MAAMO,wBAAwB,CAAC,EACpCC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,EACZC,WAAW,EAQZ;IACC,OAAO,eAAeC,eAEpB,EAAEC,MAAM,IAAI,EAAEC,aAAaN,iBAAiB,EAAEO,WAAW,IAAI,EAAE,GAAG,CAAC,CAAC;QAEpE,MAAMC,qBAAkD,CAAC;QAEzD,MAAMC,oBAA8B,EAAE;QACtC,MAAMC,mBAA6B,EAAE;QACrC,MAAMC,wBAAkC,EAAE;QAE1C,MAAMC,YAAY,CAACC,MAAcC;YAC/B,IAAI,CAACN,kBAAkB,CAACK,KAAK,EAAE;gBAC7BL,kBAAkB,CAACK,KAAK,GAAG,IAAIE;YACjC;YAEAP,kBAAkB,CAACK,KAAK,CAACG,GAAG,CAACF;QAC/B;QAEA,MAAMG,cAAc,GAAG,IAAI,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,MAAM;oBAAE,GAAGnE,MAAM;oBAAE8E,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAM3H,UAAUmB,YAAY6F,MAAM;QAElC,IAAI9F,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACgF,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE1G,YAAY;QAClD;QAEA,OAAO;YAAEA;QAAW;IACtB;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\nimport { formatGeneratedFile } from './formatGeneratedFile.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n }\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n const code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (prettify) {\n await formatGeneratedFile({ filePath: outputFile, logger: this.payload.logger })\n }\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n\n return { outputFile }\n }\n}\n"],"names":["existsSync","writeFile","path","formatGeneratedFile","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","filePath","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAAC,CAAC;IACnC;IAEA,OAAO,GAAGD,QAAQ,CAAC,EAAEJ,KAAK;AAC5B;AAEA,OAAO,MAAMO,wBAAwB,CAAC,EACpCC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,EACZC,WAAW,EAQZ;IACC,OAAO,eAAeC,eAEpB,EAAEC,MAAM,IAAI,EAAEC,aAAaN,iBAAiB,EAAEO,WAAW,IAAI,EAAE,GAAG,CAAC,CAAC;QAEpE,MAAMC,qBAAkD,CAAC;QAEzD,MAAMC,oBAA8B,EAAE;QACtC,MAAMC,mBAA6B,EAAE;QACrC,MAAMC,wBAAkC,EAAE;QAE1C,MAAMC,YAAY,CAACC,MAAcC;YAC/B,IAAI,CAACN,kBAAkB,CAACK,KAAK,EAAE;gBAC7BL,kBAAkB,CAACK,KAAK,GAAG,IAAIE;YACjC;YAEAP,kBAAkB,CAACK,KAAK,CAACG,GAAG,CAACF;QAC/B;QAEA,MAAMG,cAAc,GAAG,IAAI,CAACC,WAAW,CAAC,SAA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C,CAAC,QAAQ,EAAEpG,YAAY;QAClD;QAEA,OAAO;YAAEA;QAAW;IACtB;AACF,EAAC"}
|
|
@@ -2,7 +2,7 @@ import { extendDrizzleTable } from './extendDrizzleTable.js';
|
|
|
2
2
|
export const executeSchemaHooks = async ({ type, adapter })=>{
|
|
3
3
|
for (const hook of adapter[type]){
|
|
4
4
|
const result = await hook({
|
|
5
|
-
adapter
|
|
5
|
+
adapter,
|
|
6
6
|
extendTable: extendDrizzleTable,
|
|
7
7
|
schema: {
|
|
8
8
|
enums: adapter.enums,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/executeSchemaHooks.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { extendDrizzleTable } from './extendDrizzleTable.js'\n\ntype DatabaseSchema = {\n enums?: DrizzleAdapter['enums']\n relations: Record<string, any>\n tables: DrizzleAdapter['tables']\n}\n\ntype Adapter = {\n afterSchemaInit: DatabaseSchemaHook[]\n beforeSchemaInit: DatabaseSchemaHook[]\n} & DatabaseSchema\n\ntype DatabaseSchemaHookArgs = {\n adapter: Record<string, unknown>\n extendTable: typeof extendDrizzleTable\n schema: DatabaseSchema\n}\n\ntype DatabaseSchemaHook = (args: DatabaseSchemaHookArgs) => DatabaseSchema | Promise<DatabaseSchema>\n\ntype Args = {\n adapter: Adapter\n type: 'afterSchemaInit' | 'beforeSchemaInit'\n}\n\nexport const executeSchemaHooks = async ({ type, adapter }: Args): Promise<void> => {\n for (const hook of
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/executeSchemaHooks.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { extendDrizzleTable } from './extendDrizzleTable.js'\n\ntype DatabaseSchema = {\n enums?: DrizzleAdapter['enums']\n relations: Record<string, any>\n tables: DrizzleAdapter['tables']\n}\n\ntype Adapter = {\n afterSchemaInit: DatabaseSchemaHook[]\n beforeSchemaInit: DatabaseSchemaHook[]\n} & DatabaseSchema\n\ntype DatabaseSchemaHookArgs = {\n adapter: Record<string, unknown>\n extendTable: typeof extendDrizzleTable\n schema: DatabaseSchema\n}\n\ntype DatabaseSchemaHook = (args: DatabaseSchemaHookArgs) => DatabaseSchema | Promise<DatabaseSchema>\n\ntype Args = {\n adapter: Adapter\n type: 'afterSchemaInit' | 'beforeSchemaInit'\n}\n\nexport const executeSchemaHooks = async ({ type, adapter }: Args): Promise<void> => {\n for (const hook of adapter[type]) {\n const result = await hook({\n adapter,\n extendTable: extendDrizzleTable,\n schema: {\n enums: adapter.enums,\n relations: adapter.relations,\n tables: adapter.tables,\n },\n })\n if (result.enums) {\n adapter.enums = result.enums\n }\n\n adapter.tables = result.tables\n adapter.relations = result.relations\n }\n}\n"],"names":["extendDrizzleTable","executeSchemaHooks","type","adapter","hook","result","extendTable","schema","enums","relations","tables"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,0BAAyB;AA0B5D,OAAO,MAAMC,qBAAqB,OAAO,EAAEC,IAAI,EAAEC,OAAO,EAAQ;IAC9D,KAAK,MAAMC,QAAQD,OAAO,CAACD,KAAK,CAAE;QAChC,MAAMG,SAAS,MAAMD,KAAK;YACxBD;YACAG,aAAaN;YACbO,QAAQ;gBACNC,OAAOL,QAAQK,KAAK;gBACpBC,WAAWN,QAAQM,SAAS;gBAC5BC,QAAQP,QAAQO,MAAM;YACxB;QACF;QACA,IAAIL,OAAOG,KAAK,EAAE;YAChBL,QAAQK,KAAK,GAAGH,OAAOG,KAAK;QAC9B;QAEAL,QAAQO,MAAM,GAAGL,OAAOK,MAAM;QAC9BP,QAAQM,SAAS,GAAGJ,OAAOI,SAAS;IACtC;AACF,EAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Formats a generated file in place with the project's formatter and formatter config: oxfmt if
|
|
4
|
+
* it's installed, otherwise Prettier. Logs an error if neither can format the file.
|
|
5
|
+
*/
|
|
6
|
+
export declare function formatGeneratedFile({ filePath, logger, }: {
|
|
7
|
+
filePath: string;
|
|
8
|
+
logger: Payload['logger'];
|
|
9
|
+
}): Promise<void>;
|
|
10
|
+
//# sourceMappingURL=formatGeneratedFile.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formatGeneratedFile.d.ts","sourceRoot":"","sources":["../../src/utilities/formatGeneratedFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAoBtC;;;GAGG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,QAAQ,EACR,MAAM,GACP,EAAE;IACD,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAA;CAC1B,GAAG,OAAO,CAAC,IAAI,CAAC,CAwChB"}
|