@payloadcms/db-mongodb 3.84.0 → 4.0.0-internal.38b7f1d
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/createMigration.d.ts.map +1 -1
- package/dist/createMigration.js +44 -5
- package/dist/createMigration.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/migrateFieldDelocalized.d.ts +10 -0
- package/dist/migrateFieldDelocalized.d.ts.map +1 -0
- package/dist/migrateFieldDelocalized.js +40 -0
- package/dist/migrateFieldDelocalized.js.map +1 -0
- package/dist/migrateFieldLocalized.d.ts +10 -0
- package/dist/migrateFieldLocalized.d.ts.map +1 -0
- package/dist/migrateFieldLocalized.js +43 -0
- package/dist/migrateFieldLocalized.js.map +1 -0
- package/dist/migrateVersionsEnabled.d.ts +9 -0
- package/dist/migrateVersionsEnabled.d.ts.map +1 -0
- package/dist/migrateVersionsEnabled.js +52 -0
- package/dist/migrateVersionsEnabled.js.map +1 -0
- package/dist/queries/buildSearchParams.js +2 -1
- package/dist/queries/buildSearchParams.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAyB,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAyB,MAAM,SAAS,CAAA;AA8BrE,eAAO,MAAM,eAAe,EAAE,eA8E7B,CAAA"}
|
package/dist/createMigration.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
|
-
import { getPredefinedMigration, writeMigrationIndex } from 'payload';
|
|
3
|
+
import { bootstrapConfigState, diffConfig, generateDataMigrationCode, getPredefinedMigration, readConfigState, resolvePrompts, serializeConfig, writeMigrationIndex } from 'payload';
|
|
4
4
|
import { fileURLToPath } from 'url';
|
|
5
5
|
const migrationTemplate = ({ downSQL, imports, upSQL })=>`import {
|
|
6
6
|
MigrateDownArgs,
|
|
@@ -28,7 +28,48 @@ export const createMigration = async function createMigration({ file, migrationN
|
|
|
28
28
|
migrationName,
|
|
29
29
|
payload
|
|
30
30
|
});
|
|
31
|
-
|
|
31
|
+
// Config-diff: compute data migrations to append
|
|
32
|
+
const prevSnapshot = await readConfigState(dir);
|
|
33
|
+
const nextSnapshot = serializeConfig(payload.config);
|
|
34
|
+
let dataUpCode = '';
|
|
35
|
+
let dataDownCode = '';
|
|
36
|
+
if (prevSnapshot !== null) {
|
|
37
|
+
const changes = diffConfig(prevSnapshot, nextSnapshot);
|
|
38
|
+
if (changes.length > 0) {
|
|
39
|
+
const { shouldAbort } = await resolvePrompts(changes);
|
|
40
|
+
if (shouldAbort) {
|
|
41
|
+
process.exit(1);
|
|
42
|
+
}
|
|
43
|
+
const localization = payload.config.localization || null;
|
|
44
|
+
const { downCode, upCode } = generateDataMigrationCode(changes, {
|
|
45
|
+
defaultLocale: localization?.defaultLocale
|
|
46
|
+
});
|
|
47
|
+
dataUpCode = upCode;
|
|
48
|
+
dataDownCode = downCode;
|
|
49
|
+
}
|
|
50
|
+
} else {
|
|
51
|
+
await bootstrapConfigState(payload, dir);
|
|
52
|
+
}
|
|
53
|
+
const hasContent = predefinedMigration.upSQL || predefinedMigration.downSQL || dataUpCode;
|
|
54
|
+
if (skipEmpty && !hasContent) {
|
|
55
|
+
writeMigrationIndex({
|
|
56
|
+
migrationsDir: payload.db.migrationDir
|
|
57
|
+
});
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const mergedUpSQL = [
|
|
61
|
+
predefinedMigration.upSQL,
|
|
62
|
+
dataUpCode
|
|
63
|
+
].filter(Boolean).join('\n') || undefined;
|
|
64
|
+
const mergedDownSQL = [
|
|
65
|
+
predefinedMigration.downSQL,
|
|
66
|
+
dataDownCode
|
|
67
|
+
].filter(Boolean).join('\n') || undefined;
|
|
68
|
+
const migrationFileContent = migrationTemplate({
|
|
69
|
+
...predefinedMigration,
|
|
70
|
+
downSQL: mergedDownSQL,
|
|
71
|
+
upSQL: mergedUpSQL
|
|
72
|
+
});
|
|
32
73
|
const [yyymmdd, hhmmss] = new Date().toISOString().split('T');
|
|
33
74
|
const formattedDate = yyymmdd.replace(/\D/g, '');
|
|
34
75
|
const formattedTime = hhmmss.split('.')[0].replace(/\D/g, '');
|
|
@@ -36,9 +77,7 @@ export const createMigration = async function createMigration({ file, migrationN
|
|
|
36
77
|
const formattedName = migrationName?.replace(/\W/g, '_');
|
|
37
78
|
const fileName = migrationName ? `${timestamp}_${formattedName}.ts` : `${timestamp}_migration.ts`;
|
|
38
79
|
const filePath = `${dir}/${fileName}`;
|
|
39
|
-
|
|
40
|
-
fs.writeFileSync(filePath, migrationFileContent);
|
|
41
|
-
}
|
|
80
|
+
fs.writeFileSync(filePath, migrationFileContent);
|
|
42
81
|
writeMigrationIndex({
|
|
43
82
|
migrationsDir: payload.db.migrationDir
|
|
44
83
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["import type { CreateMigration, MigrationTemplateArgs } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport {
|
|
1
|
+
{"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["import type { CreateMigration, MigrationTemplateArgs } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport {\n bootstrapConfigState,\n diffConfig,\n generateDataMigrationCode,\n getPredefinedMigration,\n readConfigState,\n resolvePrompts,\n serializeConfig,\n writeMigrationIndex,\n} from 'payload'\nimport { fileURLToPath } from 'url'\n\nconst migrationTemplate = ({ downSQL, imports, upSQL }: MigrationTemplateArgs): string => `import {\n MigrateDownArgs,\n MigrateUpArgs,\n} from '@payloadcms/db-mongodb'\n${imports ?? ''}\nexport async function up({ payload, req, session }: MigrateUpArgs): Promise<void> {\n${upSQL ?? ` // Migration code`}\n}\n\nexport async function down({ payload, req, session }: MigrateDownArgs): Promise<void> {\n${downSQL ?? ` // Migration code`}\n}\n`\n\nexport const createMigration: CreateMigration = async function createMigration({\n file,\n migrationName,\n payload,\n skipEmpty,\n}) {\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n // Config-diff: compute data migrations to append\n const prevSnapshot = await readConfigState(dir)\n const nextSnapshot = serializeConfig(payload.config)\n let dataUpCode = ''\n let dataDownCode = ''\n\n if (prevSnapshot !== null) {\n const changes = diffConfig(prevSnapshot, nextSnapshot)\n if (changes.length > 0) {\n const { shouldAbort } = await resolvePrompts(changes)\n if (shouldAbort) {\n process.exit(1)\n }\n const localization = payload.config.localization || null\n const { downCode, upCode } = generateDataMigrationCode(changes, {\n defaultLocale: localization?.defaultLocale,\n })\n dataUpCode = upCode\n dataDownCode = downCode\n }\n } else {\n await bootstrapConfigState(payload, dir)\n }\n\n const hasContent = predefinedMigration.upSQL || predefinedMigration.downSQL || dataUpCode\n\n if (skipEmpty && !hasContent) {\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n return\n }\n\n const mergedUpSQL =\n [predefinedMigration.upSQL, dataUpCode].filter(Boolean).join('\\n') || undefined\n const mergedDownSQL =\n [predefinedMigration.downSQL, dataDownCode].filter(Boolean).join('\\n') || undefined\n\n const migrationFileContent = migrationTemplate({\n ...predefinedMigration,\n downSQL: mergedDownSQL,\n upSQL: mergedUpSQL,\n })\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n\n const formattedDate = yyymmdd!.replace(/\\D/g, '')\n const formattedTime = hhmmss!.split('.')[0]!.replace(/\\D/g, '')\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const formattedName = migrationName?.replace(/\\W/g, '_')\n const fileName = migrationName ? `${timestamp}_${formattedName}.ts` : `${timestamp}_migration.ts`\n const filePath = `${dir}/${fileName}`\n\n fs.writeFileSync(filePath, migrationFileContent)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${filePath}` })\n}\n"],"names":["fs","path","bootstrapConfigState","diffConfig","generateDataMigrationCode","getPredefinedMigration","readConfigState","resolvePrompts","serializeConfig","writeMigrationIndex","fileURLToPath","migrationTemplate","downSQL","imports","upSQL","createMigration","file","migrationName","payload","skipEmpty","filename","url","dirname","dir","db","migrationDir","existsSync","mkdirSync","predefinedMigration","prevSnapshot","nextSnapshot","config","dataUpCode","dataDownCode","changes","length","shouldAbort","process","exit","localization","downCode","upCode","defaultLocale","hasContent","migrationsDir","mergedUpSQL","filter","Boolean","join","undefined","mergedDownSQL","migrationFileContent","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","timestamp","formattedName","fileName","filePath","writeFileSync","logger","info","msg"],"mappings":"AAEA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SACEC,oBAAoB,EACpBC,UAAU,EACVC,yBAAyB,EACzBC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,eAAe,EACfC,mBAAmB,QACd,UAAS;AAChB,SAASC,aAAa,QAAQ,MAAK;AAEnC,MAAMC,oBAAoB,CAAC,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAyB,GAAa,CAAC;;;;AAI3F,EAAED,WAAW,GAAG;;AAEhB,EAAEC,SAAS,CAAC,mBAAmB,CAAC,CAAC;;;;AAIjC,EAAEF,WAAW,CAAC,mBAAmB,CAAC,CAAC;;AAEnC,CAAC;AAED,OAAO,MAAMG,kBAAmC,eAAeA,gBAAgB,EAC7EC,IAAI,EACJC,aAAa,EACbC,OAAO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AAS,EACT,wBAA6B,EAC7B,cAAc,EACd,mBAA2B,EAC3B,iBAAyB,EACzB,aAAqB,EACrB,YAAY,EAAE,eAAe,EAC7B,iBAAiB,EACjB,cAAc,EACd,kBAAuB,EACvB,GAAG,EACH,0BAAkC,EAClC,qBAA6B,EAC7B,mBAA0B,EAC1B,uBAA8B,GAC/B,EAAE,IAAI,GAAG,kBAAkB,CAsF3B;AAED,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -20,7 +20,10 @@ import { findGlobalVersions } from './findGlobalVersions.js';
|
|
|
20
20
|
import { findOne } from './findOne.js';
|
|
21
21
|
import { findVersions } from './findVersions.js';
|
|
22
22
|
import { init } from './init.js';
|
|
23
|
+
import { migrateFieldDelocalized } from './migrateFieldDelocalized.js';
|
|
24
|
+
import { migrateFieldLocalized } from './migrateFieldLocalized.js';
|
|
23
25
|
import { migrateFresh } from './migrateFresh.js';
|
|
26
|
+
import { migrateVersionsEnabled } from './migrateVersionsEnabled.js';
|
|
24
27
|
import { queryDrafts } from './queryDrafts.js';
|
|
25
28
|
import { beginTransaction } from './transactions/beginTransaction.js';
|
|
26
29
|
import { commitTransaction } from './transactions/commitTransaction.js';
|
|
@@ -88,7 +91,10 @@ export function mongooseAdapter({ afterCreateConnection, afterOpenConnection, al
|
|
|
88
91
|
findOne,
|
|
89
92
|
findVersions,
|
|
90
93
|
init,
|
|
94
|
+
migrateFieldDelocalized,
|
|
95
|
+
migrateFieldLocalized,
|
|
91
96
|
migrateFresh,
|
|
97
|
+
migrateVersionsEnabled,
|
|
92
98
|
migrationDir,
|
|
93
99
|
packageName: '@payloadcms/db-mongodb',
|
|
94
100
|
payload,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollationOptions, TransactionOptions } from 'mongodb'\nimport type { MongoMemoryReplSet } from 'mongodb-memory-server'\nimport type {\n ClientSession,\n Connection,\n ConnectOptions,\n QueryOptions,\n SchemaOptions,\n} from 'mongoose'\nimport type {\n BaseDatabaseAdapter,\n CollectionSlug,\n DatabaseAdapterObj,\n JsonObject,\n Payload,\n TypeWithVersion,\n UpdateGlobalArgs,\n UpdateGlobalVersionArgs,\n UpdateOneArgs,\n UpdateVersionArgs,\n} from 'payload'\n\nimport mongoose from 'mongoose'\nimport { createDatabaseAdapter, defaultBeginTransaction, findMigrationDir } from 'payload'\n\nimport type {\n CollectionModel,\n GlobalModel,\n MigrateDownArgs,\n MigrateUpArgs,\n MongooseMigration,\n} from './types.js'\n\nimport { connect } from './connect.js'\nimport { count } from './count.js'\nimport { countGlobalVersions } from './countGlobalVersions.js'\nimport { countVersions } from './countVersions.js'\nimport { create } from './create.js'\nimport { createGlobal } from './createGlobal.js'\nimport { createGlobalVersion } from './createGlobalVersion.js'\nimport { createMigration } from './createMigration.js'\nimport { createVersion } from './createVersion.js'\nimport { deleteMany } from './deleteMany.js'\nimport { deleteOne } from './deleteOne.js'\nimport { deleteVersions } from './deleteVersions.js'\nimport { destroy } from './destroy.js'\nimport { find } from './find.js'\nimport { findDistinct } from './findDistinct.js'\nimport { findGlobal } from './findGlobal.js'\nimport { findGlobalVersions } from './findGlobalVersions.js'\nimport { findOne } from './findOne.js'\nimport { findVersions } from './findVersions.js'\nimport { init } from './init.js'\nimport { migrateFresh } from './migrateFresh.js'\nimport { queryDrafts } from './queryDrafts.js'\nimport { beginTransaction } from './transactions/beginTransaction.js'\nimport { commitTransaction } from './transactions/commitTransaction.js'\nimport { rollbackTransaction } from './transactions/rollbackTransaction.js'\nimport { updateGlobal } from './updateGlobal.js'\nimport { updateGlobalVersion } from './updateGlobalVersion.js'\nimport { updateJobs } from './updateJobs.js'\nimport { updateMany } from './updateMany.js'\nimport { updateOne } from './updateOne.js'\nimport { updateVersion } from './updateVersion.js'\nimport { upsert } from './upsert.js'\n\nexport type { MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nexport interface Args {\n afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n /**\n * By default, Payload strips all additional keys from MongoDB data that don't exist\n * in the Payload schema. If you have some data that you want to include to the result\n * but it doesn't exist in Payload, you can enable this flag\n * @default false\n */\n allowAdditionalKeys?: boolean\n /**\n * Enable this flag if you want to thread your own ID to create operation data, for example:\n * ```ts\n * import { Types } from 'mongoose'\n *\n * const id = new Types.ObjectId().toHexString()\n * const doc = await payload.create({ collection: 'posts', data: {id, title: \"my title\"}})\n * assertEq(doc.id, id)\n * ```\n */\n allowIDOnCreate?: boolean\n /** Set to false to disable auto-pluralization of collection names, Defaults to true */\n autoPluralization?: boolean\n /**\n * When true, bulk operations will process documents one at a time\n * in separate transactions instead of all at once in a single transaction.\n * Useful for avoiding transaction limitations with large datasets in DocumentDB and Cosmos DB.\n *\n * @default false\n */\n bulkOperationsSingleTransaction?: boolean\n\n /**\n * If enabled, collation allows for language-specific rules for string comparison.\n * This configuration can include the following options:\n *\n * - `strength` (number): Comparison level (1: Primary, 2: Secondary, 3: Tertiary (default), 4: Quaternary, 5: Identical)\n * - `caseLevel` (boolean): Include case comparison at strength level 1 or 2.\n * - `caseFirst` (string): Sort order of case differences during tertiary level comparisons (\"upper\", \"lower\", \"off\").\n * - `numericOrdering` (boolean): Compare numeric strings as numbers.\n * - `alternate` (string): Consider whitespace and punctuation as base characters (\"non-ignorable\", \"shifted\").\n * - `maxVariable` (string): Characters considered ignorable when `alternate` is \"shifted\" (\"punct\", \"space\").\n * - `backwards` (boolean): Sort strings with diacritics from back of the string.\n * - `normalization` (boolean): Check if text requires normalization and perform normalization.\n *\n * Available on MongoDB version 3.4 and up.\n * The locale that gets passed is your current project's locale but defaults to \"en\".\n *\n * Example:\n * {\n * strength: 3\n * }\n *\n * Defaults to disabled.\n */\n collation?: Omit<CollationOptions, 'locale'>\n\n collectionsSchemaOptions?: Partial<Record<CollectionSlug, SchemaOptions>>\n /** Extra configuration options */\n connectOptions?: {\n /**\n * Set false to disable $facet aggregation in non-supporting databases, Defaults to true\n * @deprecated Payload doesn't use `$facet` anymore anywhere.\n */\n useFacet?: boolean\n } & ConnectOptions\n /**\n * We add a secondary sort based on `createdAt` to ensure that results are always returned in the same order when sorting by a non-unique field.\n * This is because MongoDB does not guarantee the order of results, however in very large datasets this could affect performance.\n *\n * Set to `true` to disable this behaviour.\n */\n disableFallbackSort?: boolean\n /** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */\n disableIndexHints?: boolean\n /**\n * Set to `true` to ensure that indexes are ready before completing connection.\n * NOTE: not recommended for production. This can slow down the initialization of Payload.\n */\n ensureIndexes?: boolean\n migrationDir?: string\n /**\n * typed as any to avoid dependency\n */\n mongoMemoryServer?: MongoMemoryReplSet\n prodMigrations?: MongooseMigration[]\n\n transactionOptions?: false | TransactionOptions\n\n /** The URL to connect to MongoDB or false to start payload and prevent connecting */\n url: false | string\n\n /**\n * Set to `true` to use an alternative `dropDatabase` implementation that calls `collection.deleteMany({})` on every collection instead of sending a raw `dropDatabase` command.\n * Payload only uses `dropDatabase` for testing purposes.\n * @default false\n */\n useAlternativeDropDatabase?: boolean\n\n /**\n * Set to `true` to use `BigInt` for custom ID fields of type `'number'`.\n * Useful for databases that don't support `double` or `int32` IDs.\n * @default false\n */\n useBigIntForNumberIDs?: boolean\n /**\n * Set to `false` to disable join aggregations (which use correlated subqueries) and instead populate join fields via multiple `find` queries.\n * @default true\n */\n useJoinAggregations?: boolean\n /**\n * Set to `false` to disable the use of `pipeline` in the `$lookup` aggregation in sorting.\n * @default true\n */\n usePipelineInSortLookup?: boolean\n}\n\nexport type MongooseAdapter = {\n afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n bulkOperationsSingleTransaction: boolean\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n useAlternativeDropDatabase: boolean\n useBigIntForNumberIDs: boolean\n useJoinAggregations: boolean\n usePipelineInSortLookup: boolean\n versions: {\n [slug: string]: CollectionModel\n }\n} & Args &\n BaseDatabaseAdapter\n\ndeclare module 'payload' {\n export interface DatabaseAdapter\n extends Omit<BaseDatabaseAdapter, 'sessions'>,\n Omit<Args, 'migrationDir'> {\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n transactionOptions: TransactionOptions\n updateGlobal: <T extends Record<string, unknown>>(\n args: { options?: QueryOptions } & UpdateGlobalArgs<T>,\n ) => Promise<T>\n updateGlobalVersion: <T extends JsonObject = JsonObject>(\n args: { options?: QueryOptions } & UpdateGlobalVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n\n updateOne: (args: { options?: QueryOptions } & UpdateOneArgs) => Promise<Document>\n updateVersion: <T extends JsonObject = JsonObject>(\n args: { options?: QueryOptions } & UpdateVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n useAlternativeDropDatabase: boolean\n useBigIntForNumberIDs: boolean\n useJoinAggregations: boolean\n usePipelineInSortLookup: boolean\n versions: {\n [slug: string]: CollectionModel\n }\n }\n}\n\nexport function mongooseAdapter({\n afterCreateConnection,\n afterOpenConnection,\n allowAdditionalKeys = false,\n allowIDOnCreate = false,\n autoPluralization = true,\n bulkOperationsSingleTransaction = false,\n collation,\n collectionsSchemaOptions = {},\n connectOptions,\n disableFallbackSort = false,\n disableIndexHints = false,\n ensureIndexes = false,\n migrationDir: migrationDirArg,\n mongoMemoryServer,\n prodMigrations,\n transactionOptions = {},\n url,\n useAlternativeDropDatabase = false,\n useBigIntForNumberIDs = false,\n useJoinAggregations = true,\n usePipelineInSortLookup = true,\n}: Args): DatabaseAdapterObj {\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(migrationDirArg)\n mongoose.set('strictQuery', false)\n\n return createDatabaseAdapter<MongooseAdapter>({\n name: 'mongoose',\n\n // Mongoose-specific\n afterCreateConnection,\n afterOpenConnection,\n autoPluralization,\n bulkOperationsSingleTransaction,\n collation,\n collections: {},\n // @ts-expect-error initialize without a connection\n connection: undefined,\n connectOptions: connectOptions || {},\n disableIndexHints,\n ensureIndexes,\n // @ts-expect-error don't have globals model yet\n globals: undefined,\n // @ts-expect-error Should not be required\n mongoMemoryServer,\n sessions: {},\n transactionOptions: transactionOptions === false ? undefined : transactionOptions,\n updateJobs,\n updateMany,\n url,\n versions: {},\n // DatabaseAdapter\n allowAdditionalKeys,\n allowIDOnCreate,\n beginTransaction: transactionOptions === false ? defaultBeginTransaction() : beginTransaction,\n collectionsSchemaOptions,\n commitTransaction,\n connect,\n count,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createMigration,\n createVersion,\n defaultIDType: 'text',\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n disableFallbackSort,\n find,\n findDistinct,\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n init,\n migrateFresh,\n migrationDir,\n packageName: '@payloadcms/db-mongodb',\n payload,\n prodMigrations,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n upsert,\n useAlternativeDropDatabase,\n useBigIntForNumberIDs,\n useJoinAggregations,\n usePipelineInSortLookup,\n })\n }\n\n return {\n name: 'mongoose',\n allowIDOnCreate,\n defaultIDType: 'text',\n init: adapter,\n }\n}\n\nexport { compatibilityOptions } from './utilities/compatibilityOptions.js'\n"],"names":["mongoose","createDatabaseAdapter","defaultBeginTransaction","findMigrationDir","connect","count","countGlobalVersions","countVersions","create","createGlobal","createGlobalVersion","createMigration","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findDistinct","findGlobal","findGlobalVersions","findOne","findVersions","init","migrateFresh","queryDrafts","beginTransaction","commitTransaction","rollbackTransaction","updateGlobal","updateGlobalVersion","updateJobs","updateMany","updateOne","updateVersion","upsert","mongooseAdapter","afterCreateConnection","afterOpenConnection","allowAdditionalKeys","allowIDOnCreate","autoPluralization","bulkOperationsSingleTransaction","collation","collectionsSchemaOptions","connectOptions","disableFallbackSort","disableIndexHints","ensureIndexes","migrationDir","migrationDirArg","mongoMemoryServer","prodMigrations","transactionOptions","url","useAlternativeDropDatabase","useBigIntForNumberIDs","useJoinAggregations","usePipelineInSortLookup","adapter","payload","set","name","collections","connection","undefined","globals","sessions","versions","defaultIDType","packageName","compatibilityOptions"],"mappings":"AAsBA,OAAOA,cAAc,WAAU;AAC/B,SAASC,qBAAqB,EAAEC,uBAAuB,EAAEC,gBAAgB,QAAQ,UAAS;AAU1F,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,KAAK,QAAQ,aAAY;AAClC,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,MAAM,QAAQ,cAAa;AACpC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,UAAU,QAAQ,kBA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D;YACnDC,YAAYC;YACZpB,gBAAgBA,kBAAkB,CAAC;YACnCE;YACAC;YACA,gDAAgD;YAChDkB,SAASD;YACT,0CAA0C;YAC1Cd;YACAgB,UAAU,CAAC;YACXd,oBAAoBA,uBAAuB,QAAQY,YAAYZ;YAC/DtB;YACAC;YACAsB;YACAc,UAAU,CAAC;YACX,kBAAkB;YAClB7B;YACAC;YACAd,kBAAkB2B,uBAAuB,QAAQnD,4BAA4BwB;YAC7EkB;YACAjB;YACAvB;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAyD,eAAe;YACfxD;YACAC;YACAC;YACAC;YACA8B;YACA7B;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAyB;YACAqB,aAAa;YACbV;YACAR;YACA3B;YACAG;YACAC;YACAC;YACAG;YACAC;YACAC;YACAoB;YACAC;YACAC;YACAC;QACF;IACF;IAEA,OAAO;QACLI,MAAM;QACNtB;QACA6B,eAAe;QACf9C,MAAMoC;IACR;AACF;AAEA,SAASY,oBAAoB,QAAQ,sCAAqC"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollationOptions, TransactionOptions } from 'mongodb'\nimport type { MongoMemoryReplSet } from 'mongodb-memory-server'\nimport type {\n ClientSession,\n Connection,\n ConnectOptions,\n QueryOptions,\n SchemaOptions,\n} from 'mongoose'\nimport type {\n BaseDatabaseAdapter,\n CollectionSlug,\n DatabaseAdapterObj,\n JsonObject,\n Payload,\n TypeWithVersion,\n UpdateGlobalArgs,\n UpdateGlobalVersionArgs,\n UpdateOneArgs,\n UpdateVersionArgs,\n} from 'payload'\n\nimport mongoose from 'mongoose'\nimport { createDatabaseAdapter, defaultBeginTransaction, findMigrationDir } from 'payload'\n\nimport type {\n CollectionModel,\n GlobalModel,\n MigrateDownArgs,\n MigrateUpArgs,\n MongooseMigration,\n} from './types.js'\n\nimport { connect } from './connect.js'\nimport { count } from './count.js'\nimport { countGlobalVersions } from './countGlobalVersions.js'\nimport { countVersions } from './countVersions.js'\nimport { create } from './create.js'\nimport { createGlobal } from './createGlobal.js'\nimport { createGlobalVersion } from './createGlobalVersion.js'\nimport { createMigration } from './createMigration.js'\nimport { createVersion } from './createVersion.js'\nimport { deleteMany } from './deleteMany.js'\nimport { deleteOne } from './deleteOne.js'\nimport { deleteVersions } from './deleteVersions.js'\nimport { destroy } from './destroy.js'\nimport { find } from './find.js'\nimport { findDistinct } from './findDistinct.js'\nimport { findGlobal } from './findGlobal.js'\nimport { findGlobalVersions } from './findGlobalVersions.js'\nimport { findOne } from './findOne.js'\nimport { findVersions } from './findVersions.js'\nimport { init } from './init.js'\nimport { migrateFieldDelocalized } from './migrateFieldDelocalized.js'\nimport { migrateFieldLocalized } from './migrateFieldLocalized.js'\nimport { migrateFresh } from './migrateFresh.js'\nimport { migrateVersionsEnabled } from './migrateVersionsEnabled.js'\nimport { queryDrafts } from './queryDrafts.js'\nimport { beginTransaction } from './transactions/beginTransaction.js'\nimport { commitTransaction } from './transactions/commitTransaction.js'\nimport { rollbackTransaction } from './transactions/rollbackTransaction.js'\nimport { updateGlobal } from './updateGlobal.js'\nimport { updateGlobalVersion } from './updateGlobalVersion.js'\nimport { updateJobs } from './updateJobs.js'\nimport { updateMany } from './updateMany.js'\nimport { updateOne } from './updateOne.js'\nimport { updateVersion } from './updateVersion.js'\nimport { upsert } from './upsert.js'\n\nexport type { MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nexport interface Args {\n afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n /**\n * By default, Payload strips all additional keys from MongoDB data that don't exist\n * in the Payload schema. If you have some data that you want to include to the result\n * but it doesn't exist in Payload, you can enable this flag\n * @default false\n */\n allowAdditionalKeys?: boolean\n /**\n * Enable this flag if you want to thread your own ID to create operation data, for example:\n * ```ts\n * import { Types } from 'mongoose'\n *\n * const id = new Types.ObjectId().toHexString()\n * const doc = await payload.create({ collection: 'posts', data: {id, title: \"my title\"}})\n * assertEq(doc.id, id)\n * ```\n */\n allowIDOnCreate?: boolean\n /** Set to false to disable auto-pluralization of collection names, Defaults to true */\n autoPluralization?: boolean\n /**\n * When true, bulk operations will process documents one at a time\n * in separate transactions instead of all at once in a single transaction.\n * Useful for avoiding transaction limitations with large datasets in DocumentDB and Cosmos DB.\n *\n * @default false\n */\n bulkOperationsSingleTransaction?: boolean\n\n /**\n * If enabled, collation allows for language-specific rules for string comparison.\n * This configuration can include the following options:\n *\n * - `strength` (number): Comparison level (1: Primary, 2: Secondary, 3: Tertiary (default), 4: Quaternary, 5: Identical)\n * - `caseLevel` (boolean): Include case comparison at strength level 1 or 2.\n * - `caseFirst` (string): Sort order of case differences during tertiary level comparisons (\"upper\", \"lower\", \"off\").\n * - `numericOrdering` (boolean): Compare numeric strings as numbers.\n * - `alternate` (string): Consider whitespace and punctuation as base characters (\"non-ignorable\", \"shifted\").\n * - `maxVariable` (string): Characters considered ignorable when `alternate` is \"shifted\" (\"punct\", \"space\").\n * - `backwards` (boolean): Sort strings with diacritics from back of the string.\n * - `normalization` (boolean): Check if text requires normalization and perform normalization.\n *\n * Available on MongoDB version 3.4 and up.\n * The locale that gets passed is your current project's locale but defaults to \"en\".\n *\n * Example:\n * {\n * strength: 3\n * }\n *\n * Defaults to disabled.\n */\n collation?: Omit<CollationOptions, 'locale'>\n\n collectionsSchemaOptions?: Partial<Record<CollectionSlug, SchemaOptions>>\n /** Extra configuration options */\n connectOptions?: {\n /**\n * Set false to disable $facet aggregation in non-supporting databases, Defaults to true\n * @deprecated Payload doesn't use `$facet` anymore anywhere.\n */\n useFacet?: boolean\n } & ConnectOptions\n /**\n * We add a secondary sort based on `createdAt` to ensure that results are always returned in the same order when sorting by a non-unique field.\n * This is because MongoDB does not guarantee the order of results, however in very large datasets this could affect performance.\n *\n * Set to `true` to disable this behaviour.\n */\n disableFallbackSort?: boolean\n /** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */\n disableIndexHints?: boolean\n /**\n * Set to `true` to ensure that indexes are ready before completing connection.\n * NOTE: not recommended for production. This can slow down the initialization of Payload.\n */\n ensureIndexes?: boolean\n migrationDir?: string\n /**\n * typed as any to avoid dependency\n */\n mongoMemoryServer?: MongoMemoryReplSet\n prodMigrations?: MongooseMigration[]\n\n transactionOptions?: false | TransactionOptions\n\n /** The URL to connect to MongoDB or false to start payload and prevent connecting */\n url: false | string\n\n /**\n * Set to `true` to use an alternative `dropDatabase` implementation that calls `collection.deleteMany({})` on every collection instead of sending a raw `dropDatabase` command.\n * Payload only uses `dropDatabase` for testing purposes.\n * @default false\n */\n useAlternativeDropDatabase?: boolean\n\n /**\n * Set to `true` to use `BigInt` for custom ID fields of type `'number'`.\n * Useful for databases that don't support `double` or `int32` IDs.\n * @default false\n */\n useBigIntForNumberIDs?: boolean\n /**\n * Set to `false` to disable join aggregations (which use correlated subqueries) and instead populate join fields via multiple `find` queries.\n * @default true\n */\n useJoinAggregations?: boolean\n /**\n * Set to `false` to disable the use of `pipeline` in the `$lookup` aggregation in sorting.\n * @default true\n */\n usePipelineInSortLookup?: boolean\n}\n\nexport type MongooseAdapter = {\n afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n bulkOperationsSingleTransaction: boolean\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n useAlternativeDropDatabase: boolean\n useBigIntForNumberIDs: boolean\n useJoinAggregations: boolean\n usePipelineInSortLookup: boolean\n versions: {\n [slug: string]: CollectionModel\n }\n} & Args &\n BaseDatabaseAdapter\n\ndeclare module 'payload' {\n export interface DatabaseAdapter\n extends Omit<BaseDatabaseAdapter, 'sessions'>,\n Omit<Args, 'migrationDir'> {\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n transactionOptions: TransactionOptions\n updateGlobal: <T extends Record<string, unknown>>(\n args: { options?: QueryOptions } & UpdateGlobalArgs<T>,\n ) => Promise<T>\n updateGlobalVersion: <T extends JsonObject = JsonObject>(\n args: { options?: QueryOptions } & UpdateGlobalVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n\n updateOne: (args: { options?: QueryOptions } & UpdateOneArgs) => Promise<Document>\n updateVersion: <T extends JsonObject = JsonObject>(\n args: { options?: QueryOptions } & UpdateVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n useAlternativeDropDatabase: boolean\n useBigIntForNumberIDs: boolean\n useJoinAggregations: boolean\n usePipelineInSortLookup: boolean\n versions: {\n [slug: string]: CollectionModel\n }\n }\n}\n\nexport function mongooseAdapter({\n afterCreateConnection,\n afterOpenConnection,\n allowAdditionalKeys = false,\n allowIDOnCreate = false,\n autoPluralization = true,\n bulkOperationsSingleTransaction = false,\n collation,\n collectionsSchemaOptions = {},\n connectOptions,\n disableFallbackSort = false,\n disableIndexHints = false,\n ensureIndexes = false,\n migrationDir: migrationDirArg,\n mongoMemoryServer,\n prodMigrations,\n transactionOptions = {},\n url,\n useAlternativeDropDatabase = false,\n useBigIntForNumberIDs = false,\n useJoinAggregations = true,\n usePipelineInSortLookup = true,\n}: Args): DatabaseAdapterObj {\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(migrationDirArg)\n mongoose.set('strictQuery', false)\n\n return createDatabaseAdapter<MongooseAdapter>({\n name: 'mongoose',\n\n // Mongoose-specific\n afterCreateConnection,\n afterOpenConnection,\n autoPluralization,\n bulkOperationsSingleTransaction,\n collation,\n collections: {},\n // @ts-expect-error initialize without a connection\n connection: undefined,\n connectOptions: connectOptions || {},\n disableIndexHints,\n ensureIndexes,\n // @ts-expect-error don't have globals model yet\n globals: undefined,\n // @ts-expect-error Should not be required\n mongoMemoryServer,\n sessions: {},\n transactionOptions: transactionOptions === false ? undefined : transactionOptions,\n updateJobs,\n updateMany,\n url,\n versions: {},\n // DatabaseAdapter\n allowAdditionalKeys,\n allowIDOnCreate,\n beginTransaction: transactionOptions === false ? defaultBeginTransaction() : beginTransaction,\n collectionsSchemaOptions,\n commitTransaction,\n connect,\n count,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createMigration,\n createVersion,\n defaultIDType: 'text',\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n disableFallbackSort,\n find,\n findDistinct,\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n init,\n migrateFieldDelocalized,\n migrateFieldLocalized,\n migrateFresh,\n migrateVersionsEnabled,\n migrationDir,\n packageName: '@payloadcms/db-mongodb',\n payload,\n prodMigrations,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n upsert,\n useAlternativeDropDatabase,\n useBigIntForNumberIDs,\n useJoinAggregations,\n usePipelineInSortLookup,\n })\n }\n\n return {\n name: 'mongoose',\n allowIDOnCreate,\n defaultIDType: 'text',\n init: adapter,\n }\n}\n\nexport { compatibilityOptions } from './utilities/compatibilityOptions.js'\n"],"names":["mongoose","createDatabaseAdapter","defaultBeginTransaction","findMigrationDir","connect","count","countGlobalVersions","countVersions","create","createGlobal","createGlobalVersion","createMigration","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findDistinct","findGlobal","findGlobalVersions","findOne","findVersions","init","migrateFieldDelocalized","migrateFieldLocalized","migrateFresh","migrateVersionsEnabled","queryDrafts","beginTransaction","commitTransaction","rollbackTransaction","updateGlobal","updateGlobalVersion","updateJobs","updateMany","updateOne","updateVersion","upsert","mongooseAdapter","afterCreateConnection","afterOpenConnection","allowAdditionalKeys","allowIDOnCreate","autoPluralization","bulkOperationsSingleTransaction","collation","collectionsSchemaOptions","connectOptions","disableFallbackSort","disableIndexHints","ensureIndexes","migrationDir","migrationDirArg","mongoMemoryServer","prodMigrations","transactionOptions","url","useAlternativeDropDatabase","useBigIntForNumberIDs","useJoinAggregations","usePipelineInSortLookup","adapter","payload","set","name","collections","connection","undefined","globals","sessions","versions","defaultIDType","packageName","compatibilityOptions"],"mappings":"AAsBA,OAAOA,cAAc,WAAU;AAC/B,SAASC,qBAAqB,EAAEC,uBAAuB,EAAEC,gBAAgB,QAAQ,UAAS;AAU1F,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,KAAK,QAAQ,aAAY;AAClC,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,MAAM,QAAQ,cAAa;AACpC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,YAAY,Q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,CAAC;YACXd,oBAAoBA,uBAAuB,QAAQY,YAAYZ;YAC/DtB;YACAC;YACAsB;YACAc,UAAU,CAAC;YACX,kBAAkB;YAClB7B;YACAC;YACAd,kBAAkB2B,uBAAuB,QAAQtD,4BAA4B2B;YAC7EkB;YACAjB;YACA1B;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACA4D,eAAe;YACf3D;YACAC;YACAC;YACAC;YACAiC;YACAhC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAyB;YACAqB,aAAa;YACbV;YACAR;YACA3B;YACAG;YACAC;YACAC;YACAG;YACAC;YACAC;YACAoB;YACAC;YACAC;YACAC;QACF;IACF;IAEA,OAAO;QACLI,MAAM;QACNtB;QACA6B,eAAe;QACfjD,MAAMuC;IACR;AACF;AAEA,SAASY,oBAAoB,QAAQ,sCAAqC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
import type { MongooseAdapter } from './index.js';
|
|
3
|
+
export declare function migrateFieldDelocalized(this: MongooseAdapter, args: {
|
|
4
|
+
defaultLocale: string;
|
|
5
|
+
entity: 'collection' | 'global';
|
|
6
|
+
fieldPath: string;
|
|
7
|
+
req: PayloadRequest;
|
|
8
|
+
slug: string;
|
|
9
|
+
}): Promise<void>;
|
|
10
|
+
//# sourceMappingURL=migrateFieldDelocalized.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrateFieldDelocalized.d.ts","sourceRoot":"","sources":["../src/migrateFieldDelocalized.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAUjD,wBAAsB,uBAAuB,CAC3C,IAAI,EAAE,eAAe,EACrB,IAAI,EAAE;IACJ,aAAa,EAAE,MAAM,CAAA;IACrB,MAAM,EAAE,YAAY,GAAG,QAAQ,CAAA;IAC/B,SAAS,EAAE,MAAM,CAAA;IACjB,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,MAAM,CAAA;CACb,GACA,OAAO,CAAC,IAAI,CAAC,CA6Cf"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { getCollection } from './utilities/getEntity.js';
|
|
2
|
+
function getValueAtPath(doc, path) {
|
|
3
|
+
return path.split('.').reduce((obj, key)=>obj?.[key], doc);
|
|
4
|
+
}
|
|
5
|
+
const BATCH_SIZE = 1000;
|
|
6
|
+
export async function migrateFieldDelocalized(args) {
|
|
7
|
+
const { slug, defaultLocale, entity, fieldPath } = args;
|
|
8
|
+
const { payload } = this;
|
|
9
|
+
payload.logger.warn(`[config-migration] Delocalizing field "${fieldPath}" on ${entity} "${slug}" — keeping only "${defaultLocale}" value`);
|
|
10
|
+
if (entity === 'collection') {
|
|
11
|
+
const { Model } = getCollection({
|
|
12
|
+
adapter: this,
|
|
13
|
+
collectionSlug: slug
|
|
14
|
+
});
|
|
15
|
+
const nativeCollection = Model.collection;
|
|
16
|
+
let page = 1;
|
|
17
|
+
let hasMore = true;
|
|
18
|
+
while(hasMore){
|
|
19
|
+
const docs = await nativeCollection.find({}).skip((page - 1) * BATCH_SIZE).limit(BATCH_SIZE).toArray();
|
|
20
|
+
for (const doc of docs){
|
|
21
|
+
const currentValue = getValueAtPath(doc, fieldPath);
|
|
22
|
+
if (currentValue !== null && currentValue !== undefined && typeof currentValue === 'object' && !Array.isArray(currentValue)) {
|
|
23
|
+
const defaultValue = currentValue[defaultLocale] ?? null;
|
|
24
|
+
const update = {};
|
|
25
|
+
update[fieldPath] = defaultValue;
|
|
26
|
+
await nativeCollection.updateOne({
|
|
27
|
+
_id: doc._id
|
|
28
|
+
}, {
|
|
29
|
+
$set: update
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
hasMore = docs.length === BATCH_SIZE;
|
|
34
|
+
page++;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
payload.logger.info(`[config-migration] Done delocalizing field "${fieldPath}" on ${entity} "${slug}"`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=migrateFieldDelocalized.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/migrateFieldDelocalized.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getCollection } from './utilities/getEntity.js'\n\nfunction getValueAtPath(doc: Record<string, unknown>, path: string): unknown {\n return path.split('.').reduce((obj: any, key) => obj?.[key], doc)\n}\n\nconst BATCH_SIZE = 1000\n\nexport async function migrateFieldDelocalized(\n this: MongooseAdapter,\n args: {\n defaultLocale: string\n entity: 'collection' | 'global'\n fieldPath: string\n req: PayloadRequest\n slug: string\n },\n): Promise<void> {\n const { slug, defaultLocale, entity, fieldPath } = args\n const { payload } = this\n\n payload.logger.warn(\n `[config-migration] Delocalizing field \"${fieldPath}\" on ${entity} \"${slug}\" — keeping only \"${defaultLocale}\" value`,\n )\n\n if (entity === 'collection') {\n const { Model } = getCollection({ adapter: this, collectionSlug: slug })\n const nativeCollection = Model.collection\n\n let page = 1\n let hasMore = true\n\n while (hasMore) {\n const docs = await nativeCollection\n .find({})\n .skip((page - 1) * BATCH_SIZE)\n .limit(BATCH_SIZE)\n .toArray()\n\n for (const doc of docs) {\n const currentValue = getValueAtPath(doc as any, fieldPath)\n if (\n currentValue !== null &&\n currentValue !== undefined &&\n typeof currentValue === 'object' &&\n !Array.isArray(currentValue)\n ) {\n const defaultValue = (currentValue as Record<string, unknown>)[defaultLocale] ?? null\n const update: Record<string, unknown> = {}\n update[fieldPath] = defaultValue\n await nativeCollection.updateOne({ _id: doc._id }, { $set: update })\n }\n }\n\n hasMore = docs.length === BATCH_SIZE\n page++\n }\n }\n\n payload.logger.info(\n `[config-migration] Done delocalizing field \"${fieldPath}\" on ${entity} \"${slug}\"`,\n )\n}\n"],"names":["getCollection","getValueAtPath","doc","path","split","reduce","obj","key","BATCH_SIZE","migrateFieldDelocalized","args","slug","defaultLocale","entity","fieldPath","payload","logger","warn","Model","adapter","collectionSlug","nativeCollection","collection","page","hasMore","docs","find","skip","limit","toArray","currentValue","undefined","Array","isArray","defaultValue","update","updateOne","_id","$set","length","info"],"mappings":"AAIA,SAASA,aAAa,QAAQ,2BAA0B;AAExD,SAASC,eAAeC,GAA4B,EAAEC,IAAY;IAChE,OAAOA,KAAKC,KAAK,CAAC,KAAKC,MAAM,CAAC,CAACC,KAAUC,MAAQD,KAAK,CAACC,IAAI,EAAEL;AAC/D;AAEA,MAAMM,aAAa;AAEnB,OAAO,eAAeC,wBAEpBC,IAMC;IAED,MAAM,EAAEC,IAAI,EAAEC,aAAa,EAAEC,MAAM,EAAEC,SAAS,EAAE,GAAGJ;IACnD,MAAM,EAAEK,OAAO,EAAE,GAAG,IAAI;IAExBA,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,uCAAuC,EAAEH,UAAU,KAAK,EAAED,OAAO,EAAE,EAAEF,KAAK,kBAAkB,EAAEC,cAAc,OAAO,CAAC;IAGvH,IAAIC,WAAW,cAAc;QAC3B,MAAM,EAAEK,KAAK,EAAE,GAAGlB,cAAc;YAAEmB,SAAS,IAAI;YAAEC,gBAAgBT;QAAK;QACtE,MAAMU,mBAAmBH,MAAMI,UAAU;QAEzC,IAAIC,OAAO;QACX,IAAIC,UAAU;QAEd,MAAOA,QAAS;YACd,MAAMC,OAAO,MAAMJ,iBAChBK,IAAI,CAAC,CAAC,GACNC,IAAI,CAAC,AAACJ,CAAAA,OAAO,CAAA,IAAKf,YAClBoB,KAAK,CAACpB,YACNqB,OAAO;YAEV,KAAK,MAAM3B,OAAOuB,KAAM;gBACtB,MAAMK,eAAe7B,eAAeC,KAAYY;gBAChD,IACEgB,iBAAiB,QACjBA,iBAAiBC,aACjB,OAAOD,iBAAiB,YACxB,CAACE,MAAMC,OAAO,CAACH,eACf;oBACA,MAAMI,eAAe,AAACJ,YAAwC,CAAClB,cAAc,IAAI;oBACjF,MAAMuB,SAAkC,CAAC;oBACzCA,MAAM,CAACrB,UAAU,GAAGoB;oBACpB,MAAMb,iBAAiBe,SAAS,CAAC;wBAAEC,KAAKnC,IAAImC,GAAG;oBAAC,GAAG;wBAAEC,MAAMH;oBAAO;gBACpE;YACF;YAEAX,UAAUC,KAAKc,MAAM,KAAK/B;YAC1Be;QACF;IACF;IAEAR,QAAQC,MAAM,CAACwB,IAAI,CACjB,CAAC,4CAA4C,EAAE1B,UAAU,KAAK,EAAED,OAAO,EAAE,EAAEF,KAAK,CAAC,CAAC;AAEtF"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
import type { MongooseAdapter } from './index.js';
|
|
3
|
+
export declare function migrateFieldLocalized(this: MongooseAdapter, args: {
|
|
4
|
+
defaultLocale: string;
|
|
5
|
+
entity: 'collection' | 'global';
|
|
6
|
+
fieldPath: string;
|
|
7
|
+
req: PayloadRequest;
|
|
8
|
+
slug: string;
|
|
9
|
+
}): Promise<void>;
|
|
10
|
+
//# sourceMappingURL=migrateFieldLocalized.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrateFieldLocalized.d.ts","sourceRoot":"","sources":["../src/migrateFieldLocalized.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAUjD,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,eAAe,EACrB,IAAI,EAAE;IACJ,aAAa,EAAE,MAAM,CAAA;IACrB,MAAM,EAAE,YAAY,GAAG,QAAQ,CAAA;IAC/B,SAAS,EAAE,MAAM,CAAA;IACjB,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,MAAM,CAAA;CACb,GACA,OAAO,CAAC,IAAI,CAAC,CA8Cf"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { getCollection } from './utilities/getEntity.js';
|
|
2
|
+
function getValueAtPath(doc, path) {
|
|
3
|
+
return path.split('.').reduce((obj, key)=>obj?.[key], doc);
|
|
4
|
+
}
|
|
5
|
+
const BATCH_SIZE = 1000;
|
|
6
|
+
export async function migrateFieldLocalized(args) {
|
|
7
|
+
const { slug, defaultLocale, entity, fieldPath } = args;
|
|
8
|
+
const { payload } = this;
|
|
9
|
+
payload.logger.info(`[config-migration] Localizing field "${fieldPath}" on ${entity} "${slug}" → locale "${defaultLocale}"`);
|
|
10
|
+
if (entity === 'collection') {
|
|
11
|
+
const { Model } = getCollection({
|
|
12
|
+
adapter: this,
|
|
13
|
+
collectionSlug: slug
|
|
14
|
+
});
|
|
15
|
+
const nativeCollection = Model.collection;
|
|
16
|
+
let page = 1;
|
|
17
|
+
let hasMore = true;
|
|
18
|
+
while(hasMore){
|
|
19
|
+
const docs = await nativeCollection.find({}).skip((page - 1) * BATCH_SIZE).limit(BATCH_SIZE).toArray();
|
|
20
|
+
for (const doc of docs){
|
|
21
|
+
const currentValue = getValueAtPath(doc, fieldPath);
|
|
22
|
+
// Skip if already in localized shape
|
|
23
|
+
if (currentValue !== null && currentValue !== undefined && typeof currentValue === 'object' && !Array.isArray(currentValue)) {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
const update = {};
|
|
27
|
+
update[fieldPath] = {
|
|
28
|
+
[defaultLocale]: currentValue
|
|
29
|
+
};
|
|
30
|
+
await nativeCollection.updateOne({
|
|
31
|
+
_id: doc._id
|
|
32
|
+
}, {
|
|
33
|
+
$set: update
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
hasMore = docs.length === BATCH_SIZE;
|
|
37
|
+
page++;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
payload.logger.info(`[config-migration] Done localizing field "${fieldPath}" on ${entity} "${slug}"`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=migrateFieldLocalized.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/migrateFieldLocalized.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getCollection } from './utilities/getEntity.js'\n\nfunction getValueAtPath(doc: Record<string, unknown>, path: string): unknown {\n return path.split('.').reduce((obj: any, key) => obj?.[key], doc)\n}\n\nconst BATCH_SIZE = 1000\n\nexport async function migrateFieldLocalized(\n this: MongooseAdapter,\n args: {\n defaultLocale: string\n entity: 'collection' | 'global'\n fieldPath: string\n req: PayloadRequest\n slug: string\n },\n): Promise<void> {\n const { slug, defaultLocale, entity, fieldPath } = args\n const { payload } = this\n\n payload.logger.info(\n `[config-migration] Localizing field \"${fieldPath}\" on ${entity} \"${slug}\" → locale \"${defaultLocale}\"`,\n )\n\n if (entity === 'collection') {\n const { Model } = getCollection({ adapter: this, collectionSlug: slug })\n const nativeCollection = Model.collection\n\n let page = 1\n let hasMore = true\n\n while (hasMore) {\n const docs = await nativeCollection\n .find({})\n .skip((page - 1) * BATCH_SIZE)\n .limit(BATCH_SIZE)\n .toArray()\n\n for (const doc of docs) {\n const currentValue = getValueAtPath(doc as any, fieldPath)\n // Skip if already in localized shape\n if (\n currentValue !== null &&\n currentValue !== undefined &&\n typeof currentValue === 'object' &&\n !Array.isArray(currentValue)\n ) {\n continue\n }\n const update: Record<string, unknown> = {}\n update[fieldPath] = { [defaultLocale]: currentValue }\n await nativeCollection.updateOne({ _id: doc._id }, { $set: update })\n }\n\n hasMore = docs.length === BATCH_SIZE\n page++\n }\n }\n\n payload.logger.info(\n `[config-migration] Done localizing field \"${fieldPath}\" on ${entity} \"${slug}\"`,\n )\n}\n"],"names":["getCollection","getValueAtPath","doc","path","split","reduce","obj","key","BATCH_SIZE","migrateFieldLocalized","args","slug","defaultLocale","entity","fieldPath","payload","logger","info","Model","adapter","collectionSlug","nativeCollection","collection","page","hasMore","docs","find","skip","limit","toArray","currentValue","undefined","Array","isArray","update","updateOne","_id","$set","length"],"mappings":"AAIA,SAASA,aAAa,QAAQ,2BAA0B;AAExD,SAASC,eAAeC,GAA4B,EAAEC,IAAY;IAChE,OAAOA,KAAKC,KAAK,CAAC,KAAKC,MAAM,CAAC,CAACC,KAAUC,MAAQD,KAAK,CAACC,IAAI,EAAEL;AAC/D;AAEA,MAAMM,aAAa;AAEnB,OAAO,eAAeC,sBAEpBC,IAMC;IAED,MAAM,EAAEC,IAAI,EAAEC,aAAa,EAAEC,MAAM,EAAEC,SAAS,EAAE,GAAGJ;IACnD,MAAM,EAAEK,OAAO,EAAE,GAAG,IAAI;IAExBA,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,qCAAqC,EAAEH,UAAU,KAAK,EAAED,OAAO,EAAE,EAAEF,KAAK,YAAY,EAAEC,cAAc,CAAC,CAAC;IAGzG,IAAIC,WAAW,cAAc;QAC3B,MAAM,EAAEK,KAAK,EAAE,GAAGlB,cAAc;YAAEmB,SAAS,IAAI;YAAEC,gBAAgBT;QAAK;QACtE,MAAMU,mBAAmBH,MAAMI,UAAU;QAEzC,IAAIC,OAAO;QACX,IAAIC,UAAU;QAEd,MAAOA,QAAS;YACd,MAAMC,OAAO,MAAMJ,iBAChBK,IAAI,CAAC,CAAC,GACNC,IAAI,CAAC,AAACJ,CAAAA,OAAO,CAAA,IAAKf,YAClBoB,KAAK,CAACpB,YACNqB,OAAO;YAEV,KAAK,MAAM3B,OAAOuB,KAAM;gBACtB,MAAMK,eAAe7B,eAAeC,KAAYY;gBAChD,qCAAqC;gBACrC,IACEgB,iBAAiB,QACjBA,iBAAiBC,aACjB,OAAOD,iBAAiB,YACxB,CAACE,MAAMC,OAAO,CAACH,eACf;oBACA;gBACF;gBACA,MAAMI,SAAkC,CAAC;gBACzCA,MAAM,CAACpB,UAAU,GAAG;oBAAE,CAACF,cAAc,EAAEkB;gBAAa;gBACpD,MAAMT,iBAAiBc,SAAS,CAAC;oBAAEC,KAAKlC,IAAIkC,GAAG;gBAAC,GAAG;oBAAEC,MAAMH;gBAAO;YACpE;YAEAV,UAAUC,KAAKa,MAAM,KAAK9B;YAC1Be;QACF;IACF;IAEAR,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,0CAA0C,EAAEH,UAAU,KAAK,EAAED,OAAO,EAAE,EAAEF,KAAK,CAAC,CAAC;AAEpF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
import type { MongooseAdapter } from './index.js';
|
|
3
|
+
export declare function migrateVersionsEnabled(this: MongooseAdapter, args: {
|
|
4
|
+
entity: 'collection' | 'global';
|
|
5
|
+
initialStatus: 'draft' | 'published';
|
|
6
|
+
req: PayloadRequest;
|
|
7
|
+
slug: string;
|
|
8
|
+
}): Promise<void>;
|
|
9
|
+
//# sourceMappingURL=migrateVersionsEnabled.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrateVersionsEnabled.d.ts","sourceRoot":"","sources":["../src/migrateVersionsEnabled.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAIjD,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,eAAe,EACrB,IAAI,EAAE;IACJ,MAAM,EAAE,YAAY,GAAG,QAAQ,CAAA;IAC/B,aAAa,EAAE,OAAO,GAAG,WAAW,CAAA;IACpC,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,MAAM,CAAA;CACb,GACA,OAAO,CAAC,IAAI,CAAC,CAsCf"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { batchTransform } from 'payload/migrations';
|
|
2
|
+
const BATCH_SIZE = 1000;
|
|
3
|
+
export async function migrateVersionsEnabled(args) {
|
|
4
|
+
const { slug, entity, initialStatus, req } = args;
|
|
5
|
+
const { payload } = this;
|
|
6
|
+
payload.logger.info(`[config-migration] MongoDB: creating version entries for ${entity} "${slug}" with _status: ${initialStatus}`);
|
|
7
|
+
if (entity === 'collection') {
|
|
8
|
+
await batchTransform({
|
|
9
|
+
batchSize: BATCH_SIZE,
|
|
10
|
+
fetcher: ({ limit, page })=>payload.db.find({
|
|
11
|
+
collection: slug,
|
|
12
|
+
limit,
|
|
13
|
+
page,
|
|
14
|
+
pagination: true,
|
|
15
|
+
req
|
|
16
|
+
}),
|
|
17
|
+
transform: async (doc)=>{
|
|
18
|
+
await payload.db.createVersion({
|
|
19
|
+
autosave: false,
|
|
20
|
+
collectionSlug: slug,
|
|
21
|
+
createdAt: doc.createdAt ?? new Date().toISOString(),
|
|
22
|
+
parent: doc.id,
|
|
23
|
+
req,
|
|
24
|
+
updatedAt: doc.updatedAt ?? new Date().toISOString(),
|
|
25
|
+
versionData: {
|
|
26
|
+
...doc,
|
|
27
|
+
_status: initialStatus
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
} else {
|
|
33
|
+
const globalDoc = await payload.db.findGlobal({
|
|
34
|
+
slug,
|
|
35
|
+
req
|
|
36
|
+
});
|
|
37
|
+
await payload.db.createGlobalVersion({
|
|
38
|
+
autosave: false,
|
|
39
|
+
createdAt: globalDoc.createdAt ?? new Date().toISOString(),
|
|
40
|
+
globalSlug: slug,
|
|
41
|
+
req,
|
|
42
|
+
updatedAt: globalDoc.updatedAt ?? new Date().toISOString(),
|
|
43
|
+
versionData: {
|
|
44
|
+
...globalDoc,
|
|
45
|
+
_status: initialStatus
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
payload.logger.info(`[config-migration] MongoDB: done creating version entries for "${slug}"`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=migrateVersionsEnabled.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/migrateVersionsEnabled.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { batchTransform } from 'payload/migrations'\n\nimport type { MongooseAdapter } from './index.js'\n\nconst BATCH_SIZE = 1000\n\nexport async function migrateVersionsEnabled(\n this: MongooseAdapter,\n args: {\n entity: 'collection' | 'global'\n initialStatus: 'draft' | 'published'\n req: PayloadRequest\n slug: string\n },\n): Promise<void> {\n const { slug, entity, initialStatus, req } = args\n const { payload } = this\n\n payload.logger.info(\n `[config-migration] MongoDB: creating version entries for ${entity} \"${slug}\" with _status: ${initialStatus}`,\n )\n\n if (entity === 'collection') {\n await batchTransform({\n batchSize: BATCH_SIZE,\n fetcher: ({ limit, page }: { limit: number; page: number }) =>\n payload.db.find({ collection: slug, limit, page, pagination: true, req }),\n transform: async (doc: any) => {\n await payload.db.createVersion({\n autosave: false,\n collectionSlug: slug as any,\n createdAt: doc.createdAt ?? new Date().toISOString(),\n parent: doc.id,\n req,\n updatedAt: doc.updatedAt ?? new Date().toISOString(),\n versionData: { ...doc, _status: initialStatus },\n })\n },\n })\n } else {\n const globalDoc = await payload.db.findGlobal({ slug, req })\n await payload.db.createGlobalVersion({\n autosave: false,\n createdAt: globalDoc.createdAt ?? new Date().toISOString(),\n globalSlug: slug as any,\n req,\n updatedAt: globalDoc.updatedAt ?? new Date().toISOString(),\n versionData: { ...globalDoc, _status: initialStatus },\n })\n }\n\n payload.logger.info(`[config-migration] MongoDB: done creating version entries for \"${slug}\"`)\n}\n"],"names":["batchTransform","BATCH_SIZE","migrateVersionsEnabled","args","slug","entity","initialStatus","req","payload","logger","info","batchSize","fetcher","limit","page","db","find","collection","pagination","transform","doc","createVersion","autosave","collectionSlug","createdAt","Date","toISOString","parent","id","updatedAt","versionData","_status","globalDoc","findGlobal","createGlobalVersion","globalSlug"],"mappings":"AAEA,SAASA,cAAc,QAAQ,qBAAoB;AAInD,MAAMC,aAAa;AAEnB,OAAO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|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/queries/buildSearchParams.ts"],"sourcesContent":["import type { FilterQuery } from 'mongoose'\nimport type { FlattenedField, Operator, PathToQuery, Payload } from 'payload'\n\nimport { Types } from 'mongoose'\nimport { APIError, escapeRegExp, getFieldByPath, getLocalizedPaths } from 'payload'\nimport { validOperatorSet } from 'payload/shared'\n\nimport type { MongooseAdapter } from '../index.js'\nimport type { OperatorMapKey } from './operatorMap.js'\n\nimport { getCollection } from '../utilities/getEntity.js'\nimport { isObjectID } from '../utilities/isObjectID.js'\nimport { operatorMap } from './operatorMap.js'\nimport { sanitizeQueryValue } from './sanitizeQueryValue.js'\n\ntype SearchParam = {\n path?: string\n rawQuery?: unknown\n value?: unknown\n}\n\nconst subQueryOptions = {\n lean: true,\n}\n\n/**\n * Convert the Payload key / value / operator into a MongoDB query\n */\nexport async function buildSearchParam({\n collectionSlug,\n fields,\n globalSlug,\n incomingPath,\n locale,\n operator,\n parentIsLocalized,\n payload,\n val,\n}: {\n collectionSlug?: string\n fields: FlattenedField[]\n globalSlug?: string\n incomingPath: string\n locale?: string\n operator: Operator\n parentIsLocalized: boolean\n payload: Payload\n val: unknown\n}): Promise<SearchParam | undefined> {\n // Replace GraphQL nested field double underscore formatting\n let sanitizedPath = incomingPath.replace(/__/g, '.')\n if (sanitizedPath === 'id') {\n sanitizedPath = '_id'\n }\n\n let paths: PathToQuery[] = []\n\n let hasCustomID = false\n\n if (sanitizedPath === '_id') {\n const customIDFieldType = collectionSlug\n ? payload.collections[collectionSlug]?.customIDType\n : undefined\n\n let idFieldType: 'number' | 'text' = 'text'\n\n if (customIDFieldType) {\n idFieldType = customIDFieldType\n hasCustomID = true\n }\n\n paths.push({\n collectionSlug,\n complete: true,\n field: {\n name: 'id',\n type: idFieldType,\n } as FlattenedField,\n parentIsLocalized: parentIsLocalized ?? false,\n path: '_id',\n })\n } else {\n paths = getLocalizedPaths({\n collectionSlug,\n fields,\n globalSlug,\n incomingPath: sanitizedPath,\n locale,\n parentIsLocalized,\n payload,\n })\n }\n\n if (!paths[0]) {\n return undefined\n }\n\n const [{ field, path }] = paths\n if (path) {\n const sanitizedQueryValue = sanitizeQueryValue({\n field,\n hasCustomID,\n locale,\n operator,\n parentIsLocalized,\n path,\n payload,\n val,\n })\n\n if (!sanitizedQueryValue) {\n return undefined\n }\n\n const { operator: formattedOperator, rawQuery, val: formattedValue } = sanitizedQueryValue\n\n if (rawQuery && paths.length === 1) {\n return { value: rawQuery }\n }\n\n if (!formattedOperator) {\n return undefined\n }\n\n // If there are multiple collections to search through,\n // Recursively build up a list of query constraints\n if (paths.length > 1) {\n // Remove top collection and reverse array\n // to work backwards from top\n const pathsToQuery = paths.slice(1).reverse()\n\n let relationshipQuery: SearchParam = {\n value: {},\n }\n\n for (const [i, { collectionSlug, path: subPath }] of pathsToQuery.entries()) {\n if (!collectionSlug) {\n throw new APIError(`Collection with the slug ${collectionSlug} was not found.`)\n }\n\n const { collectionConfig, Model: SubModel } = getCollection({\n adapter: payload.db as MongooseAdapter,\n collectionSlug,\n })\n\n if (i === 0) {\n const subQuery = await SubModel.buildQuery({\n locale,\n payload,\n where: {\n [subPath]: {\n [formattedOperator]: val,\n },\n },\n })\n\n const field = paths[0].field\n\n const select: Record<string, boolean> = {\n _id: true,\n }\n\n let joinPath: null | string = null\n\n if (field.type === 'join') {\n const relationshipField = getFieldByPath({\n fields: collectionConfig.flattenedFields,\n path: field.on,\n })\n if (!relationshipField) {\n throw new APIError('Relationship field was not found')\n }\n\n let path = relationshipField.localizedPath\n if (relationshipField.pathHasLocalized && payload.config.localization) {\n path = path.replace('<locale>', locale || payload.config.localization.defaultLocale)\n }\n select[path] = true\n\n joinPath = path\n }\n\n if (joinPath) {\n select[joinPath] = true\n }\n\n const result = await SubModel.find(subQuery).lean().select(select)\n\n const $in: unknown[] = []\n\n result.forEach((doc: any) => {\n if (joinPath) {\n let ref = doc\n\n for (const segment of joinPath.split('.')) {\n if (Array.isArray(ref)) {\n ref = ref\n .map((item) => (typeof item === 'object' && item ? item[segment] : undefined))\n .flat()\n .filter((item) => item != null)\n } else if (typeof ref === 'object' && ref) {\n ref = ref[segment]\n } else {\n ref = undefined\n break\n }\n }\n\n if (Array.isArray(ref)) {\n for (const item of ref) {\n if (isObjectID(item)) {\n $in.push(item)\n }\n }\n } else if (isObjectID(ref)) {\n $in.push(ref)\n }\n } else {\n const stringID = doc._id.toString()\n $in.push(stringID)\n\n if (Types.ObjectId.isValid(stringID)) {\n $in.push(doc._id)\n }\n }\n })\n\n if (pathsToQuery.length === 1) {\n return {\n path: joinPath ? '_id' : path,\n value: { $in },\n }\n }\n\n const nextSubPath = pathsToQuery[i + 1]?.path\n\n if (nextSubPath) {\n relationshipQuery = { value: { [nextSubPath]: $in } }\n }\n\n continue\n }\n\n const subQuery = relationshipQuery.value as FilterQuery<any>\n const result = await SubModel.find(subQuery, subQueryOptions)\n\n const $in = result.map((doc) => doc._id)\n\n // If it is the last recursion\n // then pass through the search param\n if (i + 1 === pathsToQuery.length) {\n relationshipQuery = {\n path,\n value: { $in },\n }\n } else {\n const nextSubPath = pathsToQuery[i + 1]?.path\n if (nextSubPath) {\n relationshipQuery = {\n value: {\n [nextSubPath]: { $in },\n },\n }\n }\n }\n }\n\n return relationshipQuery\n }\n\n if (formattedOperator && validOperatorSet.has(formattedOperator as Operator)) {\n const operatorKey = operatorMap[formattedOperator as OperatorMapKey]\n\n if (field.type === 'relationship' || field.type === 'upload') {\n let hasNumberIDRelation\n let multiIDCondition = '$or'\n if (operatorKey === '$ne') {\n multiIDCondition = '$and'\n }\n\n const result = {\n value: {\n [multiIDCondition]: [{ [path]: { [operatorKey]: formattedValue } }],\n },\n }\n\n if (typeof formattedValue === 'string') {\n if (Types.ObjectId.isValid(formattedValue)) {\n result.value[multiIDCondition]?.push({\n [path]: { [operatorKey]: new Types.ObjectId(formattedValue) },\n })\n } else {\n ;(Array.isArray(field.relationTo) ? field.relationTo : [field.relationTo]).forEach(\n (relationTo) => {\n const isRelatedToCustomNumberID =\n payload.collections[relationTo]?.customIDType === 'number'\n\n if (isRelatedToCustomNumberID) {\n hasNumberIDRelation = true\n }\n },\n )\n\n if (hasNumberIDRelation) {\n result.value[multiIDCondition]?.push({\n [path]: { [operatorKey]: parseFloat(formattedValue) },\n })\n }\n }\n }\n\n const length = result.value[multiIDCondition]?.length\n\n if (typeof length === 'number' && length > 1) {\n return result\n }\n }\n\n if (formattedOperator === 'like' && typeof formattedValue === 'string') {\n const words = formattedValue.split(' ')\n\n const result = {\n value: {\n $and: words.map((word) => ({\n [path]: {\n $options: 'i',\n $regex: escapeRegExp(word),\n },\n })),\n },\n }\n\n return result\n }\n\n if (formattedOperator === 'not_like' && typeof formattedValue === 'string') {\n const words = formattedValue.split(' ')\n\n const result = {\n value: {\n $and: words.map((word) => ({\n [path]: {\n $not: {\n $options: 'i',\n $regex: escapeRegExp(word),\n },\n },\n })),\n },\n }\n\n return result\n }\n\n // Some operators like 'near' need to define a full query\n // so if there is no operator key, just return the value\n if (!operatorKey) {\n return {\n path,\n value: formattedValue,\n }\n }\n\n return {\n path,\n value: { [operatorKey]: formattedValue },\n }\n }\n }\n return undefined\n}\n"],"names":["Types","APIError","escapeRegExp","getFieldByPath","getLocalizedPaths","validOperatorSet","getCollection","isObjectID","operatorMap","sanitizeQueryValue","subQueryOptions","lean","buildSearchParam","collectionSlug","fields","globalSlug","incomingPath","locale","operator","parentIsLocalized","payload","val","sanitizedPath","replace","paths","hasCustomID","customIDFieldType","collections","customIDType","undefined","idFieldType","push","complete","field","name","type","path","sanitizedQueryValue","formattedOperator","rawQuery","formattedValue","length","value","pathsToQuery","slice","reverse","relationshipQuery","i","subPath","entries","collectionConfig","Model","SubModel","adapter","db","subQuery","buildQuery","where","select","_id","joinPath","relationshipField","flattenedFields","on","localizedPath","pathHasLocalized","config","localization","defaultLocale","result","find","$in","forEach","doc","ref","segment","split","Array","isArray","map","item","flat","filter","stringID","toString","ObjectId","isValid","nextSubPath","has","operatorKey","hasNumberIDRelation","multiIDCondition","relationTo","isRelatedToCustomNumberID","parseFloat","words","$and","word","$options","$regex","$not"],"mappings":"AAGA,SAASA,KAAK,QAAQ,WAAU;AAChC,SAASC,QAAQ,EAAEC,YAAY,EAAEC,cAAc,EAAEC,iBAAiB,QAAQ,UAAS;AACnF,SAASC,gBAAgB,QAAQ,iBAAgB;AAKjD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAQ5D,MAAMC,kBAAkB;IACtBC,MAAM;AACR;AAEA;;CAEC,GACD,OAAO,eAAeC,iBAAiB,EACrCC,cAAc,EACdC,MAAM,EACNC,UAAU,EACVC,YAAY,EACZC,MAAM,EACNC,QAAQ,EACRC,iBAAiB,EACjBC,OAAO,EACPC,GAAG,EAWJ;IACC,4DAA4D;IAC5D,IAAIC,gBAAgBN,aAAaO,OAAO,CAAC,OAAO;IAChD,IAAID,kBAAkB,MAAM;QAC1BA,gBAAgB;IAClB;IAEA,IAAIE,QAAuB,EAAE;IAE7B,IAAIC,cAAc;IAElB,IAAIH,kBAAkB,OAAO;QAC3B,MAAMI,oBAAoBb,iBACtBO,QAAQO,WAAW,CAACd,eAAe,EAAEe,eACrCC;QAEJ,IAAIC,cAAiC;QAErC,IAAIJ,mBAAmB;YACrBI,cAAcJ;YACdD,cAAc;QAChB;QAEAD,MAAMO,IAAI,CAAC;YACTlB;YACAmB,UAAU;YACVC,OAAO;gBACLC,MAAM;gBACNC,MAAML;YACR;YACAX,mBAAmBA,qBAAqB;YACxCiB,MAAM;QACR;IACF,OAAO;QACLZ,QAAQpB,kBAAkB;YACxBS;YACAC;YACAC;YACAC,cAAcM;YACdL;YACAE;YACAC;QACF;IACF;IAEA,IAAI,CAACI,KAAK,CAAC,EAAE,EAAE;QACb,OAAOK;IACT;IAEA,MAAM,CAAC,EAAEI,KAAK,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,KAAK,CAAC;gBAEnC,MAAMP,SAAS;oBACb3B,OAAO;wBACLsD,MAAMD,MAAMhB,GAAG,CAAC,CAACkB,OAAU,CAAA;gCACzB,CAAC7D,KAAK,EAAE;oCACN8D,UAAU;oCACVC,QAAQjG,aAAa+F;gCACvB;4BACF,CAAA;oBACF;gBACF;gBAEA,OAAO5B;YACT;YAEA,IAAI/B,sBAAsB,cAAc,OAAOE,mBAAmB,UAAU;gBAC1E,MAAMuD,QAAQvD,eAAeoC,KAAK,CAAC;gBAEnC,MAAMP,SAAS;oBACb3B,OAAO;wBACLsD,MAAMD,MAAMhB,GAAG,CAAC,CAACkB,OAAU,CAAA;gCACzB,CAAC7D,KAAK,EAAE;oCACNgE,MAAM;wCACJF,UAAU;wCACVC,QAAQjG,aAAa+F;oCACvB;gCACF;4BACF,CAAA;oBACF;gBACF;gBAEA,OAAO5B;YACT;YAEA,yDAAyD;YACzD,wDAAwD;YACxD,IAAI,CAACoB,aAAa;gBAChB,OAAO;oBACLrD;oBACAM,OAAOF;gBACT;YACF;YAEA,OAAO;gBACLJ;gBACAM,OAAO;oBAAE,CAAC+C,YAAY,EAAEjD;gBAAe;YACzC;QACF;IACF;IACA,OAAOX;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../src/queries/buildSearchParams.ts"],"sourcesContent":["import type { FilterQuery } from 'mongoose'\nimport type { FlattenedField, Operator, PathToQuery, Payload } from 'payload'\n\nimport { Types } from 'mongoose'\nimport { APIError, escapeRegExp, getFieldByPath, getLocalizedPaths } from 'payload'\nimport { validOperatorSet } from 'payload/shared'\n\nimport type { MongooseAdapter } from '../index.js'\nimport type { OperatorMapKey } from './operatorMap.js'\n\nimport { getCollection } from '../utilities/getEntity.js'\nimport { isObjectID } from '../utilities/isObjectID.js'\nimport { operatorMap } from './operatorMap.js'\nimport { sanitizeQueryValue } from './sanitizeQueryValue.js'\n\ntype SearchParam = {\n path?: string\n rawQuery?: unknown\n value?: unknown\n}\n\nconst subQueryOptions = {\n lean: true,\n}\n\n/**\n * Convert the Payload key / value / operator into a MongoDB query\n */\nexport async function buildSearchParam({\n collectionSlug,\n fields,\n globalSlug,\n incomingPath,\n locale,\n operator,\n parentIsLocalized,\n payload,\n val,\n}: {\n collectionSlug?: string\n fields: FlattenedField[]\n globalSlug?: string\n incomingPath: string\n locale?: string\n operator: Operator\n parentIsLocalized: boolean\n payload: Payload\n val: unknown\n}): Promise<SearchParam | undefined> {\n // Replace GraphQL nested field double underscore formatting\n let sanitizedPath = incomingPath.replace(/__/g, '.')\n if (sanitizedPath === 'id') {\n sanitizedPath = '_id'\n }\n\n let paths: PathToQuery[] = []\n\n let hasCustomID = false\n\n if (sanitizedPath === '_id') {\n const customIDFieldType = collectionSlug\n ? payload.collections[collectionSlug]?.customIDType\n : undefined\n\n let idFieldType: 'number' | 'text' = 'text'\n\n if (customIDFieldType) {\n idFieldType = customIDFieldType\n hasCustomID = true\n }\n\n paths.push({\n collectionSlug,\n complete: true,\n field: {\n name: 'id',\n type: idFieldType,\n } as FlattenedField,\n parentIsLocalized: parentIsLocalized ?? false,\n path: '_id',\n })\n } else {\n paths = getLocalizedPaths({\n collectionSlug,\n fields,\n globalSlug,\n incomingPath: sanitizedPath,\n locale,\n parentIsLocalized,\n payload,\n })\n }\n\n if (!paths[0]) {\n return undefined\n }\n\n const [{ field, path }] = paths\n if (path) {\n const sanitizedQueryValue = sanitizeQueryValue({\n field,\n hasCustomID,\n locale,\n operator,\n parentIsLocalized,\n path,\n payload,\n val,\n })\n\n if (!sanitizedQueryValue) {\n return undefined\n }\n\n const { operator: formattedOperator, rawQuery, val: formattedValue } = sanitizedQueryValue\n\n if (rawQuery && paths.length === 1) {\n return { value: rawQuery }\n }\n\n if (!formattedOperator) {\n return undefined\n }\n\n // If there are multiple collections to search through,\n // Recursively build up a list of query constraints\n if (paths.length > 1) {\n // Remove top collection and reverse array\n // to work backwards from top\n const pathsToQuery = paths.slice(1).reverse()\n\n let relationshipQuery: SearchParam = {\n value: {},\n }\n\n for (const [i, { collectionSlug, path: subPath }] of pathsToQuery.entries()) {\n if (!collectionSlug) {\n throw new APIError(`Collection with the slug ${collectionSlug} was not found.`)\n }\n\n const { collectionConfig, Model: SubModel } = getCollection({\n adapter: payload.db as MongooseAdapter,\n collectionSlug,\n })\n\n if (i === 0) {\n const subQuery = await SubModel.buildQuery({\n locale,\n payload,\n where: {\n [subPath]: {\n [formattedOperator]: val,\n },\n },\n })\n\n const field = paths[0].field\n\n const select: Record<string, boolean> = {\n _id: true,\n }\n\n let joinPath: null | string = null\n\n if (field.type === 'join') {\n const relationshipField = getFieldByPath({\n fields: collectionConfig.flattenedFields,\n path: field.on,\n })\n if (!relationshipField) {\n throw new APIError('Relationship field was not found')\n }\n\n let path = relationshipField.localizedPath\n if (relationshipField.pathHasLocalized && payload.config.localization) {\n path = path.replace('<locale>', locale || payload.config.localization.defaultLocale)\n }\n select[path] = true\n\n joinPath = path\n }\n\n if (joinPath) {\n select[joinPath] = true\n }\n\n const result = await SubModel.find(subQuery).lean().select(select)\n\n const $in: unknown[] = []\n\n result.forEach((doc: any) => {\n if (joinPath) {\n let ref = doc\n\n for (const segment of joinPath.split('.')) {\n if (Array.isArray(ref)) {\n ref = ref\n .map((item) => (typeof item === 'object' && item ? item[segment] : undefined))\n .flat()\n .filter((item) => item != null)\n } else if (typeof ref === 'object' && ref) {\n ref = ref[segment]\n } else {\n ref = undefined\n break\n }\n }\n\n if (Array.isArray(ref)) {\n for (const item of ref) {\n if (isObjectID(item)) {\n $in.push(item)\n }\n }\n } else if (isObjectID(ref)) {\n $in.push(ref)\n }\n } else {\n const stringID = doc._id.toString()\n if (Types.ObjectId.isValid(stringID)) {\n $in.push(doc._id)\n } else {\n $in.push(stringID)\n }\n }\n })\n\n if (pathsToQuery.length === 1) {\n return {\n path: joinPath ? '_id' : path,\n value: { $in },\n }\n }\n\n const nextSubPath = pathsToQuery[i + 1]?.path\n\n if (nextSubPath) {\n relationshipQuery = { value: { [nextSubPath]: $in } }\n }\n\n continue\n }\n\n const subQuery = relationshipQuery.value as FilterQuery<any>\n const result = await SubModel.find(subQuery, subQueryOptions)\n\n const $in = result.map((doc) => doc._id)\n\n // If it is the last recursion\n // then pass through the search param\n if (i + 1 === pathsToQuery.length) {\n relationshipQuery = {\n path,\n value: { $in },\n }\n } else {\n const nextSubPath = pathsToQuery[i + 1]?.path\n if (nextSubPath) {\n relationshipQuery = {\n value: {\n [nextSubPath]: { $in },\n },\n }\n }\n }\n }\n\n return relationshipQuery\n }\n\n if (formattedOperator && validOperatorSet.has(formattedOperator as Operator)) {\n const operatorKey = operatorMap[formattedOperator as OperatorMapKey]\n\n if (field.type === 'relationship' || field.type === 'upload') {\n let hasNumberIDRelation\n let multiIDCondition = '$or'\n if (operatorKey === '$ne') {\n multiIDCondition = '$and'\n }\n\n const result = {\n value: {\n [multiIDCondition]: [{ [path]: { [operatorKey]: formattedValue } }],\n },\n }\n\n if (typeof formattedValue === 'string') {\n if (Types.ObjectId.isValid(formattedValue)) {\n result.value[multiIDCondition]?.push({\n [path]: { [operatorKey]: new Types.ObjectId(formattedValue) },\n })\n } else {\n ;(Array.isArray(field.relationTo) ? field.relationTo : [field.relationTo]).forEach(\n (relationTo) => {\n const isRelatedToCustomNumberID =\n payload.collections[relationTo]?.customIDType === 'number'\n\n if (isRelatedToCustomNumberID) {\n hasNumberIDRelation = true\n }\n },\n )\n\n if (hasNumberIDRelation) {\n result.value[multiIDCondition]?.push({\n [path]: { [operatorKey]: parseFloat(formattedValue) },\n })\n }\n }\n }\n\n const length = result.value[multiIDCondition]?.length\n\n if (typeof length === 'number' && length > 1) {\n return result\n }\n }\n\n if (formattedOperator === 'like' && typeof formattedValue === 'string') {\n const words = formattedValue.split(' ')\n\n const result = {\n value: {\n $and: words.map((word) => ({\n [path]: {\n $options: 'i',\n $regex: escapeRegExp(word),\n },\n })),\n },\n }\n\n return result\n }\n\n if (formattedOperator === 'not_like' && typeof formattedValue === 'string') {\n const words = formattedValue.split(' ')\n\n const result = {\n value: {\n $and: words.map((word) => ({\n [path]: {\n $not: {\n $options: 'i',\n $regex: escapeRegExp(word),\n },\n },\n })),\n },\n }\n\n return result\n }\n\n // Some operators like 'near' need to define a full query\n // so if there is no operator key, just return the value\n if (!operatorKey) {\n return {\n path,\n value: formattedValue,\n }\n }\n\n return {\n path,\n value: { [operatorKey]: formattedValue },\n }\n }\n }\n return undefined\n}\n"],"names":["Types","APIError","escapeRegExp","getFieldByPath","getLocalizedPaths","validOperatorSet","getCollection","isObjectID","operatorMap","sanitizeQueryValue","subQueryOptions","lean","buildSearchParam","collectionSlug","fields","globalSlug","incomingPath","locale","operator","parentIsLocalized","payload","val","sanitizedPath","replace","paths","hasCustomID","customIDFieldType","collections","customIDType","undefined","idFieldType","push","complete","field","name","type","path","sanitizedQueryValue","formattedOperator","rawQuery","formattedValue","length","value","pathsToQuery","slice","reverse","relationshipQuery","i","subPath","entries","collectionConfig","Model","SubModel","adapter","db","subQuery","buildQuery","where","select","_id","joinPath","relationshipField","flattenedFields","on","localizedPath","pathHasLocalized","config","localization","defaultLocale","result","find","$in","forEach","doc","ref","segment","split","Array","isArray","map","item","flat","filter","stringID","toString","ObjectId","isValid","nextSubPath","has","operatorKey","hasNumberIDRelation","multiIDCondition","relationTo","isRelatedToCustomNumberID","parseFloat","words","$and","word","$options","$regex","$not"],"mappings":"AAGA,SAASA,KAAK,QAAQ,WAAU;AAChC,SAASC,QAAQ,EAAEC,YAAY,EAAEC,cAAc,EAAEC,iBAAiB,QAAQ,UAAS;AACnF,SAASC,gBAAgB,QAAQ,iBAAgB;AAKjD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAQ5D,MAAMC,kBAAkB;IACtBC,MAAM;AACR;AAEA;;CAEC,GACD,OAAO,eAAeC,iBAAiB,EACrCC,cAAc,EACdC,MAAM,EACNC,UAAU,EACV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AAa+F;oCACvB;gCACF;4BACF,CAAA;oBACF;gBACF;gBAEA,OAAO5B;YACT;YAEA,yDAAyD;YACzD,wDAAwD;YACxD,IAAI,CAACoB,aAAa;gBAChB,OAAO;oBACLrD;oBACAM,OAAOF;gBACT;YACF;YAEA,OAAO;gBACLJ;gBACAM,OAAO;oBAAE,CAAC+C,YAAY,EAAEjD;gBAAe;YACzC;QACF;IACF;IACA,OAAOX;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/db-mongodb",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0-internal.38b7f1d",
|
|
4
4
|
"description": "The officially supported MongoDB database adapter for Payload",
|
|
5
5
|
"homepage": "https://payloadcms.com",
|
|
6
6
|
"repository": {
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"mongoose": "8.15.1",
|
|
47
47
|
"mongoose-paginate-v2": "1.9.4",
|
|
48
48
|
"prompts": "2.4.2",
|
|
49
|
-
"uuid": "
|
|
49
|
+
"uuid": "14.0.0"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@types/mongoose-aggregate-paginate-v2": "1.0.12",
|
|
@@ -54,10 +54,10 @@
|
|
|
54
54
|
"mongodb": "6.16.0",
|
|
55
55
|
"mongodb-memory-server": "10.1.4",
|
|
56
56
|
"@payloadcms/eslint-config": "3.28.0",
|
|
57
|
-
"payload": "
|
|
57
|
+
"payload": "4.0.0-internal.38b7f1d"
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
60
|
-
"payload": "
|
|
60
|
+
"payload": "4.0.0-internal.38b7f1d"
|
|
61
61
|
},
|
|
62
62
|
"scripts": {
|
|
63
63
|
"build": "pnpm build:types && pnpm build:swc",
|