@payloadcms/figma 0.0.1-alpha.42 → 0.0.1-alpha.44
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/constants.d.ts +1 -1
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +19 -4
- package/dist/constants.js.map +1 -1
- package/dist/db-content-api/generated/content-api-types.d.ts +6 -174
- package/dist/db-content-api/generated/content-api-types.d.ts.map +1 -1
- package/dist/db-content-api/generated/content-api-types.js.map +1 -1
- package/dist/db-content-api/index.d.ts +2 -0
- package/dist/db-content-api/index.d.ts.map +1 -1
- package/dist/db-content-api/index.js +135 -44
- package/dist/db-content-api/index.js.map +1 -1
- package/dist/db-content-api/utilities/data/castFieldValue.d.ts.map +1 -1
- package/dist/db-content-api/utilities/data/castFieldValue.js +4 -1
- package/dist/db-content-api/utilities/data/castFieldValue.js.map +1 -1
- package/dist/db-content-api/utilities/data/index.d.ts.map +1 -1
- package/dist/db-content-api/utilities/data/index.js +16 -2
- package/dist/db-content-api/utilities/data/index.js.map +1 -1
- package/dist/db-content-api/utilities/locale/index.d.ts +10 -0
- package/dist/db-content-api/utilities/locale/index.d.ts.map +1 -0
- package/dist/db-content-api/utilities/locale/index.js +21 -0
- package/dist/db-content-api/utilities/locale/index.js.map +1 -0
- package/dist/db-content-api/utilities/meta/buildLocalizedPaths.d.ts +11 -0
- package/dist/db-content-api/utilities/meta/buildLocalizedPaths.d.ts.map +1 -0
- package/dist/db-content-api/utilities/meta/buildLocalizedPaths.js +55 -0
- package/dist/db-content-api/utilities/meta/buildLocalizedPaths.js.map +1 -0
- package/dist/db-content-api/utilities/meta/buildMeta.d.ts +22 -0
- package/dist/db-content-api/utilities/meta/buildMeta.d.ts.map +1 -0
- package/dist/db-content-api/utilities/meta/buildMeta.js +30 -0
- package/dist/db-content-api/utilities/meta/buildMeta.js.map +1 -0
- package/dist/db-content-api/utilities/meta/buildPathTypes.d.ts +7 -0
- package/dist/db-content-api/utilities/meta/buildPathTypes.d.ts.map +1 -0
- package/dist/db-content-api/utilities/{buildPathTypes.js → meta/buildPathTypes.js} +3 -9
- package/dist/db-content-api/utilities/meta/buildPathTypes.js.map +1 -0
- package/dist/db-content-api/utilities/meta/index.d.ts +5 -0
- package/dist/db-content-api/utilities/meta/index.d.ts.map +1 -0
- package/dist/db-content-api/utilities/meta/index.js +5 -0
- package/dist/db-content-api/utilities/meta/index.js.map +1 -0
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.d.ts.map +1 -1
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.js +3 -3
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.js.map +1 -1
- package/dist/storage-content-api/client-uploads/generateSignedURL.d.ts.map +1 -1
- package/dist/storage-content-api/client-uploads/generateSignedURL.js +8 -1
- package/dist/storage-content-api/client-uploads/generateSignedURL.js.map +1 -1
- package/dist/storage-content-api/utilities/getSafeFilename.d.ts +12 -0
- package/dist/storage-content-api/utilities/getSafeFilename.d.ts.map +1 -0
- package/dist/storage-content-api/utilities/getSafeFilename.js +61 -0
- package/dist/storage-content-api/utilities/getSafeFilename.js.map +1 -0
- package/dist/storage-content-api/utilities/index.d.ts +2 -0
- package/dist/storage-content-api/utilities/index.d.ts.map +1 -0
- package/dist/storage-content-api/utilities/index.js +3 -0
- package/dist/storage-content-api/utilities/index.js.map +1 -0
- package/dist/templates/.env.example +11 -0
- package/dist/utils/env-management.d.ts +9 -1
- package/dist/utils/env-management.d.ts.map +1 -1
- package/dist/utils/env-management.js +39 -17
- package/dist/utils/env-management.js.map +1 -1
- package/dist/utils/payload-config-ast.d.ts.map +1 -1
- package/dist/utils/payload-config-ast.js +7 -0
- package/dist/utils/payload-config-ast.js.map +1 -1
- package/dist/utils/project.d.ts.map +1 -1
- package/dist/utils/project.js +3 -0
- package/dist/utils/project.js.map +1 -1
- package/package.json +2 -2
- package/dist/db-content-api/utilities/buildPathTypes.d.ts +0 -12
- package/dist/db-content-api/utilities/buildPathTypes.d.ts.map +0 -1
- package/dist/db-content-api/utilities/buildPathTypes.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/db-content-api/utilities/data/castFieldValue.ts"],"sourcesContent":["import type { Field, TabAsField } from 'payload'\n\n/**\n * Cast field values to the appropriate type for Content API storage.\n *\n * This function implements type coercion similar to Mongoose (used by MongoDB adapter)\n * to ensure data consistency. When users ignore TypeScript types and pass incorrect types,\n * we automatically convert them to the expected type.\n *\n */\nexport function castFieldValue(field: Field | TabAsField, value: unknown): unknown {\n if (value === null || value === undefined) {\n return value\n }\n\n if (field.type === 'number') {\n // Handle hasMany: true - array of numbers\n if ('hasMany' in field && field.hasMany && Array.isArray(value)) {\n return value.map((item) => {\n if (typeof item === 'number') {\n return item\n }\n if (typeof item === 'string' || typeof item === 'boolean') {\n return Number(item)\n }\n return item // Pass through other types (will likely fail validation)\n })\n }\n\n // Handle single number\n if (typeof value !== 'number') {\n if (typeof value === 'string' || typeof value === 'boolean') {\n return Number(value)\n }\n // For objects/arrays (when not hasMany), return as-is (will likely fail validation later)\n return value\n }\n }\n\n if (field.type === 'checkbox' && typeof value !== 'boolean') {\n if (typeof value === 'string') {\n if (value.toLowerCase() === 'true' || value === '1') {\n return true\n }\n if (value.toLowerCase() === 'false' || value === '0' || value === '') {\n return false\n }\n }\n return Boolean(value)\n }\n\n // Matches Mongoose behavior: stores dates as ISO strings\n if (field.type === 'date' && typeof value !== 'string') {\n if (value instanceof Date) {\n return value.toISOString()\n }\n if (typeof value === 'number') {\n return new Date(value).toISOString()\n }\n // For other types, return as-is (will likely fail validation)\n return value\n }\n\n // Text-like fields: convert non-strings to JSON strings\n // This handles text, textarea, email, and code fields\n if (\n (field.type === 'text' ||\n field.type === 'textarea' ||\n field.type === 'email' ||\n field.type === 'code') &&\n typeof value !== 'string'\n ) {\n return JSON.stringify(value)\n }\n\n // No casting needed for other types or already correct types\n return value\n}\n"],"names":["castFieldValue","field","value","undefined","type","hasMany","Array","isArray","map","item","Number","toLowerCase","Boolean","Date","toISOString","JSON","stringify"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,SAASA,eAAeC,KAAyB,EAAEC,KAAc;IACtE,IAAIA,UAAU,QAAQA,UAAUC,WAAW;QACzC,OAAOD;IACT;IAEA,IAAID,MAAMG,IAAI,KAAK,UAAU;QAC3B,0CAA0C;QAC1C,IAAI,aAAaH,SAASA,MAAMI,OAAO,IAAIC,MAAMC,OAAO,CAACL,QAAQ;YAC/D,OAAOA,MAAMM,GAAG,CAAC,CAACC;gBAChB,IAAI,OAAOA,SAAS,UAAU;oBAC5B,OAAOA;gBACT;gBACA,IAAI,OAAOA,SAAS,YAAY,OAAOA,SAAS,WAAW;oBACzD,OAAOC,OAAOD;gBAChB;gBACA,OAAOA,KAAK,yDAAyD;;YACvE;QACF;QAEA,uBAAuB;QACvB,IAAI,OAAOP,UAAU,UAAU;YAC7B,IAAI,OAAOA,UAAU,YAAY,OAAOA,UAAU,WAAW;gBAC3D,OAAOQ,OAAOR;YAChB;YACA,0FAA0F;YAC1F,OAAOA;QACT;IACF;IAEA,IAAID,MAAMG,IAAI,KAAK,cAAc,OAAOF,UAAU,WAAW;QAC3D,IAAI,OAAOA,UAAU,UAAU;YAC7B,IAAIA,MAAMS,WAAW,OAAO,UAAUT,UAAU,KAAK;gBACnD,OAAO;YACT;YACA,IAAIA,MAAMS,WAAW,OAAO,WAAWT,UAAU,OAAOA,UAAU,IAAI;gBACpE,OAAO;YACT;QACF;QACA,OAAOU,QAAQV;IACjB;IAEA,yDAAyD;IACzD,IAAID,MAAMG,IAAI,KAAK,UAAU,OAAOF,UAAU,UAAU;QACtD,IAAIA,iBAAiBW,MAAM;YACzB,OAAOX,MAAMY,WAAW;QAC1B;QACA,IAAI,OAAOZ,UAAU,UAAU;YAC7B,OAAO,IAAIW,KAAKX,OAAOY,WAAW;QACpC;QACA,8DAA8D;QAC9D,OAAOZ;IACT;IAEA,wDAAwD;IACxD,sDAAsD;IACtD,IACE,AAACD,CAAAA,MAAMG,IAAI,KAAK,UACdH,MAAMG,IAAI,KAAK,cACfH,MAAMG,IAAI,KAAK,WACfH,MAAMG,IAAI,KAAK,MAAK,KACtB,OAAOF,UAAU,
|
|
1
|
+
{"version":3,"sources":["../../../../src/db-content-api/utilities/data/castFieldValue.ts"],"sourcesContent":["import type { Field, TabAsField } from 'payload'\n\n/**\n * Cast field values to the appropriate type for Content API storage.\n *\n * This function implements type coercion similar to Mongoose (used by MongoDB adapter)\n * to ensure data consistency. When users ignore TypeScript types and pass incorrect types,\n * we automatically convert them to the expected type.\n *\n */\nexport function castFieldValue(field: Field | TabAsField, value: unknown): unknown {\n if (value === null || value === undefined) {\n return value\n }\n\n if (field.type === 'number') {\n // Handle hasMany: true - array of numbers\n if ('hasMany' in field && field.hasMany && Array.isArray(value)) {\n return value.map((item) => {\n if (typeof item === 'number') {\n return item\n }\n if (typeof item === 'string' || typeof item === 'boolean') {\n return Number(item)\n }\n return item // Pass through other types (will likely fail validation)\n })\n }\n\n // Handle single number\n if (typeof value !== 'number') {\n if (typeof value === 'string' || typeof value === 'boolean') {\n return Number(value)\n }\n // For objects/arrays (when not hasMany), return as-is (will likely fail validation later)\n return value\n }\n }\n\n if (field.type === 'checkbox' && typeof value !== 'boolean') {\n if (typeof value === 'string') {\n if (value.toLowerCase() === 'true' || value === '1') {\n return true\n }\n if (value.toLowerCase() === 'false' || value === '0' || value === '') {\n return false\n }\n }\n return Boolean(value)\n }\n\n // Matches Mongoose behavior: stores dates as ISO strings\n if (field.type === 'date' && typeof value !== 'string') {\n if (value instanceof Date) {\n return value.toISOString()\n }\n if (typeof value === 'number') {\n return new Date(value).toISOString()\n }\n // For other types, return as-is (will likely fail validation)\n return value\n }\n\n // Text-like fields: convert non-strings to JSON strings\n // This handles text, textarea, email, and code fields\n // EXCEPTIONS:\n // - Localized fields are stored as objects like {\"en\": \"value\", \"es\": \"valor\"}\n // - hasMany fields are stored as arrays like [\"value1\", \"value2\"]\n if (\n (field.type === 'text' ||\n field.type === 'textarea' ||\n field.type === 'email' ||\n field.type === 'code') &&\n typeof value !== 'string' &&\n !('localized' in field && field.localized) &&\n !('hasMany' in field && field.hasMany && Array.isArray(value))\n ) {\n return JSON.stringify(value)\n }\n\n // No casting needed for other types or already correct types\n return value\n}\n"],"names":["castFieldValue","field","value","undefined","type","hasMany","Array","isArray","map","item","Number","toLowerCase","Boolean","Date","toISOString","localized","JSON","stringify"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,SAASA,eAAeC,KAAyB,EAAEC,KAAc;IACtE,IAAIA,UAAU,QAAQA,UAAUC,WAAW;QACzC,OAAOD;IACT;IAEA,IAAID,MAAMG,IAAI,KAAK,UAAU;QAC3B,0CAA0C;QAC1C,IAAI,aAAaH,SAASA,MAAMI,OAAO,IAAIC,MAAMC,OAAO,CAACL,QAAQ;YAC/D,OAAOA,MAAMM,GAAG,CAAC,CAACC;gBAChB,IAAI,OAAOA,SAAS,UAAU;oBAC5B,OAAOA;gBACT;gBACA,IAAI,OAAOA,SAAS,YAAY,OAAOA,SAAS,WAAW;oBACzD,OAAOC,OAAOD;gBAChB;gBACA,OAAOA,KAAK,yDAAyD;;YACvE;QACF;QAEA,uBAAuB;QACvB,IAAI,OAAOP,UAAU,UAAU;YAC7B,IAAI,OAAOA,UAAU,YAAY,OAAOA,UAAU,WAAW;gBAC3D,OAAOQ,OAAOR;YAChB;YACA,0FAA0F;YAC1F,OAAOA;QACT;IACF;IAEA,IAAID,MAAMG,IAAI,KAAK,cAAc,OAAOF,UAAU,WAAW;QAC3D,IAAI,OAAOA,UAAU,UAAU;YAC7B,IAAIA,MAAMS,WAAW,OAAO,UAAUT,UAAU,KAAK;gBACnD,OAAO;YACT;YACA,IAAIA,MAAMS,WAAW,OAAO,WAAWT,UAAU,OAAOA,UAAU,IAAI;gBACpE,OAAO;YACT;QACF;QACA,OAAOU,QAAQV;IACjB;IAEA,yDAAyD;IACzD,IAAID,MAAMG,IAAI,KAAK,UAAU,OAAOF,UAAU,UAAU;QACtD,IAAIA,iBAAiBW,MAAM;YACzB,OAAOX,MAAMY,WAAW;QAC1B;QACA,IAAI,OAAOZ,UAAU,UAAU;YAC7B,OAAO,IAAIW,KAAKX,OAAOY,WAAW;QACpC;QACA,8DAA8D;QAC9D,OAAOZ;IACT;IAEA,wDAAwD;IACxD,sDAAsD;IACtD,cAAc;IACd,+EAA+E;IAC/E,kEAAkE;IAClE,IACE,AAACD,CAAAA,MAAMG,IAAI,KAAK,UACdH,MAAMG,IAAI,KAAK,cACfH,MAAMG,IAAI,KAAK,WACfH,MAAMG,IAAI,KAAK,MAAK,KACtB,OAAOF,UAAU,YACjB,CAAE,CAAA,eAAeD,SAASA,MAAMc,SAAS,AAAD,KACxC,CAAE,CAAA,aAAad,SAASA,MAAMI,OAAO,IAAIC,MAAMC,OAAO,CAACL,MAAK,GAC5D;QACA,OAAOc,KAAKC,SAAS,CAACf;IACxB;IAEA,6DAA6D;IAC7D,OAAOA;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/db-content-api/utilities/data/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkC,OAAO,EAA0B,MAAM,SAAS,CAAA;AAI9F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sCAAsC,CAAA;AAOtE,KAAK,kBAAkB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,oBAAoB,CAAC,CAAA;AAErE;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,OAAO,EACb,OAAO,CAAC,EAAE;IAAE,aAAa,CAAC,EAAE,OAAO,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,GACzD,kBAAkB,CA8EpB;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,OAAO,GACZ,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/db-content-api/utilities/data/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkC,OAAO,EAA0B,MAAM,SAAS,CAAA;AAI9F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sCAAsC,CAAA;AAOtE,KAAK,kBAAkB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,oBAAoB,CAAC,CAAA;AAErE;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,OAAO,EACb,OAAO,CAAC,EAAE;IAAE,aAAa,CAAC,EAAE,OAAO,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,GACzD,kBAAkB,CA8EpB;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,OAAO,GACZ,OAAO,CAyGT"}
|
|
@@ -130,8 +130,21 @@ import { stripFields } from './stripFields.js';
|
|
|
130
130
|
return;
|
|
131
131
|
}
|
|
132
132
|
if (value !== null) {
|
|
133
|
-
//
|
|
134
|
-
|
|
133
|
+
// Localized fields: JSON string -> parsed object
|
|
134
|
+
// Content API may store localized fields as JSON strings like "{\"en\":\"value\"}"
|
|
135
|
+
// so we need to parse them back to objects.
|
|
136
|
+
// Note: We return the full locale object - Payload Core handles flattening to requested locale.
|
|
137
|
+
if ('localized' in field && field.localized && typeof value === 'string') {
|
|
138
|
+
try {
|
|
139
|
+
current[field.name] = JSON.parse(value);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
const fieldPath = parentPath ? `${parentPath}.${field.name}` : field.name;
|
|
142
|
+
payload.logger.warn({
|
|
143
|
+
err: error instanceof Error ? error : new Error(String(error)),
|
|
144
|
+
msg: `Failed to parse localized field '${fieldPath}' in collection '${collectionSlug}'`
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
} else if (field.type === 'richText' && typeof value === 'string') {
|
|
135
148
|
try {
|
|
136
149
|
current[field.name] = JSON.parse(value);
|
|
137
150
|
} catch (error) {
|
|
@@ -148,6 +161,7 @@ import { stripFields } from './stripFields.js';
|
|
|
148
161
|
traverseFields({
|
|
149
162
|
callback,
|
|
150
163
|
fields: collectionConfig.fields,
|
|
164
|
+
fillEmpty: false,
|
|
151
165
|
ref: transformed
|
|
152
166
|
});
|
|
153
167
|
// Convert string ID to number if collection uses numeric custom ID
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/db-content-api/utilities/data/index.ts"],"sourcesContent":["import type { CollectionConfig, GlobalConfig, Payload, TraverseFieldsCallback } from 'payload'\n\nimport { flattenAllFields, traverseFields } from 'payload'\n\nimport type { components } from '../../generated/content-api-types.js'\n\nimport { applyDefaults } from './applyDefaults.js'\nimport { castFieldValue } from './castFieldValue.js'\nimport { removeVirtualFields } from './removeVirtualFields.js'\nimport { stripFields } from './stripFields.js'\n\ntype DataWithOperations = components['schemas']['DataWithOperations']\n\n/**\n * Transform data before sending to Content API (WRITE operations)\n *\n * Conversions applied:\n * - Default values: Apply static defaults for undefined fields (when applyDefaults=true)\n * - Type casting: Convert values to match field types (e.g., number -> string for text fields)\n * - RichText fields: Objects -> JSON strings\n * - Virtual fields: Remove fields with `virtual: true` (pure virtual fields should never be saved)\n * - Timestamps: Add updatedAt (always), and createdAt (when createdAt=true)\n *\n * Note: Date fields are automatically converted to ISO strings by JSON.stringify()\n */\nexport function dataToContentAPI(\n payload: Payload,\n collectionSlug: string,\n data: unknown,\n options?: { applyDefaults?: boolean; createdAt?: boolean },\n): DataWithOperations {\n if (!data || typeof data !== 'object') {\n return data as DataWithOperations\n }\n\n // Deep clone to avoid mutating original data\n const transformed = JSON.parse(JSON.stringify(data))\n\n // Get collection config\n const isGlobal = collectionSlug.startsWith('_global-')\n const actualSlug = isGlobal ? collectionSlug.substring(8) : collectionSlug\n const collectionConfig: CollectionConfig | GlobalConfig | undefined = isGlobal\n ? payload.config.globals?.find((g) => g.slug === actualSlug)\n : payload.config.collections.find((c) => c.slug === actualSlug)\n\n if (!collectionConfig?.fields) {\n return transformed as DataWithOperations\n }\n\n // Apply static defaults recursively to handle nested structures (arrays, groups)\n // This must happen before traverseFields to ensure defaults are in place\n if (options?.applyDefaults) {\n applyDefaults(transformed, collectionConfig.fields)\n }\n\n // Use Payload's traverseFields to iterate over all fields for transformations\n const callback: TraverseFieldsCallback = ({ field, ref }) => {\n if (!('name' in field) || !field.name) {\n return\n }\n if (!ref || typeof ref !== 'object') {\n return\n }\n\n const current = ref as Record<string, unknown>\n let value = current[field.name]\n\n // Transform existing values\n if (value !== null && value !== undefined) {\n // Step 1: Apply type casting (e.g., number -> string for text fields)\n value = castFieldValue(field, value)\n current[field.name] = value\n\n // Step 2: Apply Content API specific transformations\n // RichText: object -> JSON string\n if (field.type === 'richText' && typeof value !== 'string') {\n current[field.name] = JSON.stringify(value)\n }\n // Date fields are already handled by JSON.stringify() which converts Date -> ISO string\n }\n }\n\n traverseFields({ callback, fields: collectionConfig.fields, fillEmpty: false, ref: transformed })\n\n stripFields({\n config: payload.config,\n data: transformed,\n fields: flattenAllFields({ cache: true, fields: collectionConfig.fields }),\n reservedKeys: ['id', 'globalType'],\n })\n\n removeVirtualFields(transformed, collectionConfig.fields)\n\n // Convert numeric ID to string for Content API\n const customIDType = payload.collections?.[collectionSlug]?.customIDType\n if (customIDType === 'number') {\n transformed.id = String(transformed.id)\n }\n\n // Add timestamps (Content API no longer auto-sets these in DB)\n // updatedAt is always set, createdAt only on create operations\n const now = new Date().toISOString()\n transformed.updatedAt = now\n if (options?.createdAt) {\n transformed.createdAt = now\n }\n\n return transformed as DataWithOperations\n}\n\n/**\n * Transform data received from Content API (READ operations)\n *\n * Conversions applied:\n * - RichText fields: JSON strings -> Objects\n * - Virtual fields: Remove fields with `virtual: true` (should not be in DB but Content API backend may add them)\n *\n * Note: Date fields come as ISO strings from Content API and stay as strings\n * (matching MongoDB and other adapters' behavior)\n */\nexport function dataFromContentAPI(\n payload: Payload,\n collectionSlug: string,\n data: unknown,\n): unknown {\n if (!data || typeof data !== 'object') {\n return data\n }\n\n // Deep clone to avoid mutating original data\n const transformed = JSON.parse(JSON.stringify(data))\n\n // Get collection config\n const isGlobal = collectionSlug.startsWith('_global-')\n const actualSlug = isGlobal ? collectionSlug.substring(8) : collectionSlug\n const collectionConfig: CollectionConfig | GlobalConfig | undefined = isGlobal\n ? payload.config.globals?.find((g) => g.slug === actualSlug)\n : payload.config.collections.find((c) => c.slug === actualSlug)\n\n if (!collectionConfig?.fields) {\n return transformed\n }\n\n // Use Payload's traverseFields to iterate over all fields\n const callback: TraverseFieldsCallback = ({ field, parentPath, ref }) => {\n if (!('name' in field) || !field.name) {\n return\n }\n if (!ref || typeof ref !== 'object') {\n return\n }\n\n const current = ref as Record<string, unknown>\n const value = current[field.name]\n\n // Normalize undefined → null for optional fields\n // Content API may omit fields (undefined) but Payload expects null for optional fields\n if (value === undefined) {\n const isRequired = 'required' in field && field.required\n if (!isRequired) {\n current[field.name] = null\n }\n return\n }\n\n if (value !== null) {\n // RichText: JSON string -> object\n if (field.type === 'richText' && typeof value === 'string') {\n try {\n current[field.name] = JSON.parse(value)\n } catch (error) {\n const fieldPath = parentPath ? `${parentPath}.${field.name}` : field.name\n payload.logger.warn({\n err: error instanceof Error ? error : new Error(String(error)),\n msg: `Failed to parse richtext field '${fieldPath}' in collection '${collectionSlug}'`,\n })\n }\n }\n // Date fields: Already ISO strings from Content API, no conversion needed\n }\n }\n\n traverseFields({ callback, fields: collectionConfig.fields, ref: transformed })\n\n // Convert string ID to number if collection uses numeric custom ID\n const customIDType = payload.collections?.[collectionSlug]?.customIDType\n if (customIDType === 'number') {\n transformed.id = Number(transformed.id)\n }\n\n stripFields({\n config: payload.config,\n data: transformed,\n fields: flattenAllFields({ cache: true, fields: collectionConfig.fields }),\n reservedKeys: ['id', 'globalType'],\n })\n\n // Remove virtual fields - must happen AFTER stripFields\n removeVirtualFields(transformed, collectionConfig.fields)\n\n // Handle auth-specific fields that aren't in the field schema\n // When these fields are null in DB, Content API omits them from response (undefined)\n // But Payload expects them to be null, not undefined\n // Only add them if the collection has auth enabled\n if ('auth' in collectionConfig && collectionConfig.auth) {\n const authFields = ['resetPasswordExpiration', 'lockUntil']\n for (const fieldName of authFields) {\n if (!(fieldName in transformed)) {\n transformed[fieldName] = null\n }\n }\n }\n\n return transformed\n}\n"],"names":["flattenAllFields","traverseFields","applyDefaults","castFieldValue","removeVirtualFields","stripFields","dataToContentAPI","payload","collectionSlug","data","options","transformed","JSON","parse","stringify","isGlobal","startsWith","actualSlug","substring","collectionConfig","config","globals","find","g","slug","collections","c","fields","callback","field","ref","name","current","value","undefined","type","fillEmpty","cache","reservedKeys","customIDType","id","String","now","Date","toISOString","updatedAt","createdAt","dataFromContentAPI","parentPath","isRequired","required","error","fieldPath","logger","warn","err","Error","msg","Number","auth","authFields","fieldName"],"mappings":"AAEA,SAASA,gBAAgB,EAAEC,cAAc,QAAQ,UAAS;AAI1D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,WAAW,QAAQ,mBAAkB;AAI9C;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,iBACdC,OAAgB,EAChBC,cAAsB,EACtBC,IAAa,EACbC,OAA0D;IAE1D,IAAI,CAACD,QAAQ,OAAOA,SAAS,UAAU;QACrC,OAAOA;IACT;IAEA,6CAA6C;IAC7C,MAAME,cAAcC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACL;IAE9C,wBAAwB;IACxB,MAAMM,WAAWP,eAAeQ,UAAU,CAAC;IAC3C,MAAMC,aAAaF,WAAWP,eAAeU,SAA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AC9D,qFAAqF;IACrF,qDAAqD;IACrD,mDAAmD;IACnD,IAAI,UAAUR,oBAAoBA,iBAAiBwC,IAAI,EAAE;QACvD,MAAMC,aAAa;YAAC;YAA2B;SAAY;QAC3D,KAAK,MAAMC,aAAaD,WAAY;YAClC,IAAI,CAAEC,CAAAA,aAAalD,WAAU,GAAI;gBAC/BA,WAAW,CAACkD,UAAU,GAAG;YAC3B;QACF;IACF;IAEA,OAAOlD;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/db-content-api/utilities/data/index.ts"],"sourcesContent":["import type { CollectionConfig, GlobalConfig, Payload, TraverseFieldsCallback } from 'payload'\n\nimport { flattenAllFields, traverseFields } from 'payload'\n\nimport type { components } from '../../generated/content-api-types.js'\n\nimport { applyDefaults } from './applyDefaults.js'\nimport { castFieldValue } from './castFieldValue.js'\nimport { removeVirtualFields } from './removeVirtualFields.js'\nimport { stripFields } from './stripFields.js'\n\ntype DataWithOperations = components['schemas']['DataWithOperations']\n\n/**\n * Transform data before sending to Content API (WRITE operations)\n *\n * Conversions applied:\n * - Default values: Apply static defaults for undefined fields (when applyDefaults=true)\n * - Type casting: Convert values to match field types (e.g., number -> string for text fields)\n * - RichText fields: Objects -> JSON strings\n * - Virtual fields: Remove fields with `virtual: true` (pure virtual fields should never be saved)\n * - Timestamps: Add updatedAt (always), and createdAt (when createdAt=true)\n *\n * Note: Date fields are automatically converted to ISO strings by JSON.stringify()\n */\nexport function dataToContentAPI(\n payload: Payload,\n collectionSlug: string,\n data: unknown,\n options?: { applyDefaults?: boolean; createdAt?: boolean },\n): DataWithOperations {\n if (!data || typeof data !== 'object') {\n return data as DataWithOperations\n }\n\n // Deep clone to avoid mutating original data\n const transformed = JSON.parse(JSON.stringify(data))\n\n // Get collection config\n const isGlobal = collectionSlug.startsWith('_global-')\n const actualSlug = isGlobal ? collectionSlug.substring(8) : collectionSlug\n const collectionConfig: CollectionConfig | GlobalConfig | undefined = isGlobal\n ? payload.config.globals?.find((g) => g.slug === actualSlug)\n : payload.config.collections.find((c) => c.slug === actualSlug)\n\n if (!collectionConfig?.fields) {\n return transformed as DataWithOperations\n }\n\n // Apply static defaults recursively to handle nested structures (arrays, groups)\n // This must happen before traverseFields to ensure defaults are in place\n if (options?.applyDefaults) {\n applyDefaults(transformed, collectionConfig.fields)\n }\n\n // Use Payload's traverseFields to iterate over all fields for transformations\n const callback: TraverseFieldsCallback = ({ field, ref }) => {\n if (!('name' in field) || !field.name) {\n return\n }\n if (!ref || typeof ref !== 'object') {\n return\n }\n\n const current = ref as Record<string, unknown>\n let value = current[field.name]\n\n // Transform existing values\n if (value !== null && value !== undefined) {\n // Step 1: Apply type casting (e.g., number -> string for text fields)\n value = castFieldValue(field, value)\n current[field.name] = value\n\n // Step 2: Apply Content API specific transformations\n // RichText: object -> JSON string\n if (field.type === 'richText' && typeof value !== 'string') {\n current[field.name] = JSON.stringify(value)\n }\n // Date fields are already handled by JSON.stringify() which converts Date -> ISO string\n }\n }\n\n traverseFields({ callback, fields: collectionConfig.fields, fillEmpty: false, ref: transformed })\n\n stripFields({\n config: payload.config,\n data: transformed,\n fields: flattenAllFields({ cache: true, fields: collectionConfig.fields }),\n reservedKeys: ['id', 'globalType'],\n })\n\n removeVirtualFields(transformed, collectionConfig.fields)\n\n // Convert numeric ID to string for Content API\n const customIDType = payload.collections?.[collectionSlug]?.customIDType\n if (customIDType === 'number') {\n transformed.id = String(transformed.id)\n }\n\n // Add timestamps (Content API no longer auto-sets these in DB)\n // updatedAt is always set, createdAt only on create operations\n const now = new Date().toISOString()\n transformed.updatedAt = now\n if (options?.createdAt) {\n transformed.createdAt = now\n }\n\n return transformed as DataWithOperations\n}\n\n/**\n * Transform data received from Content API (READ operations)\n *\n * Conversions applied:\n * - RichText fields: JSON strings -> Objects\n * - Virtual fields: Remove fields with `virtual: true` (should not be in DB but Content API backend may add them)\n *\n * Note: Date fields come as ISO strings from Content API and stay as strings\n * (matching MongoDB and other adapters' behavior)\n */\nexport function dataFromContentAPI(\n payload: Payload,\n collectionSlug: string,\n data: unknown,\n): unknown {\n if (!data || typeof data !== 'object') {\n return data\n }\n\n // Deep clone to avoid mutating original data\n const transformed = JSON.parse(JSON.stringify(data))\n\n // Get collection config\n const isGlobal = collectionSlug.startsWith('_global-')\n const actualSlug = isGlobal ? collectionSlug.substring(8) : collectionSlug\n const collectionConfig: CollectionConfig | GlobalConfig | undefined = isGlobal\n ? payload.config.globals?.find((g) => g.slug === actualSlug)\n : payload.config.collections.find((c) => c.slug === actualSlug)\n\n if (!collectionConfig?.fields) {\n return transformed\n }\n\n // Use Payload's traverseFields to iterate over all fields\n const callback: TraverseFieldsCallback = ({ field, parentPath, ref }) => {\n if (!('name' in field) || !field.name) {\n return\n }\n if (!ref || typeof ref !== 'object') {\n return\n }\n\n const current = ref as Record<string, unknown>\n const value = current[field.name]\n\n // Normalize undefined → null for optional fields\n // Content API may omit fields (undefined) but Payload expects null for optional fields\n if (value === undefined) {\n const isRequired = 'required' in field && field.required\n if (!isRequired) {\n current[field.name] = null\n }\n return\n }\n\n if (value !== null) {\n // Localized fields: JSON string -> parsed object\n // Content API may store localized fields as JSON strings like \"{\\\"en\\\":\\\"value\\\"}\"\n // so we need to parse them back to objects.\n // Note: We return the full locale object - Payload Core handles flattening to requested locale.\n if ('localized' in field && field.localized && typeof value === 'string') {\n try {\n current[field.name] = JSON.parse(value)\n } catch (error) {\n const fieldPath = parentPath ? `${parentPath}.${field.name}` : field.name\n payload.logger.warn({\n err: error instanceof Error ? error : new Error(String(error)),\n msg: `Failed to parse localized field '${fieldPath}' in collection '${collectionSlug}'`,\n })\n }\n }\n // RichText: JSON string -> object\n else if (field.type === 'richText' && typeof value === 'string') {\n try {\n current[field.name] = JSON.parse(value)\n } catch (error) {\n const fieldPath = parentPath ? `${parentPath}.${field.name}` : field.name\n payload.logger.warn({\n err: error instanceof Error ? error : new Error(String(error)),\n msg: `Failed to parse richtext field '${fieldPath}' in collection '${collectionSlug}'`,\n })\n }\n }\n // Date fields: Already ISO strings from Content API, no conversion needed\n }\n }\n\n traverseFields({ callback, fields: collectionConfig.fields, fillEmpty: false, ref: transformed })\n\n // Convert string ID to number if collection uses numeric custom ID\n const customIDType = payload.collections?.[collectionSlug]?.customIDType\n if (customIDType === 'number') {\n transformed.id = Number(transformed.id)\n }\n\n stripFields({\n config: payload.config,\n data: transformed,\n fields: flattenAllFields({ cache: true, fields: collectionConfig.fields }),\n reservedKeys: ['id', 'globalType'],\n })\n\n // Remove virtual fields - must happen AFTER stripFields\n removeVirtualFields(transformed, collectionConfig.fields)\n\n // Handle auth-specific fields that aren't in the field schema\n // When these fields are null in DB, Content API omits them from response (undefined)\n // But Payload expects them to be null, not undefined\n // Only add them if the collection has auth enabled\n if ('auth' in collectionConfig && collectionConfig.auth) {\n const authFields = ['resetPasswordExpiration', 'lockUntil']\n for (const fieldName of authFields) {\n if (!(fieldName in transformed)) {\n transformed[fieldName] = null\n }\n }\n }\n\n return transformed\n}\n"],"names":["flattenAllFields","traverseFields","applyDefaults","castFieldValue","removeVirtualFields","stripFields","dataToContentAPI","payload","collectionSlug","data","options","transformed","JSON","parse","stringify","isGlobal","startsWith","actualSlug","substring","collectionConfig","config","globals","find","g","slug","collections","c","fields","callback","field","ref","name","current","value","undefined","type","fillEmpty","cache","reservedKeys","customIDType","id","String","now","Date","toISOString","updatedAt","createdAt","dataFromContentAPI","parentPath","isRequired","required","localized","error","fieldPath","logger","warn","err","Error","msg","Number","auth","authFields","fieldName"],"mappings":"AAEA,SAASA,gBAAgB,EAAEC,cAAc,QAAQ,UAAS;AAI1D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,WAAW,QAAQ,mBAAkB;AAI9C;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,iBACdC,OAAgB,EAChBC,cAAsB,EACtBC,IAAa,EACbC,OAA0D;IAE1D,IAAI,CAACD,QAAQ,OAA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I;oBACzExB,QAAQ+C,MAAM,CAACC,IAAI,CAAC;wBAClBC,KAAKJ,iBAAiBK,QAAQL,QAAQ,IAAIK,MAAMhB,OAAOW;wBACvDM,KAAK,CAAC,gCAAgC,EAAEL,UAAU,iBAAiB,EAAE7C,eAAe,CAAC,CAAC;oBACxF;gBACF;YACF;QACA,0EAA0E;QAC5E;IACF;IAEAP,eAAe;QAAE2B;QAAUD,QAAQR,iBAAiBQ,MAAM;QAAES,WAAW;QAAON,KAAKnB;IAAY;IAE/F,mEAAmE;IACnE,MAAM4B,eAAehC,QAAQkB,WAAW,EAAE,CAACjB,eAAe,EAAE+B;IAC5D,IAAIA,iBAAiB,UAAU;QAC7B5B,YAAY6B,EAAE,GAAGmB,OAAOhD,YAAY6B,EAAE;IACxC;IAEAnC,YAAY;QACVe,QAAQb,QAAQa,MAAM;QACtBX,MAAME;QACNgB,QAAQ3B,iBAAiB;YAAEqC,OAAO;YAAMV,QAAQR,iBAAiBQ,MAAM;QAAC;QACxEW,cAAc;YAAC;YAAM;SAAa;IACpC;IAEA,wDAAwD;IACxDlC,oBAAoBO,aAAaQ,iBAAiBQ,MAAM;IAExD,8DAA8D;IAC9D,qFAAqF;IACrF,qDAAqD;IACrD,mDAAmD;IACnD,IAAI,UAAUR,oBAAoBA,iBAAiByC,IAAI,EAAE;QACvD,MAAMC,aAAa;YAAC;YAA2B;SAAY;QAC3D,KAAK,MAAMC,aAAaD,WAAY;YAClC,IAAI,CAAEC,CAAAA,aAAanD,WAAU,GAAI;gBAC/BA,WAAW,CAACmD,UAAU,GAAG;YAC3B;QACF;IACF;IAEA,OAAOnD;AACT"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Determines what locale to send to Content API based on request locale value
|
|
4
|
+
* and config's defaultLocale.
|
|
5
|
+
*
|
|
6
|
+
* If no locale is provided, falls back to the default locale from config.
|
|
7
|
+
* Returns undefined for 'all' and '*' (special Payload values for returning all locales).
|
|
8
|
+
*/
|
|
9
|
+
export declare function addFallbackLocale(locale: null | string | undefined, payload: Payload): string | undefined;
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/db-content-api/utilities/locale/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAEtC;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,IAAI,GAAG,MAAM,GAAG,SAAS,EACjC,OAAO,EAAE,OAAO,GACf,MAAM,GAAG,SAAS,CAgBpB"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Determines what locale to send to Content API based on request locale value
|
|
3
|
+
* and config's defaultLocale.
|
|
4
|
+
*
|
|
5
|
+
* If no locale is provided, falls back to the default locale from config.
|
|
6
|
+
* Returns undefined for 'all' and '*' (special Payload values for returning all locales).
|
|
7
|
+
*/ export function addFallbackLocale(locale, payload) {
|
|
8
|
+
const defaultLocale = payload.config.localization ? payload.config.localization.defaultLocale : undefined;
|
|
9
|
+
if (locale) {
|
|
10
|
+
// 'all' and '*' are special Payload values meaning "return all locales" - don't send to Content API
|
|
11
|
+
if (locale === 'all' || locale === '*') {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
return locale;
|
|
15
|
+
} else if (defaultLocale) {
|
|
16
|
+
return defaultLocale;
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/db-content-api/utilities/locale/index.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\n/**\n * Determines what locale to send to Content API based on request locale value\n * and config's defaultLocale.\n *\n * If no locale is provided, falls back to the default locale from config.\n * Returns undefined for 'all' and '*' (special Payload values for returning all locales).\n */\nexport function addFallbackLocale(\n locale: null | string | undefined,\n payload: Payload,\n): string | undefined {\n const defaultLocale = payload.config.localization\n ? payload.config.localization.defaultLocale\n : undefined\n\n if (locale) {\n // 'all' and '*' are special Payload values meaning \"return all locales\" - don't send to Content API\n if (locale === 'all' || locale === '*') {\n return undefined\n }\n return locale\n } else if (defaultLocale) {\n return defaultLocale\n }\n\n return undefined\n}\n"],"names":["addFallbackLocale","locale","payload","defaultLocale","config","localization","undefined"],"mappings":"AAEA;;;;;;CAMC,GACD,OAAO,SAASA,kBACdC,MAAiC,EACjCC,OAAgB;IAEhB,MAAMC,gBAAgBD,QAAQE,MAAM,CAACC,YAAY,GAC7CH,QAAQE,MAAM,CAACC,YAAY,CAACF,aAAa,GACzCG;IAEJ,IAAIL,QAAQ;QACV,oGAAoG;QACpG,IAAIA,WAAW,SAASA,WAAW,KAAK;YACtC,OAAOK;QACT;QACA,OAAOL;IACT,OAAO,IAAIE,eAAe;QACxB,OAAOA;IACT;IAEA,OAAOG;AACT"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Extracts all localized field paths from a collection's field configuration.
|
|
4
|
+
* Recursively traverses nested structures (groups, arrays, blocks, tabs) to find fields marked as localized.
|
|
5
|
+
*
|
|
6
|
+
* @param payload - The Payload instance containing collection configurations
|
|
7
|
+
* @param collectionSlug - The slug of the collection to extract localized paths from
|
|
8
|
+
* @returns Array of dot-notation paths to localized fields (e.g., ['title', 'metadata.description'])
|
|
9
|
+
*/
|
|
10
|
+
export declare function buildLocalizedPaths(payload: Payload, collectionSlug: string): string[];
|
|
11
|
+
//# sourceMappingURL=buildLocalizedPaths.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildLocalizedPaths.d.ts","sourceRoot":"","sources":["../../../../src/db-content-api/utilities/meta/buildLocalizedPaths.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAS,OAAO,EAAE,MAAM,SAAS,CAAA;AAE7C;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,MAAM,EAAE,CAStF"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extracts all localized field paths from a collection's field configuration.
|
|
3
|
+
* Recursively traverses nested structures (groups, arrays, blocks, tabs) to find fields marked as localized.
|
|
4
|
+
*
|
|
5
|
+
* @param payload - The Payload instance containing collection configurations
|
|
6
|
+
* @param collectionSlug - The slug of the collection to extract localized paths from
|
|
7
|
+
* @returns Array of dot-notation paths to localized fields (e.g., ['title', 'metadata.description'])
|
|
8
|
+
*/ export function buildLocalizedPaths(payload, collectionSlug) {
|
|
9
|
+
const collectionConfig = payload.config.collections.find((c)=>c.slug === collectionSlug);
|
|
10
|
+
if (!collectionConfig) {
|
|
11
|
+
return [];
|
|
12
|
+
}
|
|
13
|
+
const localizedPaths = [];
|
|
14
|
+
traverseFields(collectionConfig.fields, localizedPaths);
|
|
15
|
+
return localizedPaths;
|
|
16
|
+
}
|
|
17
|
+
/** Recursively traverses fields to find and collect localized paths */ function traverseFields(fields, localizedPaths, parentPath = '', parentIsLocalized = false) {
|
|
18
|
+
for (const field of fields){
|
|
19
|
+
// Only field types that have names can support localization
|
|
20
|
+
// See: https://payloadcms.com/docs/configuration/localization
|
|
21
|
+
//
|
|
22
|
+
// This will skip presentational fields like ui, collapsible, row, tabs (if unnamed), groups (if unnamed)
|
|
23
|
+
// which do not store data in the database and thus are not relevant for querying localized paths
|
|
24
|
+
// See: https://payloadcms.com/docs/fields/overview#presentational-fields
|
|
25
|
+
if (!('name' in field)) {
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const fieldPath = buildPath(parentPath, field.name);
|
|
29
|
+
const isLocalized = 'localized' in field && field.localized === true;
|
|
30
|
+
const includeNestedPaths = isLocalized || parentIsLocalized;
|
|
31
|
+
// Add field to results if localized or parent is localized
|
|
32
|
+
if (includeNestedPaths) {
|
|
33
|
+
localizedPaths.push(fieldPath);
|
|
34
|
+
}
|
|
35
|
+
// Handle blocks field - has a special 'blocks' array structure and each block has its own nested fields
|
|
36
|
+
if (field.type === 'blocks' && 'blocks' in field) {
|
|
37
|
+
for (const block of field.blocks){
|
|
38
|
+
if ('fields' in block) {
|
|
39
|
+
traverseFields(block.fields, localizedPaths, fieldPath, includeNestedPaths);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
// Handle field type that support nested fields
|
|
45
|
+
// Recursively handle nested structures (groups, arrays, tab, etc)
|
|
46
|
+
if ('fields' in field) {
|
|
47
|
+
traverseFields(field.fields, localizedPaths, fieldPath, includeNestedPaths);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Builds a dot-notation path from parent path and field name */ function buildPath(parentPath, fieldName) {
|
|
52
|
+
return parentPath ? `${parentPath}.${fieldName}` : fieldName;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=buildLocalizedPaths.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/db-content-api/utilities/meta/buildLocalizedPaths.ts"],"sourcesContent":["import type { Field, Payload } from 'payload'\n\n/**\n * Extracts all localized field paths from a collection's field configuration.\n * Recursively traverses nested structures (groups, arrays, blocks, tabs) to find fields marked as localized.\n *\n * @param payload - The Payload instance containing collection configurations\n * @param collectionSlug - The slug of the collection to extract localized paths from\n * @returns Array of dot-notation paths to localized fields (e.g., ['title', 'metadata.description'])\n */\nexport function buildLocalizedPaths(payload: Payload, collectionSlug: string): string[] {\n const collectionConfig = payload.config.collections.find((c) => c.slug === collectionSlug)\n if (!collectionConfig) {\n return []\n }\n\n const localizedPaths: string[] = []\n traverseFields(collectionConfig.fields, localizedPaths)\n return localizedPaths\n}\n\n/** Recursively traverses fields to find and collect localized paths */\nfunction traverseFields(\n fields: Field[],\n localizedPaths: string[],\n parentPath = '',\n parentIsLocalized = false,\n): void {\n for (const field of fields) {\n // Only field types that have names can support localization\n // See: https://payloadcms.com/docs/configuration/localization\n //\n // This will skip presentational fields like ui, collapsible, row, tabs (if unnamed), groups (if unnamed)\n // which do not store data in the database and thus are not relevant for querying localized paths\n // See: https://payloadcms.com/docs/fields/overview#presentational-fields\n if (!('name' in field)) {\n continue\n }\n\n const fieldPath = buildPath(parentPath, field.name)\n const isLocalized = 'localized' in field && field.localized === true\n const includeNestedPaths = isLocalized || parentIsLocalized\n\n // Add field to results if localized or parent is localized\n if (includeNestedPaths) {\n localizedPaths.push(fieldPath)\n }\n\n // Handle blocks field - has a special 'blocks' array structure and each block has its own nested fields\n if (field.type === 'blocks' && 'blocks' in field) {\n for (const block of field.blocks) {\n if ('fields' in block) {\n traverseFields(block.fields, localizedPaths, fieldPath, includeNestedPaths)\n }\n }\n continue\n }\n\n // Handle field type that support nested fields\n // Recursively handle nested structures (groups, arrays, tab, etc)\n if ('fields' in field) {\n traverseFields(field.fields, localizedPaths, fieldPath, includeNestedPaths)\n }\n }\n}\n\n/** Builds a dot-notation path from parent path and field name */\nfunction buildPath(parentPath: string, fieldName: string): string {\n return parentPath ? `${parentPath}.${fieldName}` : fieldName\n}\n"],"names":["buildLocalizedPaths","payload","collectionSlug","collectionConfig","config","collections","find","c","slug","localizedPaths","traverseFields","fields","parentPath","parentIsLocalized","field","fieldPath","buildPath","name","isLocalized","localized","includeNestedPaths","push","type","block","blocks","fieldName"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,SAASA,oBAAoBC,OAAgB,EAAEC,cAAsB;IAC1E,MAAMC,mBAAmBF,QAAQG,MAAM,CAACC,WAAW,CAACC,IAAI,CAAC,CAACC,IAAMA,EAAEC,IAAI,KAAKN;IAC3E,IAAI,CAACC,kBAAkB;QACrB,OAAO,EAAE;IACX;IAEA,MAAMM,iBAA2B,EAAE;IACnCC,eAAeP,iBAAiBQ,MAAM,EAAEF;IACxC,OAAOA;AACT;AAEA,qEAAqE,GACrE,SAASC,eACPC,MAAe,EACfF,cAAwB,EACxBG,aAAa,EAAE,EACfC,oBAAoB,KAAK;IAEzB,KAAK,MAAMC,SAASH,OAAQ;QAC1B,4DAA4D;QAC5D,8DAA8D;QAC9D,EAAE;QACF,yGAAyG;QACzG,iGAAiG;QACjG,yEAAyE;QACzE,IAAI,CAAE,CAAA,UAAUG,KAAI,GAAI;YACtB;QACF;QAEA,MAAMC,YAAYC,UAAUJ,YAAYE,MAAMG,IAAI;QAClD,MAAMC,cAAc,eAAeJ,SAASA,MAAMK,SAAS,KAAK;QAChE,MAAMC,qBAAqBF,eAAeL;QAE1C,2DAA2D;QAC3D,IAAIO,oBAAoB;YACtBX,eAAeY,IAAI,CAACN;QACtB;QAEA,wGAAwG;QACxG,IAAID,MAAMQ,IAAI,KAAK,YAAY,YAAYR,OAAO;YAChD,KAAK,MAAMS,SAAST,MAAMU,MAAM,CAAE;gBAChC,IAAI,YAAYD,OAAO;oBACrBb,eAAea,MAAMZ,MAAM,EAAEF,gBAAgBM,WAAWK;gBAC1D;YACF;YACA;QACF;QAEA,+CAA+C;QAC/C,kEAAkE;QAClE,IAAI,YAAYN,OAAO;YACrBJ,eAAeI,MAAMH,MAAM,EAAEF,gBAAgBM,WAAWK;QAC1D;IACF;AACF;AAEA,+DAA+D,GAC/D,SAASJ,UAAUJ,UAAkB,EAAEa,SAAiB;IACtD,OAAOb,aAAa,GAAGA,WAAW,CAAC,EAAEa,WAAW,GAAGA;AACrD"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Payload, Where } from 'payload';
|
|
2
|
+
export interface ContentAPIMeta {
|
|
3
|
+
localizedPaths?: string[];
|
|
4
|
+
pathTypes?: Record<string, 'array'>;
|
|
5
|
+
}
|
|
6
|
+
export interface BuildMetaOptions {
|
|
7
|
+
collection: string;
|
|
8
|
+
locale: string | undefined;
|
|
9
|
+
where?: Where;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Builds the `meta` object for Content API requests.
|
|
13
|
+
* Combines pathTypes (for array field handling) and localizedPaths (for locale queries).
|
|
14
|
+
*
|
|
15
|
+
* @param payload - The Payload instance
|
|
16
|
+
* @param options - Options including collection slug, locale, and where clause
|
|
17
|
+
* @returns Object with meta property ready to spread into request body, or empty object if no meta needed
|
|
18
|
+
*/
|
|
19
|
+
export declare function buildMeta(payload: Payload, options: BuildMetaOptions): {
|
|
20
|
+
meta?: ContentAPIMeta;
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=buildMeta.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildMeta.d.ts","sourceRoot":"","sources":["../../../../src/db-content-api/utilities/meta/buildMeta.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAK7C,MAAM,WAAW,cAAc;IAC7B,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACpC;AAED,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,KAAK,CAAC,EAAE,KAAK,CAAA;CACd;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,gBAAgB,GAAG;IAAE,IAAI,CAAC,EAAE,cAAc,CAAA;CAAE,CAoBhG"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { buildLocalizedPaths } from './buildLocalizedPaths.js';
|
|
2
|
+
import { buildPathTypes } from './buildPathTypes.js';
|
|
3
|
+
/**
|
|
4
|
+
* Builds the `meta` object for Content API requests.
|
|
5
|
+
* Combines pathTypes (for array field handling) and localizedPaths (for locale queries).
|
|
6
|
+
*
|
|
7
|
+
* @param payload - The Payload instance
|
|
8
|
+
* @param options - Options including collection slug, locale, and where clause
|
|
9
|
+
* @returns Object with meta property ready to spread into request body, or empty object if no meta needed
|
|
10
|
+
*/ export function buildMeta(payload, options) {
|
|
11
|
+
const { collection, locale, where } = options;
|
|
12
|
+
const meta = {};
|
|
13
|
+
// Add pathTypes if there are array fields in the where clause
|
|
14
|
+
const pathTypes = buildPathTypes(payload, collection, where);
|
|
15
|
+
if (Object.keys(pathTypes).length > 0) {
|
|
16
|
+
meta.pathTypes = pathTypes;
|
|
17
|
+
}
|
|
18
|
+
// Add localizedPaths if locale is specified (but not 'all')
|
|
19
|
+
if (locale && locale !== 'all') {
|
|
20
|
+
const localizedPaths = buildLocalizedPaths(payload, collection);
|
|
21
|
+
if (localizedPaths.length > 0) {
|
|
22
|
+
meta.localizedPaths = localizedPaths;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return Object.keys(meta).length > 0 ? {
|
|
26
|
+
meta
|
|
27
|
+
} : {};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=buildMeta.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/db-content-api/utilities/meta/buildMeta.ts"],"sourcesContent":["import type { Payload, Where } from 'payload'\n\nimport { buildLocalizedPaths } from './buildLocalizedPaths.js'\nimport { buildPathTypes } from './buildPathTypes.js'\n\nexport interface ContentAPIMeta {\n localizedPaths?: string[]\n pathTypes?: Record<string, 'array'>\n}\n\nexport interface BuildMetaOptions {\n collection: string\n locale: string | undefined\n where?: Where\n}\n\n/**\n * Builds the `meta` object for Content API requests.\n * Combines pathTypes (for array field handling) and localizedPaths (for locale queries).\n *\n * @param payload - The Payload instance\n * @param options - Options including collection slug, locale, and where clause\n * @returns Object with meta property ready to spread into request body, or empty object if no meta needed\n */\nexport function buildMeta(payload: Payload, options: BuildMetaOptions): { meta?: ContentAPIMeta } {\n const { collection, locale, where } = options\n\n const meta: ContentAPIMeta = {}\n\n // Add pathTypes if there are array fields in the where clause\n const pathTypes = buildPathTypes(payload, collection, where)\n if (Object.keys(pathTypes).length > 0) {\n meta.pathTypes = pathTypes\n }\n\n // Add localizedPaths if locale is specified (but not 'all')\n if (locale && locale !== 'all') {\n const localizedPaths = buildLocalizedPaths(payload, collection)\n if (localizedPaths.length > 0) {\n meta.localizedPaths = localizedPaths\n }\n }\n\n return Object.keys(meta).length > 0 ? { meta } : {}\n}\n"],"names":["buildLocalizedPaths","buildPathTypes","buildMeta","payload","options","collection","locale","where","meta","pathTypes","Object","keys","length","localizedPaths"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,cAAc,QAAQ,sBAAqB;AAapD;;;;;;;CAOC,GACD,OAAO,SAASC,UAAUC,OAAgB,EAAEC,OAAyB;IACnE,MAAM,EAAEC,UAAU,EAAEC,MAAM,EAAEC,KAAK,EAAE,GAAGH;IAEtC,MAAMI,OAAuB,CAAC;IAE9B,8DAA8D;IAC9D,MAAMC,YAAYR,eAAeE,SAASE,YAAYE;IACtD,IAAIG,OAAOC,IAAI,CAACF,WAAWG,MAAM,GAAG,GAAG;QACrCJ,KAAKC,SAAS,GAAGA;IACnB;IAEA,4DAA4D;IAC5D,IAAIH,UAAUA,WAAW,OAAO;QAC9B,MAAMO,iBAAiBb,oBAAoBG,SAASE;QACpD,IAAIQ,eAAeD,MAAM,GAAG,GAAG;YAC7BJ,KAAKK,cAAc,GAAGA;QACxB;IACF;IAEA,OAAOH,OAAOC,IAAI,CAACH,MAAMI,MAAM,GAAG,IAAI;QAAEJ;IAAK,IAAI,CAAC;AACpD"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Payload, Where } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Builds pathTypes metadata for Content API request.
|
|
4
|
+
* Returns a record of paths that are arrays for proper query generation.
|
|
5
|
+
*/
|
|
6
|
+
export declare function buildPathTypes(payload: Payload, collectionSlug: string, where: undefined | Where): Record<string, 'array'>;
|
|
7
|
+
//# sourceMappingURL=buildPathTypes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildPathTypes.d.ts","sourceRoot":"","sources":["../../../../src/db-content-api/utilities/meta/buildPathTypes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAS,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AA8JpD;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,SAAS,GAAG,KAAK,GACvB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CA0BzB"}
|
|
@@ -123,9 +123,8 @@
|
|
|
123
123
|
return currentField;
|
|
124
124
|
}
|
|
125
125
|
/**
|
|
126
|
-
* Builds metadata for Content API request
|
|
127
|
-
* Returns
|
|
128
|
-
* This tells the Content API which paths are arrays/objects for proper query generation
|
|
126
|
+
* Builds pathTypes metadata for Content API request.
|
|
127
|
+
* Returns a record of paths that are arrays for proper query generation.
|
|
129
128
|
*/ export function buildPathTypes(payload, collectionSlug, where) {
|
|
130
129
|
if (!where) {
|
|
131
130
|
return {};
|
|
@@ -146,12 +145,7 @@
|
|
|
146
145
|
}
|
|
147
146
|
}
|
|
148
147
|
}
|
|
149
|
-
|
|
150
|
-
return Object.keys(pathTypes).length > 0 ? {
|
|
151
|
-
meta: {
|
|
152
|
-
pathTypes
|
|
153
|
-
}
|
|
154
|
-
} : {};
|
|
148
|
+
return pathTypes;
|
|
155
149
|
}
|
|
156
150
|
|
|
157
151
|
//# sourceMappingURL=buildPathTypes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/db-content-api/utilities/meta/buildPathTypes.ts"],"sourcesContent":["import type { Field, Payload, Where } from 'payload'\n\n/**\n * Extracts all field paths from a where clause recursively\n */\nfunction extractPathsFromWhere(where: Where, paths: Set<string> = new Set()): Set<string> {\n if (!where || typeof where !== 'object') {\n return paths\n }\n\n // Handle 'and' operator\n if ('and' in where && Array.isArray(where.and)) {\n for (const clause of where.and) {\n extractPathsFromWhere(clause, paths)\n }\n return paths\n }\n\n // Handle 'or' operator\n if ('or' in where && Array.isArray(where.or)) {\n for (const clause of where.or) {\n extractPathsFromWhere(clause, paths)\n }\n return paths\n }\n\n // Handle regular conditions - keys are field paths\n for (const key in where) {\n if (key === 'and' || key === 'or') {\n continue\n }\n\n // Add the path\n paths.add(key)\n\n // Check if the value is a nested where clause (for relationships)\n const value = where[key]\n if (value && typeof value === 'object' && !('equals' in value) && !('in' in value)) {\n // Might be a nested where, recurse\n extractPathsFromWhere(value as Where, paths)\n }\n }\n\n return paths\n}\n\n/**\n * Determines the type of a field based on its configuration\n */\nfunction getFieldType(field: Field): 'array' | null {\n // Array field\n if (field.type === 'array') {\n return 'array'\n }\n\n // Blocks field (array of objects)\n if (field.type === 'blocks') {\n return 'array'\n }\n\n // Relationship field with hasMany (array)\n if (field.type === 'relationship' && 'hasMany' in field && field.hasMany) {\n return 'array'\n }\n\n // Select field with hasMany (array)\n if (field.type === 'select' && 'hasMany' in field && field.hasMany) {\n return 'array'\n }\n\n // Upload field with hasMany (array)\n if (field.type === 'upload' && 'hasMany' in field && field.hasMany) {\n return 'array'\n }\n\n // Objects (group, collapsible, row, tabs) don't need traversal\n return null\n}\n\n/**\n * Finds a field in the collection schema by its path\n * Supports nested paths like \"access.read.users\"\n */\nfunction findFieldByPath(\n payload: Payload,\n collectionSlug: string,\n path: string,\n): Field | undefined {\n const collectionConfig = payload.config.collections.find((c) => c.slug === collectionSlug)\n if (!collectionConfig) {\n return undefined\n }\n\n const pathSegments = path.split('.')\n\n // Walk through the path segments to find the field\n let currentFields = collectionConfig.fields\n let currentField: Field | undefined = undefined\n\n for (let i = 0; i < pathSegments.length; i++) {\n const segment = pathSegments[i]\n\n // First try to find a direct match\n currentField = currentFields.find((f) => 'name' in f && f.name === segment)\n\n // If not found, check if any unnamed container fields (collapsible, row) contain it\n if (!currentField) {\n for (const field of currentFields) {\n if (!('name' in field) || !field.name) {\n // This is an unnamed field, check its contents\n if (\n ('fields' in field && field.type === 'collapsible') ||\n ('fields' in field && field.type === 'row')\n ) {\n currentField = field.fields.find((f) => 'name' in f && f.name === segment)\n if (currentField) {\n break\n }\n } else if ('tabs' in field && field.type === 'tabs') {\n // Check all tabs\n for (const tab of field.tabs) {\n currentField = tab.fields.find((f) => 'name' in f && f.name === segment)\n if (currentField) {\n break\n }\n }\n if (currentField) {\n break\n }\n }\n }\n }\n }\n\n if (!currentField) {\n return undefined\n }\n\n // If we're not at the end, get nested fields\n if (i < pathSegments.length - 1) {\n if (currentField.type === 'group' && 'fields' in currentField) {\n currentFields = currentField.fields\n } else if (currentField.type === 'array' && 'fields' in currentField) {\n currentFields = currentField.fields\n } else if (currentField.type === 'blocks' && 'blocks' in currentField) {\n // For blocks, we can't determine the exact field without knowing the block type\n // Return the blocks field itself\n return currentField\n } else {\n // Field doesn't have nested fields, can't continue\n return undefined\n }\n }\n }\n\n return currentField\n}\n\n/**\n * Builds pathTypes metadata for Content API request.\n * Returns a record of paths that are arrays for proper query generation.\n */\nexport function buildPathTypes(\n payload: Payload,\n collectionSlug: string,\n where: undefined | Where,\n): Record<string, 'array'> {\n if (!where) {\n return {}\n }\n\n const pathTypes: Record<string, 'array'> = {}\n const paths = extractPathsFromWhere(where)\n\n for (const path of paths) {\n // For each path, we need to check all segments to see if any intermediate ones are arrays/objects\n const segments = path.split('.')\n\n for (let i = 0; i < segments.length; i++) {\n const partialPath = segments.slice(0, i + 1).join('.')\n const field = findFieldByPath(payload, collectionSlug, partialPath)\n\n if (field) {\n const fieldType = getFieldType(field)\n if (fieldType === 'array') {\n pathTypes[partialPath] = fieldType\n }\n }\n }\n }\n\n return pathTypes\n}\n"],"names":["extractPathsFromWhere","where","paths","Set","Array","isArray","and","clause","or","key","add","value","getFieldType","field","type","hasMany","findFieldByPath","payload","collectionSlug","path","collectionConfig","config","collections","find","c","slug","undefined","pathSegments","split","currentFields","fields","currentField","i","length","segment","f","name","tab","tabs","buildPathTypes","pathTypes","segments","partialPath","slice","join","fieldType"],"mappings":"AAEA;;CAEC,GACD,SAASA,sBAAsBC,KAAY,EAAEC,QAAqB,IAAIC,KAAK;IACzE,IAAI,CAACF,SAAS,OAAOA,UAAU,UAAU;QACvC,OAAOC;IACT;IAEA,wBAAwB;IACxB,IAAI,SAASD,SAASG,MAAMC,OAAO,CAACJ,MAAMK,GAAG,GAAG;QAC9C,KAAK,MAAMC,UAAUN,MAAMK,GAAG,CAAE;YAC9BN,sBAAsBO,QAAQL;QAChC;QACA,OAAOA;IACT;IAEA,uBAAuB;IACvB,IAAI,QAAQD,SAASG,MAAMC,OAAO,CAACJ,MAAMO,EAAE,GAAG;QAC5C,KAAK,MAAMD,UAAUN,MAAMO,EAAE,CAAE;YAC7BR,sBAAsBO,QAAQL;QAChC;QACA,OAAOA;IACT;IAEA,mDAAmD;IACnD,IAAK,MAAMO,OAAOR,MAAO;QACvB,IAAIQ,QAAQ,SAASA,QAAQ,MAAM;YACjC;QACF;QAEA,eAAe;QACfP,MAAMQ,GAAG,CAACD;QAEV,kEAAkE;QAClE,MAAME,QAAQV,KAAK,CAACQ,IAAI;QACxB,IAAIE,SAAS,OAAOA,UAAU,YAAY,CAAE,CAAA,YAAYA,KAAI,KAAM,CAAE,CAAA,QAAQA,KAAI,GAAI;YAClF,mCAAmC;YACnCX,sBAAsBW,OAAgBT;QACxC;IACF;IAEA,OAAOA;AACT;AAEA;;CAEC,GACD,SAASU,aAAaC,KAAY;IAChC,cAAc;IACd,IAAIA,MAAMC,IAAI,KAAK,SAAS;QAC1B,OAAO;IACT;IAEA,kCAAkC;IAClC,IAAID,MAAMC,IAAI,KAAK,UAAU;QAC3B,OAAO;IACT;IAEA,0CAA0C;IAC1C,IAAID,MAAMC,IAAI,KAAK,kBAAkB,aAAaD,SAASA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,aAAaC;gBAC/B,IAAIgC,cAAc,SAAS;oBACzBL,SAAS,CAACE,YAAY,GAAGG;gBAC3B;YACF;QACF;IACF;IAEA,OAAOL;AACT"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { buildLocalizedPaths } from './buildLocalizedPaths.js';
|
|
2
|
+
export { buildMeta } from './buildMeta.js';
|
|
3
|
+
export type { BuildMetaOptions, ContentAPIMeta } from './buildMeta.js';
|
|
4
|
+
export { buildPathTypes } from './buildPathTypes.js';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/db-content-api/utilities/meta/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC1C,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/db-content-api/utilities/meta/index.ts"],"sourcesContent":["export { buildLocalizedPaths } from './buildLocalizedPaths.js'\nexport { buildMeta } from './buildMeta.js'\nexport type { BuildMetaOptions, ContentAPIMeta } from './buildMeta.js'\nexport { buildPathTypes } from './buildPathTypes.js'\n"],"names":["buildLocalizedPaths","buildMeta","buildPathTypes"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,SAAS,QAAQ,iBAAgB;AAE1C,SAASC,cAAc,QAAQ,sBAAqB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ClientUploadHandler.d.ts","sourceRoot":"","sources":["../../../src/storage-content-api/client-uploads/ClientUploadHandler.tsx"],"names":[],"mappings":"AAGA,eAAO,MAAM,6BAA6B;;;;;;;aAoBf,OAAO,
|
|
1
|
+
{"version":3,"file":"ClientUploadHandler.d.ts","sourceRoot":"","sources":["../../../src/storage-content-api/client-uploads/ClientUploadHandler.tsx"],"names":[],"mappings":"AAGA,eAAO,MAAM,6BAA6B;;;;;;;aAoBf,OAAO,aAqBhC,CAAA"}
|
|
@@ -19,7 +19,8 @@ export const ContentApiClientUploadHandler = createClientUploadHandler({
|
|
|
19
19
|
if (!response.ok) {
|
|
20
20
|
throw new Error(`Failed to get presigned URL: ${response.status} ${response.statusText}`);
|
|
21
21
|
}
|
|
22
|
-
const { url } = await response.json();
|
|
22
|
+
const { filename: safeFilename, url } = await response.json();
|
|
23
|
+
const uploadFilename = safeFilename || file.name;
|
|
23
24
|
const uploadResponse = await fetch(url, {
|
|
24
25
|
body: file,
|
|
25
26
|
headers: {
|
|
@@ -30,10 +31,9 @@ export const ContentApiClientUploadHandler = createClientUploadHandler({
|
|
|
30
31
|
if (!uploadResponse.ok) {
|
|
31
32
|
throw new Error(`Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`);
|
|
32
33
|
}
|
|
33
|
-
// Include original filename so handleUpload can distinguish from resized versions
|
|
34
34
|
return {
|
|
35
35
|
clientUploaded: true,
|
|
36
|
-
filename:
|
|
36
|
+
filename: uploadFilename,
|
|
37
37
|
prefix
|
|
38
38
|
};
|
|
39
39
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/storage-content-api/client-uploads/ClientUploadHandler.tsx"],"sourcesContent":["'use client'\nimport { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client'\n\nexport const ContentApiClientUploadHandler = createClientUploadHandler({\n handler: async ({ apiRoute, collectionSlug, file, prefix, serverHandlerPath, serverURL }) => {\n // Build endpoint URL: serverURL + apiRoute + serverHandlerPath\n const endpointRoute = `${serverURL}${apiRoute}${serverHandlerPath}`\n\n const response = await fetch(endpointRoute, {\n body: JSON.stringify({\n collectionSlug,\n filename: file.name,\n mimeType: file.type,\n }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n\n if (!response.ok) {\n throw new Error(`Failed to get presigned URL: ${response.status} ${response.statusText}`)\n }\n\n const { url } = (await response.json()) as { url: string
|
|
1
|
+
{"version":3,"sources":["../../../src/storage-content-api/client-uploads/ClientUploadHandler.tsx"],"sourcesContent":["'use client'\nimport { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client'\n\nexport const ContentApiClientUploadHandler = createClientUploadHandler({\n handler: async ({ apiRoute, collectionSlug, file, prefix, serverHandlerPath, serverURL }) => {\n // Build endpoint URL: serverURL + apiRoute + serverHandlerPath\n const endpointRoute = `${serverURL}${apiRoute}${serverHandlerPath}`\n\n const response = await fetch(endpointRoute, {\n body: JSON.stringify({\n collectionSlug,\n filename: file.name,\n mimeType: file.type,\n }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n\n if (!response.ok) {\n throw new Error(`Failed to get presigned URL: ${response.status} ${response.statusText}`)\n }\n\n const { filename: safeFilename, url } = (await response.json()) as {\n filename?: string\n url: string\n }\n\n const uploadFilename = safeFilename || file.name\n\n const uploadResponse = await fetch(url, {\n body: file,\n headers: { 'Content-Type': file.type },\n method: 'PUT',\n })\n\n if (!uploadResponse.ok) {\n throw new Error(\n `Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`,\n )\n }\n\n return { clientUploaded: true, filename: uploadFilename, prefix }\n },\n})\n"],"names":["createClientUploadHandler","ContentApiClientUploadHandler","handler","apiRoute","collectionSlug","file","prefix","serverHandlerPath","serverURL","endpointRoute","response","fetch","body","JSON","stringify","filename","name","mimeType","type","credentials","headers","method","ok","Error","status","statusText","safeFilename","url","json","uploadFilename","uploadResponse","clientUploaded"],"mappings":"AAAA;AACA,SAASA,yBAAyB,QAAQ,0CAAyC;AAEnF,OAAO,MAAMC,gCAAgCD,0BAA0B;IACrEE,SAAS,OAAO,EAAEC,QAAQ,EAAEC,cAAc,EAAEC,IAAI,EAAEC,MAAM,EAAEC,iBAAiB,EAAEC,SAAS,EAAE;QACtF,+DAA+D;QAC/D,MAAMC,gBAAgB,GAAGD,YAAYL,WAAWI,mBAAmB;QAEnE,MAAMG,WAAW,MAAMC,MAAMF,eAAe;YAC1CG,MAAMC,KAAKC,SAAS,CAAC;gBACnBV;gBACAW,UAAUV,KAAKW,IAAI;gBACnBC,UAAUZ,KAAKa,IAAI;YACrB;YACAC,aAAa;YACbC,SAAS;gBAAE,gBAAgB;YAAmB;YAC9CC,QAAQ;QACV;QAEA,IAAI,CAACX,SAASY,EAAE,EAAE;YAChB,MAAM,IAAIC,MAAM,CAAC,6BAA6B,EAAEb,SAASc,MAAM,CAAC,CAAC,EAAEd,SAASe,UAAU,EAAE;QAC1F;QAEA,MAAM,EAAEV,UAAUW,YAAY,EAAEC,GAAG,EAAE,GAAI,MAAMjB,SAASkB,IAAI;QAK5D,MAAMC,iBAAiBH,gBAAgBrB,KAAKW,IAAI;QAEhD,MAAMc,iBAAiB,MAAMnB,MAAMgB,KAAK;YACtCf,MAAMP;YACNe,SAAS;gBAAE,gBAAgBf,KAAKa,IAAI;YAAC;YACrCG,QAAQ;QACV;QAEA,IAAI,CAACS,eAAeR,EAAE,EAAE;YACtB,MAAM,IAAIC,MACR,CAAC,wBAAwB,EAAEO,eAAeN,MAAM,CAAC,CAAC,EAAEM,eAAeL,UAAU,EAAE;QAEnF;QAEA,OAAO;YAAEM,gBAAgB;YAAMhB,UAAUc;YAAgBvB;QAAO;IAClE;AACF,GAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateSignedURL.d.ts","sourceRoot":"","sources":["../../../src/storage-content-api/client-uploads/generateSignedURL.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"generateSignedURL.d.ts","sourceRoot":"","sources":["../../../src/storage-content-api/client-uploads/generateSignedURL.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAIjD,KAAK,mBAAmB,GAAG,CAAC,IAAI,EAAE;IAChC,cAAc,EAAE,MAAM,CAAA;IACtB,GAAG,EAAE,UAAU,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAA;CACnC,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;AAEhC,KAAK,IAAI,GAAG;IACV,MAAM,CAAC,EAAE,mBAAmB,CAAA;IAC5B,MAAM,EAAE,aAAa,CAAA;CACtB,CAAA;AAID,eAAO,MAAM,2BAA2B,wBAGrC,IAAI,KAAG,cAqCT,CAAA"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { APIError, Forbidden } from 'payload';
|
|
2
|
+
import { getSafeFilename } from '../utilities/index.js';
|
|
2
3
|
const defaultAccess = ({ req })=>!!req.user;
|
|
3
4
|
export const getGenerateSignedURLHandler = ({ access = defaultAccess, client })=>{
|
|
4
5
|
return async (req)=>{
|
|
@@ -12,18 +13,24 @@ export const getGenerateSignedURLHandler = ({ access = defaultAccess, client })=
|
|
|
12
13
|
})) {
|
|
13
14
|
throw new Forbidden();
|
|
14
15
|
}
|
|
16
|
+
const safeFilename = await getSafeFilename({
|
|
17
|
+
collectionSlug,
|
|
18
|
+
desiredFilename: filename,
|
|
19
|
+
req
|
|
20
|
+
});
|
|
15
21
|
const { data, error } = await client.POST('/api/v0/uploads/sign', {
|
|
16
22
|
body: {
|
|
17
23
|
collectionId: collectionSlug,
|
|
18
24
|
contentType: mimeType,
|
|
19
25
|
expiresIn: 3600,
|
|
20
|
-
filename
|
|
26
|
+
filename: safeFilename
|
|
21
27
|
}
|
|
22
28
|
});
|
|
23
29
|
if (error || !data) {
|
|
24
30
|
throw new APIError(`Failed to get presigned upload URL: ${JSON.stringify(error)}`);
|
|
25
31
|
}
|
|
26
32
|
return Response.json({
|
|
33
|
+
filename: safeFilename,
|
|
27
34
|
url: data.url
|
|
28
35
|
});
|
|
29
36
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/storage-content-api/client-uploads/generateSignedURL.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\n\nimport { APIError, Forbidden } from 'payload'\n\nimport type { StorageClient } from '../client.js'\n\ntype ClientUploadsAccess = (args: {\n collectionSlug: string\n req: Parameters<PayloadHandler>[0]\n}) => boolean | Promise<boolean>\n\ntype Args = {\n access?: ClientUploadsAccess\n client: StorageClient\n}\n\nconst defaultAccess: ClientUploadsAccess = ({ req }) => !!req.user\n\nexport const getGenerateSignedURLHandler = ({\n access = defaultAccess,\n client,\n}: Args): PayloadHandler => {\n return async (req) => {\n if (!req.json) {\n throw new APIError('Content-Type expected to be application/json', 400)\n }\n\n const { collectionSlug, filename, mimeType } = (await req.json()) as {\n collectionSlug: string\n filename: string\n mimeType: string\n }\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n\n const { data, error } = await client.POST('/api/v0/uploads/sign', {\n body: {
|
|
1
|
+
{"version":3,"sources":["../../../src/storage-content-api/client-uploads/generateSignedURL.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\n\nimport { APIError, Forbidden } from 'payload'\n\nimport type { StorageClient } from '../client.js'\n\nimport { getSafeFilename } from '../utilities/index.js'\n\ntype ClientUploadsAccess = (args: {\n collectionSlug: string\n req: Parameters<PayloadHandler>[0]\n}) => boolean | Promise<boolean>\n\ntype Args = {\n access?: ClientUploadsAccess\n client: StorageClient\n}\n\nconst defaultAccess: ClientUploadsAccess = ({ req }) => !!req.user\n\nexport const getGenerateSignedURLHandler = ({\n access = defaultAccess,\n client,\n}: Args): PayloadHandler => {\n return async (req) => {\n if (!req.json) {\n throw new APIError('Content-Type expected to be application/json', 400)\n }\n\n const { collectionSlug, filename, mimeType } = (await req.json()) as {\n collectionSlug: string\n filename: string\n mimeType: string\n }\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n\n const safeFilename = await getSafeFilename({\n collectionSlug,\n desiredFilename: filename,\n req,\n })\n\n const { data, error } = await client.POST('/api/v0/uploads/sign', {\n body: {\n collectionId: collectionSlug,\n contentType: mimeType,\n expiresIn: 3600,\n filename: safeFilename,\n },\n })\n\n if (error || !data) {\n throw new APIError(`Failed to get presigned upload URL: ${JSON.stringify(error)}`)\n }\n\n return Response.json({ filename: safeFilename, url: data.url })\n }\n}\n"],"names":["APIError","Forbidden","getSafeFilename","defaultAccess","req","user","getGenerateSignedURLHandler","access","client","json","collectionSlug","filename","mimeType","safeFilename","desiredFilename","data","error","POST","body","collectionId","contentType","expiresIn","JSON","stringify","Response","url"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAI7C,SAASC,eAAe,QAAQ,wBAAuB;AAYvD,MAAMC,gBAAqC,CAAC,EAAEC,GAAG,EAAE,GAAK,CAAC,CAACA,IAAIC,IAAI;AAElE,OAAO,MAAMC,8BAA8B,CAAC,EAC1CC,SAASJ,aAAa,EACtBK,MAAM,EACD;IACL,OAAO,OAAOJ;QACZ,IAAI,CAACA,IAAIK,IAAI,EAAE;YACb,MAAM,IAAIT,SAAS,gDAAgD;QACrE;QAEA,MAAM,EAAEU,cAAc,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAI,MAAMR,IAAIK,IAAI;QAM9D,IAAI,CAAE,MAAMF,OAAO;YAAEG;YAAgBN;QAAI,IAAK;YAC5C,MAAM,IAAIH;QACZ;QAEA,MAAMY,eAAe,MAAMX,gBAAgB;YACzCQ;YACAI,iBAAiBH;YACjBP;QACF;QAEA,MAAM,EAAEW,IAAI,EAAEC,KAAK,EAAE,GAAG,MAAMR,OAAOS,IAAI,CAAC,wBAAwB;YAChEC,MAAM;gBACJC,cAAcT;gBACdU,aAAaR;gBACbS,WAAW;gBACXV,UAAUE;YACZ;QACF;QAEA,IAAIG,SAAS,CAACD,MAAM;YAClB,MAAM,IAAIf,SAAS,CAAC,oCAAoC,EAAEsB,KAAKC,SAAS,CAACP,QAAQ;QACnF;QAEA,OAAOQ,SAASf,IAAI,CAAC;YAAEE,UAAUE;YAAcY,KAAKV,KAAKU,GAAG;QAAC;IAC/D;AACF,EAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Get a safe filename that doesn't collide with existing documents
|
|
4
|
+
* Similar to Payload's getSafeFileName
|
|
5
|
+
*/
|
|
6
|
+
export declare function getSafeFilename({ collectionSlug, desiredFilename, prefix, req, }: {
|
|
7
|
+
collectionSlug: string;
|
|
8
|
+
desiredFilename: string;
|
|
9
|
+
prefix?: string;
|
|
10
|
+
req: PayloadRequest;
|
|
11
|
+
}): Promise<string>;
|
|
12
|
+
//# sourceMappingURL=getSafeFilename.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getSafeFilename.d.ts","sourceRoot":"","sources":["../../../src/storage-content-api/utilities/getSafeFilename.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,SAAS,CAAA;AAkEpD;;;GAGG;AACH,wBAAsB,eAAe,CAAC,EACpC,cAAc,EACd,eAAe,EACf,MAAM,EACN,GAAG,GACJ,EAAE;IACD,cAAc,EAAE,MAAM,CAAA;IACtB,eAAe,EAAE,MAAM,CAAA;IACvB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,EAAE,cAAc,CAAA;CACpB,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBlB"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import sanitize from 'sanitize-filename';
|
|
2
|
+
/**
|
|
3
|
+
* Check if a document with the given filename already exists in the database
|
|
4
|
+
* Matches Payload's docWithFilenameExists
|
|
5
|
+
*/ async function docWithFilenameExists({ collectionSlug, filename, prefix, req }) {
|
|
6
|
+
const where = {
|
|
7
|
+
filename: {
|
|
8
|
+
equals: filename
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
if (prefix) {
|
|
12
|
+
where.prefix = {
|
|
13
|
+
equals: prefix
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
const doc = await req.payload.db.findOne({
|
|
17
|
+
collection: collectionSlug,
|
|
18
|
+
req,
|
|
19
|
+
where
|
|
20
|
+
});
|
|
21
|
+
return !!doc;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Increment filename by adding -1, -2, etc. suffix
|
|
25
|
+
* photo.jpg → photo-1.jpg
|
|
26
|
+
* photo-1.jpg → photo-2.jpg
|
|
27
|
+
* Matches Payload's incrementName
|
|
28
|
+
*/ function incrementFilename(name) {
|
|
29
|
+
const extension = name.split('.').pop();
|
|
30
|
+
const baseFilename = sanitize(name.substring(0, name.lastIndexOf('.')) || name);
|
|
31
|
+
let incrementedName = baseFilename;
|
|
32
|
+
const regex = /(.*)-(\d+)$/;
|
|
33
|
+
const found = baseFilename.match(regex);
|
|
34
|
+
if (found === null) {
|
|
35
|
+
incrementedName += '-1';
|
|
36
|
+
} else {
|
|
37
|
+
const matchedName = found[1];
|
|
38
|
+
const matchedNumber = found[2];
|
|
39
|
+
const incremented = Number(matchedNumber) + 1;
|
|
40
|
+
incrementedName = `${matchedName}-${incremented}`;
|
|
41
|
+
}
|
|
42
|
+
return `${incrementedName}.${extension}`;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Get a safe filename that doesn't collide with existing documents
|
|
46
|
+
* Similar to Payload's getSafeFileName
|
|
47
|
+
*/ export async function getSafeFilename({ collectionSlug, desiredFilename, prefix, req }) {
|
|
48
|
+
let modifiedFilename = desiredFilename;
|
|
49
|
+
// Keep incrementing until we find a filename that doesn't exist
|
|
50
|
+
while(await docWithFilenameExists({
|
|
51
|
+
collectionSlug,
|
|
52
|
+
filename: modifiedFilename,
|
|
53
|
+
prefix,
|
|
54
|
+
req
|
|
55
|
+
})){
|
|
56
|
+
modifiedFilename = incrementFilename(modifiedFilename);
|
|
57
|
+
}
|
|
58
|
+
return modifiedFilename;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=getSafeFilename.js.map
|