@warlock.js/seal 5.5.0 → 5.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/cjs/index.cjs +20 -14
- package/cjs/index.cjs.map +1 -1
- package/esm/factory/validate.mjs.map +1 -1
- package/esm/factory/validators.mjs.map +1 -1
- package/esm/helpers/validation-helpers.mjs +7 -1
- package/esm/helpers/validation-helpers.mjs.map +1 -1
- package/esm/rules/date/date-period-rules.d.mts.map +1 -1
- package/esm/rules/date/date-period-rules.mjs +2 -0
- package/esm/rules/date/date-period-rules.mjs.map +1 -1
- package/esm/rules/string/credit-card.mjs +1 -1
- package/esm/rules/string/credit-card.mjs.map +1 -1
- package/esm/validators/base-validator.mjs +2 -2
- package/esm/validators/base-validator.mjs.map +1 -1
- package/esm/validators/object-validator.d.mts.map +1 -1
- package/esm/validators/object-validator.mjs +8 -10
- package/esm/validators/object-validator.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -84,9 +84,9 @@ var ObjectValidator = class ObjectValidator extends BaseValidator {
|
|
|
84
84
|
clone(keys) {
|
|
85
85
|
const cloned = super.clone();
|
|
86
86
|
const newSchema = {};
|
|
87
|
-
for (const key
|
|
87
|
+
for (const [key, validator] of Object.entries(this.schema)) {
|
|
88
88
|
if (keys && !keys.includes(key)) continue;
|
|
89
|
-
newSchema[key] =
|
|
89
|
+
newSchema[key] = validator.clone();
|
|
90
90
|
}
|
|
91
91
|
cloned.schema = newSchema;
|
|
92
92
|
cloned.shouldAllowUnknown = this.shouldAllowUnknown;
|
|
@@ -137,7 +137,7 @@ var ObjectValidator = class ObjectValidator extends BaseValidator {
|
|
|
137
137
|
extend(schemaOrValidator) {
|
|
138
138
|
const extended = this.clone();
|
|
139
139
|
const schemaToAdd = schemaOrValidator instanceof ObjectValidator ? schemaOrValidator.schema : schemaOrValidator;
|
|
140
|
-
for (const key
|
|
140
|
+
for (const [key, validator] of Object.entries(schemaToAdd)) extended.schema[key] = validator.clone();
|
|
141
141
|
return extended;
|
|
142
142
|
}
|
|
143
143
|
/**
|
|
@@ -171,7 +171,7 @@ var ObjectValidator = class ObjectValidator extends BaseValidator {
|
|
|
171
171
|
*/
|
|
172
172
|
merge(validator) {
|
|
173
173
|
const merged = this.clone();
|
|
174
|
-
for (const key
|
|
174
|
+
for (const [key, schemaValidator] of Object.entries(validator.schema)) merged.schema[key] = schemaValidator.clone();
|
|
175
175
|
merged.shouldAllowUnknown = validator.shouldAllowUnknown;
|
|
176
176
|
merged.allowedKeys = [...merged.allowedKeys, ...validator.allowedKeys];
|
|
177
177
|
merged.rules.push(...validator.rules);
|
|
@@ -228,7 +228,7 @@ var ObjectValidator = class ObjectValidator extends BaseValidator {
|
|
|
228
228
|
partial(...keys) {
|
|
229
229
|
const validationSchema = this.clone();
|
|
230
230
|
if (keys.length === 0) keys = Object.keys(validationSchema.schema);
|
|
231
|
-
for (const key of keys) validationSchema.schema[key] =
|
|
231
|
+
for (const [key, validator] of Object.entries(validationSchema.schema)) if (keys.length === 0 || keys.includes(key)) validationSchema.schema[key] = validator.optional();
|
|
232
232
|
return validationSchema;
|
|
233
233
|
}
|
|
234
234
|
/**
|
|
@@ -237,7 +237,7 @@ var ObjectValidator = class ObjectValidator extends BaseValidator {
|
|
|
237
237
|
requiredFields(...keys) {
|
|
238
238
|
const validationSchema = this.clone();
|
|
239
239
|
if (keys.length === 0) keys = Object.keys(validationSchema.schema);
|
|
240
|
-
for (const key of keys) validationSchema.schema[key] =
|
|
240
|
+
for (const [key, validator] of Object.entries(validationSchema.schema)) if (keys.length === 0 || keys.includes(key)) validationSchema.schema[key] = validator.required();
|
|
241
241
|
return validationSchema;
|
|
242
242
|
}
|
|
243
243
|
/**
|
|
@@ -301,8 +301,7 @@ var ObjectValidator = class ObjectValidator extends BaseValidator {
|
|
|
301
301
|
if (data === void 0) return result;
|
|
302
302
|
const errors = [];
|
|
303
303
|
const validatedData = {};
|
|
304
|
-
const validationPromises = Object.
|
|
305
|
-
const validator = this.schema[key];
|
|
304
|
+
const validationPromises = Object.entries(this.schema).filter(([, validator]) => !this.isComputedValidator(validator)).map(async ([key, validator]) => {
|
|
306
305
|
const value = mutatedData?.[key] !== void 0 ? mutatedData[key] : validator.getDefaultValue();
|
|
307
306
|
const childContext = {
|
|
308
307
|
...context,
|
|
@@ -322,8 +321,7 @@ var ObjectValidator = class ObjectValidator extends BaseValidator {
|
|
|
322
321
|
data: void 0
|
|
323
322
|
};
|
|
324
323
|
const computedFields = this.getComputedFields();
|
|
325
|
-
const computedPromises = Object.
|
|
326
|
-
const validator = computedFields[key];
|
|
324
|
+
const computedPromises = Object.entries(computedFields).map(async ([key, validator]) => {
|
|
327
325
|
const childContext = {
|
|
328
326
|
...context,
|
|
329
327
|
parent: validatedData,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object-validator.mjs","names":[],"sources":["../../../../../../../seal/src/validators/object-validator.ts"],"sourcesContent":["import { except } from \"@mongez/reinforcements\";\nimport { isPlainObject } from \"@mongez/supportive-is\";\nimport { setKeyPath } from \"../helpers\";\nimport { objectTrimMutator, stripUnknownMutator } from \"../mutators\";\nimport { objectRule, unknownKeyRule } from \"../rules\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { applyNullable, wrapNullableStrict } from \"../standard-schema/json-schema\";\nimport type { Schema, SchemaContext, ValidationResult } from \"../types\";\nimport type {\n InferInputObjectShape,\n InferOutputObjectShape,\n} from \"../types/inference-types\";\nimport { BaseValidator } from \"./base-validator\";\nimport { ComputedValidator } from \"./computed-validator\";\n\n/**\n * Object validator class with generic schema type for proper type inference.\n *\n * Threads two distinct inferred shapes into `BaseValidator`'s `TInput`/`TOutput`:\n *\n * - `TInput` = `InferInputObjectShape<TSchema>` — what `~standard.validate()`\n * accepts (caller's pre-validation payload; defaults/catches make\n * keys optional)\n * - `TOutput` = `InferOutputObjectShape<TSchema>` — what `~standard.validate()`\n * returns on success (post-default, post-catch shape; guaranteed\n * keys are required)\n *\n * Both helpers are used directly (not the full `Infer.*` walker) to avoid a\n * recursive class-base evaluation that would otherwise occur when the\n * brand-aware widening tries to inspect the class type.\n */\nexport class ObjectValidator<TSchema extends Schema = Schema> extends BaseValidator<\n InferInputObjectShape<TSchema>,\n InferOutputObjectShape<TSchema>\n> {\n protected shouldAllowUnknown = false;\n protected allowedKeys: string[] = [];\n protected hasUnknownKeyRule = false;\n\n public constructor(\n public schema: TSchema,\n errorMessage?: string,\n ) {\n super();\n this.addMutableRule(objectRule, errorMessage);\n }\n\n /**\n * Check if value is an object type (plain object, not array or date)\n */\n public matchesType(value: any): boolean {\n return isPlainObject(value);\n }\n\n /** Strip unknown keys from the data */\n public stripUnknown() {\n const validator = this.instance;\n return validator.addMutator(stripUnknownMutator, {\n get allowedKeys() {\n return validator.allowedKeys;\n },\n });\n }\n\n /** Add list of allowed keys that could be in the data but not necessarily validated */\n public allow(...keys: string[]) {\n const validator = this.instance;\n validator.allowedKeys.push(...keys);\n return validator;\n }\n\n /** Trim values of the object properties */\n public trim(recursive = true) {\n const validator = this.instance;\n return validator.addMutator(objectTrimMutator, { recursive });\n }\n\n /** Whether to allow unknown properties\n * Please note it will allow only unknown direct children keys, not nested children keys\n */\n public allowUnknown(allow = true) {\n const validator = this.instance;\n validator.shouldAllowUnknown = allow;\n return validator;\n }\n\n /**\n * Create a copy of this object validator with the same configuration\n * Copies schema, rules, mutators, transformers, and object-specific settings\n *\n * @returns A new ObjectValidator instance with copied configuration\n *\n * @example\n * ```ts\n * const baseUser = v.object({ name: v.string() }).allowUnknown();\n * const userCopy = baseUser.clone();\n * // userCopy has the same schema and allowUnknown setting\n * ```\n */\n public override clone(keys?: string[]): this {\n // Get cloned instance with all BaseValidator properties\n const cloned = super.clone();\n\n // Clone schema with deep copy of validators\n const newSchema = {} as TSchema;\n for (const key in this.schema) {\n if (keys && !keys.includes(key)) continue;\n (newSchema as any)[key] = this.schema[key].clone();\n }\n\n cloned.schema = newSchema;\n\n // Add ObjectValidator-specific properties\n cloned.shouldAllowUnknown = this.shouldAllowUnknown;\n cloned.allowedKeys = [...this.allowedKeys];\n // NOTE: hasUnknownKeyRule is intentionally NOT copied.\n // Each clone must add its own unknownKeyRule on first validate()\n // so it holds references to its own schema/allowedKeys, not the original's.\n\n return cloned;\n }\n\n /**\n * Extend this schema with additional fields\n * Clones the current validator and adds new fields to the schema\n * **Keeps original configuration** (allowUnknown, stripUnknown, etc.)\n *\n * If an ObjectValidator is provided, only its schema is used - its configuration is ignored.\n * This is useful for creating reusable field collections that can be added to different schemas.\n *\n * @param schemaOrValidator - Plain schema object or ObjectValidator to extend with\n * @returns A new ObjectValidator with merged schema and original configuration\n *\n * @example\n * ```ts\n * // Extend with plain schema\n * const baseUser = v.object({\n * name: v.string().required(),\n * email: v.string().email().required()\n * }).allowUnknown();\n *\n * const adminUser = baseUser.extend({\n * role: v.string().in(['admin', 'superadmin']).required()\n * });\n * // adminUser has: name, email, role\n * // adminUser keeps: allowUnknown() from base ✅\n *\n * // Extend with ObjectValidator (only schema is used)\n * const auditFields = v.object({\n * createdAt: v.date().required(),\n * updatedAt: v.date().required()\n * }).stripUnknown(); // This config is ignored!\n *\n * const fullUser = baseUser.extend(auditFields);\n * // fullUser has: name, email, createdAt, updatedAt\n * // fullUser keeps: allowUnknown() from base (NOT stripUnknown from auditFields) ✅\n *\n * // Chain multiple extends\n * const complexSchema = baseUser\n * .extend(auditFields)\n * .extend({ metadata: v.object({}) });\n * ```\n */\n public extend<TExtension extends Schema>(\n schemaOrValidator: TExtension | ObjectValidator<TExtension>,\n ): ObjectValidator<TSchema & TExtension> {\n // Clone current validator to preserve original\n const extended = this.clone() as any;\n\n // Extract schema from parameter\n const schemaToAdd =\n schemaOrValidator instanceof ObjectValidator ? schemaOrValidator.schema : schemaOrValidator;\n\n // Merge schemas with cloned validators (later fields override earlier ones)\n for (const key in schemaToAdd) {\n extended.schema[key] = schemaToAdd[key].clone();\n }\n\n return extended as ObjectValidator<TSchema & TExtension>;\n }\n\n /**\n * Merge with another ObjectValidator\n * Clones current validator, merges schemas, and **overrides configuration** with other validator's config\n *\n * Unlike extend(), merge() combines both schemas AND configurations.\n * The other validator's configuration (allowUnknown, stripUnknown, etc.) takes precedence.\n *\n * @param validator - Another ObjectValidator to merge with\n * @returns A new ObjectValidator with merged schema and configuration\n *\n * @example\n * ```ts\n * const baseUser = v.object({\n * name: v.string().required()\n * }).allowUnknown();\n *\n * const timestamps = v.object({\n * createdAt: v.date().required(),\n * updatedAt: v.date().required()\n * }).stripUnknown();\n *\n * const merged = baseUser.merge(timestamps);\n * // merged has: name, createdAt, updatedAt\n * // merged config: stripUnknown() from timestamps (overrides allowUnknown) ✅\n *\n * // Chain multiple merges\n * const full = baseUser.merge(timestamps).merge(softDeleteSchema);\n * ```\n */\n public merge<TMerge extends Schema>(\n validator: ObjectValidator<TMerge>,\n ): ObjectValidator<TSchema & TMerge> {\n // Clone current validator\n const merged = this.clone() as any;\n\n // Merge schemas with cloned validators (later fields override earlier ones)\n for (const key in validator.schema) {\n merged.schema[key] = validator.schema[key].clone();\n }\n\n // Override configuration with other validator's config\n merged.shouldAllowUnknown = validator.shouldAllowUnknown;\n merged.allowedKeys = [...merged.allowedKeys, ...validator.allowedKeys];\n\n // Append rules, mutators, transformers from other validator\n merged.rules.push(...validator.rules);\n merged.mutators.push(...validator.mutators);\n merged.dataTransformers.push(...validator.dataTransformers);\n\n // Merge attributes text (later wins)\n merged.attributesText = {\n ...merged.attributesText,\n ...validator.attributesText,\n };\n\n merged.translatedAttributes = {\n ...merged.translatedAttributes,\n ...validator.translatedAttributes,\n };\n\n return merged as ObjectValidator<TSchema & TMerge>;\n }\n\n /**\n * Create a new schema with only the specified fields\n * Clones the current validator and keeps only the selected fields\n * **Preserves all configuration** (allowUnknown, stripUnknown, etc.)\n *\n * @param keys - Field names to keep in the schema\n * @returns A new ObjectValidator with only the picked fields\n *\n * @example\n * ```ts\n * const fullUser = v.object({\n * id: v.int().required(),\n * name: v.string().required(),\n * email: v.string().email().required(),\n * password: v.string().required(),\n * role: v.string()\n * }).allowUnknown();\n *\n * // For login - only need email and password\n * const loginSchema = fullUser.pick('email', 'password');\n * // loginSchema has: { email, password }\n * // loginSchema keeps: allowUnknown() ✅\n *\n * // For public profile\n * const publicSchema = fullUser.pick('id', 'name', 'role');\n * // publicSchema has: { id, name, role }\n * ```\n */\n public pick<K extends keyof TSchema>(...keys: K[]): ObjectValidator<Pick<TSchema, K>> {\n // Clone current validator\n const picked = this.clone() as any;\n\n // Create new schema with only picked keys\n const newSchema = {} as Pick<TSchema, K>;\n for (const key of keys) {\n if (key in picked.schema) {\n (newSchema as any)[key] = picked.schema[key];\n }\n }\n\n picked.schema = newSchema;\n\n return picked as ObjectValidator<Pick<TSchema, K>>;\n }\n\n /**\n * Mark all or the given schema fields as optional\n */\n public partial<K extends keyof TSchema>(...keys: K[]) {\n const validationSchema = this.clone();\n\n if (keys.length === 0) {\n keys = Object.keys(validationSchema.schema) as K[];\n }\n\n for (const key of keys) {\n validationSchema.schema[key] = validationSchema.schema[key].optional();\n }\n\n return validationSchema;\n }\n\n /**\n * Make the all or the given fields as required\n */\n public requiredFields<K extends keyof TSchema>(...keys: K[]) {\n const validationSchema = this.clone();\n\n if (keys.length === 0) {\n keys = Object.keys(validationSchema.schema) as K[];\n }\n\n for (const key of keys) {\n validationSchema.schema[key] = validationSchema.schema[key].required();\n }\n\n return validationSchema;\n }\n\n /**\n * Create a new schema excluding the specified fields\n * Clones the current validator and removes the specified fields\n * **Preserves all configuration** (allowUnknown, stripUnknown, etc.)\n *\n * @param keys - Field names to exclude from the schema\n * @returns A new ObjectValidator without the excluded fields\n *\n * @example\n * ```ts\n * const fullUser = v.object({\n * id: v.int().required(),\n * name: v.string().required(),\n * email: v.string().email().required(),\n * password: v.string().required(),\n * role: v.string()\n * }).allowUnknown();\n *\n * // For updates - exclude id\n * const updateSchema = fullUser.without('id');\n * // updateSchema has: { name, email, password, role }\n * // updateSchema keeps: allowUnknown() ✅\n *\n * // For public API - exclude sensitive fields\n * const publicSchema = fullUser.without('password', 'role');\n * // publicSchema has: { id, name, email }\n *\n * // Combine with other methods\n * const patchSchema = fullUser.without('id', 'password');\n * // patchSchema has: { name, email, role }\n * ```\n */\n public without<K extends keyof TSchema>(...keys: K[]): ObjectValidator<Omit<TSchema, K>> {\n // Clone current validator\n const filtered = this.clone() as any;\n\n // Create new schema excluding specified keys\n const newSchema = {} as Omit<TSchema, K>;\n for (const key in filtered.schema) {\n if (!keys.includes(key as any)) {\n (newSchema as any)[key] = filtered.schema[key];\n }\n }\n\n filtered.schema = newSchema;\n\n return filtered as ObjectValidator<Omit<TSchema, K>>;\n }\n\n /** Mutate the data */\n public mutate(data: any, context: SchemaContext) {\n if (!isPlainObject(data)) return data;\n return super.mutate({ ...data }, context);\n }\n\n /** Validate the data */\n public async validate(\n data: any,\n context: SchemaContext = { path: \"\" } as SchemaContext,\n ): Promise<ValidationResult> {\n context.schema = this.schema;\n const mutatedData = await this.mutate(data, context);\n\n // Check for unknown properties\n if (this.shouldAllowUnknown === false && !this.hasUnknownKeyRule) {\n this.hasUnknownKeyRule = true;\n const rule = this.addMutableRule(unknownKeyRule, undefined, {\n allowedKeys: this.allowedKeys,\n schema: this.schema,\n });\n\n this.setRuleAttributesList(rule);\n }\n\n const result = await super.validate(mutatedData, context);\n\n if (result.isValid === false) return result;\n if (data === undefined) return result;\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 1: Validate user input fields (skip computed/managed)\n // ═══════════════════════════════════════════════════════════\n const errors: ValidationResult[\"errors\"] = [];\n const validatedData: any = {};\n\n const userInputKeys = Object.keys(this.schema).filter(\n (key) => !this.isComputedValidator(this.schema[key]),\n );\n\n const validationPromises = userInputKeys.map(async (key) => {\n const validator = this.schema[key];\n const value =\n mutatedData?.[key] !== undefined ? mutatedData[key] : validator.getDefaultValue();\n\n const childContext: SchemaContext = {\n ...context,\n parent: mutatedData,\n value,\n key,\n path: setKeyPath(context.path, key),\n };\n\n const childResult = await validator.validate(value, childContext);\n\n // Only include in validated data if not omitted\n if (childResult.data !== undefined && !validator.isOmitted()) {\n validatedData[key] = childResult.data;\n }\n\n if (childResult.isValid === false) {\n errors.push(...childResult.errors);\n }\n });\n\n await Promise.all(validationPromises);\n\n // If Phase 1 failed, return early\n if (errors.length > 0) {\n return {\n isValid: false,\n errors,\n data: undefined,\n };\n }\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 2: Execute computed/managed fields with validated data\n // ═══════════════════════════════════════════════════════════\n const computedFields = this.getComputedFields();\n\n const computedPromises = Object.keys(computedFields).map(async (key) => {\n const validator = computedFields[key];\n\n const childContext: SchemaContext = {\n ...context,\n parent: validatedData,\n value: undefined, // Computed fields don't have input value\n };\n\n // Execute computed callback with validated data\n const childResult = await validator.validate(validatedData, childContext);\n\n // Only include in final data if not omitted\n if (childResult.data !== undefined && !validator.isOmitted()) {\n validatedData[key] = childResult.data;\n }\n\n if (childResult.isValid === false) {\n errors.push(...childResult.errors);\n }\n });\n\n await Promise.all(computedPromises);\n\n // If Phase 2 failed, return early\n if (errors.length > 0) {\n return {\n isValid: false,\n errors,\n data: undefined,\n };\n }\n\n // Remove undefined values\n const cleanedData = removeUndefinedValues(validatedData);\n\n const transformedData = await this.startTransformationPipeline(cleanedData, context);\n\n const output =\n this.shouldAllowUnknown === false\n ? transformedData\n : {\n ...transformedData,\n ...except(mutatedData, Object.keys(this.schema)),\n };\n\n return {\n isValid: true,\n errors: [],\n data: output,\n };\n }\n\n /**\n * Check if a validator is a computed or managed field\n * ManagedValidator extends ComputedValidator, so instanceof catches both\n */\n private isComputedValidator(validator: BaseValidator): boolean {\n return validator instanceof ComputedValidator;\n }\n\n /**\n * Get all computed/managed fields from the schema\n */\n private getComputedFields(): Record<string, ComputedValidator> {\n const computed: Record<string, any> = {};\n\n for (const [key, validator] of Object.entries(this.schema)) {\n if (validator instanceof ComputedValidator) {\n computed[key] = validator;\n }\n }\n\n return computed;\n }\n\n /**\n * @inheritdoc\n *\n * Recursively generates JSON Schema for all input fields in the schema.\n * Computed/managed fields are skipped — they have no input representation.\n *\n * **Standard targets** (`draft-2020-12`, `draft-07`, `openapi-3.0`):\n * - Fields marked `.optional()` are excluded from `required`.\n *\n * **`openai-strict` target** (OpenAI Structured Outputs):\n * - ALL fields appear in `required` — OpenAI rejects schemas with optional fields.\n * - Optional fields are instead expressed as nullable types:\n * `{ type: [\"string\", \"null\"] }` so the model can output `null` for them.\n * - Recursively applies `openai-strict` to all nested objects.\n *\n * @example\n * ```ts\n * v.object({\n * name: v.string().required(),\n * age: v.int().optional(),\n * }).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"object\",\n * // properties: { name: { type: \"string\" }, age: { type: \"integer\" } },\n * // required: [\"name\"], additionalProperties: false }\n *\n * v.object({\n * name: v.string().required(),\n * age: v.int().optional(),\n * }).toJsonSchema(\"openai-strict\")\n * // → { type: \"object\",\n * // properties: { name: { type: \"string\" }, age: { type: [\"integer\", \"null\"] } },\n * // required: [\"name\", \"age\"], ← all fields\n * // additionalProperties: false }\n * ```\n */\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n const properties: Record<string, JsonSchemaResult> = {};\n const required: string[] = [];\n const isOpenAIStrict = target === \"openai-strict\";\n\n for (const [key, validator] of Object.entries(this.schema)) {\n // Skip computed/managed — runtime-only, no input schema\n if (validator instanceof ComputedValidator) continue;\n\n let fieldSchema = validator.toJsonSchema(target);\n\n if (isOpenAIStrict) {\n // OpenAI strict: every field must be in required.\n // Optional fields are expressed as nullable rather than absent.\n if (validator.isOptional) {\n fieldSchema = wrapNullableStrict(fieldSchema);\n }\n required.push(key);\n } else {\n // Standard JSON Schema: only non-optional fields go in required\n if (!validator.isOptional) {\n required.push(key);\n }\n }\n\n properties[key] = fieldSchema;\n }\n\n const schema: JsonSchemaResult = { type: \"object\", properties };\n\n if (required.length > 0) schema.required = required;\n if (!this.shouldAllowUnknown) schema.additionalProperties = false;\n if (this.isNullable) applyNullable(schema, target);\n\n return schema;\n }\n}\n\n/** Recursively remove undefined values from an object */\nfunction removeUndefinedValues(obj: any, visited = new WeakMap<object, any>()): any {\n // Handle primitives and null\n if (obj === null) {\n return obj;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => removeUndefinedValues(item, visited));\n }\n\n // Skip non-plain objects (class instances, Dates, Buffers, etc.)\n if (!isPlainObject(obj)) {\n return obj;\n }\n\n // Handle circular references - return already processed result\n if (visited.has(obj)) {\n return visited.get(obj);\n }\n\n // Process plain objects\n const result: any = {};\n visited.set(obj, result); // Mark as processing BEFORE recursion\n\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined) {\n result[key] = removeUndefinedValues(value, visited);\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,kBAAb,MAAa,wBAAyD,cAGpE;CAKA,AAAO,YACL,AAAO,QACP,cACA;EACA,MAAM;EAHC;4BALsB;qBACG,CAAC;2BACL;EAO5B,KAAK,eAAe,YAAY,YAAY;CAC9C;;;;CAKA,AAAO,YAAY,OAAqB;EACtC,OAAO,cAAc,KAAK;CAC5B;;CAGA,AAAO,eAAe;EACpB,MAAM,YAAY,KAAK;EACvB,OAAO,UAAU,WAAW,qBAAqB,EAC/C,IAAI,cAAc;GAChB,OAAO,UAAU;EACnB,EACF,CAAC;CACH;;CAGA,AAAO,MAAM,GAAG,MAAgB;EAC9B,MAAM,YAAY,KAAK;EACvB,UAAU,YAAY,KAAK,GAAG,IAAI;EAClC,OAAO;CACT;;CAGA,AAAO,KAAK,YAAY,MAAM;EAE5B,OADkB,KAAK,SACN,WAAW,mBAAmB,EAAE,UAAU,CAAC;CAC9D;;;;CAKA,AAAO,aAAa,QAAQ,MAAM;EAChC,MAAM,YAAY,KAAK;EACvB,UAAU,qBAAqB;EAC/B,OAAO;CACT;;;;;;;;;;;;;;CAeA,AAAgB,MAAM,MAAu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I,KAAK,YAAY,cAAc,QAAQ,MAAM;EAEjD,OAAO;CACT;AACF;;AAGA,SAAS,sBAAsB,KAAU,0BAAU,IAAI,QAAqB,GAAQ;CAElF,IAAI,QAAQ,MACV,OAAO;CAIT,IAAI,MAAM,QAAQ,GAAG,GACnB,OAAO,IAAI,KAAK,SAAS,sBAAsB,MAAM,OAAO,CAAC;CAI/D,IAAI,CAAC,cAAc,GAAG,GACpB,OAAO;CAIT,IAAI,QAAQ,IAAI,GAAG,GACjB,OAAO,QAAQ,IAAI,GAAG;CAIxB,MAAM,SAAc,CAAC;CACrB,QAAQ,IAAI,KAAK,MAAM;CAEvB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAC3C,IAAI,UAAU,QACZ,OAAO,OAAO,sBAAsB,OAAO,OAAO;CAItD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"object-validator.mjs","names":[],"sources":["../../../../../../../seal/src/validators/object-validator.ts"],"sourcesContent":["import { except } from \"@mongez/reinforcements\";\nimport { isPlainObject } from \"@mongez/supportive-is\";\nimport { setKeyPath } from \"../helpers\";\nimport { objectTrimMutator, stripUnknownMutator } from \"../mutators\";\nimport { objectRule, unknownKeyRule } from \"../rules\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { applyNullable, wrapNullableStrict } from \"../standard-schema/json-schema\";\nimport type { Schema, SchemaContext, ValidationResult } from \"../types\";\nimport type {\n InferInputObjectShape,\n InferOutputObjectShape,\n} from \"../types/inference-types\";\nimport { BaseValidator } from \"./base-validator\";\nimport { ComputedValidator } from \"./computed-validator\";\n\n/**\n * Object validator class with generic schema type for proper type inference.\n *\n * Threads two distinct inferred shapes into `BaseValidator`'s `TInput`/`TOutput`:\n *\n * - `TInput` = `InferInputObjectShape<TSchema>` — what `~standard.validate()`\n * accepts (caller's pre-validation payload; defaults/catches make\n * keys optional)\n * - `TOutput` = `InferOutputObjectShape<TSchema>` — what `~standard.validate()`\n * returns on success (post-default, post-catch shape; guaranteed\n * keys are required)\n *\n * Both helpers are used directly (not the full `Infer.*` walker) to avoid a\n * recursive class-base evaluation that would otherwise occur when the\n * brand-aware widening tries to inspect the class type.\n */\nexport class ObjectValidator<TSchema extends Schema = Schema> extends BaseValidator<\n InferInputObjectShape<TSchema>,\n InferOutputObjectShape<TSchema>\n> {\n protected shouldAllowUnknown = false;\n protected allowedKeys: string[] = [];\n protected hasUnknownKeyRule = false;\n\n public constructor(\n public schema: TSchema,\n errorMessage?: string,\n ) {\n super();\n this.addMutableRule(objectRule, errorMessage);\n }\n\n /**\n * Check if value is an object type (plain object, not array or date)\n */\n public matchesType(value: any): boolean {\n return isPlainObject(value);\n }\n\n /** Strip unknown keys from the data */\n public stripUnknown() {\n const validator = this.instance;\n return validator.addMutator(stripUnknownMutator, {\n get allowedKeys() {\n return validator.allowedKeys;\n },\n });\n }\n\n /** Add list of allowed keys that could be in the data but not necessarily validated */\n public allow(...keys: string[]) {\n const validator = this.instance;\n validator.allowedKeys.push(...keys);\n return validator;\n }\n\n /** Trim values of the object properties */\n public trim(recursive = true) {\n const validator = this.instance;\n return validator.addMutator(objectTrimMutator, { recursive });\n }\n\n /** Whether to allow unknown properties\n * Please note it will allow only unknown direct children keys, not nested children keys\n */\n public allowUnknown(allow = true) {\n const validator = this.instance;\n validator.shouldAllowUnknown = allow;\n return validator;\n }\n\n /**\n * Create a copy of this object validator with the same configuration\n * Copies schema, rules, mutators, transformers, and object-specific settings\n *\n * @returns A new ObjectValidator instance with copied configuration\n *\n * @example\n * ```ts\n * const baseUser = v.object({ name: v.string() }).allowUnknown();\n * const userCopy = baseUser.clone();\n * // userCopy has the same schema and allowUnknown setting\n * ```\n */\n public override clone(keys?: string[]): this {\n // Get cloned instance with all BaseValidator properties\n const cloned = super.clone();\n\n // Clone schema with deep copy of validators\n const newSchema = {} as TSchema;\n for (const [key, validator] of Object.entries(this.schema)) {\n if (keys && !keys.includes(key)) continue;\n (newSchema as Schema)[key] = validator.clone();\n }\n\n cloned.schema = newSchema;\n\n // Add ObjectValidator-specific properties\n cloned.shouldAllowUnknown = this.shouldAllowUnknown;\n cloned.allowedKeys = [...this.allowedKeys];\n // NOTE: hasUnknownKeyRule is intentionally NOT copied.\n // Each clone must add its own unknownKeyRule on first validate()\n // so it holds references to its own schema/allowedKeys, not the original's.\n\n return cloned;\n }\n\n /**\n * Extend this schema with additional fields\n * Clones the current validator and adds new fields to the schema\n * **Keeps original configuration** (allowUnknown, stripUnknown, etc.)\n *\n * If an ObjectValidator is provided, only its schema is used - its configuration is ignored.\n * This is useful for creating reusable field collections that can be added to different schemas.\n *\n * @param schemaOrValidator - Plain schema object or ObjectValidator to extend with\n * @returns A new ObjectValidator with merged schema and original configuration\n *\n * @example\n * ```ts\n * // Extend with plain schema\n * const baseUser = v.object({\n * name: v.string().required(),\n * email: v.string().email().required()\n * }).allowUnknown();\n *\n * const adminUser = baseUser.extend({\n * role: v.string().in(['admin', 'superadmin']).required()\n * });\n * // adminUser has: name, email, role\n * // adminUser keeps: allowUnknown() from base ✅\n *\n * // Extend with ObjectValidator (only schema is used)\n * const auditFields = v.object({\n * createdAt: v.date().required(),\n * updatedAt: v.date().required()\n * }).stripUnknown(); // This config is ignored!\n *\n * const fullUser = baseUser.extend(auditFields);\n * // fullUser has: name, email, createdAt, updatedAt\n * // fullUser keeps: allowUnknown() from base (NOT stripUnknown from auditFields) ✅\n *\n * // Chain multiple extends\n * const complexSchema = baseUser\n * .extend(auditFields)\n * .extend({ metadata: v.object({}) });\n * ```\n */\n public extend<TExtension extends Schema>(\n schemaOrValidator: TExtension | ObjectValidator<TExtension>,\n ): ObjectValidator<TSchema & TExtension> {\n // Clone current validator to preserve original\n const extended = this.clone() as any;\n\n // Extract schema from parameter\n const schemaToAdd =\n schemaOrValidator instanceof ObjectValidator ? schemaOrValidator.schema : schemaOrValidator;\n\n // Merge schemas with cloned validators (later fields override earlier ones)\n for (const [key, validator] of Object.entries(schemaToAdd)) {\n (extended.schema as Schema)[key] = validator.clone();\n }\n\n return extended as ObjectValidator<TSchema & TExtension>;\n }\n\n /**\n * Merge with another ObjectValidator\n * Clones current validator, merges schemas, and **overrides configuration** with other validator's config\n *\n * Unlike extend(), merge() combines both schemas AND configurations.\n * The other validator's configuration (allowUnknown, stripUnknown, etc.) takes precedence.\n *\n * @param validator - Another ObjectValidator to merge with\n * @returns A new ObjectValidator with merged schema and configuration\n *\n * @example\n * ```ts\n * const baseUser = v.object({\n * name: v.string().required()\n * }).allowUnknown();\n *\n * const timestamps = v.object({\n * createdAt: v.date().required(),\n * updatedAt: v.date().required()\n * }).stripUnknown();\n *\n * const merged = baseUser.merge(timestamps);\n * // merged has: name, createdAt, updatedAt\n * // merged config: stripUnknown() from timestamps (overrides allowUnknown) ✅\n *\n * // Chain multiple merges\n * const full = baseUser.merge(timestamps).merge(softDeleteSchema);\n * ```\n */\n public merge<TMerge extends Schema>(\n validator: ObjectValidator<TMerge>,\n ): ObjectValidator<TSchema & TMerge> {\n // Clone current validator\n const merged = this.clone() as any;\n\n // Merge schemas with cloned validators (later fields override earlier ones)\n for (const [key, schemaValidator] of Object.entries(validator.schema)) {\n (merged.schema as Schema)[key] = schemaValidator.clone();\n }\n\n // Override configuration with other validator's config\n merged.shouldAllowUnknown = validator.shouldAllowUnknown;\n merged.allowedKeys = [...merged.allowedKeys, ...validator.allowedKeys];\n\n // Append rules, mutators, transformers from other validator\n merged.rules.push(...validator.rules);\n merged.mutators.push(...validator.mutators);\n merged.dataTransformers.push(...validator.dataTransformers);\n\n // Merge attributes text (later wins)\n merged.attributesText = {\n ...merged.attributesText,\n ...validator.attributesText,\n };\n\n merged.translatedAttributes = {\n ...merged.translatedAttributes,\n ...validator.translatedAttributes,\n };\n\n return merged as ObjectValidator<TSchema & TMerge>;\n }\n\n /**\n * Create a new schema with only the specified fields\n * Clones the current validator and keeps only the selected fields\n * **Preserves all configuration** (allowUnknown, stripUnknown, etc.)\n *\n * @param keys - Field names to keep in the schema\n * @returns A new ObjectValidator with only the picked fields\n *\n * @example\n * ```ts\n * const fullUser = v.object({\n * id: v.int().required(),\n * name: v.string().required(),\n * email: v.string().email().required(),\n * password: v.string().required(),\n * role: v.string()\n * }).allowUnknown();\n *\n * // For login - only need email and password\n * const loginSchema = fullUser.pick('email', 'password');\n * // loginSchema has: { email, password }\n * // loginSchema keeps: allowUnknown() ✅\n *\n * // For public profile\n * const publicSchema = fullUser.pick('id', 'name', 'role');\n * // publicSchema has: { id, name, role }\n * ```\n */\n public pick<K extends keyof TSchema>(...keys: K[]): ObjectValidator<Pick<TSchema, K>> {\n // Clone current validator\n const picked = this.clone() as any;\n\n // Create new schema with only picked keys\n const newSchema = {} as Pick<TSchema, K>;\n for (const key of keys) {\n if (key in picked.schema) {\n (newSchema as any)[key] = picked.schema[key];\n }\n }\n\n picked.schema = newSchema;\n\n return picked as ObjectValidator<Pick<TSchema, K>>;\n }\n\n /**\n * Mark all or the given schema fields as optional\n */\n public partial<K extends keyof TSchema>(...keys: K[]) {\n const validationSchema = this.clone();\n\n if (keys.length === 0) {\n keys = Object.keys(validationSchema.schema) as K[];\n }\n\n for (const [key, validator] of Object.entries(validationSchema.schema)) {\n if (keys.length === 0 || keys.includes(key as K)) {\n (validationSchema.schema as Schema)[key] = validator.optional();\n }\n }\n\n return validationSchema;\n }\n\n /**\n * Make the all or the given fields as required\n */\n public requiredFields<K extends keyof TSchema>(...keys: K[]) {\n const validationSchema = this.clone();\n\n if (keys.length === 0) {\n keys = Object.keys(validationSchema.schema) as K[];\n }\n\n for (const [key, validator] of Object.entries(validationSchema.schema)) {\n if (keys.length === 0 || keys.includes(key as K)) {\n (validationSchema.schema as Schema)[key] = validator.required();\n }\n }\n\n return validationSchema;\n }\n\n /**\n * Create a new schema excluding the specified fields\n * Clones the current validator and removes the specified fields\n * **Preserves all configuration** (allowUnknown, stripUnknown, etc.)\n *\n * @param keys - Field names to exclude from the schema\n * @returns A new ObjectValidator without the excluded fields\n *\n * @example\n * ```ts\n * const fullUser = v.object({\n * id: v.int().required(),\n * name: v.string().required(),\n * email: v.string().email().required(),\n * password: v.string().required(),\n * role: v.string()\n * }).allowUnknown();\n *\n * // For updates - exclude id\n * const updateSchema = fullUser.without('id');\n * // updateSchema has: { name, email, password, role }\n * // updateSchema keeps: allowUnknown() ✅\n *\n * // For public API - exclude sensitive fields\n * const publicSchema = fullUser.without('password', 'role');\n * // publicSchema has: { id, name, email }\n *\n * // Combine with other methods\n * const patchSchema = fullUser.without('id', 'password');\n * // patchSchema has: { name, email, role }\n * ```\n */\n public without<K extends keyof TSchema>(...keys: K[]): ObjectValidator<Omit<TSchema, K>> {\n // Clone current validator\n const filtered = this.clone() as any;\n\n // Create new schema excluding specified keys\n const newSchema = {} as Omit<TSchema, K>;\n for (const key in filtered.schema) {\n if (!keys.includes(key as any)) {\n (newSchema as any)[key] = filtered.schema[key];\n }\n }\n\n filtered.schema = newSchema;\n\n return filtered as ObjectValidator<Omit<TSchema, K>>;\n }\n\n /** Mutate the data */\n public mutate(data: any, context: SchemaContext) {\n if (!isPlainObject(data)) return data;\n return super.mutate({ ...data }, context);\n }\n\n /** Validate the data */\n public async validate(\n data: any,\n context: SchemaContext = { path: \"\" } as SchemaContext,\n ): Promise<ValidationResult> {\n context.schema = this.schema;\n const mutatedData = await this.mutate(data, context);\n\n // Check for unknown properties\n if (this.shouldAllowUnknown === false && !this.hasUnknownKeyRule) {\n this.hasUnknownKeyRule = true;\n const rule = this.addMutableRule(unknownKeyRule, undefined, {\n allowedKeys: this.allowedKeys,\n schema: this.schema,\n });\n\n this.setRuleAttributesList(rule);\n }\n\n const result = await super.validate(mutatedData, context);\n\n if (result.isValid === false) return result;\n if (data === undefined) return result;\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 1: Validate user input fields (skip computed/managed)\n // ═══════════════════════════════════════════════════════════\n const errors: ValidationResult[\"errors\"] = [];\n const validatedData: any = {};\n\n const userInputEntries = Object.entries(this.schema).filter(\n ([, validator]) => !this.isComputedValidator(validator),\n );\n\n const validationPromises = userInputEntries.map(async ([key, validator]) => {\n const value =\n mutatedData?.[key] !== undefined ? mutatedData[key] : validator.getDefaultValue();\n\n const childContext: SchemaContext = {\n ...context,\n parent: mutatedData,\n value,\n key,\n path: setKeyPath(context.path, key),\n };\n\n const childResult = await validator.validate(value, childContext);\n\n // Only include in validated data if not omitted\n if (childResult.data !== undefined && !validator.isOmitted()) {\n validatedData[key] = childResult.data;\n }\n\n if (childResult.isValid === false) {\n errors.push(...childResult.errors);\n }\n });\n\n await Promise.all(validationPromises);\n\n // If Phase 1 failed, return early\n if (errors.length > 0) {\n return {\n isValid: false,\n errors,\n data: undefined,\n };\n }\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 2: Execute computed/managed fields with validated data\n // ═══════════════════════════════════════════════════════════\n const computedFields = this.getComputedFields();\n\n const computedPromises = Object.entries(computedFields).map(async ([key, validator]) => {\n\n const childContext: SchemaContext = {\n ...context,\n parent: validatedData,\n value: undefined, // Computed fields don't have input value\n };\n\n // Execute computed callback with validated data\n const childResult = await validator.validate(validatedData, childContext);\n\n // Only include in final data if not omitted\n if (childResult.data !== undefined && !validator.isOmitted()) {\n validatedData[key] = childResult.data;\n }\n\n if (childResult.isValid === false) {\n errors.push(...childResult.errors);\n }\n });\n\n await Promise.all(computedPromises);\n\n // If Phase 2 failed, return early\n if (errors.length > 0) {\n return {\n isValid: false,\n errors,\n data: undefined,\n };\n }\n\n // Remove undefined values\n const cleanedData = removeUndefinedValues(validatedData);\n\n const transformedData = await this.startTransformationPipeline(cleanedData, context);\n\n const output =\n this.shouldAllowUnknown === false\n ? transformedData\n : {\n ...transformedData,\n ...except(mutatedData, Object.keys(this.schema)),\n };\n\n return {\n isValid: true,\n errors: [],\n data: output,\n };\n }\n\n /**\n * Check if a validator is a computed or managed field\n * ManagedValidator extends ComputedValidator, so instanceof catches both\n */\n private isComputedValidator(validator: BaseValidator): boolean {\n return validator instanceof ComputedValidator;\n }\n\n /**\n * Get all computed/managed fields from the schema\n */\n private getComputedFields(): Record<string, ComputedValidator> {\n const computed: Record<string, ComputedValidator> = {};\n\n for (const [key, validator] of Object.entries(this.schema)) {\n if (validator instanceof ComputedValidator) {\n computed[key] = validator;\n }\n }\n\n return computed;\n }\n\n /**\n * @inheritdoc\n *\n * Recursively generates JSON Schema for all input fields in the schema.\n * Computed/managed fields are skipped — they have no input representation.\n *\n * **Standard targets** (`draft-2020-12`, `draft-07`, `openapi-3.0`):\n * - Fields marked `.optional()` are excluded from `required`.\n *\n * **`openai-strict` target** (OpenAI Structured Outputs):\n * - ALL fields appear in `required` — OpenAI rejects schemas with optional fields.\n * - Optional fields are instead expressed as nullable types:\n * `{ type: [\"string\", \"null\"] }` so the model can output `null` for them.\n * - Recursively applies `openai-strict` to all nested objects.\n *\n * @example\n * ```ts\n * v.object({\n * name: v.string().required(),\n * age: v.int().optional(),\n * }).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"object\",\n * // properties: { name: { type: \"string\" }, age: { type: \"integer\" } },\n * // required: [\"name\"], additionalProperties: false }\n *\n * v.object({\n * name: v.string().required(),\n * age: v.int().optional(),\n * }).toJsonSchema(\"openai-strict\")\n * // → { type: \"object\",\n * // properties: { name: { type: \"string\" }, age: { type: [\"integer\", \"null\"] } },\n * // required: [\"name\", \"age\"], ← all fields\n * // additionalProperties: false }\n * ```\n */\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n const properties: Record<string, JsonSchemaResult> = {};\n const required: string[] = [];\n const isOpenAIStrict = target === \"openai-strict\";\n\n for (const [key, validator] of Object.entries(this.schema)) {\n // Skip computed/managed — runtime-only, no input schema\n if (validator instanceof ComputedValidator) continue;\n\n let fieldSchema = validator.toJsonSchema(target);\n\n if (isOpenAIStrict) {\n // OpenAI strict: every field must be in required.\n // Optional fields are expressed as nullable rather than absent.\n if (validator.isOptional) {\n fieldSchema = wrapNullableStrict(fieldSchema);\n }\n required.push(key);\n } else {\n // Standard JSON Schema: only non-optional fields go in required\n if (!validator.isOptional) {\n required.push(key);\n }\n }\n\n properties[key] = fieldSchema;\n }\n\n const schema: JsonSchemaResult = { type: \"object\", properties };\n\n if (required.length > 0) schema.required = required;\n if (!this.shouldAllowUnknown) schema.additionalProperties = false;\n if (this.isNullable) applyNullable(schema, target);\n\n return schema;\n }\n}\n\n/** Recursively remove undefined values from an object */\nfunction removeUndefinedValues(obj: any, visited = new WeakMap<object, any>()): any {\n // Handle primitives and null\n if (obj === null) {\n return obj;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => removeUndefinedValues(item, visited));\n }\n\n // Skip non-plain objects (class instances, Dates, Buffers, etc.)\n if (!isPlainObject(obj)) {\n return obj;\n }\n\n // Handle circular references - return already processed result\n if (visited.has(obj)) {\n return visited.get(obj);\n }\n\n // Process plain objects\n const result: any = {};\n visited.set(obj, result); // Mark as processing BEFORE recursion\n\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined) {\n result[key] = removeUndefinedValues(value, visited);\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,kBAAb,MAAa,wBAAyD,cAGpE;CAKA,AAAO,YACL,AAAO,QACP,cACA;EACA,MAAM;EAHC;4BALsB;qBACG,CAAC;2BACL;EAO5B,KAAK,eAAe,YAAY,YAAY;CAC9C;;;;CAKA,AAAO,YAAY,OAAqB;EACtC,OAAO,cAAc,KAAK;CAC5B;;CAGA,AAAO,eAAe;EACpB,MAAM,YAAY,KAAK;EACvB,OAAO,UAAU,WAAW,qBAAqB,EAC/C,IAAI,cAAc;GAChB,OAAO,UAAU;EACnB,EACF,CAAC;CACH;;CAGA,AAAO,MAAM,GAAG,MAAgB;EAC9B,MAAM,YAAY,KAAK;EACvB,UAAU,YAAY,KAAK,GAAG,IAAI;EAClC,OAAO;CACT;;CAGA,AAAO,KAAK,YAAY,MAAM;EAE5B,OADkB,KAAK,SACN,WAAW,mBAAmB,EAAE,UAAU,CA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