@empathyco/x-adapter 8.10.0 → 9.0.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.
Files changed (41) hide show
  1. package/README.md +111 -1
  2. package/dist/cjs/mappers/index.js +1 -0
  3. package/dist/cjs/mappers/index.js.map +1 -1
  4. package/dist/cjs/mappers/schema-mapper.factory.js +1 -0
  5. package/dist/cjs/mappers/schema-mapper.factory.js.map +1 -1
  6. package/dist/cjs/mappers/transform-schema-mapper.factory.js +21 -0
  7. package/dist/cjs/mappers/transform-schema-mapper.factory.js.map +1 -0
  8. package/dist/cjs/schemas/index.js +2 -0
  9. package/dist/cjs/schemas/index.js.map +1 -1
  10. package/dist/cjs/schemas/transform-schema.js +98 -0
  11. package/dist/cjs/schemas/transform-schema.js.map +1 -0
  12. package/dist/cjs/schemas/transform-schema.types.js +3 -0
  13. package/dist/cjs/schemas/transform-schema.types.js.map +1 -0
  14. package/dist/cjs/schemas/types.js.map +1 -1
  15. package/dist/cjs/schemas/utils.js +2 -0
  16. package/dist/cjs/schemas/utils.js.map +1 -1
  17. package/dist/esm/mappers/index.js +1 -0
  18. package/dist/esm/mappers/index.js.map +1 -1
  19. package/dist/esm/mappers/schema-mapper.factory.js +1 -0
  20. package/dist/esm/mappers/schema-mapper.factory.js.map +1 -1
  21. package/dist/esm/mappers/transform-schema-mapper.factory.js +18 -0
  22. package/dist/esm/mappers/transform-schema-mapper.factory.js.map +1 -0
  23. package/dist/esm/schemas/index.js +2 -0
  24. package/dist/esm/schemas/index.js.map +1 -1
  25. package/dist/esm/schemas/transform-schema.js +94 -0
  26. package/dist/esm/schemas/transform-schema.js.map +1 -0
  27. package/dist/esm/schemas/transform-schema.types.js +2 -0
  28. package/dist/esm/schemas/transform-schema.types.js.map +1 -0
  29. package/dist/esm/schemas/types.js.map +1 -1
  30. package/dist/esm/schemas/utils.js +2 -0
  31. package/dist/esm/schemas/utils.js.map +1 -1
  32. package/dist/types/mappers/index.d.ts +1 -0
  33. package/dist/types/mappers/schema-mapper.factory.d.ts +1 -0
  34. package/dist/types/mappers/transform-schema-mapper.factory.d.ts +23 -0
  35. package/dist/types/schemas/index.d.ts +2 -0
  36. package/dist/types/schemas/transform-schema.d.ts +30 -0
  37. package/dist/types/schemas/transform-schema.types.d.ts +127 -0
  38. package/dist/types/schemas/types.d.ts +7 -0
  39. package/dist/types/schemas/utils.d.ts +2 -0
  40. package/package.json +5 -4
  41. package/skills/x-adapter/SKILL.md +9 -5
package/README.md CHANGED
@@ -7,7 +7,7 @@ Some features that it provides:
7
7
  - Create an API request function based on a simple configuration.
8
8
  - Allow to configure several endpoints by extending the initial configuration.
9
9
  - Allow to configure the response/request mapping.
10
- - Create mapping functions based on Schemas.
10
+ - Create mapping functions based on Schemas, with optional [Zod](https://zod.dev) validation.
11
11
 
12
12
  <br>
13
13
 
@@ -231,8 +231,118 @@ export const searchProducts = endpointAdapterFactory({
231
231
 
232
232
  <br>
233
233
 
234
+ ### Implement your own adapter using transform schemas
235
+
236
+ A `TransformSchema` maps a source object to a target object with a plain `transform` function. As
237
+ there are no path strings involved, TypeScript does not need to compute every possible path of your
238
+ models.
239
+
240
+ ```ts
241
+ import {
242
+ createTransformSchema,
243
+ endpointAdapterFactory,
244
+ transformSchemaMapperFactory,
245
+ } from '@empathyco/x-adapter'
246
+
247
+ const userSchema = createTransformSchema<ApiUser, AppUser>({
248
+ transform: (source, context) => ({
249
+ id: source.id.toString(),
250
+ name: source.firstName,
251
+ city: source.address?.city,
252
+ }),
253
+ })
254
+
255
+ const usersResponseSchema = createTransformSchema<ApiSearchUsersResponse, AppSearchUsersResponse>({
256
+ // Nested models are mapped calling the `parse` method of their schema.
257
+ transform: (source, context) => ({
258
+ people: source.users.map(user => userSchema.parse(user, context)),
259
+ }),
260
+ })
261
+
262
+ export const searchUsers = endpointAdapterFactory({
263
+ endpoint: 'https://dummyjson.com/users/search',
264
+ requestMapper: transformSchemaMapperFactory(
265
+ createTransformSchema<AppSearchUsersRequest, ApiSearchUsersRequest>({
266
+ transform: ({ query }) => ({ q: query }),
267
+ }),
268
+ ),
269
+ responseMapper: transformSchemaMapperFactory<ApiSearchUsersResponse, AppSearchUsersResponse>(
270
+ usersResponseSchema,
271
+ ),
272
+ })
273
+ ```
274
+
275
+ The properties of the object returned by `transform` whose value is `undefined` are not added to
276
+ the target.
277
+
278
+ A `TransformSchema` can be modified after its creation:
279
+
280
+ - `$override`: modifies the schema, so the change affects all the schemas and `EndpointAdapter`(s)
281
+ that use it. It receives a `transform` function whose result is shallow merged with the already
282
+ mapped target.
283
+ - `$extends`: same as `$override`, but it creates a new schema and the original remains unchanged.
284
+ - `$replace`: replaces completely the transformation of the schema.
285
+
286
+ ```ts
287
+ interface ApiUserWithAge extends ApiUser {
288
+ age: number
289
+ }
290
+
291
+ userSchema.$override<ApiUserWithAge, { age: number }>({
292
+ // `target` is the object mapped so far, and `context` the mapper context.
293
+ transform: (source, target, context) => ({
294
+ age: source.age,
295
+ name: target.name.toUpperCase(),
296
+ }),
297
+ })
298
+ ```
299
+
300
+ #### Validating the source (optional)
301
+
302
+ A schema, and each one of its modifications, accepts a `source` validator: any object with a
303
+ `safeParse` method, like a [Zod](https://zod.dev) schema. `@empathyco/x-adapter` does not depend on
304
+ Zod, so install it in your project if you want to use it. **Zod 4 is required** (`zod@^4`): the
305
+ examples use `z.looseObject` and `zod/mini`, which do not exist in Zod 3. The types of the source
306
+ are then inferred from the validator:
307
+
308
+ ```ts
309
+ import * as z from 'zod/mini' // or `import { z } from 'zod'`
310
+
311
+ const userSchema = createTransformSchema({
312
+ source: z.looseObject({
313
+ id: z.number(),
314
+ firstName: z.string(),
315
+ address: z.optional(z.looseObject({ city: z.string() })),
316
+ }),
317
+ transform: (source): AppUser => ({
318
+ id: source.id.toString(),
319
+ name: source.firstName,
320
+ city: source.address?.city,
321
+ }),
322
+ })
323
+
324
+ userSchema.$override({
325
+ source: z.looseObject({ age: z.number() }),
326
+ transform: source => ({ age: source.age }),
327
+ })
328
+ ```
329
+
330
+ - **Validation never breaks the mapping**. If the source does not match the validator, a warning is
331
+ logged (once per different issue) and the raw source is mapped.
332
+ - Use `z.looseObject()` to describe only the properties you need. The properties that a validator
333
+ strips are kept anyway, so the schemas that extend it can still read them.
334
+ - `transformSchemaMapperFactory` also accepts a raw Zod schema (`z.object().transform()`). In that case the
335
+ mapper is strict: it throws if the source is not valid.
336
+
337
+ <br>
338
+
234
339
  ### Implement your own adapter using schemas
235
340
 
341
+ > **Deprecated**: `Schema`, `schemaMapperFactory` and `createMutableSchema` are deprecated. Their
342
+ > path based typings (`ExtractPath`) make TypeScript compute every possible path of the source
343
+ > object, which ends in huge compilation times, `TS2590` errors or the compiler running out of
344
+ > memory on big models. Use [transform schemas](#implement-your-own-adapter-using-transform-schemas) instead.
345
+
236
346
  Sometimes the transformations you will need to do in the mappers are just renaming parameters. What
237
347
  the API calls `q` might be called `query` in your request. To ease this transformations,
238
348
  `@empathyco/x-adapter` allows to create mappers using schemas.
@@ -4,5 +4,6 @@ const tslib_1 = require("tslib");
4
4
  tslib_1.__exportStar(require("./combine-mappers"), exports);
5
5
  tslib_1.__exportStar(require("./identity.mapper"), exports);
6
6
  tslib_1.__exportStar(require("./schema-mapper.factory"), exports);
7
+ tslib_1.__exportStar(require("./transform-schema-mapper.factory"), exports);
7
8
  tslib_1.__exportStar(require("./types"), exports);
8
9
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/mappers/index.ts"],"names":[],"mappings":";;;AAAA,4DAAiC;AACjC,4DAAiC;AACjC,kEAAuC;AACvC,kDAAuB","sourcesContent":["export * from './combine-mappers'\nexport * from './identity.mapper'\nexport * from './schema-mapper.factory'\nexport * from './types'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/mappers/index.ts"],"names":[],"mappings":";;;AAAA,4DAAiC;AACjC,4DAAiC;AACjC,kEAAuC;AACvC,4EAAiD;AACjD,kDAAuB","sourcesContent":["export * from './combine-mappers'\nexport * from './identity.mapper'\nexport * from './schema-mapper.factory'\nexport * from './transform-schema-mapper.factory'\nexport * from './types'\n"]}
@@ -9,6 +9,7 @@ const utils_1 = require("../schemas/utils");
9
9
  *
10
10
  * @param schema - The {@link Schema | schema} to apply in the {@link Mapper | mapper function}.
11
11
  * @returns A {@link Mapper | mapper function} that applies the given {@link Schema | schema}.
12
+ * @deprecated Use {@link transformSchemaMapperFactory} with a {@link TransformSchema} instead.
12
13
  * @public
13
14
  */
14
15
  function schemaMapperFactory(schema) {
@@ -1 +1 @@
1
- {"version":3,"file":"schema-mapper.factory.js","sourceRoot":"","sources":["../../../src/mappers/schema-mapper.factory.ts"],"names":[],"mappings":";;AAsBA,kDAMC;AAzBD,gDAQ2B;AAC3B,4CAAwE;AAExE;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CACjC,MAA8D;IAE9D,OAAO,SAAS,MAAM,CAAC,MAAc,EAAE,OAAsB;QAC3D,OAAO,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAA;IAC3C,CAAC,CAAA;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,SAAS,CAChB,MAAc,EACd,MAA8B,EAC9B,OAAsB;IAEtB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,IAAA,2BAAmB,EAAC,MAAM,CAAC,CAAC,CAAA;QAC1E,OAAO,SAAgB,CAAA;IACzB,CAAC;IACD,OAAO,IAAA,gBAAM,EACX,MAAM,EACN,CAAC,MAAM,EAAE,GAAG,EAAE,WAAW,EAAE,EAAE;QAE3B,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,IAAA,gBAAM,EAAC,MAAM,EAAE,WAAW,CAAC,EAAE,CAAC;YACnE,MAAM,CAAC,GAAG,CAAC,GAAG,IAAA,8BAAoB,EAAC,MAAM,EAAE,WAAW,CAAc,CAAA;QACtE,CAA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BAAU,EAAC,KAAK,CAAC;gBACtC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC;gBACf,CAAC,CAAC,IAAA,8BAAoB,EAAC,MAAM,EAAE,KAAmC,CAAC,CAAA;QACvE,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,IAAA,mBAAS,EAAC,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAA;IACpE,IAAI,SAA4C,CAAA;IAChD,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,SAAS,GAAG,MAAM,CAAA;IACpB,CAAC;SAAM,IAAI,IAAA,oBAAU,EAAC,UAAU,CAAC,EAAE,CAAC;QAClC,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,CAAA;IAChC,CAAC;SAAM,CAAC;QACN,SAAS,GAAG,UAAU,CAAA;IACxB,CAAC;IACD,OAAO,IAAA,iBAAO,EAAC,SAAS,CAAC;QACvB,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAW,CAAC;QACtE,CAAC,CAAC,SAAS,CACP,SAAS,EACT,SAA6C,EAC7C,OAAO,CACR,CAAA;AACP,CAAC","sourcesContent":["import type { Dictionary, ExtractPath } from '@empathyco/x-utils'\nimport type { MutableSchema, Schema, SubSchemaTransformer } from '../schemas/types'\nimport type { Mapper, MapperContext } from './types'\nimport {\n deepMerge,\n getSafePropertyChain,\n isArray,\n isFunction,\n isObject,\n isPath,\n reduce,\n} from '@empathyco/x-utils'\nimport { createMutableSchema, isInternalMethod } from '../schemas/utils'\n\n/**\n * The 'schemaMapperFactory' function creates a {@link Mapper | mapper function} for a given\n * {@link Schema | schema}.\n *\n * @param schema - The {@link Schema | schema} to apply in the {@link Mapper | mapper function}.\n * @returns A {@link Mapper | mapper function} that applies the given {@link Schema | schema}.\n * @public\n */\nexport function schemaMapperFactory<Source, Target>(\n schema: Schema<Source, Target> | MutableSchema<Source, Target>,\n): Mapper<Source, Target> {\n return function mapper(source: Source, context: MapperContext): Target {\n return mapSchema(source, schema, context)\n }\n}\n\n/**\n * The `mapSchema()` function creates a new object populated with the transformations defined by a\n * {@link Schema} applied to a source object.\n *\n * @param source - The object to apply the transformations to.\n * @param schema - The object that defines the transformations to apply.\n * @param context - The {@link MapperContext | mapper context} to feed the transformations with.\n * @returns A new object with each element being the result of the applied transformation.\n * @internal\n */\nfunction mapSchema<Source, Target>(\n source: Source,\n schema: Schema<Source, Target>,\n context: MapperContext,\n): Target {\n if (!source) {\n console.warn('This schema cannot be applied', createMutableSchema(schema))\n return undefined as any\n }\n return reduce(\n schema,\n (target, key, transformer) => {\n type TargetKey = Target[keyof Target]\n if (typeof transformer === 'string' && isPath(source, transformer)) {\n target[key] = getSafePropertyChain(source, transformer) as TargetKey\n } else if (isFunction(transformer) && !isInternalMethod(transformer.name)) {\n target[key] = transformer(source, context)\n } else if (isObject(transformer)) {\n const value =\n '$subSchema' in transformer\n ? (applySubSchemaTransformer<Source, TargetKey>(\n source,\n transformer as SubSchemaTransformer<Source, TargetKey>,\n context,\n schema as unknown as Schema<Source, TargetKey>,\n ) as TargetKey)\n : mapSchema<Source, TargetKey>(\n source,\n transformer as Schema<Source, TargetKey>,\n context,\n )\n\n if (value) {\n target[key] = value\n }\n }\n return target\n },\n {} as Target,\n )\n}\n\n/**\n * The `applySubSchemaTransformer()` function executes a `mapSchema()` function applying the defined\n * {@link SubSchemaTransformer.$subSchema}.\n *\n * @param source - The object to feed the schema.\n * @param subSchemaTransformer - The {@link SubSchemaTransformer} object with a $path, $subSchema\n * and $context options.\n * @param subSchemaTransformer.$path\n * @param subSchemaTransformer.$subSchema\n * @param subSchemaTransformer.$context\n * @param rawContext - The {@link MapperContext | mapper context} to feed the mapSchema function.\n * @param schema - The {@link Schema} to apply.\n * @returns The result of calling `mapSchema()` with the source, schema and context arguments.\n * @internal\n */\nfunction applySubSchemaTransformer<Source, Target>(\n source: Source,\n { $subSchema, $path, $context }: SubSchemaTransformer<Source, Target>,\n rawContext: MapperContext,\n schema: Schema<Source, Target>,\n): Target | Target[] | undefined {\n const subSource = getSafePropertyChain(source, $path)\n\n if (!subSource) {\n return\n }\n\n const extendedContext: Dictionary = {}\n if ($context) {\n Object.entries($context).forEach(([key, value]) => {\n if (['requestParameters', 'endpoint', 'mappedValue'].includes(key)) {\n return\n }\n extendedContext[key] = isFunction(value)\n ? value(source)\n : getSafePropertyChain(source, value as ExtractPath<typeof source>)\n })\n }\n\n const context = deepMerge({}, rawContext, $context, extendedContext)\n let subSchema: typeof $subSchema | typeof schema\n if ($subSchema === '$self') {\n subSchema = schema\n } else if (isFunction($subSchema)) {\n subSchema = $subSchema(source)\n } else {\n subSchema = $subSchema\n }\n return isArray(subSource)\n ? subSource.map(item => mapSchema(item, subSchema, context) as Target)\n : mapSchema<typeof subSource, Target>(\n subSource,\n subSchema as Schema<typeof subSource, Target>,\n context,\n )\n}\n"]}
1
+ {"version":3,"file":"schema-mapper.factory.js","sourceRoot":"","sources":["../../../src/mappers/schema-mapper.factory.ts"],"names":[],"mappings":";;AAuBA,kDAMC;AA1BD,gDAQ2B;AAC3B,4CAAwE;AAExE;;;;;;;;GAQG;AACH,SAAgB,mBAAmB,CACjC,MAA8D;IAE9D,OAAO,SAAS,MAAM,CAAC,MAAc,EAAE,OAAsB;QAC3D,OAAO,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAA;IAC3C,CAAC,CAAA;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,SAAS,CAChB,MAAc,EACd,MAA8B,EAC9B,OAAsB;IAEtB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,IAAA,2BAAmB,EAAC,MAAM,CAAC,CAAC,CAAA;QAC1E,OAAO,SAAgB,CAAA;IACzB,CAAC;IACD,OAAO,IAAA,gBAAM,EACX,MAAM,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AC,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;YAChD,IAAI,CAAC,mBAAmB,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;gBACnE,OAAM;YACR,CAAC;YACD,eAAe,CAAC,GAAG,CAAC,GAAG,IAAA,oBAAU,EAAC,KAAK,CAAC;gBACtC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC;gBACf,CAAC,CAAC,IAAA,8BAAoB,EAAC,MAAM,EAAE,KAAmC,CAAC,CAAA;QACvE,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,IAAA,mBAAS,EAAC,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAA;IACpE,IAAI,SAA4C,CAAA;IAChD,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,SAAS,GAAG,MAAM,CAAA;IACpB,CAAC;SAAM,IAAI,IAAA,oBAAU,EAAC,UAAU,CAAC,EAAE,CAAC;QAClC,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,CAAA;IAChC,CAAC;SAAM,CAAC;QACN,SAAS,GAAG,UAAU,CAAA;IACxB,CAAC;IACD,OAAO,IAAA,iBAAO,EAAC,SAAS,CAAC;QACvB,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAW,CAAC;QACtE,CAAC,CAAC,SAAS,CACP,SAAS,EACT,SAA6C,EAC7C,OAAO,CACR,CAAA;AACP,CAAC","sourcesContent":["import type { Dictionary, ExtractPath } from '@empathyco/x-utils'\nimport type { MutableSchema, Schema, SubSchemaTransformer } from '../schemas/types'\nimport type { Mapper, MapperContext } from './types'\nimport {\n deepMerge,\n getSafePropertyChain,\n isArray,\n isFunction,\n isObject,\n isPath,\n reduce,\n} from '@empathyco/x-utils'\nimport { createMutableSchema, isInternalMethod } from '../schemas/utils'\n\n/**\n * The 'schemaMapperFactory' function creates a {@link Mapper | mapper function} for a given\n * {@link Schema | schema}.\n *\n * @param schema - The {@link Schema | schema} to apply in the {@link Mapper | mapper function}.\n * @returns A {@link Mapper | mapper function} that applies the given {@link Schema | schema}.\n * @deprecated Use {@link transformSchemaMapperFactory} with a {@link TransformSchema} instead.\n * @public\n */\nexport function schemaMapperFactory<Source, Target>(\n schema: Schema<Source, Target> | MutableSchema<Source, Target>,\n): Mapper<Source, Target> {\n return function mapper(source: Source, context: MapperContext): Target {\n return mapSchema(source, schema, context)\n }\n}\n\n/**\n * The `mapSchema()` function creates a new object populated with the transformations defined by a\n * {@link Schema} applied to a source object.\n *\n * @param source - The object to apply the transformations to.\n * @param schema - The object that defines the transformations to apply.\n * @param context - The {@link MapperContext | mapper context} to feed the transformations with.\n * @returns A new object with each element being the result of the applied transformation.\n * @internal\n */\nfunction mapSchema<Source, Target>(\n source: Source,\n schema: Schema<Source, Target>,\n context: MapperContext,\n): Target {\n if (!source) {\n console.warn('This schema cannot be applied', createMutableSchema(schema))\n return undefined as any\n }\n return reduce(\n schema,\n (target, key, transformer) => {\n type TargetKey = Target[keyof Target]\n if (typeof transformer === 'string' && isPath(source, transformer)) {\n target[key] = getSafePropertyChain(source, transformer) as TargetKey\n } else if (isFunction(transformer) && !isInternalMethod(transformer.name)) {\n target[key] = transformer(source, context)\n } else if (isObject(transformer)) {\n const value =\n '$subSchema' in transformer\n ? (applySubSchemaTransformer<Source, TargetKey>(\n source,\n transformer as SubSchemaTransformer<Source, TargetKey>,\n context,\n schema as unknown as Schema<Source, TargetKey>,\n ) as TargetKey)\n : mapSchema<Source, TargetKey>(\n source,\n transformer as Schema<Source, TargetKey>,\n context,\n )\n\n if (value) {\n target[key] = value\n }\n }\n return target\n },\n {} as Target,\n )\n}\n\n/**\n * The `applySubSchemaTransformer()` function executes a `mapSchema()` function applying the defined\n * {@link SubSchemaTransformer.$subSchema}.\n *\n * @param source - The object to feed the schema.\n * @param subSchemaTransformer - The {@link SubSchemaTransformer} object with a $path, $subSchema\n * and $context options.\n * @param subSchemaTransformer.$path\n * @param subSchemaTransformer.$subSchema\n * @param subSchemaTransformer.$context\n * @param rawContext - The {@link MapperContext | mapper context} to feed the mapSchema function.\n * @param schema - The {@link Schema} to apply.\n * @returns The result of calling `mapSchema()` with the source, schema and context arguments.\n * @internal\n */\nfunction applySubSchemaTransformer<Source, Target>(\n source: Source,\n { $subSchema, $path, $context }: SubSchemaTransformer<Source, Target>,\n rawContext: MapperContext,\n schema: Schema<Source, Target>,\n): Target | Target[] | undefined {\n const subSource = getSafePropertyChain(source, $path)\n\n if (!subSource) {\n return\n }\n\n const extendedContext: Dictionary = {}\n if ($context) {\n Object.entries($context).forEach(([key, value]) => {\n if (['requestParameters', 'endpoint', 'mappedValue'].includes(key)) {\n return\n }\n extendedContext[key] = isFunction(value)\n ? value(source)\n : getSafePropertyChain(source, value as ExtractPath<typeof source>)\n })\n }\n\n const context = deepMerge({}, rawContext, $context, extendedContext)\n let subSchema: typeof $subSchema | typeof schema\n if ($subSchema === '$self') {\n subSchema = schema\n } else if (isFunction($subSchema)) {\n subSchema = $subSchema(source)\n } else {\n subSchema = $subSchema\n }\n return isArray(subSource)\n ? subSource.map(item => mapSchema(item, subSchema, context) as Target)\n : mapSchema<typeof subSource, Target>(\n subSource,\n subSchema as Schema<typeof subSource, Target>,\n context,\n )\n}\n"]}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transformSchemaMapperFactory = transformSchemaMapperFactory;
4
+ const transform_schema_1 = require("../schemas/transform-schema");
5
+ /**
6
+ * The `transformSchemaMapperFactory` function creates a {@link Mapper | mapper function} for a given
7
+ * {@link TransformSchema} or a raw Zod schema.
8
+ *
9
+ * @remarks A {@link TransformSchema} receives the {@link MapperContext | mapper context} and
10
+ * never throws on invalid sources. A raw Zod schema is strict: it throws if the source is not
11
+ * valid.
12
+ * @param schema - The schema to apply in the {@link Mapper | mapper function}.
13
+ * @returns A {@link Mapper | mapper function} that applies the given schema.
14
+ * @public
15
+ */
16
+ function transformSchemaMapperFactory(schema) {
17
+ return function mapper(source, context) {
18
+ return (0, transform_schema_1.isTransformSchema)(schema) ? schema.parse(source, context) : schema.parse(source);
19
+ };
20
+ }
21
+ //# sourceMappingURL=transform-schema-mapper.factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-schema-mapper.factory.js","sourceRoot":"","sources":["../../../src/mappers/transform-schema-mapper.factory.ts"],"names":[],"mappings":";;AAyBA,oEAMC;AA7BD,kEAA+D;AAY/D;;;;;;;;;;GAUG;AACH,SAAgB,4BAA4B,CAC1C,MAA8D;IAE9D,OAAO,SAAS,MAAM,CAAC,MAAc,EAAE,OAAsB;QAC3D,OAAO,IAAA,oCAAiB,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACzF,CAAC,CAAA;AACH,CAAC","sourcesContent":["import type { TransformSchema } from '../schemas/transform-schema.types'\nimport type { Mapper, MapperContext } from './types'\nimport { isTransformSchema } from '../schemas/transform-schema'\n\n/**\n * A schema-like object that has a `parse` method that throws if the input is not valid, like\n * any Zod schema: `z.object()`, `z.object().transform()`...\n *\n * @public\n */\nexport interface ParseableSchema<Target> {\n parse: (input: unknown) => Target\n}\n\n/**\n * The `transformSchemaMapperFactory` function creates a {@link Mapper | mapper function} for a given\n * {@link TransformSchema} or a raw Zod schema.\n *\n * @remarks A {@link TransformSchema} receives the {@link MapperContext | mapper context} and\n * never throws on invalid sources. A raw Zod schema is strict: it throws if the source is not\n * valid.\n * @param schema - The schema to apply in the {@link Mapper | mapper function}.\n * @returns A {@link Mapper | mapper function} that applies the given schema.\n * @public\n */\nexport function transformSchemaMapperFactory<Source, Target>(\n schema: TransformSchema<any, Target> | ParseableSchema<Target>,\n): Mapper<Source, Target> {\n return function mapper(source: Source, context: MapperContext): Target {\n return isTransformSchema(schema) ? schema.parse(source, context) : schema.parse(source)\n }\n}\n"]}
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./transform-schema"), exports);
5
+ tslib_1.__exportStar(require("./transform-schema.types"), exports);
4
6
  tslib_1.__exportStar(require("./types"), exports);
5
7
  tslib_1.__exportStar(require("./utils"), exports);
6
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/schemas/index.ts"],"names":[],"mappings":";;;AAAA,kDAAuB;AACvB,kDAAuB","sourcesContent":["export * from './types'\nexport * from './utils'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/schemas/index.ts"],"names":[],"mappings":";;;AAAA,6DAAkC;AAClC,mEAAwC;AACxC,kDAAuB;AACvB,kDAAuB","sourcesContent":["export * from './transform-schema'\nexport * from './transform-schema.types'\nexport * from './types'\nexport * from './utils'\n"]}
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTransformSchema = createTransformSchema;
4
+ exports.isTransformSchema = isTransformSchema;
5
+ /** Max number of different validation warnings that a schema reports. */
6
+ const MAX_REPORTED_ISSUES = 20;
7
+ function isPlainObject(value) {
8
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
9
+ }
10
+ function merge(base, value) {
11
+ return isPlainObject(base) && isPlainObject(value) ? { ...base, ...value } : value;
12
+ }
13
+ /**
14
+ * Removes the `undefined` properties of a mapped object. This way a transformation never adds
15
+ * properties that the source does not have, nor replaces already mapped ones with `undefined`.
16
+ */
17
+ function clean(value) {
18
+ return isPlainObject(value)
19
+ ? Object.fromEntries(Object.entries(value).filter(([, property]) => property !== undefined))
20
+ : value;
21
+ }
22
+ function createSchema(layers) {
23
+ const reportedIssues = new Set();
24
+ function validate(validator, source) {
25
+ const result = validator.safeParse(source);
26
+ if (result.success) {
27
+ return result.data;
28
+ }
29
+ const message = result.error instanceof Error ? result.error.message : String(result.error);
30
+ if (!reportedIssues.has(message) && reportedIssues.size < MAX_REPORTED_ISSUES) {
31
+ reportedIssues.add(message);
32
+ console.warn('[x-adapter] The source does not match the schema', result.error, source);
33
+ }
34
+ return source;
35
+ }
36
+ return {
37
+ parse(source, context = {}) {
38
+ if (source === undefined || source === null) {
39
+ console.warn('[x-adapter] This schema cannot be applied to an empty source');
40
+ return undefined;
41
+ }
42
+ // The raw source is the base, so validators that strip unknown keys do not lose data.
43
+ // Each validator receives the data accumulated so far, so it does not undo the values
44
+ // coerced by the previous ones.
45
+ const validated = layers.reduce((data, layer) => (layer.source ? merge(data, validate(layer.source, data)) : data), source);
46
+ return layers.reduce((target, layer) => merge(target, clean(layer.transform(validated, target, context))), undefined);
47
+ },
48
+ $override(override) {
49
+ layers.push(override);
50
+ return this;
51
+ },
52
+ $extends(override) {
53
+ return createSchema([...layers, override]);
54
+ },
55
+ $replace(definition) {
56
+ layers.splice(0, layers.length, toLayer(definition));
57
+ reportedIssues.clear();
58
+ return this;
59
+ },
60
+ };
61
+ }
62
+ function toLayer({ source, transform }) {
63
+ return { source, transform: (data, _target, context) => transform(data, context) };
64
+ }
65
+ /**
66
+ * Creates a {@link TransformSchema} that maps a source object to a target object with a plain
67
+ * function. Optionally, the source can be validated with a [Zod](https://zod.dev) schema.
68
+ *
69
+ * @param definition - The validator and the transformation of the schema.
70
+ * @returns A {@link TransformSchema}.
71
+ * @example
72
+ * ```typescript
73
+ * const resultSchema = createTransformSchema<ApiResult, Result>({
74
+ * transform: source => ({ id: source.__id, name: source.__name }),
75
+ * })
76
+ *
77
+ * // With a validator the types of the source are inferred from it.
78
+ * resultSchema.$override({
79
+ * source: z.looseObject({ brand: z.string() }),
80
+ * transform: source => ({ brand: source.brand }),
81
+ * })
82
+ * ```
83
+ * @public
84
+ */
85
+ function createTransformSchema(definition) {
86
+ return createSchema([toLayer(definition)]);
87
+ }
88
+ /**
89
+ * Checks if the given schema is a {@link TransformSchema}.
90
+ *
91
+ * @param schema - The schema to check.
92
+ * @returns True if it is a {@link TransformSchema}, false otherwise.
93
+ * @public
94
+ */
95
+ function isTransformSchema(schema) {
96
+ return isPlainObject(schema) && '$override' in schema && '$extends' in schema;
97
+ }
98
+ //# sourceMappingURL=transform-schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-schema.js","sourceRoot":"","sources":["../../../src/schemas/transform-schema.ts"],"names":[],"mappings":";;AA4GA,sDAIC;AASD,8CAEC;AA7GD,yEAAyE;AACzE,MAAM,mBAAmB,GAAG,EAAE,CAAA;AAE9B,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;AAC7E,CAAC;AAED,SAAS,KAAK,CAAC,IAAa,EAAE,KAAc;IAC1C,OAAO,aAAa,CAAC,IAAI,CAAC,IAAI,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAA;AACpF,CAAC;AAED;;;GAGG;AACH,SAAS,KAAK,CAAC,KAAc;IAC3B,OAAO,aAAa,CAAC,KAAK,CAAC;QACzB,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE,EAAE,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC;QAC5F,CAAC,CAAC,KAAK,CAAA;AACX,CAAC;AAED,SAAS,YAAY,CAAC,MAAe;IACnC,MAAM,cAAc,G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M,CAClB,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EACpF,SAAS,CACV,CAAA;QACH,CAAC;QACD,SAAS,CAAC,QAAqD;YAC7D,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YACrB,OAAO,IAAI,CAAA;QACb,CAAC;QACD,QAAQ,CAAC,QAAqD;YAC5D,OAAO,YAAY,CAAC,CAAC,GAAG,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;QAC5C,CAAC;QACD,QAAQ,CAAC,UAA+C;YACtD,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAA;YACpD,cAAc,CAAC,KAAK,EAAE,CAAA;YACtB,OAAO,IAAI,CAAA;QACb,CAAC;KACF,CAAA;AACH,CAAC;AAED,SAAS,OAAO,CAAC,EAAE,MAAM,EAAE,SAAS,EAAuC;IACzE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,CAAA;AACpF,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,qBAAqB,CACnC,UAAqD;IAErD,OAAO,YAAY,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;AAC5C,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAAC,MAAe;IAC/C,OAAO,aAAa,CAAC,MAAM,CAAC,IAAI,WAAW,IAAI,MAAM,IAAI,UAAU,IAAI,MAAM,CAAA;AAC/E,CAAC","sourcesContent":["import type { MapperContext } from '../mappers/types'\nimport type {\n SourceValidator,\n TransformSchema,\n TransformSchemaDefinition,\n TransformSchemaOverride,\n} from './transform-schema.types'\n\n/** A step of the mapping: an optional validator plus the transformation to merge. */\ninterface Layer {\n source?: SourceValidator\n transform: (source: any, target: any, context: MapperContext) => unknown\n}\n\n/** Max number of different validation warnings that a schema reports. */\nconst MAX_REPORTED_ISSUES = 20\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction merge(base: unknown, value: unknown): unknown {\n return isPlainObject(base) && isPlainObject(value) ? { ...base, ...value } : value\n}\n\n/**\n * Removes the `undefined` properties of a mapped object. This way a transformation never adds\n * properties that the source does not have, nor replaces already mapped ones with `undefined`.\n */\nfunction clean(value: unknown): unknown {\n return isPlainObject(value)\n ? Object.fromEntries(Object.entries(value).filter(([, property]) => property !== undefined))\n : value\n}\n\nfunction createSchema(layers: Layer[]): TransformSchema<any, any> {\n const reportedIssues = new Set<string>()\n\n function validate(validator: SourceValidator, source: unknown): unknown {\n const result = validator.safeParse(source)\n if (result.success) {\n return result.data\n }\n const message = result.error instanceof Error ? result.error.message : String(result.error)\n if (!reportedIssues.has(message) && reportedIssues.size < MAX_REPORTED_ISSUES) {\n reportedIssues.add(message)\n console.warn('[x-adapter] The source does not match the schema', result.error, source)\n }\n return source\n }\n\n return {\n parse(source, context = {}) {\n if (source === undefined || source === null) {\n console.warn('[x-adapter] This schema cannot be applied to an empty source')\n return undefined\n }\n // The raw source is the base, so validators that strip unknown keys do not lose data.\n // Each validator receives the data accumulated so far, so it does not undo the values\n // coerced by the previous ones.\n const validated = layers.reduce<unknown>(\n (data, layer) => (layer.source ? merge(data, validate(layer.source, data)) : data),\n source,\n )\n return layers.reduce<unknown>(\n (target, layer) => merge(target, clean(layer.transform(validated, target, context))),\n undefined,\n )\n },\n $override(override: TransformSchemaOverride<any, any, any, any>) {\n layers.push(override)\n return this\n },\n $extends(override: TransformSchemaOverride<any, any, any, any>) {\n return createSchema([...layers, override])\n },\n $replace(definition: TransformSchemaDefinition<any, any>) {\n layers.splice(0, layers.length, toLayer(definition))\n reportedIssues.clear()\n return this\n },\n }\n}\n\nfunction toLayer({ source, transform }: TransformSchemaDefinition<any, any>): Layer {\n return { source, transform: (data, _target, context) => transform(data, context) }\n}\n\n/**\n * Creates a {@link TransformSchema} that maps a source object to a target object with a plain\n * function. Optionally, the source can be validated with a [Zod](https://zod.dev) schema.\n *\n * @param definition - The validator and the transformation of the schema.\n * @returns A {@link TransformSchema}.\n * @example\n * ```typescript\n * const resultSchema = createTransformSchema<ApiResult, Result>({\n * transform: source => ({ id: source.__id, name: source.__name }),\n * })\n *\n * // With a validator the types of the source are inferred from it.\n * resultSchema.$override({\n * source: z.looseObject({ brand: z.string() }),\n * transform: source => ({ brand: source.brand }),\n * })\n * ```\n * @public\n */\nexport function createTransformSchema<Source, Target>(\n definition: TransformSchemaDefinition<Source, Target>,\n): TransformSchema<Source, Target> {\n return createSchema([toLayer(definition)])\n}\n\n/**\n * Checks if the given schema is a {@link TransformSchema}.\n *\n * @param schema - The schema to check.\n * @returns True if it is a {@link TransformSchema}, false otherwise.\n * @public\n */\nexport function isTransformSchema(schema: unknown): schema is TransformSchema<any, any> {\n return isPlainObject(schema) && '$override' in schema && '$extends' in schema\n}\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=transform-schema.types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-schema.types.js","sourceRoot":"","sources":["../../../src/schemas/transform-schema.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { MapperContext } from '../mappers/types'\n\n/**\n * The result of validating a source object with a {@link SourceValidator}.\n *\n * @public\n */\nexport type SourceValidatorResult<Output> =\n | { success: true; data: Output }\n | { success: false; error: unknown }\n\n/**\n * Minimal structural contract of a validator. Any [Zod](https://zod.dev) schema (`zod` or\n * `zod/mini`) satisfies it, so `@empathyco/x-adapter` does not need to depend on a concrete Zod\n * version.\n *\n * @param Output - The type of the validated source.\n * @public\n */\nexport interface SourceValidator<Output = unknown> {\n safeParse: (input: unknown) => SourceValidatorResult<Output>\n}\n\n/**\n * Definition of a {@link TransformSchema}.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * const userSchema = createTransformSchema({\n * source: z.looseObject({ id: z.string(), price: z.object({ max: z.number() }) }),\n * transform: (source): User => ({ identifier: source.id, maxPrice: source.price.max }),\n * })\n * ```\n * @public\n */\nexport interface TransformSchemaDefinition<Source, Target> {\n /**\n * Validator of the source object. When omitted the source is not validated and its type has\n * to be provided through the `Source` type parameter.\n */\n source?: SourceValidator<Source>\n /**\n * Maps the (validated) source object to the target object.\n *\n * @remarks The properties of the returned object whose value is `undefined` are not added to\n * the target.\n * @param source - The validated source object.\n * @param context - The {@link MapperContext | mapper context}.\n * @returns The target object.\n */\n transform: (source: Source, context: MapperContext) => Target\n}\n\n/**\n * Definition of a modification to apply on top of a {@link TransformSchema}.\n *\n * @param Source - The source object of the schema to modify.\n * @param Target - The target object of the schema to modify.\n * @param NewSource - The extra properties of the source object.\n * @param NewTarget - The extra properties of the target object.\n * @public\n */\nexport interface TransformSchemaOverride<Source, Target, NewSource, NewTarget> {\n /**\n * Validator for the extra properties of the source object. Its output is merged with the\n * output of the validators that the schema already has.\n */\n source?: SourceValidator<NewSource>\n /**\n * Maps the source object to the properties of the target to add or replace. The returned\n * object is shallow merged with the target mapped so far.\n *\n * @remarks The properties of the returned object whose value is `undefined` are ignored, so\n * they do not replace the ones already mapped.\n * @param source - The validated source object.\n * @param target - The target object mapped so far by the schema.\n * @param context - The {@link MapperContext | mapper context}.\n * @returns The properties to add or replace in the target object.\n */\n transform: (\n source: Source & NewSource,\n target: Target,\n context: MapperContext,\n ) => Partial<Target> & NewTarget\n}\n\n/**\n * A schema that maps a source object to a target object, optionally validating the source. It can\n * be modified after its creation to: partially override it, create a new one or completely replace\n * it.\n *\n * @remarks It replaces the deprecated {@link MutableSchema}, whose path based typings forced\n * TypeScript to recursively compute every possible path of the source object.\n * @param Source - The source object.\n * @param Target - The target object.\n * @public\n */\nexport interface TransformSchema<Source, Target> {\n /**\n * Validates the source object and maps it to the target object.\n *\n * @remarks Validation never breaks the mapping: if the source does not match the validators, a\n * warning is logged and the raw source is mapped.\n * @param source - The object to map.\n * @param context - The {@link MapperContext | mapper context} to feed the transformations with.\n * @returns The target object.\n */\n parse: (source: unknown, context?: MapperContext) => Target\n /**\n * Modifies this schema, so every usage of it applies the given modification.\n *\n * @param override - The validator and the transformation to apply on top of this schema.\n * @returns This schema.\n */\n $override: <NewSource = unknown, NewTarget = unknown>(\n override: TransformSchemaOverride<Source, Target, NewSource, NewTarget>,\n ) => TransformSchema<Source & NewSource, Target & NewTarget>\n /**\n * Creates a new schema using this one as starting point. This schema remains unchanged.\n *\n * @param override - The validator and the transformation to apply on top of this schema.\n * @returns The new schema.\n */\n $extends: <NewSource = unknown, NewTarget = unknown>(\n override: TransformSchemaOverride<Source, Target, NewSource, NewTarget>,\n ) => TransformSchema<Source & NewSource, Target & NewTarget>\n /**\n * Replaces all usages of this schema with the given definition.\n *\n * @param definition - The definition to use instead of the current one.\n * @returns This schema.\n */\n $replace: <NewSource, NewTarget>(\n definition: TransformSchemaDefinition<NewSource, NewTarget>,\n ) => TransformSchema<NewSource, NewTarget>\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/schemas/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AnyFunction,\n DeepPartial,\n ExtractPath,\n ExtractPathByType,\n ExtractType,\n Primitive,\n} from '@empathyco/x-utils'\nimport type { MapperContext } from '../mappers/types'\n\n// TODO: EX-5830 - Enhance Schema type to support optional properties in the Source object\n/**\n * Template object to transform a source object to a target object.\n *\n * @remarks The source object must not have optional properties, as it could cause infinite\n * type instantiations.\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * price: {\n * max: number;\n * min: number;\n * };\n * images: string[];\n * }\n *\n * interface Target {\n * identifier: string;\n * maxPrice: number;\n * minPrice: number;\n * img: string[]\n * }\n *\n * const schema: Schema<Source, Target> = {\n * identifier: 'id',\n * maxPrice: 'price.max',\n * minPrice: ({ price }) => Math.min(0, price.min),\n * img: 'images'\n * };\n * ```\n * @public\n */\nexport type Schema<Source = any, Target = any> = {\n [TargetKey in keyof Target]: SchemaTransformer<Source, Target, TargetKey>\n}\n\n/**\n * A {@link Schema | schema} with extended functionality to: completely replace\n * the original schema, partially override it or create a new one.\n *\n * @param OriginalSchema - The {@link Schema | schema} that will be mutable.\n * @public\n */\nexport type MutableSchema<Source, Target> = Schema<Source, Target> & {\n /**\n * Replaces all usages of the original {@link Schema | schema} with the given one.\n *\n * @param newSchema - The {@link Schema | schema} to use instead of the original one.\n * @returns The new {@link Schema | schema} that will be used.\n */\n $replace: <NewSource, NewTarget>(\n newSchema: Schema<NewSource, NewTarget>,\n ) => MutableSchema<NewSource, NewTarget>\n /**\n * Merges the original {@link Schema | schema} with the given one.\n *\n * @param newSchema - The {@link Schema | schema} to use to merge with the original one.\n * @returns The {@link Schema | schema} returned by the merge.\n */\n $override: <NewSource, NewTarget = object>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, NewTarget>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>\n /**\n * Creates a new {@link Schema | schema} using the original one as starting point.\n * The original {@link Schema | schema} will remain unchanged.\n *\n * @param newSchema - The {@link Schema | schema} to be used to extend the original one.\n * Both schema's Target and Source can be unique or also be extending from another one.\n * @returns The {@link Schema | schema} created.\n */\n $extends: (<NewSource extends Source, NewTarget extends Target>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, Omit<NewTarget, keyof Target>>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>) &\n (<NewSource, NewTarget = object>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, NewTarget>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>)\n /**\n * Returns a string representing of the {@link Schema | schema}.\n *\n * @param includeInternalMethods - Flag to include in the string representation\n * the internal methods. Disabled by default.\n * @returns The string representation.\n */\n toString: (includeInternalMethods?: boolean) => string\n}\n/**\n * The possible transformers to apply to the target key.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @param TargetKey - The target key to apply the transformation.\n * @public\n */\nexport type SchemaTransformer<Source, Target, TargetKey extends keyof Target> =\n | PathTransformer<Source, Target[TargetKey]>\n | FunctionTransformer<Source, Target[TargetKey]>\n | SubSchemaTransformer<Source, Target[TargetKey]>\n | Schema<Source, Exclude<Target[TargetKey], AnyFunction | Primitive>>\n\n/**\n * A function with the source object and mapper context as parameters that returns the value of a\n * target's property.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * count: number;\n * }\n *\n * interface Target {\n * title: string;\n * hits: number;\n * }\n *\n * const subSchema: Schema<Source, Target> = {\n * title: 'id',\n * hits: 'count'\n * };\n *\n * const wrongSubSchema: Schema<Source, Target> = {\n * // @ts-expect-error\n * title: 'count', // This raises a TS error\n * hits: 'count'\n * };\n * ```\n * @public\n */\nexport type PathTransformer<Source, Target> = ExtractPathByType<Source, Target>\n\n/**\n * A function with the source object and mapper context as parameters that returns the value of a\n * target's property.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * count: number;\n * }\n *\n * interface Target {\n * title: string;\n * hits: number;\n * }\n *\n * const subSchema: Schema<Source, Target> = {\n * title: source => source.id,\n * hits: (source, context) => context.requestParameters.query === 'example'\n * ? source.count\n * : 0\n * };\n * ```\n * @public\n */\nexport type FunctionTransformer<Source, Target> = (\n source: Source,\n context?: MapperContext,\n) => Target\n\n/**\n * An object containing a schema narrowing its source object based on the given path.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * facets: {\n * name: string;\n * count: number;\n * };\n * images: string[];\n * }\n *\n * interface Target {\n * identifier: string;\n * filters: {\n * id: string;\n * numFound: number;\n * };\n * img: string[]\n * }\n *\n * const subSchema: SubSchemaTransformer<Source, Target['filters']> = {\n * $path: 'facets',\n * $subSchema: {\n * id: 'name',\n * numFound: 'count'\n * }\n * };\n * ```\n * @public\n */\nexport type SubSchemaTransformer<Source, Target> = {\n [Path in ExtractPath<Source>]: {\n $context?: MapperContext\n $path: Path\n $subSchema:\n | SubSchema<Source, Target, Path>\n | '$self'\n | ((source: Source) => SubSchema<Source, Target, Path>)\n }\n}[ExtractPath<Source>]\n\n/**\n * A {@link Schema | schema} that will be applied to an inner path of an object.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @param Path - The path where the schema will be applied.\n * @public\n */\nexport type SubSchema<Source, Target, Path extends ExtractPath<Source>> =\n ExtractType<Source, Path> extends (infer SourceArrayType)[]\n ? Target extends (infer TargetArrayType)[]\n ? Schema<SourceArrayType, TargetArrayType>\n : never\n : Target extends []\n ? never\n : Schema<ExtractType<Source, Path>, Target>\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/schemas/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AnyFunction,\n DeepPartial,\n ExtractPath,\n ExtractPathByType,\n ExtractType,\n Primitive,\n} from '@empathyco/x-utils'\nimport type { MapperContext } from '../mappers/types'\n\n// TODO: EX-5830 - Enhance Schema type to support optional properties in the Source object\n/**\n * Template object to transform a source object to a target object.\n *\n * @remarks The source object must not have optional properties, as it could cause infinite\n * type instantiations.\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * price: {\n * max: number;\n * min: number;\n * };\n * images: string[];\n * }\n *\n * interface Target {\n * identifier: string;\n * maxPrice: number;\n * minPrice: number;\n * img: string[]\n * }\n *\n * const schema: Schema<Source, Target> = {\n * identifier: 'id',\n * maxPrice: 'price.max',\n * minPrice: ({ price }) => Math.min(0, price.min),\n * img: 'images'\n * };\n * ```\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type Schema<Source = any, Target = any> = {\n [TargetKey in keyof Target]: SchemaTransformer<Source, Target, TargetKey>\n}\n\n/**\n * A {@link Schema | schema} with extended functionality to: completely replace\n * the original schema, partially override it or create a new one.\n *\n * @param OriginalSchema - The {@link Schema | schema} that will be mutable.\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type MutableSchema<Source, Target> = Schema<Source, Target> & {\n /**\n * Replaces all usages of the original {@link Schema | schema} with the given one.\n *\n * @param newSchema - The {@link Schema | schema} to use instead of the original one.\n * @returns The new {@link Schema | schema} that will be used.\n */\n $replace: <NewSource, NewTarget>(\n newSchema: Schema<NewSource, NewTarget>,\n ) => MutableSchema<NewSource, NewTarget>\n /**\n * Merges the original {@link Schema | schema} with the given one.\n *\n * @param newSchema - The {@link Schema | schema} to use to merge with the original one.\n * @returns The {@link Schema | schema} returned by the merge.\n */\n $override: <NewSource, NewTarget = object>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, NewTarget>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>\n /**\n * Creates a new {@link Schema | schema} using the original one as starting point.\n * The original {@link Schema | schema} will remain unchanged.\n *\n * @param newSchema - The {@link Schema | schema} to be used to extend the original one.\n * Both schema's Target and Source can be unique or also be extending from another one.\n * @returns The {@link Schema | schema} created.\n */\n $extends: (<NewSource extends Source, NewTarget extends Target>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, Omit<NewTarget, keyof Target>>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>) &\n (<NewSource, NewTarget = object>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, NewTarget>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>)\n /**\n * Returns a string representing of the {@link Schema | schema}.\n *\n * @param includeInternalMethods - Flag to include in the string representation\n * the internal methods. Disabled by default.\n * @returns The string representation.\n */\n toString: (includeInternalMethods?: boolean) => string\n}\n/**\n * The possible transformers to apply to the target key.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @param TargetKey - The target key to apply the transformation.\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type SchemaTransformer<Source, Target, TargetKey extends keyof Target> =\n | PathTransformer<Source, Target[TargetKey]>\n | FunctionTransformer<Source, Target[TargetKey]>\n | SubSchemaTransformer<Source, Target[TargetKey]>\n | Schema<Source, Exclude<Target[TargetKey], AnyFunction | Primitive>>\n\n/**\n * A function with the source object and mapper context as parameters that returns the value of a\n * target's property.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * count: number;\n * }\n *\n * interface Target {\n * title: string;\n * hits: number;\n * }\n *\n * const subSchema: Schema<Source, Target> = {\n * title: 'id',\n * hits: 'count'\n * };\n *\n * const wrongSubSchema: Schema<Source, Target> = {\n * // @ts-expect-error\n * title: 'count', // This raises a TS error\n * hits: 'count'\n * };\n * ```\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type PathTransformer<Source, Target> = ExtractPathByType<Source, Target>\n\n/**\n * A function with the source object and mapper context as parameters that returns the value of a\n * target's property.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * count: number;\n * }\n *\n * interface Target {\n * title: string;\n * hits: number;\n * }\n *\n * const subSchema: Schema<Source, Target> = {\n * title: source => source.id,\n * hits: (source, context) => context.requestParameters.query === 'example'\n * ? source.count\n * : 0\n * };\n * ```\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type FunctionTransformer<Source, Target> = (\n source: Source,\n context?: MapperContext,\n) => Target\n\n/**\n * An object containing a schema narrowing its source object based on the given path.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * facets: {\n * name: string;\n * count: number;\n * };\n * images: string[];\n * }\n *\n * interface Target {\n * identifier: string;\n * filters: {\n * id: string;\n * numFound: number;\n * };\n * img: string[]\n * }\n *\n * const subSchema: SubSchemaTransformer<Source, Target['filters']> = {\n * $path: 'facets',\n * $subSchema: {\n * id: 'name',\n * numFound: 'count'\n * }\n * };\n * ```\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type SubSchemaTransformer<Source, Target> = {\n [Path in ExtractPath<Source>]: {\n $context?: MapperContext\n $path: Path\n $subSchema:\n | SubSchema<Source, Target, Path>\n | '$self'\n | ((source: Source) => SubSchema<Source, Target, Path>)\n }\n}[ExtractPath<Source>]\n\n/**\n * A {@link Schema | schema} that will be applied to an inner path of an object.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @param Path - The path where the schema will be applied.\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type SubSchema<Source, Target, Path extends ExtractPath<Source>> =\n ExtractType<Source, Path> extends (infer SourceArrayType)[]\n ? Target extends (infer TargetArrayType)[]\n ? Schema<SourceArrayType, TargetArrayType>\n : never\n : Target extends []\n ? never\n : Schema<ExtractType<Source, Path>, Target>\n"]}
@@ -14,6 +14,7 @@ const mutableSchemasInternalMethods = ['$replace', '$override', '$extends', 'toS
14
14
  *
15
15
  * @returns A {@link MutableSchema | mutable schema} version of the given {@link Schema | schema}.
16
16
  *
17
+ * @deprecated Use {@link createTransformSchema} instead.
17
18
  * @public
18
19
  */
19
20
  function createMutableSchema(schema) {
@@ -50,6 +51,7 @@ function createMutableSchema(schema) {
50
51
  * @returns True if it is a {@link MutableSchema | mutableSchema} method,
51
52
  * false otherwise.
52
53
  *
54
+ * @deprecated Only used by the deprecated {@link MutableSchema}.
53
55
  * @public
54
56
  */
55
57
  function isInternalMethod(name) {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/schemas/utils.ts"],"names":[],"mappings":";;AAiBA,kDA2BC;AAYD,4CAEC;AAzDD,gDAA6E;AAE7E;;GAEG;AACH,MAAM,6BAA6B,GAAa,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,CAAC,CAAA;AAEjG;;;;;;;;GAQG;AACH,SAAgB,mBAAmB,CACjC,MAA8B;IAE9B,OAAO;QACL,GAAG,MAAM;QACT,QAAQ,CAAC,SAAS;YAChB,IAAA,iBAAO,EAAC,IAAI,EAAE,GAAG,CAAC,EAAE;gBAClB,IAAI,gBAAgB,CAAC,GAAa,CAAC,EAAE,CAAC;oBACpC,OAAM;gBACR,CAAC;gBACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAA;YAClB,CAAC,CAAC,CAAA;YACF,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;YAC9B;+EACmE;YACnE,OAAO,IAAW,CAAA;QACpB,CAAC;QACD,SAAS,CAAC,SAAS;YACjB,OAAO,IAAA,mBAAS,EAAC,IAAI,EAAE,SAAS,CAAC,CAAA;QACnC,CAAC;QACD,QAAQ,CAAC,SAAkB;YACzB,OAAO,IAAA,mBAAS,EAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAA;QACvC,CAAC;QACD,QAAQ,CAAC,sBAAsB,GAAG,KAAK;YACrC,OAAO,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,sBAAsB,CAAC,CAAA;QAClD,CAAC;KACF,CAAA;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAgB,gBAAgB,CAAC,IAAY;IAC3C,OAAO,6BAA6B,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;AACrD,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,SAAS,CAChB,IAA6B,EAC7B,sBAA+B,EAC/B,IAAI,GAAG,CAAC;IAER,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACrC,IAAI,MAAM,GAAG,EAAE,CAAA;IACf,IAAA,iBAAO,EAAC,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;QAC3B,IAAI,IAAA,kBAAQ,EAAC,KAAK,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,WAAW,GAAG,GAAG,QAAQ,SAAS,CAC7C,KAAK,EACL,sBAAsB,EACtB,EAAE,IAAI,CACP,GAAG,WAAW,MAAM,CAAA;QACvB,CAAC;aAAM,IAAI,CAAC,IAAA,oBAAU,EAAC,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,sBAAsB,EAAE,CAAC;YAClF,MAAM,IAAI,GAAG,WAAW,GAAG,GAAG,KAAK,KAAY,KAAK,CAAA;QACtD,CAAC;IACH,CAAC,CAAC,CAAA;IACF,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import type { MutableSchema, Schema } from './types'\nimport { deepMerge, forEach, isFunction, isObject } from '@empathyco/x-utils'\n\n/**\n * Collection of internal method names for {@link MutableSchema | mutable schemas}.\n */\nconst mutableSchemasInternalMethods: string[] = ['$replace', '$override', '$extends', 'toString']\n\n/**\n * Creates a {@link MutableSchema | mutable schema } version of a given {@link Schema | schema}.\n *\n * @param schema - The {@link Schema | schema} to make mutable.\n *\n * @returns A {@link MutableSchema | mutable schema} version of the given {@link Schema | schema}.\n *\n * @public\n */\nexport function createMutableSchema<Source, Target>(\n schema: Schema<Source, Target>,\n): MutableSchema<Source, Target> {\n return {\n ...schema,\n $replace(newSchema) {\n forEach(this, key => {\n if (isInternalMethod(key as string)) {\n return\n }\n delete this[key]\n })\n Object.assign(this, newSchema)\n /* We are replacing the schema with a completely new schema , so it makes sense that TS\n complains that the old schema and the new one are not the same. */\n return this as any\n },\n $override(newSchema) {\n return deepMerge(this, newSchema)\n },\n $extends(newSchema: unknown) {\n return deepMerge({}, this, newSchema)\n },\n toString(includeInternalMethods = false) {\n return serialize(this, !!includeInternalMethods)\n },\n }\n}\n\n/**\n * Checks if the given key is a {@link MutableSchema | mutableSchema} method.\n *\n * @param name - The key to check.\n *\n * @returns True if it is a {@link MutableSchema | mutableSchema} method,\n * false otherwise.\n *\n * @public\n */\nexport function isInternalMethod(name: string): boolean {\n return mutableSchemasInternalMethods.includes(name)\n}\n\n/**\n * Returns a string representing of the given object.\n *\n * @param data - The object to get the string representation from.\n * @param includeInternalMethods - Flag to include in the string representation\n * the internal methods. Disabled by default.\n * @param deep - The level of indentation.\n * @returns The string representation.\n */\nfunction serialize(\n data: Record<string, unknown>,\n includeInternalMethods: boolean,\n deep = 0,\n): string {\n const indentation = ' '.repeat(deep)\n let output = ''\n forEach(data, (key, value) => {\n if (isObject(value)) {\n output += `${indentation}${key}: {\\n${serialize(\n value,\n includeInternalMethods,\n ++deep,\n )}${indentation}},\\n`\n } else if (!isFunction(value) || !isInternalMethod(key) || includeInternalMethods) {\n output += `${indentation}${key}: ${value as any},\\n`\n }\n })\n return output\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/schemas/utils.ts"],"names":[],"mappings":";;AAkBA,kDA2BC;AAaD,4CAEC;AA3DD,gDAA6E;AAE7E;;GAEG;AACH,MAAM,6BAA6B,GAAa,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,CAAC,CAAA;AAEjG;;;;;;;;;GASG;AACH,SAAgB,mBAAmB,CACjC,MAA8B;IAE9B,OAAO;QACL,GAAG,MAAM;QACT,QAAQ,CAAC,SAAS;YAChB,IAAA,iBAAO,EAAC,IAAI,EAAE,GAAG,CAAC,EAAE;gBAClB,IAAI,gBAAgB,CAAC,GAAa,CAAC,EAAE,CAAC;oBACpC,OAAM;gBACR,CAAC;gBACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAA;YAClB,CAAC,CAAC,CAAA;YACF,MAA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,CAAC,CAAC,CAAA;IACF,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import type { MutableSchema, Schema } from './types'\nimport { deepMerge, forEach, isFunction, isObject } from '@empathyco/x-utils'\n\n/**\n * Collection of internal method names for {@link MutableSchema | mutable schemas}.\n */\nconst mutableSchemasInternalMethods: string[] = ['$replace', '$override', '$extends', 'toString']\n\n/**\n * Creates a {@link MutableSchema | mutable schema } version of a given {@link Schema | schema}.\n *\n * @param schema - The {@link Schema | schema} to make mutable.\n *\n * @returns A {@link MutableSchema | mutable schema} version of the given {@link Schema | schema}.\n *\n * @deprecated Use {@link createTransformSchema} instead.\n * @public\n */\nexport function createMutableSchema<Source, Target>(\n schema: Schema<Source, Target>,\n): MutableSchema<Source, Target> {\n return {\n ...schema,\n $replace(newSchema) {\n forEach(this, key => {\n if (isInternalMethod(key as string)) {\n return\n }\n delete this[key]\n })\n Object.assign(this, newSchema)\n /* We are replacing the schema with a completely new schema , so it makes sense that TS\n complains that the old schema and the new one are not the same. */\n return this as any\n },\n $override(newSchema) {\n return deepMerge(this, newSchema)\n },\n $extends(newSchema: unknown) {\n return deepMerge({}, this, newSchema)\n },\n toString(includeInternalMethods = false) {\n return serialize(this, !!includeInternalMethods)\n },\n }\n}\n\n/**\n * Checks if the given key is a {@link MutableSchema | mutableSchema} method.\n *\n * @param name - The key to check.\n *\n * @returns True if it is a {@link MutableSchema | mutableSchema} method,\n * false otherwise.\n *\n * @deprecated Only used by the deprecated {@link MutableSchema}.\n * @public\n */\nexport function isInternalMethod(name: string): boolean {\n return mutableSchemasInternalMethods.includes(name)\n}\n\n/**\n * Returns a string representing of the given object.\n *\n * @param data - The object to get the string representation from.\n * @param includeInternalMethods - Flag to include in the string representation\n * the internal methods. Disabled by default.\n * @param deep - The level of indentation.\n * @returns The string representation.\n */\nfunction serialize(\n data: Record<string, unknown>,\n includeInternalMethods: boolean,\n deep = 0,\n): string {\n const indentation = ' '.repeat(deep)\n let output = ''\n forEach(data, (key, value) => {\n if (isObject(value)) {\n output += `${indentation}${key}: {\\n${serialize(\n value,\n includeInternalMethods,\n ++deep,\n )}${indentation}},\\n`\n } else if (!isFunction(value) || !isInternalMethod(key) || includeInternalMethods) {\n output += `${indentation}${key}: ${value as any},\\n`\n }\n })\n return output\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  export * from './combine-mappers';
2
2
  export * from './identity.mapper';
3
3
  export * from './schema-mapper.factory';
4
+ export * from './transform-schema-mapper.factory';
4
5
  export * from './types';
5
6
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/mappers/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAA;AACjC,cAAc,mBAAmB,CAAA;AACjC,cAAc,yBAAyB,CAAA;AACvC,cAAc,SAAS,CAAA","sourcesContent":["export * from './combine-mappers'\nexport * from './identity.mapper'\nexport * from './schema-mapper.factory'\nexport * from './types'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/mappers/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAA;AACjC,cAAc,mBAAmB,CAAA;AACjC,cAAc,yBAAyB,CAAA;AACvC,cAAc,mCAAmC,CAAA;AACjD,cAAc,SAAS,CAAA","sourcesContent":["export * from './combine-mappers'\nexport * from './identity.mapper'\nexport * from './schema-mapper.factory'\nexport * from './transform-schema-mapper.factory'\nexport * from './types'\n"]}
@@ -6,6 +6,7 @@ import { createMutableSchema, isInternalMethod } from '../schemas/utils';
6
6
  *
7
7
  * @param schema - The {@link Schema | schema} to apply in the {@link Mapper | mapper function}.
8
8
  * @returns A {@link Mapper | mapper function} that applies the given {@link Schema | schema}.
9
+ * @deprecated Use {@link transformSchemaMapperFactory} with a {@link TransformSchema} instead.
9
10
  * @public
10
11
  */
11
12
  export function schemaMapperFactory(schema) {
@@ -1 +1 @@
1
- {"version":3,"file":"schema-mapper.factory.js","sourceRoot":"","sources":["../../../src/mappers/schema-m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AAA;IACpB,CAAC;SAAM,IAAI,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAClC,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,CAAA;IAChC,CAAC;SAAM,CAAC;QACN,SAAS,GAAG,UAAU,CAAA;IACxB,CAAC;IACD,OAAO,OAAO,CAAC,SAAS,CAAC;QACvB,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAW,CAAC;QACtE,CAAC,CAAC,SAAS,CACP,SAAS,EACT,SAA6C,EAC7C,OAAO,CACR,CAAA;AACP,CAAC","sourcesContent":["import type { Dictionary, ExtractPath } from '@empathyco/x-utils'\nimport type { MutableSchema, Schema, SubSchemaTransformer } from '../schemas/types'\nimport type { Mapper, MapperContext } from './types'\nimport {\n deepMerge,\n getSafePropertyChain,\n isArray,\n isFunction,\n isObject,\n isPath,\n reduce,\n} from '@empathyco/x-utils'\nimport { createMutableSchema, isInternalMethod } from '../schemas/utils'\n\n/**\n * The 'schemaMapperFactory' function creates a {@link Mapper | mapper function} for a given\n * {@link Schema | schema}.\n *\n * @param schema - The {@link Schema | schema} to apply in the {@link Mapper | mapper function}.\n * @returns A {@link Mapper | mapper function} that applies the given {@link Schema | schema}.\n * @public\n */\nexport function schemaMapperFactory<Source, Target>(\n schema: Schema<Source, Target> | MutableSchema<Source, Target>,\n): Mapper<Source, Target> {\n return function mapper(source: Source, context: MapperContext): Target {\n return mapSchema(source, schema, context)\n }\n}\n\n/**\n * The `mapSchema()` function creates a new object populated with the transformations defined by a\n * {@link Schema} applied to a source object.\n *\n * @param source - The object to apply the transformations to.\n * @param schema - The object that defines the transformations to apply.\n * @param context - The {@link MapperContext | mapper context} to feed the transformations with.\n * @returns A new object with each element being the result of the applied transformation.\n * @internal\n */\nfunction mapSchema<Source, Target>(\n source: Source,\n schema: Schema<Source, Target>,\n context: MapperContext,\n): Target {\n if (!source) {\n console.warn('This schema cannot be applied', createMutableSchema(schema))\n return undefined as any\n }\n return reduce(\n schema,\n (target, key, transformer) => {\n type TargetKey = Target[keyof Target]\n if (typeof transformer === 'string' && isPath(source, transformer)) {\n target[key] = getSafePropertyChain(source, transformer) as TargetKey\n } else if (isFunction(transformer) && !isInternalMethod(transformer.name)) {\n target[key] = transformer(source, context)\n } else if (isObject(transformer)) {\n const value =\n '$subSchema' in transformer\n ? (applySubSchemaTransformer<Source, TargetKey>(\n source,\n transformer as SubSchemaTransformer<Source, TargetKey>,\n context,\n schema as unknown as Schema<Source, TargetKey>,\n ) as TargetKey)\n : mapSchema<Source, TargetKey>(\n source,\n transformer as Schema<Source, TargetKey>,\n context,\n )\n\n if (value) {\n target[key] = value\n }\n }\n return target\n },\n {} as Target,\n )\n}\n\n/**\n * The `applySubSchemaTransformer()` function executes a `mapSchema()` function applying the defined\n * {@link SubSchemaTransformer.$subSchema}.\n *\n * @param source - The object to feed the schema.\n * @param subSchemaTransformer - The {@link SubSchemaTransformer} object with a $path, $subSchema\n * and $context options.\n * @param subSchemaTransformer.$path\n * @param subSchemaTransformer.$subSchema\n * @param subSchemaTransformer.$context\n * @param rawContext - The {@link MapperContext | mapper context} to feed the mapSchema function.\n * @param schema - The {@link Schema} to apply.\n * @returns The result of calling `mapSchema()` with the source, schema and context arguments.\n * @internal\n */\nfunction applySubSchemaTransformer<Source, Target>(\n source: Source,\n { $subSchema, $path, $context }: SubSchemaTransformer<Source, Target>,\n rawContext: MapperContext,\n schema: Schema<Source, Target>,\n): Target | Target[] | undefined {\n const subSource = getSafePropertyChain(source, $path)\n\n if (!subSource) {\n return\n }\n\n const extendedContext: Dictionary = {}\n if ($context) {\n Object.entries($context).forEach(([key, value]) => {\n if (['requestParameters', 'endpoint', 'mappedValue'].includes(key)) {\n return\n }\n extendedContext[key] = isFunction(value)\n ? value(source)\n : getSafePropertyChain(source, value as ExtractPath<typeof source>)\n })\n }\n\n const context = deepMerge({}, rawContext, $context, extendedContext)\n let subSchema: typeof $subSchema | typeof schema\n if ($subSchema === '$self') {\n subSchema = schema\n } else if (isFunction($subSchema)) {\n subSchema = $subSchema(source)\n } else {\n subSchema = $subSchema\n }\n return isArray(subSource)\n ? subSource.map(item => mapSchema(item, subSchema, context) as Target)\n : mapSchema<typeof subSource, Target>(\n subSource,\n subSchema as Schema<typeof subSource, Target>,\n context,\n )\n}\n"]}
1
+ {"version":3,"file":"schema-mapper.factory.js","sourceRoot":"","sources":["../../../src/mappers/schema-mapper.factory.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,OAAO,EACP,UAAU,EACV,QAAQ,EACR,MAAM,EACN,MAAM,GACP,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AAExE;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA8D;IAE9D,OAAO,SAAS,MAAM,CAAC,MAAc,EAAE,OAAsB;QAC3D,OAAO,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAA;IAC3C,CAAC,CAAA;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,SAAS,CAChB,MAAc,EACd,MAA8B,EAC9B,OAAsB;IAEtB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAA;QAC1E,OAAO,SAAgB,CAAA;IACzB,CAAC;IACD,OAAO,MAAM,CACX,MAAM,EACN,CAAC,MAAM,EAAE,GAAG,EAAE,WAAW,EAAE,EAAE;QAE3B,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE,CAAC;YACnE,MAAM,CAAC,GAAG,CAAC,GAAG,oBAAoB,CAAC,MAAM,EAAE,WAAW,CAAc,CAAA;QACtE,CAAC;aAAM,IAAI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K,CAAC,MAAM,CAAC;gBACf,CAAC,CAAC,oBAAoB,CAAC,MAAM,EAAE,KAAmC,CAAC,CAAA;QACvE,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,SAAS,CAAC,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAA;IACpE,IAAI,SAA4C,CAAA;IAChD,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,SAAS,GAAG,MAAM,CAAA;IACpB,CAAC;SAAM,IAAI,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAClC,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,CAAA;IAChC,CAAC;SAAM,CAAC;QACN,SAAS,GAAG,UAAU,CAAA;IACxB,CAAC;IACD,OAAO,OAAO,CAAC,SAAS,CAAC;QACvB,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAW,CAAC;QACtE,CAAC,CAAC,SAAS,CACP,SAAS,EACT,SAA6C,EAC7C,OAAO,CACR,CAAA;AACP,CAAC","sourcesContent":["import type { Dictionary, ExtractPath } from '@empathyco/x-utils'\nimport type { MutableSchema, Schema, SubSchemaTransformer } from '../schemas/types'\nimport type { Mapper, MapperContext } from './types'\nimport {\n deepMerge,\n getSafePropertyChain,\n isArray,\n isFunction,\n isObject,\n isPath,\n reduce,\n} from '@empathyco/x-utils'\nimport { createMutableSchema, isInternalMethod } from '../schemas/utils'\n\n/**\n * The 'schemaMapperFactory' function creates a {@link Mapper | mapper function} for a given\n * {@link Schema | schema}.\n *\n * @param schema - The {@link Schema | schema} to apply in the {@link Mapper | mapper function}.\n * @returns A {@link Mapper | mapper function} that applies the given {@link Schema | schema}.\n * @deprecated Use {@link transformSchemaMapperFactory} with a {@link TransformSchema} instead.\n * @public\n */\nexport function schemaMapperFactory<Source, Target>(\n schema: Schema<Source, Target> | MutableSchema<Source, Target>,\n): Mapper<Source, Target> {\n return function mapper(source: Source, context: MapperContext): Target {\n return mapSchema(source, schema, context)\n }\n}\n\n/**\n * The `mapSchema()` function creates a new object populated with the transformations defined by a\n * {@link Schema} applied to a source object.\n *\n * @param source - The object to apply the transformations to.\n * @param schema - The object that defines the transformations to apply.\n * @param context - The {@link MapperContext | mapper context} to feed the transformations with.\n * @returns A new object with each element being the result of the applied transformation.\n * @internal\n */\nfunction mapSchema<Source, Target>(\n source: Source,\n schema: Schema<Source, Target>,\n context: MapperContext,\n): Target {\n if (!source) {\n console.warn('This schema cannot be applied', createMutableSchema(schema))\n return undefined as any\n }\n return reduce(\n schema,\n (target, key, transformer) => {\n type TargetKey = Target[keyof Target]\n if (typeof transformer === 'string' && isPath(source, transformer)) {\n target[key] = getSafePropertyChain(source, transformer) as TargetKey\n } else if (isFunction(transformer) && !isInternalMethod(transformer.name)) {\n target[key] = transformer(source, context)\n } else if (isObject(transformer)) {\n const value =\n '$subSchema' in transformer\n ? (applySubSchemaTransformer<Source, TargetKey>(\n source,\n transformer as SubSchemaTransformer<Source, TargetKey>,\n context,\n schema as unknown as Schema<Source, TargetKey>,\n ) as TargetKey)\n : mapSchema<Source, TargetKey>(\n source,\n transformer as Schema<Source, TargetKey>,\n context,\n )\n\n if (value) {\n target[key] = value\n }\n }\n return target\n },\n {} as Target,\n )\n}\n\n/**\n * The `applySubSchemaTransformer()` function executes a `mapSchema()` function applying the defined\n * {@link SubSchemaTransformer.$subSchema}.\n *\n * @param source - The object to feed the schema.\n * @param subSchemaTransformer - The {@link SubSchemaTransformer} object with a $path, $subSchema\n * and $context options.\n * @param subSchemaTransformer.$path\n * @param subSchemaTransformer.$subSchema\n * @param subSchemaTransformer.$context\n * @param rawContext - The {@link MapperContext | mapper context} to feed the mapSchema function.\n * @param schema - The {@link Schema} to apply.\n * @returns The result of calling `mapSchema()` with the source, schema and context arguments.\n * @internal\n */\nfunction applySubSchemaTransformer<Source, Target>(\n source: Source,\n { $subSchema, $path, $context }: SubSchemaTransformer<Source, Target>,\n rawContext: MapperContext,\n schema: Schema<Source, Target>,\n): Target | Target[] | undefined {\n const subSource = getSafePropertyChain(source, $path)\n\n if (!subSource) {\n return\n }\n\n const extendedContext: Dictionary = {}\n if ($context) {\n Object.entries($context).forEach(([key, value]) => {\n if (['requestParameters', 'endpoint', 'mappedValue'].includes(key)) {\n return\n }\n extendedContext[key] = isFunction(value)\n ? value(source)\n : getSafePropertyChain(source, value as ExtractPath<typeof source>)\n })\n }\n\n const context = deepMerge({}, rawContext, $context, extendedContext)\n let subSchema: typeof $subSchema | typeof schema\n if ($subSchema === '$self') {\n subSchema = schema\n } else if (isFunction($subSchema)) {\n subSchema = $subSchema(source)\n } else {\n subSchema = $subSchema\n }\n return isArray(subSource)\n ? subSource.map(item => mapSchema(item, subSchema, context) as Target)\n : mapSchema<typeof subSource, Target>(\n subSource,\n subSchema as Schema<typeof subSource, Target>,\n context,\n )\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import { isTransformSchema } from '../schemas/transform-schema';
2
+ /**
3
+ * The `transformSchemaMapperFactory` function creates a {@link Mapper | mapper function} for a given
4
+ * {@link TransformSchema} or a raw Zod schema.
5
+ *
6
+ * @remarks A {@link TransformSchema} receives the {@link MapperContext | mapper context} and
7
+ * never throws on invalid sources. A raw Zod schema is strict: it throws if the source is not
8
+ * valid.
9
+ * @param schema - The schema to apply in the {@link Mapper | mapper function}.
10
+ * @returns A {@link Mapper | mapper function} that applies the given schema.
11
+ * @public
12
+ */
13
+ export function transformSchemaMapperFactory(schema) {
14
+ return function mapper(source, context) {
15
+ return isTransformSchema(schema) ? schema.parse(source, context) : schema.parse(source);
16
+ };
17
+ }
18
+ //# sourceMappingURL=transform-schema-mapper.factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-schema-mapper.factory.js","sourceRoot":"","sources":["../../../src/mappers/transform-schema-mapper.factory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AAY/D;;;;;;;;;;GAUG;AACH,MAAM,UAAU,4BAA4B,CAC1C,MAA8D;IAE9D,OAAO,SAAS,MAAM,CAAC,MAAc,EAAE,OAAsB;QAC3D,OAAO,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACzF,CAAC,CAAA;AACH,CAAC","sourcesContent":["import type { TransformSchema } from '../schemas/transform-schema.types'\nimport type { Mapper, MapperContext } from './types'\nimport { isTransformSchema } from '../schemas/transform-schema'\n\n/**\n * A schema-like object that has a `parse` method that throws if the input is not valid, like\n * any Zod schema: `z.object()`, `z.object().transform()`...\n *\n * @public\n */\nexport interface ParseableSchema<Target> {\n parse: (input: unknown) => Target\n}\n\n/**\n * The `transformSchemaMapperFactory` function creates a {@link Mapper | mapper function} for a given\n * {@link TransformSchema} or a raw Zod schema.\n *\n * @remarks A {@link TransformSchema} receives the {@link MapperContext | mapper context} and\n * never throws on invalid sources. A raw Zod schema is strict: it throws if the source is not\n * valid.\n * @param schema - The schema to apply in the {@link Mapper | mapper function}.\n * @returns A {@link Mapper | mapper function} that applies the given schema.\n * @public\n */\nexport function transformSchemaMapperFactory<Source, Target>(\n schema: TransformSchema<any, Target> | ParseableSchema<Target>,\n): Mapper<Source, Target> {\n return function mapper(source: Source, context: MapperContext): Target {\n return isTransformSchema(schema) ? schema.parse(source, context) : schema.parse(source)\n }\n}\n"]}
@@ -1,3 +1,5 @@
1
+ export * from './transform-schema';
2
+ export * from './transform-schema.types';
1
3
  export * from './types';
2
4
  export * from './utils';
3
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/schemas/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAA;AACvB,cAAc,SAAS,CAAA","sourcesContent":["export * from './types'\nexport * from './utils'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/schemas/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAA;AAClC,cAAc,0BAA0B,CAAA;AACxC,cAAc,SAAS,CAAA;AACvB,cAAc,SAAS,CAAA","sourcesContent":["export * from './transform-schema'\nexport * from './transform-schema.types'\nexport * from './types'\nexport * from './utils'\n"]}
@@ -0,0 +1,94 @@
1
+ /** Max number of different validation warnings that a schema reports. */
2
+ const MAX_REPORTED_ISSUES = 20;
3
+ function isPlainObject(value) {
4
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
5
+ }
6
+ function merge(base, value) {
7
+ return isPlainObject(base) && isPlainObject(value) ? { ...base, ...value } : value;
8
+ }
9
+ /**
10
+ * Removes the `undefined` properties of a mapped object. This way a transformation never adds
11
+ * properties that the source does not have, nor replaces already mapped ones with `undefined`.
12
+ */
13
+ function clean(value) {
14
+ return isPlainObject(value)
15
+ ? Object.fromEntries(Object.entries(value).filter(([, property]) => property !== undefined))
16
+ : value;
17
+ }
18
+ function createSchema(layers) {
19
+ const reportedIssues = new Set();
20
+ function validate(validator, source) {
21
+ const result = validator.safeParse(source);
22
+ if (result.success) {
23
+ return result.data;
24
+ }
25
+ const message = result.error instanceof Error ? result.error.message : String(result.error);
26
+ if (!reportedIssues.has(message) && reportedIssues.size < MAX_REPORTED_ISSUES) {
27
+ reportedIssues.add(message);
28
+ console.warn('[x-adapter] The source does not match the schema', result.error, source);
29
+ }
30
+ return source;
31
+ }
32
+ return {
33
+ parse(source, context = {}) {
34
+ if (source === undefined || source === null) {
35
+ console.warn('[x-adapter] This schema cannot be applied to an empty source');
36
+ return undefined;
37
+ }
38
+ // The raw source is the base, so validators that strip unknown keys do not lose data.
39
+ // Each validator receives the data accumulated so far, so it does not undo the values
40
+ // coerced by the previous ones.
41
+ const validated = layers.reduce((data, layer) => (layer.source ? merge(data, validate(layer.source, data)) : data), source);
42
+ return layers.reduce((target, layer) => merge(target, clean(layer.transform(validated, target, context))), undefined);
43
+ },
44
+ $override(override) {
45
+ layers.push(override);
46
+ return this;
47
+ },
48
+ $extends(override) {
49
+ return createSchema([...layers, override]);
50
+ },
51
+ $replace(definition) {
52
+ layers.splice(0, layers.length, toLayer(definition));
53
+ reportedIssues.clear();
54
+ return this;
55
+ },
56
+ };
57
+ }
58
+ function toLayer({ source, transform }) {
59
+ return { source, transform: (data, _target, context) => transform(data, context) };
60
+ }
61
+ /**
62
+ * Creates a {@link TransformSchema} that maps a source object to a target object with a plain
63
+ * function. Optionally, the source can be validated with a [Zod](https://zod.dev) schema.
64
+ *
65
+ * @param definition - The validator and the transformation of the schema.
66
+ * @returns A {@link TransformSchema}.
67
+ * @example
68
+ * ```typescript
69
+ * const resultSchema = createTransformSchema<ApiResult, Result>({
70
+ * transform: source => ({ id: source.__id, name: source.__name }),
71
+ * })
72
+ *
73
+ * // With a validator the types of the source are inferred from it.
74
+ * resultSchema.$override({
75
+ * source: z.looseObject({ brand: z.string() }),
76
+ * transform: source => ({ brand: source.brand }),
77
+ * })
78
+ * ```
79
+ * @public
80
+ */
81
+ export function createTransformSchema(definition) {
82
+ return createSchema([toLayer(definition)]);
83
+ }
84
+ /**
85
+ * Checks if the given schema is a {@link TransformSchema}.
86
+ *
87
+ * @param schema - The schema to check.
88
+ * @returns True if it is a {@link TransformSchema}, false otherwise.
89
+ * @public
90
+ */
91
+ export function isTransformSchema(schema) {
92
+ return isPlainObject(schema) && '$override' in schema && '$extends' in schema;
93
+ }
94
+ //# sourceMappingURL=transform-schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-schema.js","sourceRoot":"","sources":["../../../src/schemas/transform-schema.ts"],"names":[],"mappings":"AAcA,yEAAyE;AACzE,MAAM,mBAAmB,GAAG,EAAE,CAAA;AAE9B,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,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AAA;AACH,CAAC;AAED,SAAS,OAAO,CAAC,EAAE,MAAM,EAAE,SAAS,EAAuC;IACzE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,CAAA;AACpF,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,qBAAqB,CACnC,UAAqD;IAErD,OAAO,YAAY,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;AAC5C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAe;IAC/C,OAAO,aAAa,CAAC,MAAM,CAAC,IAAI,WAAW,IAAI,MAAM,IAAI,UAAU,IAAI,MAAM,CAAA;AAC/E,CAAC","sourcesContent":["import type { MapperContext } from '../mappers/types'\nimport type {\n SourceValidator,\n TransformSchema,\n TransformSchemaDefinition,\n TransformSchemaOverride,\n} from './transform-schema.types'\n\n/** A step of the mapping: an optional validator plus the transformation to merge. */\ninterface Layer {\n source?: SourceValidator\n transform: (source: any, target: any, context: MapperContext) => unknown\n}\n\n/** Max number of different validation warnings that a schema reports. */\nconst MAX_REPORTED_ISSUES = 20\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction merge(base: unknown, value: unknown): unknown {\n return isPlainObject(base) && isPlainObject(value) ? { ...base, ...value } : value\n}\n\n/**\n * Removes the `undefined` properties of a mapped object. This way a transformation never adds\n * properties that the source does not have, nor replaces already mapped ones with `undefined`.\n */\nfunction clean(value: unknown): unknown {\n return isPlainObject(value)\n ? Object.fromEntries(Object.entries(value).filter(([, property]) => property !== undefined))\n : value\n}\n\nfunction createSchema(layers: Layer[]): TransformSchema<any, any> {\n const reportedIssues = new Set<string>()\n\n function validate(validator: SourceValidator, source: unknown): unknown {\n const result = validator.safeParse(source)\n if (result.success) {\n return result.data\n }\n const message = result.error instanceof Error ? result.error.message : String(result.error)\n if (!reportedIssues.has(message) && reportedIssues.size < MAX_REPORTED_ISSUES) {\n reportedIssues.add(message)\n console.warn('[x-adapter] The source does not match the schema', result.error, source)\n }\n return source\n }\n\n return {\n parse(source, context = {}) {\n if (source === undefined || source === null) {\n console.warn('[x-adapter] This schema cannot be applied to an empty source')\n return undefined\n }\n // The raw source is the base, so validators that strip unknown keys do not lose data.\n // Each validator receives the data accumulated so far, so it does not undo the values\n // coerced by the previous ones.\n const validated = layers.reduce<unknown>(\n (data, layer) => (layer.source ? merge(data, validate(layer.source, data)) : data),\n source,\n )\n return layers.reduce<unknown>(\n (target, layer) => merge(target, clean(layer.transform(validated, target, context))),\n undefined,\n )\n },\n $override(override: TransformSchemaOverride<any, any, any, any>) {\n layers.push(override)\n return this\n },\n $extends(override: TransformSchemaOverride<any, any, any, any>) {\n return createSchema([...layers, override])\n },\n $replace(definition: TransformSchemaDefinition<any, any>) {\n layers.splice(0, layers.length, toLayer(definition))\n reportedIssues.clear()\n return this\n },\n }\n}\n\nfunction toLayer({ source, transform }: TransformSchemaDefinition<any, any>): Layer {\n return { source, transform: (data, _target, context) => transform(data, context) }\n}\n\n/**\n * Creates a {@link TransformSchema} that maps a source object to a target object with a plain\n * function. Optionally, the source can be validated with a [Zod](https://zod.dev) schema.\n *\n * @param definition - The validator and the transformation of the schema.\n * @returns A {@link TransformSchema}.\n * @example\n * ```typescript\n * const resultSchema = createTransformSchema<ApiResult, Result>({\n * transform: source => ({ id: source.__id, name: source.__name }),\n * })\n *\n * // With a validator the types of the source are inferred from it.\n * resultSchema.$override({\n * source: z.looseObject({ brand: z.string() }),\n * transform: source => ({ brand: source.brand }),\n * })\n * ```\n * @public\n */\nexport function createTransformSchema<Source, Target>(\n definition: TransformSchemaDefinition<Source, Target>,\n): TransformSchema<Source, Target> {\n return createSchema([toLayer(definition)])\n}\n\n/**\n * Checks if the given schema is a {@link TransformSchema}.\n *\n * @param schema - The schema to check.\n * @returns True if it is a {@link TransformSchema}, false otherwise.\n * @public\n */\nexport function isTransformSchema(schema: unknown): schema is TransformSchema<any, any> {\n return isPlainObject(schema) && '$override' in schema && '$extends' in schema\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=transform-schema.types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-schema.types.js","sourceRoot":"","sources":["../../../src/schemas/transform-schema.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { MapperContext } from '../mappers/types'\n\n/**\n * The result of validating a source object with a {@link SourceValidator}.\n *\n * @public\n */\nexport type SourceValidatorResult<Output> =\n | { success: true; data: Output }\n | { success: false; error: unknown }\n\n/**\n * Minimal structural contract of a validator. Any [Zod](https://zod.dev) schema (`zod` or\n * `zod/mini`) satisfies it, so `@empathyco/x-adapter` does not need to depend on a concrete Zod\n * version.\n *\n * @param Output - The type of the validated source.\n * @public\n */\nexport interface SourceValidator<Output = unknown> {\n safeParse: (input: unknown) => SourceValidatorResult<Output>\n}\n\n/**\n * Definition of a {@link TransformSchema}.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * const userSchema = createTransformSchema({\n * source: z.looseObject({ id: z.string(), price: z.object({ max: z.number() }) }),\n * transform: (source): User => ({ identifier: source.id, maxPrice: source.price.max }),\n * })\n * ```\n * @public\n */\nexport interface TransformSchemaDefinition<Source, Target> {\n /**\n * Validator of the source object. When omitted the source is not validated and its type has\n * to be provided through the `Source` type parameter.\n */\n source?: SourceValidator<Source>\n /**\n * Maps the (validated) source object to the target object.\n *\n * @remarks The properties of the returned object whose value is `undefined` are not added to\n * the target.\n * @param source - The validated source object.\n * @param context - The {@link MapperContext | mapper context}.\n * @returns The target object.\n */\n transform: (source: Source, context: MapperContext) => Target\n}\n\n/**\n * Definition of a modification to apply on top of a {@link TransformSchema}.\n *\n * @param Source - The source object of the schema to modify.\n * @param Target - The target object of the schema to modify.\n * @param NewSource - The extra properties of the source object.\n * @param NewTarget - The extra properties of the target object.\n * @public\n */\nexport interface TransformSchemaOverride<Source, Target, NewSource, NewTarget> {\n /**\n * Validator for the extra properties of the source object. Its output is merged with the\n * output of the validators that the schema already has.\n */\n source?: SourceValidator<NewSource>\n /**\n * Maps the source object to the properties of the target to add or replace. The returned\n * object is shallow merged with the target mapped so far.\n *\n * @remarks The properties of the returned object whose value is `undefined` are ignored, so\n * they do not replace the ones already mapped.\n * @param source - The validated source object.\n * @param target - The target object mapped so far by the schema.\n * @param context - The {@link MapperContext | mapper context}.\n * @returns The properties to add or replace in the target object.\n */\n transform: (\n source: Source & NewSource,\n target: Target,\n context: MapperContext,\n ) => Partial<Target> & NewTarget\n}\n\n/**\n * A schema that maps a source object to a target object, optionally validating the source. It can\n * be modified after its creation to: partially override it, create a new one or completely replace\n * it.\n *\n * @remarks It replaces the deprecated {@link MutableSchema}, whose path based typings forced\n * TypeScript to recursively compute every possible path of the source object.\n * @param Source - The source object.\n * @param Target - The target object.\n * @public\n */\nexport interface TransformSchema<Source, Target> {\n /**\n * Validates the source object and maps it to the target object.\n *\n * @remarks Validation never breaks the mapping: if the source does not match the validators, a\n * warning is logged and the raw source is mapped.\n * @param source - The object to map.\n * @param context - The {@link MapperContext | mapper context} to feed the transformations with.\n * @returns The target object.\n */\n parse: (source: unknown, context?: MapperContext) => Target\n /**\n * Modifies this schema, so every usage of it applies the given modification.\n *\n * @param override - The validator and the transformation to apply on top of this schema.\n * @returns This schema.\n */\n $override: <NewSource = unknown, NewTarget = unknown>(\n override: TransformSchemaOverride<Source, Target, NewSource, NewTarget>,\n ) => TransformSchema<Source & NewSource, Target & NewTarget>\n /**\n * Creates a new schema using this one as starting point. This schema remains unchanged.\n *\n * @param override - The validator and the transformation to apply on top of this schema.\n * @returns The new schema.\n */\n $extends: <NewSource = unknown, NewTarget = unknown>(\n override: TransformSchemaOverride<Source, Target, NewSource, NewTarget>,\n ) => TransformSchema<Source & NewSource, Target & NewTarget>\n /**\n * Replaces all usages of this schema with the given definition.\n *\n * @param definition - The definition to use instead of the current one.\n * @returns This schema.\n */\n $replace: <NewSource, NewTarget>(\n definition: TransformSchemaDefinition<NewSource, NewTarget>,\n ) => TransformSchema<NewSource, NewTarget>\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/schemas/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AnyFunction,\n DeepPartial,\n ExtractPath,\n ExtractPathByType,\n ExtractType,\n Primitive,\n} from '@empathyco/x-utils'\nimport type { MapperContext } from '../mappers/types'\n\n// TODO: EX-5830 - Enhance Schema type to support optional properties in the Source object\n/**\n * Template object to transform a source object to a target object.\n *\n * @remarks The source object must not have optional properties, as it could cause infinite\n * type instantiations.\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * price: {\n * max: number;\n * min: number;\n * };\n * images: string[];\n * }\n *\n * interface Target {\n * identifier: string;\n * maxPrice: number;\n * minPrice: number;\n * img: string[]\n * }\n *\n * const schema: Schema<Source, Target> = {\n * identifier: 'id',\n * maxPrice: 'price.max',\n * minPrice: ({ price }) => Math.min(0, price.min),\n * img: 'images'\n * };\n * ```\n * @public\n */\nexport type Schema<Source = any, Target = any> = {\n [TargetKey in keyof Target]: SchemaTransformer<Source, Target, TargetKey>\n}\n\n/**\n * A {@link Schema | schema} with extended functionality to: completely replace\n * the original schema, partially override it or create a new one.\n *\n * @param OriginalSchema - The {@link Schema | schema} that will be mutable.\n * @public\n */\nexport type MutableSchema<Source, Target> = Schema<Source, Target> & {\n /**\n * Replaces all usages of the original {@link Schema | schema} with the given one.\n *\n * @param newSchema - The {@link Schema | schema} to use instead of the original one.\n * @returns The new {@link Schema | schema} that will be used.\n */\n $replace: <NewSource, NewTarget>(\n newSchema: Schema<NewSource, NewTarget>,\n ) => MutableSchema<NewSource, NewTarget>\n /**\n * Merges the original {@link Schema | schema} with the given one.\n *\n * @param newSchema - The {@link Schema | schema} to use to merge with the original one.\n * @returns The {@link Schema | schema} returned by the merge.\n */\n $override: <NewSource, NewTarget = object>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, NewTarget>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>\n /**\n * Creates a new {@link Schema | schema} using the original one as starting point.\n * The original {@link Schema | schema} will remain unchanged.\n *\n * @param newSchema - The {@link Schema | schema} to be used to extend the original one.\n * Both schema's Target and Source can be unique or also be extending from another one.\n * @returns The {@link Schema | schema} created.\n */\n $extends: (<NewSource extends Source, NewTarget extends Target>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, Omit<NewTarget, keyof Target>>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>) &\n (<NewSource, NewTarget = object>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, NewTarget>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>)\n /**\n * Returns a string representing of the {@link Schema | schema}.\n *\n * @param includeInternalMethods - Flag to include in the string representation\n * the internal methods. Disabled by default.\n * @returns The string representation.\n */\n toString: (includeInternalMethods?: boolean) => string\n}\n/**\n * The possible transformers to apply to the target key.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @param TargetKey - The target key to apply the transformation.\n * @public\n */\nexport type SchemaTransformer<Source, Target, TargetKey extends keyof Target> =\n | PathTransformer<Source, Target[TargetKey]>\n | FunctionTransformer<Source, Target[TargetKey]>\n | SubSchemaTransformer<Source, Target[TargetKey]>\n | Schema<Source, Exclude<Target[TargetKey], AnyFunction | Primitive>>\n\n/**\n * A function with the source object and mapper context as parameters that returns the value of a\n * target's property.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * count: number;\n * }\n *\n * interface Target {\n * title: string;\n * hits: number;\n * }\n *\n * const subSchema: Schema<Source, Target> = {\n * title: 'id',\n * hits: 'count'\n * };\n *\n * const wrongSubSchema: Schema<Source, Target> = {\n * // @ts-expect-error\n * title: 'count', // This raises a TS error\n * hits: 'count'\n * };\n * ```\n * @public\n */\nexport type PathTransformer<Source, Target> = ExtractPathByType<Source, Target>\n\n/**\n * A function with the source object and mapper context as parameters that returns the value of a\n * target's property.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * count: number;\n * }\n *\n * interface Target {\n * title: string;\n * hits: number;\n * }\n *\n * const subSchema: Schema<Source, Target> = {\n * title: source => source.id,\n * hits: (source, context) => context.requestParameters.query === 'example'\n * ? source.count\n * : 0\n * };\n * ```\n * @public\n */\nexport type FunctionTransformer<Source, Target> = (\n source: Source,\n context?: MapperContext,\n) => Target\n\n/**\n * An object containing a schema narrowing its source object based on the given path.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * facets: {\n * name: string;\n * count: number;\n * };\n * images: string[];\n * }\n *\n * interface Target {\n * identifier: string;\n * filters: {\n * id: string;\n * numFound: number;\n * };\n * img: string[]\n * }\n *\n * const subSchema: SubSchemaTransformer<Source, Target['filters']> = {\n * $path: 'facets',\n * $subSchema: {\n * id: 'name',\n * numFound: 'count'\n * }\n * };\n * ```\n * @public\n */\nexport type SubSchemaTransformer<Source, Target> = {\n [Path in ExtractPath<Source>]: {\n $context?: MapperContext\n $path: Path\n $subSchema:\n | SubSchema<Source, Target, Path>\n | '$self'\n | ((source: Source) => SubSchema<Source, Target, Path>)\n }\n}[ExtractPath<Source>]\n\n/**\n * A {@link Schema | schema} that will be applied to an inner path of an object.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @param Path - The path where the schema will be applied.\n * @public\n */\nexport type SubSchema<Source, Target, Path extends ExtractPath<Source>> =\n ExtractType<Source, Path> extends (infer SourceArrayType)[]\n ? Target extends (infer TargetArrayType)[]\n ? Schema<SourceArrayType, TargetArrayType>\n : never\n : Target extends []\n ? never\n : Schema<ExtractType<Source, Path>, Target>\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/schemas/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AnyFunction,\n DeepPartial,\n ExtractPath,\n ExtractPathByType,\n ExtractType,\n Primitive,\n} from '@empathyco/x-utils'\nimport type { MapperContext } from '../mappers/types'\n\n// TODO: EX-5830 - Enhance Schema type to support optional properties in the Source object\n/**\n * Template object to transform a source object to a target object.\n *\n * @remarks The source object must not have optional properties, as it could cause infinite\n * type instantiations.\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * price: {\n * max: number;\n * min: number;\n * };\n * images: string[];\n * }\n *\n * interface Target {\n * identifier: string;\n * maxPrice: number;\n * minPrice: number;\n * img: string[]\n * }\n *\n * const schema: Schema<Source, Target> = {\n * identifier: 'id',\n * maxPrice: 'price.max',\n * minPrice: ({ price }) => Math.min(0, price.min),\n * img: 'images'\n * };\n * ```\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type Schema<Source = any, Target = any> = {\n [TargetKey in keyof Target]: SchemaTransformer<Source, Target, TargetKey>\n}\n\n/**\n * A {@link Schema | schema} with extended functionality to: completely replace\n * the original schema, partially override it or create a new one.\n *\n * @param OriginalSchema - The {@link Schema | schema} that will be mutable.\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type MutableSchema<Source, Target> = Schema<Source, Target> & {\n /**\n * Replaces all usages of the original {@link Schema | schema} with the given one.\n *\n * @param newSchema - The {@link Schema | schema} to use instead of the original one.\n * @returns The new {@link Schema | schema} that will be used.\n */\n $replace: <NewSource, NewTarget>(\n newSchema: Schema<NewSource, NewTarget>,\n ) => MutableSchema<NewSource, NewTarget>\n /**\n * Merges the original {@link Schema | schema} with the given one.\n *\n * @param newSchema - The {@link Schema | schema} to use to merge with the original one.\n * @returns The {@link Schema | schema} returned by the merge.\n */\n $override: <NewSource, NewTarget = object>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, NewTarget>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>\n /**\n * Creates a new {@link Schema | schema} using the original one as starting point.\n * The original {@link Schema | schema} will remain unchanged.\n *\n * @param newSchema - The {@link Schema | schema} to be used to extend the original one.\n * Both schema's Target and Source can be unique or also be extending from another one.\n * @returns The {@link Schema | schema} created.\n */\n $extends: (<NewSource extends Source, NewTarget extends Target>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, Omit<NewTarget, keyof Target>>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>) &\n (<NewSource, NewTarget = object>(\n newSchema: DeepPartial<Schema<Source & NewSource, Target>> &\n Schema<Source & NewSource, NewTarget>,\n ) => MutableSchema<Source & NewSource, Target & NewTarget>)\n /**\n * Returns a string representing of the {@link Schema | schema}.\n *\n * @param includeInternalMethods - Flag to include in the string representation\n * the internal methods. Disabled by default.\n * @returns The string representation.\n */\n toString: (includeInternalMethods?: boolean) => string\n}\n/**\n * The possible transformers to apply to the target key.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @param TargetKey - The target key to apply the transformation.\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type SchemaTransformer<Source, Target, TargetKey extends keyof Target> =\n | PathTransformer<Source, Target[TargetKey]>\n | FunctionTransformer<Source, Target[TargetKey]>\n | SubSchemaTransformer<Source, Target[TargetKey]>\n | Schema<Source, Exclude<Target[TargetKey], AnyFunction | Primitive>>\n\n/**\n * A function with the source object and mapper context as parameters that returns the value of a\n * target's property.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * count: number;\n * }\n *\n * interface Target {\n * title: string;\n * hits: number;\n * }\n *\n * const subSchema: Schema<Source, Target> = {\n * title: 'id',\n * hits: 'count'\n * };\n *\n * const wrongSubSchema: Schema<Source, Target> = {\n * // @ts-expect-error\n * title: 'count', // This raises a TS error\n * hits: 'count'\n * };\n * ```\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type PathTransformer<Source, Target> = ExtractPathByType<Source, Target>\n\n/**\n * A function with the source object and mapper context as parameters that returns the value of a\n * target's property.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * count: number;\n * }\n *\n * interface Target {\n * title: string;\n * hits: number;\n * }\n *\n * const subSchema: Schema<Source, Target> = {\n * title: source => source.id,\n * hits: (source, context) => context.requestParameters.query === 'example'\n * ? source.count\n * : 0\n * };\n * ```\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type FunctionTransformer<Source, Target> = (\n source: Source,\n context?: MapperContext,\n) => Target\n\n/**\n * An object containing a schema narrowing its source object based on the given path.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @example\n * ```typescript\n * interface Source {\n * id: string;\n * facets: {\n * name: string;\n * count: number;\n * };\n * images: string[];\n * }\n *\n * interface Target {\n * identifier: string;\n * filters: {\n * id: string;\n * numFound: number;\n * };\n * img: string[]\n * }\n *\n * const subSchema: SubSchemaTransformer<Source, Target['filters']> = {\n * $path: 'facets',\n * $subSchema: {\n * id: 'name',\n * numFound: 'count'\n * }\n * };\n * ```\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type SubSchemaTransformer<Source, Target> = {\n [Path in ExtractPath<Source>]: {\n $context?: MapperContext\n $path: Path\n $subSchema:\n | SubSchema<Source, Target, Path>\n | '$self'\n | ((source: Source) => SubSchema<Source, Target, Path>)\n }\n}[ExtractPath<Source>]\n\n/**\n * A {@link Schema | schema} that will be applied to an inner path of an object.\n *\n * @param Source - The source object.\n * @param Target - The target object.\n * @param Path - The path where the schema will be applied.\n * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.\n * @public\n */\nexport type SubSchema<Source, Target, Path extends ExtractPath<Source>> =\n ExtractType<Source, Path> extends (infer SourceArrayType)[]\n ? Target extends (infer TargetArrayType)[]\n ? Schema<SourceArrayType, TargetArrayType>\n : never\n : Target extends []\n ? never\n : Schema<ExtractType<Source, Path>, Target>\n"]}
@@ -10,6 +10,7 @@ const mutableSchemasInternalMethods = ['$replace', '$override', '$extends', 'toS
10
10
  *
11
11
  * @returns A {@link MutableSchema | mutable schema} version of the given {@link Schema | schema}.
12
12
  *
13
+ * @deprecated Use {@link createTransformSchema} instead.
13
14
  * @public
14
15
  */
15
16
  export function createMutableSchema(schema) {
@@ -46,6 +47,7 @@ export function createMutableSchema(schema) {
46
47
  * @returns True if it is a {@link MutableSchema | mutableSchema} method,
47
48
  * false otherwise.
48
49
  *
50
+ * @deprecated Only used by the deprecated {@link MutableSchema}.
49
51
  * @public
50
52
  */
51
53
  export function isInternalMethod(name) {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/schemas/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAE7E;;GAEG;AACH,MAAM,6BAA6B,GAAa,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,CAAC,CAAA;AAEjG;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA8B;IAE9B,OAAO;QACL,GAAG,MAAM;QACT,QAAQ,CAAC,SAAS;YAChB,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE;gBAClB,IAAI,gBAAgB,CAAC,GAAa,CAAC,EAAE,CAAC;oBACpC,OAAM;gBACR,CAAC;gBACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAA;YAClB,CAAC,CAAC,CAAA;YACF,MAAM,CAAC,MAAM,CAAC,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ourcesContent":["import type { MutableSchema, Schema } from './types'\nimport { deepMerge, forEach, isFunction, isObject } from '@empathyco/x-utils'\n\n/**\n * Collection of internal method names for {@link MutableSchema | mutable schemas}.\n */\nconst mutableSchemasInternalMethods: string[] = ['$replace', '$override', '$extends', 'toString']\n\n/**\n * Creates a {@link MutableSchema | mutable schema } version of a given {@link Schema | schema}.\n *\n * @param schema - The {@link Schema | schema} to make mutable.\n *\n * @returns A {@link MutableSchema | mutable schema} version of the given {@link Schema | schema}.\n *\n * @public\n */\nexport function createMutableSchema<Source, Target>(\n schema: Schema<Source, Target>,\n): MutableSchema<Source, Target> {\n return {\n ...schema,\n $replace(newSchema) {\n forEach(this, key => {\n if (isInternalMethod(key as string)) {\n return\n }\n delete this[key]\n })\n Object.assign(this, newSchema)\n /* We are replacing the schema with a completely new schema , so it makes sense that TS\n complains that the old schema and the new one are not the same. */\n return this as any\n },\n $override(newSchema) {\n return deepMerge(this, newSchema)\n },\n $extends(newSchema: unknown) {\n return deepMerge({}, this, newSchema)\n },\n toString(includeInternalMethods = false) {\n return serialize(this, !!includeInternalMethods)\n },\n }\n}\n\n/**\n * Checks if the given key is a {@link MutableSchema | mutableSchema} method.\n *\n * @param name - The key to check.\n *\n * @returns True if it is a {@link MutableSchema | mutableSchema} method,\n * false otherwise.\n *\n * @public\n */\nexport function isInternalMethod(name: string): boolean {\n return mutableSchemasInternalMethods.includes(name)\n}\n\n/**\n * Returns a string representing of the given object.\n *\n * @param data - The object to get the string representation from.\n * @param includeInternalMethods - Flag to include in the string representation\n * the internal methods. Disabled by default.\n * @param deep - The level of indentation.\n * @returns The string representation.\n */\nfunction serialize(\n data: Record<string, unknown>,\n includeInternalMethods: boolean,\n deep = 0,\n): string {\n const indentation = ' '.repeat(deep)\n let output = ''\n forEach(data, (key, value) => {\n if (isObject(value)) {\n output += `${indentation}${key}: {\\n${serialize(\n value,\n includeInternalMethods,\n ++deep,\n )}${indentation}},\\n`\n } else if (!isFunction(value) || !isInternalMethod(key) || includeInternalMethods) {\n output += `${indentation}${key}: ${value as any},\\n`\n }\n })\n return output\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/schemas/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAE7E;;GAEG;AACH,MAAM,6BAA6B,GAAa,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,CAAC,CAAA;AAEjG;;;;;;;;;GASG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA8B;IAE9B,OAAO;QACL,GAAG,MAAM;QACT,QAAQ,CAAC,SAAS;YAChB,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE;gBAClB,IAAI,gBAAgB,CAAC,GAAa,CAAC,EAAE,CAAC;oBACpC,OAAM;gBACR,CAAC;gBACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAA;YAClB,CAAC,CAAC,CAAA;YACF,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;YAC9B;+EACmE;YACnE,OAAO,IAAW,CAAA;QACpB,CAAC;QACD,SAAS,CAAC,SAAS;YACjB,OAAO,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;QACnC,CAAC;QACD,QAAQ,CAAC,SAAkB;YACzB,OAAO,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAA;QACvC,CAAC;QACD,QAAQ,CAAC,sBAAsB,GAAG,KAAK;YACrC,OAAO,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,sBAAsB,CAAC,CAAA;QAClD,CAAC;KACF,CAAA;AACH,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAC3C,OAAO,6BAA6B,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;AACrD,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,SAAS,CAChB,IAA6B,EAC7B,sBAA+B,EAC/B,IAAI,GAAG,CAAC;IAER,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACrC,IAAI,MAAM,GAAG,EAAE,CAAA;IACf,OAAO,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;QAC3B,IAAI,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,WAAW,GAAG,GAAG,QAAQ,SAAS,CAC7C,KAAK,EACL,sBAAsB,EACtB,EAAE,IAAI,CACP,GAAG,WAAW,MAAM,CAAA;QACvB,CAAC;aAAM,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,sBAAsB,EAAE,CAAC;YAClF,MAAM,IAAI,GAAG,WAAW,GAAG,GAAG,KAAK,KAAY,KAAK,CAAA;QACtD,CAAC;IACH,CAAC,CAAC,CAAA;IACF,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import type { MutableSchema, Schema } from './types'\nimport { deepMerge, forEach, isFunction, isObject } from '@empathyco/x-utils'\n\n/**\n * Collection of internal method names for {@link MutableSchema | mutable schemas}.\n */\nconst mutableSchemasInternalMethods: string[] = ['$replace', '$override', '$extends', 'toString']\n\n/**\n * Creates a {@link MutableSchema | mutable schema } version of a given {@link Schema | schema}.\n *\n * @param schema - The {@link Schema | schema} to make mutable.\n *\n * @returns A {@link MutableSchema | mutable schema} version of the given {@link Schema | schema}.\n *\n * @deprecated Use {@link createTransformSchema} instead.\n * @public\n */\nexport function createMutableSchema<Source, Target>(\n schema: Schema<Source, Target>,\n): MutableSchema<Source, Target> {\n return {\n ...schema,\n $replace(newSchema) {\n forEach(this, key => {\n if (isInternalMethod(key as string)) {\n return\n }\n delete this[key]\n })\n Object.assign(this, newSchema)\n /* We are replacing the schema with a completely new schema , so it makes sense that TS\n complains that the old schema and the new one are not the same. */\n return this as any\n },\n $override(newSchema) {\n return deepMerge(this, newSchema)\n },\n $extends(newSchema: unknown) {\n return deepMerge({}, this, newSchema)\n },\n toString(includeInternalMethods = false) {\n return serialize(this, !!includeInternalMethods)\n },\n }\n}\n\n/**\n * Checks if the given key is a {@link MutableSchema | mutableSchema} method.\n *\n * @param name - The key to check.\n *\n * @returns True if it is a {@link MutableSchema | mutableSchema} method,\n * false otherwise.\n *\n * @deprecated Only used by the deprecated {@link MutableSchema}.\n * @public\n */\nexport function isInternalMethod(name: string): boolean {\n return mutableSchemasInternalMethods.includes(name)\n}\n\n/**\n * Returns a string representing of the given object.\n *\n * @param data - The object to get the string representation from.\n * @param includeInternalMethods - Flag to include in the string representation\n * the internal methods. Disabled by default.\n * @param deep - The level of indentation.\n * @returns The string representation.\n */\nfunction serialize(\n data: Record<string, unknown>,\n includeInternalMethods: boolean,\n deep = 0,\n): string {\n const indentation = ' '.repeat(deep)\n let output = ''\n forEach(data, (key, value) => {\n if (isObject(value)) {\n output += `${indentation}${key}: {\\n${serialize(\n value,\n includeInternalMethods,\n ++deep,\n )}${indentation}},\\n`\n } else if (!isFunction(value) || !isInternalMethod(key) || includeInternalMethods) {\n output += `${indentation}${key}: ${value as any},\\n`\n }\n })\n return output\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export * from './combine-mappers';
2
2
  export * from './identity.mapper';
3
3
  export * from './schema-mapper.factory';
4
+ export * from './transform-schema-mapper.factory';
4
5
  export * from './types';
@@ -6,6 +6,7 @@ import type { Mapper } from './types';
6
6
  *
7
7
  * @param schema - The {@link Schema | schema} to apply in the {@link Mapper | mapper function}.
8
8
  * @returns A {@link Mapper | mapper function} that applies the given {@link Schema | schema}.
9
+ * @deprecated Use {@link transformSchemaMapperFactory} with a {@link TransformSchema} instead.
9
10
  * @public
10
11
  */
11
12
  export declare function schemaMapperFactory<Source, Target>(schema: Schema<Source, Target> | MutableSchema<Source, Target>): Mapper<Source, Target>;
@@ -0,0 +1,23 @@
1
+ import type { TransformSchema } from '../schemas/transform-schema.types';
2
+ import type { Mapper } from './types';
3
+ /**
4
+ * A schema-like object that has a `parse` method that throws if the input is not valid, like
5
+ * any Zod schema: `z.object()`, `z.object().transform()`...
6
+ *
7
+ * @public
8
+ */
9
+ export interface ParseableSchema<Target> {
10
+ parse: (input: unknown) => Target;
11
+ }
12
+ /**
13
+ * The `transformSchemaMapperFactory` function creates a {@link Mapper | mapper function} for a given
14
+ * {@link TransformSchema} or a raw Zod schema.
15
+ *
16
+ * @remarks A {@link TransformSchema} receives the {@link MapperContext | mapper context} and
17
+ * never throws on invalid sources. A raw Zod schema is strict: it throws if the source is not
18
+ * valid.
19
+ * @param schema - The schema to apply in the {@link Mapper | mapper function}.
20
+ * @returns A {@link Mapper | mapper function} that applies the given schema.
21
+ * @public
22
+ */
23
+ export declare function transformSchemaMapperFactory<Source, Target>(schema: TransformSchema<any, Target> | ParseableSchema<Target>): Mapper<Source, Target>;
@@ -1,2 +1,4 @@
1
+ export * from './transform-schema';
2
+ export * from './transform-schema.types';
1
3
  export * from './types';
2
4
  export * from './utils';
@@ -0,0 +1,30 @@
1
+ import type { TransformSchema, TransformSchemaDefinition } from './transform-schema.types';
2
+ /**
3
+ * Creates a {@link TransformSchema} that maps a source object to a target object with a plain
4
+ * function. Optionally, the source can be validated with a [Zod](https://zod.dev) schema.
5
+ *
6
+ * @param definition - The validator and the transformation of the schema.
7
+ * @returns A {@link TransformSchema}.
8
+ * @example
9
+ * ```typescript
10
+ * const resultSchema = createTransformSchema<ApiResult, Result>({
11
+ * transform: source => ({ id: source.__id, name: source.__name }),
12
+ * })
13
+ *
14
+ * // With a validator the types of the source are inferred from it.
15
+ * resultSchema.$override({
16
+ * source: z.looseObject({ brand: z.string() }),
17
+ * transform: source => ({ brand: source.brand }),
18
+ * })
19
+ * ```
20
+ * @public
21
+ */
22
+ export declare function createTransformSchema<Source, Target>(definition: TransformSchemaDefinition<Source, Target>): TransformSchema<Source, Target>;
23
+ /**
24
+ * Checks if the given schema is a {@link TransformSchema}.
25
+ *
26
+ * @param schema - The schema to check.
27
+ * @returns True if it is a {@link TransformSchema}, false otherwise.
28
+ * @public
29
+ */
30
+ export declare function isTransformSchema(schema: unknown): schema is TransformSchema<any, any>;
@@ -0,0 +1,127 @@
1
+ import type { MapperContext } from '../mappers/types';
2
+ /**
3
+ * The result of validating a source object with a {@link SourceValidator}.
4
+ *
5
+ * @public
6
+ */
7
+ export type SourceValidatorResult<Output> = {
8
+ success: true;
9
+ data: Output;
10
+ } | {
11
+ success: false;
12
+ error: unknown;
13
+ };
14
+ /**
15
+ * Minimal structural contract of a validator. Any [Zod](https://zod.dev) schema (`zod` or
16
+ * `zod/mini`) satisfies it, so `@empathyco/x-adapter` does not need to depend on a concrete Zod
17
+ * version.
18
+ *
19
+ * @param Output - The type of the validated source.
20
+ * @public
21
+ */
22
+ export interface SourceValidator<Output = unknown> {
23
+ safeParse: (input: unknown) => SourceValidatorResult<Output>;
24
+ }
25
+ /**
26
+ * Definition of a {@link TransformSchema}.
27
+ *
28
+ * @param Source - The source object.
29
+ * @param Target - The target object.
30
+ * @example
31
+ * ```typescript
32
+ * const userSchema = createTransformSchema({
33
+ * source: z.looseObject({ id: z.string(), price: z.object({ max: z.number() }) }),
34
+ * transform: (source): User => ({ identifier: source.id, maxPrice: source.price.max }),
35
+ * })
36
+ * ```
37
+ * @public
38
+ */
39
+ export interface TransformSchemaDefinition<Source, Target> {
40
+ /**
41
+ * Validator of the source object. When omitted the source is not validated and its type has
42
+ * to be provided through the `Source` type parameter.
43
+ */
44
+ source?: SourceValidator<Source>;
45
+ /**
46
+ * Maps the (validated) source object to the target object.
47
+ *
48
+ * @remarks The properties of the returned object whose value is `undefined` are not added to
49
+ * the target.
50
+ * @param source - The validated source object.
51
+ * @param context - The {@link MapperContext | mapper context}.
52
+ * @returns The target object.
53
+ */
54
+ transform: (source: Source, context: MapperContext) => Target;
55
+ }
56
+ /**
57
+ * Definition of a modification to apply on top of a {@link TransformSchema}.
58
+ *
59
+ * @param Source - The source object of the schema to modify.
60
+ * @param Target - The target object of the schema to modify.
61
+ * @param NewSource - The extra properties of the source object.
62
+ * @param NewTarget - The extra properties of the target object.
63
+ * @public
64
+ */
65
+ export interface TransformSchemaOverride<Source, Target, NewSource, NewTarget> {
66
+ /**
67
+ * Validator for the extra properties of the source object. Its output is merged with the
68
+ * output of the validators that the schema already has.
69
+ */
70
+ source?: SourceValidator<NewSource>;
71
+ /**
72
+ * Maps the source object to the properties of the target to add or replace. The returned
73
+ * object is shallow merged with the target mapped so far.
74
+ *
75
+ * @remarks The properties of the returned object whose value is `undefined` are ignored, so
76
+ * they do not replace the ones already mapped.
77
+ * @param source - The validated source object.
78
+ * @param target - The target object mapped so far by the schema.
79
+ * @param context - The {@link MapperContext | mapper context}.
80
+ * @returns The properties to add or replace in the target object.
81
+ */
82
+ transform: (source: Source & NewSource, target: Target, context: MapperContext) => Partial<Target> & NewTarget;
83
+ }
84
+ /**
85
+ * A schema that maps a source object to a target object, optionally validating the source. It can
86
+ * be modified after its creation to: partially override it, create a new one or completely replace
87
+ * it.
88
+ *
89
+ * @remarks It replaces the deprecated {@link MutableSchema}, whose path based typings forced
90
+ * TypeScript to recursively compute every possible path of the source object.
91
+ * @param Source - The source object.
92
+ * @param Target - The target object.
93
+ * @public
94
+ */
95
+ export interface TransformSchema<Source, Target> {
96
+ /**
97
+ * Validates the source object and maps it to the target object.
98
+ *
99
+ * @remarks Validation never breaks the mapping: if the source does not match the validators, a
100
+ * warning is logged and the raw source is mapped.
101
+ * @param source - The object to map.
102
+ * @param context - The {@link MapperContext | mapper context} to feed the transformations with.
103
+ * @returns The target object.
104
+ */
105
+ parse: (source: unknown, context?: MapperContext) => Target;
106
+ /**
107
+ * Modifies this schema, so every usage of it applies the given modification.
108
+ *
109
+ * @param override - The validator and the transformation to apply on top of this schema.
110
+ * @returns This schema.
111
+ */
112
+ $override: <NewSource = unknown, NewTarget = unknown>(override: TransformSchemaOverride<Source, Target, NewSource, NewTarget>) => TransformSchema<Source & NewSource, Target & NewTarget>;
113
+ /**
114
+ * Creates a new schema using this one as starting point. This schema remains unchanged.
115
+ *
116
+ * @param override - The validator and the transformation to apply on top of this schema.
117
+ * @returns The new schema.
118
+ */
119
+ $extends: <NewSource = unknown, NewTarget = unknown>(override: TransformSchemaOverride<Source, Target, NewSource, NewTarget>) => TransformSchema<Source & NewSource, Target & NewTarget>;
120
+ /**
121
+ * Replaces all usages of this schema with the given definition.
122
+ *
123
+ * @param definition - The definition to use instead of the current one.
124
+ * @returns This schema.
125
+ */
126
+ $replace: <NewSource, NewTarget>(definition: TransformSchemaDefinition<NewSource, NewTarget>) => TransformSchema<NewSource, NewTarget>;
127
+ }
@@ -32,6 +32,7 @@ import type { MapperContext } from '../mappers/types';
32
32
  * img: 'images'
33
33
  * };
34
34
  * ```
35
+ * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.
35
36
  * @public
36
37
  */
37
38
  export type Schema<Source = any, Target = any> = {
@@ -42,6 +43,7 @@ export type Schema<Source = any, Target = any> = {
42
43
  * the original schema, partially override it or create a new one.
43
44
  *
44
45
  * @param OriginalSchema - The {@link Schema | schema} that will be mutable.
46
+ * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.
45
47
  * @public
46
48
  */
47
49
  export type MutableSchema<Source, Target> = Schema<Source, Target> & {
@@ -83,6 +85,7 @@ export type MutableSchema<Source, Target> = Schema<Source, Target> & {
83
85
  * @param Source - The source object.
84
86
  * @param Target - The target object.
85
87
  * @param TargetKey - The target key to apply the transformation.
88
+ * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.
86
89
  * @public
87
90
  */
88
91
  export type SchemaTransformer<Source, Target, TargetKey extends keyof Target> = PathTransformer<Source, Target[TargetKey]> | FunctionTransformer<Source, Target[TargetKey]> | SubSchemaTransformer<Source, Target[TargetKey]> | Schema<Source, Exclude<Target[TargetKey], AnyFunction | Primitive>>;
@@ -115,6 +118,7 @@ export type SchemaTransformer<Source, Target, TargetKey extends keyof Target> =
115
118
  * hits: 'count'
116
119
  * };
117
120
  * ```
121
+ * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.
118
122
  * @public
119
123
  */
120
124
  export type PathTransformer<Source, Target> = ExtractPathByType<Source, Target>;
@@ -143,6 +147,7 @@ export type PathTransformer<Source, Target> = ExtractPathByType<Source, Target>;
143
147
  * : 0
144
148
  * };
145
149
  * ```
150
+ * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.
146
151
  * @public
147
152
  */
148
153
  export type FunctionTransformer<Source, Target> = (source: Source, context?: MapperContext) => Target;
@@ -179,6 +184,7 @@ export type FunctionTransformer<Source, Target> = (source: Source, context?: Map
179
184
  * }
180
185
  * };
181
186
  * ```
187
+ * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.
182
188
  * @public
183
189
  */
184
190
  export type SubSchemaTransformer<Source, Target> = {
@@ -194,6 +200,7 @@ export type SubSchemaTransformer<Source, Target> = {
194
200
  * @param Source - The source object.
195
201
  * @param Target - The target object.
196
202
  * @param Path - The path where the schema will be applied.
203
+ * @deprecated Its path based typings make TypeScript run out of memory on big models. Use {@link TransformSchema} instead.
197
204
  * @public
198
205
  */
199
206
  export type SubSchema<Source, Target, Path extends ExtractPath<Source>> = ExtractType<Source, Path> extends (infer SourceArrayType)[] ? Target extends (infer TargetArrayType)[] ? Schema<SourceArrayType, TargetArrayType> : never : Target extends [] ? never : Schema<ExtractType<Source, Path>, Target>;
@@ -6,6 +6,7 @@ import type { MutableSchema, Schema } from './types';
6
6
  *
7
7
  * @returns A {@link MutableSchema | mutable schema} version of the given {@link Schema | schema}.
8
8
  *
9
+ * @deprecated Use {@link createTransformSchema} instead.
9
10
  * @public
10
11
  */
11
12
  export declare function createMutableSchema<Source, Target>(schema: Schema<Source, Target>): MutableSchema<Source, Target>;
@@ -17,6 +18,7 @@ export declare function createMutableSchema<Source, Target>(schema: Schema<Sourc
17
18
  * @returns True if it is a {@link MutableSchema | mutableSchema} method,
18
19
  * false otherwise.
19
20
  *
21
+ * @deprecated Only used by the deprecated {@link MutableSchema}.
20
22
  * @public
21
23
  */
22
24
  export declare function isInternalMethod(name: string): boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@empathyco/x-adapter",
3
- "version": "8.10.0",
3
+ "version": "9.0.0",
4
4
  "description": "A utils library to create a client for any API",
5
5
  "author": "Empathy Systems Corporation S.L.",
6
6
  "license": "Apache-2.0",
@@ -44,16 +44,17 @@
44
44
  "prepublishOnly": "pnpm run build"
45
45
  },
46
46
  "dependencies": {
47
- "@empathyco/x-utils": "1.9.0"
47
+ "@empathyco/x-utils": "1.11.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@vitest/coverage-v8": "4.1.12",
51
51
  "jsdom": "30.1.3",
52
52
  "typescript": "5.9.3",
53
- "vitest": "4.1.12"
53
+ "vitest": "4.1.12",
54
+ "zod": "4.6.7"
54
55
  },
55
56
  "publishConfig": {
56
57
  "access": "public"
57
58
  },
58
- "gitHead": "376994a87bf15133fb9428dd730329fa867c560c"
59
+ "gitHead": "809c98c9606704be1e6fd8c206be177d3bcd160d"
59
60
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: x-adapter
3
- description: 'Generic toolkit to build typed API clients (@empathyco/x-adapter): endpointAdapterFactory, schemaMapperFactory, createMutableSchema, fetchHttpClient, buildUrl and interpolate. Use when creating an endpoint adapter for a custom or third-party API, writing request/response mappers or schemas, replacing the HTTP client, or debugging cancelled or wrongly built requests. To customize the existing Empathy Platform endpoints use x-adapter-platform.'
3
+ description: 'Generic toolkit to build typed API clients (@empathyco/x-adapter): endpointAdapterFactory, createTransformSchema, transformSchemaMapperFactory, fetchHttpClient, buildUrl and interpolate. Use when creating an endpoint adapter for a custom or third-party API, writing request/response mappers or schemas, replacing the HTTP client, or debugging cancelled or wrongly built requests. To customize the existing Empathy Platform endpoints use x-adapter-platform.'
4
4
  ---
5
5
 
6
6
  <!-- skills-check ignore: httpClient, requestMapper, responseMapper, $subSchema, Response -->
@@ -15,12 +15,16 @@ calls an HTTP client and maps the response.
15
15
  - `endpointAdapterFactory({ endpoint, httpClient, requestMapper, responseMapper })` returns an
16
16
  endpoint adapter. The result has `.extends(options)` to create a customized copy — prefer it
17
17
  over rebuilding the adapter.
18
- - `schemaMapperFactory(schema)` creates a mapper from a `Schema`: an object whose values are
19
- source paths, functions, nested schemas or `$subSchema`/`$path` definitions.
20
- - `createMutableSchema(schema)` adds `$extends`, `$override` and `$replace`:
18
+ - `createTransformSchema({ source?, transform })` creates a `TransformSchema`: `transform` maps
19
+ the source with a function and the optional Zod `source` schema validates it. It adds
20
+ `$extends`, `$override` and `$replace`:
21
21
  - `$extends` returns a **new** schema;
22
22
  - `$override` and `$replace` **mutate** the schema in place, affecting every adapter that
23
23
  uses it.
24
+ - `transformSchemaMapperFactory(schema)` creates request/response mappers from a
25
+ `TransformSchema` or a Zod schema.
26
+ - **Deprecated:** `schemaMapperFactory` (path based `Schema`, use `transformSchemaMapperFactory`)
27
+ and `createMutableSchema` (use `createTransformSchema`).
24
28
  - `identityMapper`, `combineMappers` — helper mappers.
25
29
  - `fetchHttpClient` (parses JSON) and `fetchRawHttpClient` (returns the raw `Response`).
26
30
  - `buildUrl`, `interpolate` — URL helpers; `interpolate` fills `{param}` placeholders in an
@@ -36,4 +40,4 @@ calls an HTTP client and maps the response.
36
40
  ## More
37
41
 
38
42
  The package `README.md` (in `node_modules/@empathyco/x-adapter`) has complete examples of
39
- schemas, sub-schemas, mutable schemas and `.extends`.
43
+ schemas, sub-schemas, transform schemas and `.extends`.