@tsed/json-mapper 8.10.0-rc.1 → 8.10.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/browser/components/DateMapper.js +22 -0
- package/lib/browser/components/DateMapper.js.map +1 -0
- package/lib/browser/components/PrimitiveMapper.js +52 -0
- package/lib/browser/components/PrimitiveMapper.js.map +1 -0
- package/lib/browser/components/SymbolMapper.js +21 -0
- package/lib/browser/components/SymbolMapper.js.map +1 -0
- package/lib/browser/decorators/afterDeserialize.js +10 -0
- package/lib/browser/decorators/afterDeserialize.js.map +1 -0
- package/lib/browser/decorators/beforeDeserialize.js +10 -0
- package/lib/browser/decorators/beforeDeserialize.js.map +1 -0
- package/lib/browser/decorators/jsonMapper.js +12 -0
- package/lib/browser/decorators/jsonMapper.js.map +1 -0
- package/lib/browser/decorators/onDeserialize.js +10 -0
- package/lib/browser/decorators/onDeserialize.js.map +1 -0
- package/lib/browser/decorators/onSerialize.js +10 -0
- package/lib/browser/decorators/onSerialize.js.map +1 -0
- package/lib/browser/domain/JsonDeserializer.js +179 -0
- package/lib/browser/domain/JsonDeserializer.js.map +1 -0
- package/lib/browser/domain/JsonDeserializerOptions.js +2 -0
- package/lib/browser/domain/JsonDeserializerOptions.js.map +1 -0
- package/lib/browser/domain/JsonMapperCompiler.js +110 -0
- package/lib/browser/domain/JsonMapperCompiler.js.map +1 -0
- package/lib/browser/domain/JsonMapperGlobalOptions.js +2 -0
- package/lib/browser/domain/JsonMapperGlobalOptions.js.map +1 -0
- package/lib/browser/domain/JsonMapperSettings.js +9 -0
- package/lib/browser/domain/JsonMapperSettings.js.map +1 -0
- package/lib/browser/domain/JsonMapperTypesContainer.js +12 -0
- package/lib/browser/domain/JsonMapperTypesContainer.js.map +1 -0
- package/lib/browser/domain/JsonSerializer.js +164 -0
- package/lib/browser/domain/JsonSerializer.js.map +1 -0
- package/lib/browser/domain/JsonSerializerOptions.js +2 -0
- package/lib/browser/domain/JsonSerializerOptions.js.map +1 -0
- package/lib/browser/domain/Writer.js +124 -0
- package/lib/browser/domain/Writer.js.map +1 -0
- package/lib/browser/hooks/alterAfterDeserialize.js +8 -0
- package/lib/browser/hooks/alterAfterDeserialize.js.map +1 -0
- package/lib/browser/hooks/alterBeforeDeserialize.js +8 -0
- package/lib/browser/hooks/alterBeforeDeserialize.js.map +1 -0
- package/lib/browser/hooks/alterOnDeserialize.js +7 -0
- package/lib/browser/hooks/alterOnDeserialize.js.map +1 -0
- package/lib/browser/hooks/alterOnSerialize.js +7 -0
- package/lib/browser/hooks/alterOnSerialize.js.map +1 -0
- package/lib/browser/index.js +47 -0
- package/lib/browser/index.js.map +1 -0
- package/lib/browser/utils/deserialize.js +12 -0
- package/lib/browser/utils/deserialize.js.map +1 -0
- package/lib/browser/utils/getObjectProperties.js +8 -0
- package/lib/browser/utils/getObjectProperties.js.map +1 -0
- package/lib/browser/utils/serialize.js +12 -0
- package/lib/browser/utils/serialize.js.map +1 -0
- package/package.json +7 -7
- package/vite.config.mts +30 -4
- package/lib/browser/json-mapper.umd.cjs +0 -34
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { isBoolean as s } from "@tsed/core";
|
|
2
|
+
import { JsonMapper as u } from "../decorators/jsonMapper.js";
|
|
3
|
+
var v = Object.getOwnPropertyDescriptor, D = (e, t, p, i) => {
|
|
4
|
+
for (var r = i > 1 ? void 0 : i ? v(t, p) : t, n = e.length - 1, l; n >= 0; n--)
|
|
5
|
+
(l = e[n]) && (r = l(r) || r);
|
|
6
|
+
return r;
|
|
7
|
+
};
|
|
8
|
+
let o = class {
|
|
9
|
+
deserialize(e) {
|
|
10
|
+
return s(e) || e === null || e === void 0 ? e : new Date(e);
|
|
11
|
+
}
|
|
12
|
+
serialize(e) {
|
|
13
|
+
return e && new Date(e).toISOString();
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
o = D([
|
|
17
|
+
u(Date)
|
|
18
|
+
], o);
|
|
19
|
+
export {
|
|
20
|
+
o as DateMapper
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=DateMapper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DateMapper.js","sources":["../../../src/components/DateMapper.ts"],"sourcesContent":["import {isBoolean} from \"@tsed/core\";\n\nimport {JsonMapper} from \"../decorators/jsonMapper.js\";\nimport {JsonMapperMethods} from \"../interfaces/JsonMapperMethods.js\";\n\n/**\n * Mapper for `Date` type.\n * @jsonmapper\n * @component\n */\n@JsonMapper(Date)\nexport class DateMapper implements JsonMapperMethods {\n deserialize(data: string | number): Date;\n deserialize(data: boolean | null | undefined): boolean | null | undefined;\n deserialize(data: any): any {\n // don't convert unexpected data. In normal case, Ajv reject unexpected data.\n // But by default, we have to skip data deserialization and let user to apply\n // the right mapping\n if (isBoolean(data) || data === null || data === undefined) {\n return data;\n }\n\n return new Date(data);\n }\n\n serialize(object: Date): any {\n return object ? new Date(object).toISOString() : object;\n }\n}\n"],"names":["DateMapper","data","isBoolean","object","__decorateClass","JsonMapper"],"mappings":";;;;;;;AAWO,IAAMA,IAAN,MAA8C;AAAA,EAGnD,YAAYC,GAAgB;AAI1B,WAAIC,EAAUD,CAAI,KAAKA,MAAS,QAAQA,MAAS,SACxCA,IAGF,IAAI,KAAKA,CAAI;AAAA,EAAA;AAAA,EAGtB,UAAUE,GAAmB;AAC3B,WAAOA,KAAS,IAAI,KAAKA,CAAM,EAAE,YAAgB;AAAA,EAAA;AAErD;AAjBaH,IAANI,EAAA;AAAA,EADNC,EAAW,IAAI;AAAA,GACHL,CAAA;"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { nameOf as i } from "@tsed/core";
|
|
2
|
+
import { JsonMapper as p } from "../decorators/jsonMapper.js";
|
|
3
|
+
var v = Object.getOwnPropertyDescriptor, m = (r, e, f, l) => {
|
|
4
|
+
for (var n = l > 1 ? void 0 : l ? v(e, f) : e, u = r.length - 1, t; u >= 0; u--)
|
|
5
|
+
(t = r[u]) && (n = t(n) || n);
|
|
6
|
+
return n;
|
|
7
|
+
};
|
|
8
|
+
function s(r) {
|
|
9
|
+
return [null, "null"].includes(r);
|
|
10
|
+
}
|
|
11
|
+
class h extends Error {
|
|
12
|
+
constructor(e) {
|
|
13
|
+
super(`Cast error. ${e}`), this.name = "CAST_ERROR";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
let o = class {
|
|
17
|
+
deserialize(r, e) {
|
|
18
|
+
return this[i(e.type)] ? this[i(e.type)](r, e) : void 0;
|
|
19
|
+
}
|
|
20
|
+
serialize(r, e) {
|
|
21
|
+
return this[i(e == null ? void 0 : e.type)] && typeof r != "object" ? this[i(e.type)](r, e) : r;
|
|
22
|
+
}
|
|
23
|
+
String(r) {
|
|
24
|
+
return r === null ? null : "" + r;
|
|
25
|
+
}
|
|
26
|
+
Boolean(r) {
|
|
27
|
+
if (["true", "1", !0].includes(r)) return !0;
|
|
28
|
+
if (["false", "0", !1].includes(r)) return !1;
|
|
29
|
+
if (s(r)) return null;
|
|
30
|
+
if (r !== void 0)
|
|
31
|
+
return !!r;
|
|
32
|
+
}
|
|
33
|
+
Number(r) {
|
|
34
|
+
if (s(r)) return null;
|
|
35
|
+
if (r === void 0) return r;
|
|
36
|
+
const e = +r;
|
|
37
|
+
if (isNaN(e))
|
|
38
|
+
throw new h("Expression value is not a number.");
|
|
39
|
+
return e;
|
|
40
|
+
}
|
|
41
|
+
BigInt(r) {
|
|
42
|
+
return s(r) ? null : BigInt(r);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
o = m([
|
|
46
|
+
p(String, Number, Boolean, BigInt)
|
|
47
|
+
], o);
|
|
48
|
+
export {
|
|
49
|
+
h as CastError,
|
|
50
|
+
o as PrimitiveMapper
|
|
51
|
+
};
|
|
52
|
+
//# sourceMappingURL=PrimitiveMapper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PrimitiveMapper.js","sources":["../../../src/components/PrimitiveMapper.ts"],"sourcesContent":["import {nameOf} from \"@tsed/core\";\n\nimport {JsonMapper} from \"../decorators/jsonMapper.js\";\nimport {JsonMapperCtx, JsonMapperMethods} from \"../interfaces/JsonMapperMethods.js\";\n\nfunction isNullish(data: any) {\n return [null, \"null\"].includes(data);\n}\n\nexport class CastError extends Error {\n name = \"CAST_ERROR\";\n\n constructor(message: string) {\n super(`Cast error. ${message}`);\n }\n}\n\n/**\n * Mapper for the `String`, `Number`, `BigInt` and `Boolean` types.\n * @jsonmapper\n * @component\n */\n@JsonMapper(String, Number, Boolean, BigInt)\nexport class PrimitiveMapper implements JsonMapperMethods {\n deserialize<T>(data: any, ctx: JsonMapperCtx): string | number | boolean | void | null | BigInt {\n return (this as any)[nameOf(ctx.type)] ? (this as any)[nameOf(ctx.type)](data, ctx) : undefined;\n }\n\n serialize(object: string | number | boolean | BigInt, ctx: JsonMapperCtx): string | number | boolean | BigInt {\n return (this as any)[nameOf(ctx?.type)] && typeof object !== \"object\" ? (this as any)[nameOf(ctx.type)](object, ctx) : object;\n }\n\n protected String(data: any) {\n return data === null ? null : \"\" + data;\n }\n\n protected Boolean(data: any) {\n if ([\"true\", \"1\", true].includes(data)) return true;\n if ([\"false\", \"0\", false].includes(data)) return false;\n if (isNullish(data)) return null;\n if (data === undefined) return undefined;\n\n return !!data;\n }\n\n protected Number(data: any) {\n if (isNullish(data)) return null;\n if (data === undefined) return data;\n\n const n = +data;\n\n if (isNaN(n)) {\n throw new CastError(\"Expression value is not a number.\");\n }\n\n return n;\n }\n\n protected BigInt(data: any) {\n if (isNullish(data)) return null;\n\n return BigInt(data);\n }\n}\n"],"names":["isNullish","data","CastError","message","PrimitiveMapper","ctx","nameOf","object","n","__decorateClass","JsonMapper"],"mappings":";;;;;;;AAKA,SAASA,EAAUC,GAAW;AAC5B,SAAO,CAAC,MAAM,MAAM,EAAE,SAASA,CAAI;AACrC;AAEO,MAAMC,UAAkB,MAAM;AAAA,EAGnC,YAAYC,GAAiB;AAC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jsonMapper.js";
|
|
2
|
+
var i = Object.getOwnPropertyDescriptor, m = (r, o, s, t) => {
|
|
3
|
+
for (var e = t > 1 ? void 0 : t ? i(o, s) : o, l = r.length - 1, p; l >= 0; l--)
|
|
4
|
+
(p = r[l]) && (e = p(e) || e);
|
|
5
|
+
return e;
|
|
6
|
+
};
|
|
7
|
+
let a = class {
|
|
8
|
+
deserialize(r) {
|
|
9
|
+
return Symbol.for(r);
|
|
10
|
+
}
|
|
11
|
+
serialize(r) {
|
|
12
|
+
return r.toString().replace("Symbol(", "").replace(")", "");
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
a = m([
|
|
16
|
+
n(Symbol)
|
|
17
|
+
], a);
|
|
18
|
+
export {
|
|
19
|
+
a as SymbolMapper
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=SymbolMapper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SymbolMapper.js","sources":["../../../src/components/SymbolMapper.ts"],"sourcesContent":["import {JsonMapper} from \"../decorators/jsonMapper.js\";\nimport {JsonMapperMethods} from \"../interfaces/JsonMapperMethods.js\";\n\n/**\n * Mapper for the `Symbol` type.\n *\n * @jsonmapper\n * @component\n */\n@JsonMapper(Symbol)\nexport class SymbolMapper implements JsonMapperMethods {\n deserialize(data: string): symbol {\n return Symbol.for(data);\n }\n\n serialize(object: Symbol): any {\n return object.toString().replace(\"Symbol(\", \"\").replace(\")\", \"\");\n }\n}\n"],"names":["SymbolMapper","data","object","__decorateClass","JsonMapper"],"mappings":";;;;;;AAUO,IAAMA,IAAN,MAAgD;AAAA,EACrD,YAAYC,GAAsB;AACzB,WAAA,OAAO,IAAIA,CAAI;AAAA,EAAA;AAAA,EAGxB,UAAUC,GAAqB;AACtB,WAAAA,EAAO,SAAW,EAAA,QAAQ,WAAW,EAAE,EAAE,QAAQ,KAAK,EAAE;AAAA,EAAA;AAEnE;AARaF,IAANG,EAAA;AAAA,EADNC,EAAW,MAAM;AAAA,GACLJ,CAAA;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"afterDeserialize.js","sources":["../../../src/decorators/afterDeserialize.ts"],"sourcesContent":["import {JsonEntityFn, JsonHookContext} from \"@tsed/schema\";\n\nexport interface AfterDeserializeCallback {\n (value: any, ctx: JsonHookContext): any;\n}\n\n/**\n * Call the function after JsonMapper.\n *\n * ## Example\n *\n * ```typescript\n * @AfterDeserialize((data: Model) => { // After deserialize get the instance class\n * if (data.prop1 === 'VALUE' && data.prop2 !== 'VALUE2') {\n * throw BadRequest('MyMessage'); // or throw a ValidationError\n * } else {\n * data.prop2 = 'VALUE2';\n * return data;\n * }\n * })\n * class Model {\n * @Property()\n * prop1: string;\n * @Property()\n * prop2: string;\n * }\n * ```\n *\n * @returns {Function}\n * @decorator\n * @schema\n * @property\n * @param cb\n */\nexport function AfterDeserialize(cb: AfterDeserializeCallback): ClassDecorator {\n return JsonEntityFn((storedJson) => {\n storedJson.schema.$hooks.on(\"afterDeserialize\", cb);\n });\n}\n"],"names":["AfterDeserialize","cb","JsonEntityFn","storedJson"],"mappings":";AAkCO,SAASA,EAAiBC,GAA8C;AACtE,SAAAC,EAAa,CAACC,MAAe;AAClC,IAAAA,EAAW,OAAO,OAAO,GAAG,oBAAoBF,CAAE;AAAA,EAAA,CACnD;AACH;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"beforeDeserialize.js","sources":["../../../src/decorators/beforeDeserialize.ts"],"sourcesContent":["import {JsonEntityFn, JsonHookContext} from \"@tsed/schema\";\n\nexport interface BeforeDeserializeCallback {\n (value: any, ctx: JsonHookContext): any;\n}\n\n/**\n * Call the function before JsonMapper.\n *\n * ## Example\n *\n * ```typescript\n * @BeforeDeserialize((data: Record<string, unknown>) => { // Before deserialize get the data\n * if (data.prop1 === 'VALUE' && data.prop2 !== 'VALUE2') {\n * throw BadRequest('MyMessage'); // or throw a ValidationError\n * } else {\n * data.prop2 = 'VALUE2';\n * return data;\n * }\n * })\n * class Model {\n * @Property()\n * prop1: string;\n * @Property()\n * prop2: string;\n * }\n * ```\n *\n * @returns {Function}\n * @decorator\n * @schema\n * @property\n * @param cb\n */\nexport function BeforeDeserialize(cb: BeforeDeserializeCallback): ClassDecorator {\n return JsonEntityFn((storedJson) => {\n storedJson.schema.$hooks.on(\"beforeDeserialize\", cb);\n });\n}\n"],"names":["BeforeDeserialize","cb","JsonEntityFn","storedJson"],"mappings":";AAkCO,SAASA,EAAkBC,GAA+C;AACxE,SAAAC,EAAa,CAACC,MAAe;AAClC,IAAAA,EAAW,OAAO,OAAO,GAAG,qBAAqBF,CAAE;AAAA,EAAA,CACpD;AACH;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonMapper.js","sources":["../../../src/decorators/jsonMapper.ts"],"sourcesContent":["import {Type} from \"@tsed/core\";\n\nimport {registerJsonTypeMapper} from \"../domain/JsonMapperTypesContainer.js\";\n\n/**\n * Register a new JsonMapper Type\n * @param types\n * @constructor\n */\nexport function JsonMapper(...types: (any | Type)[]): ClassDecorator {\n return (target) => {\n types.forEach((type) => {\n registerJsonTypeMapper(type, target as any);\n });\n };\n}\n"],"names":["JsonMapper","types","target","type","registerJsonTypeMapper"],"mappings":";AASO,SAASA,KAAcC,GAAuC;AACnE,SAAO,CAACC,MAAW;AACX,IAAAD,EAAA,QAAQ,CAACE,MAAS;AACtB,MAAAC,EAAuBD,GAAMD,CAAa;AAAA,IAAA,CAC3C;AAAA,EACH;AACF;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"onDeserialize.js","sources":["../../../src/decorators/onDeserialize.ts"],"sourcesContent":["import {JsonEntityFn, JsonHookContext} from \"@tsed/schema\";\n\nexport interface OnDeserializeCallback {\n (value: any, ctx: JsonHookContext): any;\n}\n\n/**\n * Call the function before property deserialization.\n *\n * ## Example\n *\n * ```typescript\n * class Model {\n * @OnDeserialize(v => v + 1)\n * property: string;\n * }\n * ```\n *\n * @returns {Function}\n * @decorator\n * @schema\n * @property\n * @param cb\n */\nexport function OnDeserialize(cb: OnDeserializeCallback): PropertyDecorator {\n return JsonEntityFn((storedJson) => {\n storedJson.schema.$hooks.on(\"onDeserialize\", cb);\n });\n}\n"],"names":["OnDeserialize","cb","JsonEntityFn","storedJson"],"mappings":";AAwBO,SAASA,EAAcC,GAA8C;AACnE,SAAAC,EAAa,CAACC,MAAe;AAClC,IAAAA,EAAW,OAAO,OAAO,GAAG,iBAAiBF,CAAE;AAAA,EAAA,CAChD;AACH;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"onSerialize.js","sources":["../../../src/decorators/onSerialize.ts"],"sourcesContent":["import {JsonEntityFn, JsonHookContext} from \"@tsed/schema\";\n\nexport interface OnSerializeCallback {\n (value: any, ctx: JsonHookContext): any;\n}\n\n/**\n * Call the function before property serialization.\n *\n * ## Example\n *\n * ```typescript\n * class Model {\n * @OnSerialize(v => v + 1)\n * property: string;\n * }\n * ```\n *\n * @returns {Function}\n * @decorator\n * @schema\n * @property\n * @param cb\n */\nexport function OnSerialize(cb: OnSerializeCallback): PropertyDecorator {\n return JsonEntityFn((storedJson) => {\n storedJson.schema.$hooks.on(\"onSerialize\", cb);\n });\n}\n"],"names":["OnSerialize","cb","JsonEntityFn","storedJson"],"mappings":";AAwBO,SAASA,EAAYC,GAA4C;AAC/D,SAAAC,EAAa,CAACC,MAAe;AAClC,IAAAA,EAAW,OAAO,OAAO,GAAG,eAAeF,CAAE;AAAA,EAAA,CAC9C;AACH;"}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { isArray as O, classOf as j, nameOf as b, isBoolean as A, isClass as P, isNil as M, objectKeys as k, isEmpty as G } from "@tsed/core";
|
|
2
|
+
import { JsonEntityStore as I, getPropertiesStores as C, JsonParameterStore as v } from "@tsed/schema";
|
|
3
|
+
import { alterAfterDeserialize as x } from "../hooks/alterAfterDeserialize.js";
|
|
4
|
+
import { alterBeforeDeserialize as B } from "../hooks/alterBeforeDeserialize.js";
|
|
5
|
+
import { alterOnDeserialize as E } from "../hooks/alterOnDeserialize.js";
|
|
6
|
+
import { JsonMapperCompiler as J } from "./JsonMapperCompiler.js";
|
|
7
|
+
import { JsonMapperSettings as w } from "./JsonMapperSettings.js";
|
|
8
|
+
import { getJsonMapperTypes as K } from "./JsonMapperTypesContainer.js";
|
|
9
|
+
import { Writer as f } from "./Writer.js";
|
|
10
|
+
function N(l, e) {
|
|
11
|
+
return e.collectionType && M(l) || l === void 0 ? !1 : !(G(e.type) || e.type === Object && !e.collectionType);
|
|
12
|
+
}
|
|
13
|
+
function d(l) {
|
|
14
|
+
return `__${l}`;
|
|
15
|
+
}
|
|
16
|
+
function U(l, e) {
|
|
17
|
+
return {
|
|
18
|
+
...e,
|
|
19
|
+
store: void 0,
|
|
20
|
+
type: l.getBestType(),
|
|
21
|
+
collectionType: l.collectionType,
|
|
22
|
+
groups: l.parameter.groups,
|
|
23
|
+
// genericTypes: store.nestedGenerics[0],
|
|
24
|
+
generics: l.nestedGenerics
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function W(l) {
|
|
28
|
+
return l.parent.schema.genericLabels.indexOf(l.itemSchema.genericType);
|
|
29
|
+
}
|
|
30
|
+
class X extends J {
|
|
31
|
+
constructor() {
|
|
32
|
+
super(), this.constructors = {}, this.addGlobal("newInstanceOf", this.newInstanceOf.bind(this)), this.addGlobal("alterBeforeDeserialize", this.alterBeforeDeserialize.bind(this)), this.addGlobal("alterAfterDeserialize", this.alterAfterDeserialize.bind(this)), this.addTypeMapper(Object, this.mapObject.bind(this)), this.addTypeMapper(Array, this.mapArray.bind(this)), this.addTypeMapper(Map, this.mapMap.bind(this)), this.addTypeMapper(Set, this.mapSet.bind(this)), this.addTypeMapper("ObjectId", (e) => String(e));
|
|
33
|
+
}
|
|
34
|
+
map(e, i = {}) {
|
|
35
|
+
if (i = this.mapOptions(i), !N(e, i))
|
|
36
|
+
return e;
|
|
37
|
+
!i.collectionType && O(e) && (i.collectionType = Array);
|
|
38
|
+
const s = i.type || j(e), t = this.compile(s, i.groups);
|
|
39
|
+
return i.collectionType ? this.compile(i.collectionType, i.groups).fn(e, { ...i, id: t.id }) : t.fn(e, this.createContext(i));
|
|
40
|
+
}
|
|
41
|
+
compile(e, i) {
|
|
42
|
+
if ([WeakMap, WeakSet].includes(e))
|
|
43
|
+
throw new Error(`${b(e)} is not supported by JsonMapper.`);
|
|
44
|
+
return super.compile(e, i);
|
|
45
|
+
}
|
|
46
|
+
eval(e, {
|
|
47
|
+
id: i,
|
|
48
|
+
groupsId: s,
|
|
49
|
+
model: t
|
|
50
|
+
}) {
|
|
51
|
+
return this.constructors[i] = t, super.eval(e, { id: i, groupsId: s, model: t });
|
|
52
|
+
}
|
|
53
|
+
newInstanceOf(e, i, s) {
|
|
54
|
+
try {
|
|
55
|
+
return new this.constructors[e](s.disableUnsecureConstructor ? {} : i);
|
|
56
|
+
} catch {
|
|
57
|
+
return i;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
createMapper(e, i, s) {
|
|
61
|
+
var o, p, h;
|
|
62
|
+
const t = I.from(e), n = /* @__PURE__ */ new Set(), c = [...C(t).values()], r = new f().arrow("input", "options");
|
|
63
|
+
return r.if("isNil(input)").return("input"), t.schema.hasDiscriminator && r.add(this.mapDiscriminator(t, s)), (o = t.schema.$hooks) != null && o.has("beforeDeserialize") && (this.schemes[i] = t.schema, r.set("input", `alterBeforeDeserialize('${i}', input, options)`)), r.const("generics", "options.generics[0]"), (p = t.schema.genericLabels) != null && p.length ? r.set("options", "{...options, self: input, generics: [...options.generics].slice(1)}") : r.set("options", "{...options, self: input}"), r.const("obj", `newInstanceOf('${i}', input, options)`), r.add(
|
|
64
|
+
...c.flatMap((a) => {
|
|
65
|
+
var m, y, g, $;
|
|
66
|
+
const u = a.propertyName;
|
|
67
|
+
if (n.add(String(a.parent.schema.getAliasOf(u) || u)), !((m = a.schema) != null && m.$ignore && A((y = a.schema) == null ? void 0 : y.$ignore) || a.isGetterOnly() || ($ = (g = a.schema) == null ? void 0 : g.$hooks) != null && $.has("groups") && this.alterGroups(a.schema, s)))
|
|
68
|
+
return this.mapProperty(a, i, s);
|
|
69
|
+
})
|
|
70
|
+
), r.add(this.mapAdditionalProperties(t, n, s)), (h = t.schema.$hooks) != null && h.has("afterDeserialize") ? (this.schemes[i] = t.schema, r.return(`alterAfterDeserialize('${i}', obj, options)`).root().toString()) : r.return("obj").root().toString();
|
|
71
|
+
}
|
|
72
|
+
alterValue(e, i, s) {
|
|
73
|
+
return E(this.schemes[e], i, s);
|
|
74
|
+
}
|
|
75
|
+
mapDiscriminator(e, i) {
|
|
76
|
+
const s = new f(), t = e.schema.discriminator(), n = s.switch(`input['${t.propertyName}']`);
|
|
77
|
+
return t.values.forEach((c, r) => {
|
|
78
|
+
const o = this.compile(c, i);
|
|
79
|
+
n.case(`'${r}'`).returnCallMapper(o.id, "input");
|
|
80
|
+
}), s;
|
|
81
|
+
}
|
|
82
|
+
mapProperty(e, i, s) {
|
|
83
|
+
var g, $, D, T;
|
|
84
|
+
const t = String(e.propertyKey), n = String(e.parent.schema.getAliasOf(t) || t), c = this.getSchemaId(i, t), r = e.itemSchema.get("format"), o = r && `options: {format: '${r}'}`;
|
|
85
|
+
let p = new f().add(`// Map ${t} ${i} ${s || ""}`);
|
|
86
|
+
const h = t !== n ? `options.useAlias ? '${n}' : '${t}'` : `'${t}'`;
|
|
87
|
+
($ = (g = e.schema) == null ? void 0 : g.$hooks) != null && $.has("ignore") && (this.schemes[c] = e.schema, p = p.if(`!alterIgnore('${c}', {...options, self: input})`));
|
|
88
|
+
const a = (T = (D = e.schema) == null ? void 0 : D.$hooks) == null ? void 0 : T.has("onDeserialize");
|
|
89
|
+
let u = `input[${h}]`;
|
|
90
|
+
if (a) {
|
|
91
|
+
this.schemes[c] = e.schema;
|
|
92
|
+
const z = f.options(o);
|
|
93
|
+
u = `alterValue('${c}', input[${h}], ${z})`;
|
|
94
|
+
}
|
|
95
|
+
const m = p.set(`let ${d(t)}`, u).if(`${d(t)} !== undefined`), y = this.getPropertyFiller(e, i, s, o);
|
|
96
|
+
return y(a ? m.if(`${d(t)} === input.${t}`) : m), m.set(`obj.${t}`, d(t)), s && s.includes("partial") && m.else().add(`delete obj.${t}`), p.root();
|
|
97
|
+
}
|
|
98
|
+
getPropertyFiller(e, i, s, t) {
|
|
99
|
+
const n = String(e.propertyKey), c = this.getSchemaId(i, n), r = e.itemSchema.nestedGenerics;
|
|
100
|
+
if (e.itemSchema.isGeneric && !(r != null && r.length)) {
|
|
101
|
+
const a = W(e), u = f.options(t, `type: generics[${a}]`);
|
|
102
|
+
return (m) => m.set(d(n), `compileAndMap(${d(n)}, ${u})`);
|
|
103
|
+
}
|
|
104
|
+
const p = e.itemSchema.hasDiscriminator ? e.itemSchema.discriminator().base : e.getBestType(), h = this.compile(p, s);
|
|
105
|
+
return e.isCollection ? (a) => a.callMapper(b(e.collectionType), d(n), `id: '${h.id}'`, t) : r != null && r.length ? (this.schemes[c] = e.schema, (a) => a.callMapper(h.id, d(n), t, `generics: schemes['${c}'].nestedGenerics`)) : (a) => a.callMapper(h.id, d(n), t);
|
|
106
|
+
}
|
|
107
|
+
mapOptions({ groups: e, useAlias: i = !0, types: s, ...t }) {
|
|
108
|
+
if (t.store instanceof v)
|
|
109
|
+
return this.mapOptions(U(t.store, t));
|
|
110
|
+
const n = {};
|
|
111
|
+
s = s || K(), s.forEach((r, o) => {
|
|
112
|
+
if (![Array, Set, Map].includes(o)) {
|
|
113
|
+
const p = b(o);
|
|
114
|
+
b(o) in r ? this.addTypeMapper(o, r[p].bind(r)) : this.addTypeMapper(
|
|
115
|
+
o,
|
|
116
|
+
(h, a) => r.deserialize(h, {
|
|
117
|
+
...a,
|
|
118
|
+
type: o
|
|
119
|
+
})
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
const c = t.strictGroups ?? w.strictGroups;
|
|
124
|
+
return {
|
|
125
|
+
...t,
|
|
126
|
+
additionalProperties: t.additionalProperties ?? w.additionalProperties,
|
|
127
|
+
disableUnsecureConstructor: t.disableUnsecureConstructor ?? w.disableUnsecureConstructor,
|
|
128
|
+
groups: e === void 0 ? c ? [] : !1 : e || !1,
|
|
129
|
+
useAlias: i,
|
|
130
|
+
customMappers: n,
|
|
131
|
+
generics: t.generics || []
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
mapAdditionalProperties(e, i, s) {
|
|
135
|
+
const t = e.schema.get("additionalProperties"), n = [...i.values()].map((o) => `'${o}'`).join(", "), c = new f();
|
|
136
|
+
c.add("// add additional properties");
|
|
137
|
+
let r = c.each("objectKeys(input)", ["key"]);
|
|
138
|
+
if (n.length && (r = r.if(`![${n}].includes(key)`)), P(t)) {
|
|
139
|
+
const o = this.compile(t.getComputedType(), s);
|
|
140
|
+
return r.set("obj[key]", f.mapper(o.id, "input[key]", "options")), c;
|
|
141
|
+
}
|
|
142
|
+
return t ? (r.set("obj[key]", "input[key]"), c) : (r.if("options.additionalProperties && obj[key] === undefined").set("obj[key]", "input[key]"), c);
|
|
143
|
+
}
|
|
144
|
+
mapObject(e, i) {
|
|
145
|
+
return e;
|
|
146
|
+
}
|
|
147
|
+
mapSet(e, i) {
|
|
148
|
+
if (M(e))
|
|
149
|
+
return e;
|
|
150
|
+
const s = /* @__PURE__ */ new Set();
|
|
151
|
+
return k(e).forEach((t) => {
|
|
152
|
+
s.add(this.mapItem(e[t], i));
|
|
153
|
+
}), s;
|
|
154
|
+
}
|
|
155
|
+
mapArray(e, i) {
|
|
156
|
+
return M(e) ? e : [].concat(e).map((s) => this.mapItem(s, i));
|
|
157
|
+
}
|
|
158
|
+
mapMap(e, i) {
|
|
159
|
+
if (M(e))
|
|
160
|
+
return e;
|
|
161
|
+
const s = /* @__PURE__ */ new Map();
|
|
162
|
+
return k(e).forEach((t) => {
|
|
163
|
+
s.set(t, this.mapItem(e[t], i));
|
|
164
|
+
}), s;
|
|
165
|
+
}
|
|
166
|
+
mapItem(e, { id: i, ...s }) {
|
|
167
|
+
return this.execMapper(i, e, s);
|
|
168
|
+
}
|
|
169
|
+
alterBeforeDeserialize(e, i, s) {
|
|
170
|
+
return B(i, this.schemes[e], s);
|
|
171
|
+
}
|
|
172
|
+
alterAfterDeserialize(e, i, s) {
|
|
173
|
+
return x(i, this.schemes[e], s);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
export {
|
|
177
|
+
X as JsonDeserializer
|
|
178
|
+
};
|
|
179
|
+
//# sourceMappingURL=JsonDeserializer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonDeserializer.js","sources":["../../../src/domain/JsonDeserializer.ts"],"sourcesContent":["import {classOf, isArray, isBoolean, isClass, isEmpty, isNil, nameOf, objectKeys, Type} from \"@tsed/core\";\nimport {getPropertiesStores, JsonClassStore, JsonEntityStore, JsonParameterStore, JsonPropertyStore} from \"@tsed/schema\";\n\nimport {alterAfterDeserialize} from \"../hooks/alterAfterDeserialize.js\";\nimport {alterBeforeDeserialize} from \"../hooks/alterBeforeDeserialize.js\";\nimport {alterOnDeserialize} from \"../hooks/alterOnDeserialize.js\";\nimport {JsonDeserializerOptions} from \"./JsonDeserializerOptions.js\";\nimport {CachedJsonMapper, JsonMapperCompiler} from \"./JsonMapperCompiler.js\";\nimport {JsonMapperSettings} from \"./JsonMapperSettings.js\";\nimport {getJsonMapperTypes} from \"./JsonMapperTypesContainer.js\";\nimport {Writer} from \"./Writer.js\";\n\nfunction isDeserializable(obj: any, options: JsonDeserializerOptions) {\n if ((!!options.collectionType && isNil(obj)) || obj === undefined) {\n return false;\n }\n\n return !(isEmpty(options.type) || (options.type === Object && !options.collectionType));\n}\n\nfunction varKey(k: string) {\n return `__${k}`;\n}\n\nfunction mapParamStoreOptions(store: JsonParameterStore, options: JsonDeserializerOptions) {\n return {\n ...options,\n store: undefined,\n type: store.getBestType(),\n collectionType: store.collectionType,\n groups: store.parameter.groups,\n // genericTypes: store.nestedGenerics[0],\n generics: store.nestedGenerics\n };\n}\n\nfunction getGenericIndex(propertyStore: JsonPropertyStore) {\n return propertyStore.parent.schema.genericLabels.indexOf(propertyStore.itemSchema.genericType);\n}\n\nexport class JsonDeserializer extends JsonMapperCompiler<JsonDeserializerOptions> {\n /**\n * Cached classes by his id\n * @protected\n */\n protected constructors: Record<string, Type<any>> = {};\n\n constructor() {\n super();\n\n this.addGlobal(\"newInstanceOf\", this.newInstanceOf.bind(this));\n this.addGlobal(\"alterBeforeDeserialize\", this.alterBeforeDeserialize.bind(this));\n this.addGlobal(\"alterAfterDeserialize\", this.alterAfterDeserialize.bind(this));\n\n this.addTypeMapper(Object, this.mapObject.bind(this));\n this.addTypeMapper(Array, this.mapArray.bind(this));\n this.addTypeMapper(Map, this.mapMap.bind(this));\n this.addTypeMapper(Set, this.mapSet.bind(this));\n this.addTypeMapper(\"ObjectId\", (value: any) => String(value));\n }\n\n map<Model = any>(input: any, options: JsonDeserializerOptions = {}): Model {\n options = this.mapOptions(options);\n\n if (!isDeserializable(input, options)) {\n return input;\n }\n\n if (!options.collectionType && isArray(input)) {\n options.collectionType = Array;\n }\n\n const model = options.type || classOf(input);\n\n const mapper = this.compile(model, options.groups!);\n\n if (options.collectionType) {\n const collectionMapper = this.compile(options.collectionType, options.groups!);\n return collectionMapper.fn(input, {...options, id: mapper.id});\n }\n\n return mapper.fn(input, this.createContext(options));\n }\n\n compile(model: Type<any>, groups: false | string[]): CachedJsonMapper<JsonDeserializerOptions> {\n if ([WeakMap, WeakSet].includes(model)) {\n throw new Error(`${nameOf(model)} is not supported by JsonMapper.`);\n }\n\n return super.compile(model, groups);\n }\n\n eval(\n mapper: string,\n {\n id,\n groupsId,\n model\n }: {\n id: string;\n model: Type<any>;\n groupsId: string;\n }\n ): CachedJsonMapper<JsonDeserializerOptions> {\n this.constructors[id] = model;\n\n return super.eval(mapper, {id, groupsId, model});\n }\n\n protected newInstanceOf(id: string, obj: any, options: any) {\n try {\n return new this.constructors[id](options.disableUnsecureConstructor ? {} : obj);\n } catch (er) {\n return obj;\n }\n }\n\n protected createMapper(model: Type<any>, id: string, groups: false | string[]): string {\n const entity = JsonEntityStore.from(model);\n const properties = new Set<string>();\n const schemaProperties = [...getPropertiesStores(entity).values()];\n\n const writer = new Writer().arrow(\"input\", \"options\");\n\n writer.if(\"isNil(input)\").return(\"input\");\n\n if (entity.schema.hasDiscriminator) {\n writer.add(this.mapDiscriminator(entity, groups));\n }\n\n // pre hook\n if (entity.schema.$hooks?.has(\"beforeDeserialize\")) {\n this.schemes[id] = entity.schema;\n writer.set(\"input\", `alterBeforeDeserialize('${id}', input, options)`);\n }\n\n // generics and options\n writer.const(\"generics\", \"options.generics[0]\");\n\n if (entity.schema.genericLabels?.length) {\n writer.set(\"options\", \"{...options, self: input, generics: [...options.generics].slice(1)}\");\n } else {\n writer.set(\"options\", \"{...options, self: input}\");\n }\n\n writer.const(\"obj\", `newInstanceOf('${id}', input, options)`);\n\n // properties\n writer.add(\n ...schemaProperties.flatMap((propertyStore) => {\n const key = propertyStore.propertyName;\n\n // TODO V8 add this line: properties.add(key as string);\n properties.add(String(propertyStore.parent.schema.getAliasOf(key) || key));\n\n if (\n (propertyStore.schema?.$ignore && isBoolean(propertyStore.schema?.$ignore)) ||\n propertyStore.isGetterOnly() ||\n (propertyStore.schema?.$hooks?.has(\"groups\") && this.alterGroups(propertyStore.schema, groups))\n ) {\n return;\n }\n\n return this.mapProperty(propertyStore, id, groups);\n })\n );\n\n // additional properties\n writer.add(this.mapAdditionalProperties(entity, properties, groups));\n\n // post hook\n if (entity.schema.$hooks?.has(\"afterDeserialize\")) {\n this.schemes[id] = entity.schema;\n\n return writer.return(`alterAfterDeserialize('${id}', obj, options)`).root().toString();\n }\n\n return writer.return(\"obj\").root().toString();\n }\n\n protected alterValue(schemaId: string, value: any, options: JsonDeserializerOptions): any {\n return alterOnDeserialize(this.schemes[schemaId], value, options as any);\n }\n\n private mapDiscriminator(entity: JsonClassStore, groups: false | string[]) {\n const writer = new Writer();\n const discriminator = entity.schema.discriminator();\n\n const sw = writer.switch(`input['${discriminator.propertyName}']`);\n\n discriminator.values.forEach((value, kind) => {\n const nestedMapper = this.compile(value, groups);\n\n sw.case(`'${kind}'`).returnCallMapper(nestedMapper.id, \"input\");\n });\n\n return writer;\n }\n\n private mapProperty(propertyStore: JsonPropertyStore, id: string, groups: false | string[]) {\n const key = String(propertyStore.propertyKey);\n const aliasKey: string = String(propertyStore.parent.schema.getAliasOf(key) || key);\n const schemaId = this.getSchemaId(id, key);\n const format = propertyStore.itemSchema.get(\"format\");\n const formatOpts = format && `options: {format: '${format}'}`;\n\n let writer = new Writer().add(`// Map ${key} ${id} ${groups || \"\"}`);\n const pick = key !== aliasKey ? `options.useAlias ? '${aliasKey}' : '${key}'` : `'${key}'`;\n\n // ignore hook (deprecated)\n if (propertyStore.schema?.$hooks?.has(\"ignore\")) {\n this.schemes[schemaId] = propertyStore.schema;\n\n writer = writer.if(`!alterIgnore('${schemaId}', {...options, self: input})`);\n }\n\n // pre hook\n const hasDeserializer = propertyStore.schema?.$hooks?.has(\"onDeserialize\");\n let getter = `input[${pick}]`;\n\n if (hasDeserializer) {\n this.schemes[schemaId] = propertyStore.schema;\n const opts = Writer.options(formatOpts);\n\n getter = `alterValue('${schemaId}', input[${pick}], ${opts})`;\n }\n\n const ifWriter = writer.set(`let ${varKey(key)}`, getter).if(`${varKey(key)} !== undefined`);\n\n const fill = this.getPropertyFiller(propertyStore, id, groups, formatOpts);\n\n if (hasDeserializer) {\n fill(ifWriter.if(`${varKey(key)} === input.${key}`));\n } else {\n fill(ifWriter);\n }\n\n ifWriter.set(`obj.${key}`, varKey(key));\n\n if (groups && groups.includes(\"partial\")) {\n ifWriter.else().add(`delete obj.${key}`);\n }\n\n return writer.root();\n }\n\n private getPropertyFiller(propertyStore: JsonPropertyStore, id: string, groups: false | string[], formatOpts: any) {\n const key = String(propertyStore.propertyKey);\n const schemaId = this.getSchemaId(id, key);\n const generics = propertyStore.itemSchema.nestedGenerics;\n const isGeneric = propertyStore.itemSchema.isGeneric && !generics?.length;\n\n if (isGeneric) {\n const index = getGenericIndex(propertyStore);\n const opts = Writer.options(formatOpts, `type: generics[${index}]`);\n\n return (writer: Writer) => writer.set(varKey(key), `compileAndMap(${varKey(key)}, ${opts})`);\n }\n\n const type = propertyStore.itemSchema.hasDiscriminator ? propertyStore.itemSchema.discriminator().base : propertyStore.getBestType();\n const nestedMapper = this.compile(type, groups);\n\n if (propertyStore.isCollection) {\n return (writer: Writer) =>\n writer.callMapper(nameOf(propertyStore.collectionType), varKey(key), `id: '${nestedMapper.id}'`, formatOpts);\n }\n\n if (generics?.length) {\n this.schemes[schemaId] = propertyStore.schema;\n\n return (writer: Writer) =>\n writer.callMapper(nestedMapper.id, varKey(key), formatOpts, `generics: schemes['${schemaId}'].nestedGenerics`);\n }\n\n return (writer: Writer) => writer.callMapper(nestedMapper.id, varKey(key), formatOpts);\n }\n\n private mapOptions({groups, useAlias = true, types, ...options}: JsonDeserializerOptions<any, any>): JsonDeserializerOptions {\n if (options.store instanceof JsonParameterStore) {\n return this.mapOptions(mapParamStoreOptions(options.store, options));\n }\n\n const customMappers: Record<string, any> = {};\n types = types || getJsonMapperTypes();\n\n types.forEach((mapper, model) => {\n if (![Array, Set, Map].includes(model as any)) {\n const typeName = nameOf(model);\n\n if (nameOf(model) in mapper) {\n this.addTypeMapper(model as any, (mapper as any)[typeName].bind(mapper));\n } else {\n this.addTypeMapper(model as any, (value: any, options: any) =>\n mapper.deserialize(value, {\n ...options,\n type: model\n })\n );\n }\n }\n });\n\n const strictGroups = options.strictGroups ?? JsonMapperSettings.strictGroups;\n\n return {\n ...options,\n additionalProperties: options.additionalProperties ?? JsonMapperSettings.additionalProperties,\n disableUnsecureConstructor: options.disableUnsecureConstructor ?? JsonMapperSettings.disableUnsecureConstructor,\n groups: groups === undefined ? (strictGroups ? [] : false) : groups || false,\n useAlias,\n customMappers,\n generics: options.generics || []\n };\n }\n\n private mapAdditionalProperties(entity: JsonClassStore, properties: Set<string>, groups: string[] | false) {\n const additionalProperties = entity.schema.get(\"additionalProperties\");\n\n const exclude = [...properties.values()].map((key) => `'${key}'`).join(\", \");\n const writer = new Writer();\n\n writer.add(\"// add additional properties\");\n let each = writer.each(\"objectKeys(input)\", [\"key\"]);\n\n if (exclude.length) {\n each = each.if(`![${exclude}].includes(key)`);\n }\n\n if (isClass(additionalProperties)) {\n const nestedMapper = this.compile(additionalProperties.getComputedType(), groups);\n\n each.set(\"obj[key]\", Writer.mapper(nestedMapper.id, \"input[key]\", \"options\"));\n\n return writer;\n }\n\n if (additionalProperties) {\n each.set(\"obj[key]\", \"input[key]\");\n\n return writer;\n }\n\n // dynamic additional properties options\n each.if(`options.additionalProperties && obj[key] === undefined`).set(\"obj[key]\", \"input[key]\");\n\n return writer;\n }\n\n private mapObject(input: any, options: JsonDeserializerOptions) {\n return input;\n }\n\n private mapSet(input: any, options: JsonDeserializerOptions): Set<any> {\n if (isNil(input)) {\n return input;\n }\n\n const obj = new Set<any>();\n\n objectKeys(input).forEach((key) => {\n obj.add(this.mapItem(input[key], options));\n });\n\n return obj;\n }\n\n private mapArray(input: any, options: JsonDeserializerOptions) {\n if (isNil(input)) {\n return input;\n }\n\n return [].concat(input).map((item: any) => {\n return this.mapItem(item, options);\n });\n }\n\n private mapMap(input: any, options: JsonDeserializerOptions): Map<string, any> {\n if (isNil(input)) {\n return input;\n }\n\n const obj = new Map<string, any>();\n\n objectKeys(input).forEach((key) => {\n obj.set(key, this.mapItem(input[key], options));\n });\n\n return obj;\n }\n\n private mapItem(input: any, {id, ...options}: JsonDeserializerOptions) {\n return this.execMapper(id, input, options);\n }\n\n private alterBeforeDeserialize(schemaId: string, value: any, options: JsonDeserializerOptions): any {\n return alterBeforeDeserialize(value, this.schemes[schemaId], options);\n }\n\n private alterAfterDeserialize(schemaId: string, value: any, options: JsonDeserializerOptions): any {\n return alterAfterDeserialize(value, this.schemes[schemaId], options);\n }\n}\n"],"names":["isDeserializable","obj","options","isNil","isEmpty","varKey","k","mapParamStoreOptions","store","getGenericIndex","propertyStore","JsonDeserializer","JsonMapperCompiler","value","input","isArray","model","classOf","mapper","groups","nameOf","id","groupsId","entity","JsonEntityStore","properties","schemaProperties","getPropertiesStores","writer","Writer","_a","_b","key","isBoolean","_d","_c","schemaId","alterOnDeserialize","discriminator","sw","kind","nestedMapper","aliasKey","format","formatOpts","pick","hasDeserializer","getter","opts","ifWriter","fill","generics","index","type","useAlias","types","JsonParameterStore","customMappers","getJsonMapperTypes","typeName","strictGroups","JsonMapperSettings","additionalProperties","exclude","each","isClass","objectKeys","item","alterBeforeDeserialize","alterAfterDeserialize"],"mappings":";;;;;;;;;AAYA,SAASA,EAAiBC,GAAUC,GAAkC;AAC/D,SAAEA,EAAQ,kBAAkBC,EAAMF,CAAG,KAAMA,MAAQ,SAC/C,KAGF,EAAEG,EAAQF,EAAQ,IAAI,KAAMA,EAAQ,SAAS,UAAU,CAACA,EAAQ;AACzE;AAEA,SAASG,EAAOC,GAAW;AACzB,SAAO,KAAKA,CAAC;AACf;AAEA,SAASC,EAAqBC,GAA2BN,GAAkC;AAClF,SAAA;AAAA,IACL,GAAGA;AAAA,IACH,OAAO;AAAA,IACP,MAAMM,EAAM,YAAY;AAAA,IACxB,gBAAgBA,EAAM;AAAA,IACtB,QAAQA,EAAM,UAAU;AAAA;AAAA,IAExB,UAAUA,EAAM;AAAA,EAClB;AACF;AAEA,SAASC,EAAgBC,GAAkC;AACzD,SAAOA,EAAc,OAAO,OAAO,cAAc,QAAQA,EAAc,WAAW,WAAW;AAC/F;AAEO,MAAMC,UAAyBC,EAA4C;AAAA,EAOhF,cAAc;AACN,UAAA,GAHR,KAAU,eAA0C,CAAC,GAKnD,KAAK,UAAU,iBAAiB,KAAK,cAAc,KAAK,IAAI,CAAC,GAC7D,KAAK,UAAU,0BAA0B,KAAK,uBAAuB,KAAK,IAAI,CAAC,GAC/E,KAAK,UAAU,yBA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AO,KAAK,QAAQuB,CAAQ,GAAGlC,CAAO;AAAA,EAAA;AAEvE;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonDeserializerOptions.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { isMomentObject, objectKeys, isDate, isNil, isMongooseObject, hasJsonMethod, nameOf, classOf, isObject, isClass, isCollection, isString, isObjectID, ancestorsOf, getRandomId } from "@tsed/core";
|
|
2
|
+
class JsonMapperCompiler {
|
|
3
|
+
constructor() {
|
|
4
|
+
this.cache = /* @__PURE__ */ new Map(), this.mappers = {}, this.schemes = {}, this.constructors = {}, this.globals = {
|
|
5
|
+
isCollection,
|
|
6
|
+
isClass,
|
|
7
|
+
isObject,
|
|
8
|
+
classOf,
|
|
9
|
+
nameOf,
|
|
10
|
+
hasJsonMethod,
|
|
11
|
+
isMongooseObject,
|
|
12
|
+
isNil,
|
|
13
|
+
isDate,
|
|
14
|
+
objectKeys,
|
|
15
|
+
isMomentObject
|
|
16
|
+
}, this.addGlobal("alterIgnore", this.alterIgnore.bind(this)), this.addGlobal("alterValue", this.alterValue.bind(this)), this.addGlobal("execMapper", this.execMapper.bind(this)), this.addGlobal("compileAndMap", this.map.bind(this));
|
|
17
|
+
}
|
|
18
|
+
addTypeMapper(e, t) {
|
|
19
|
+
const s = nameOf(e);
|
|
20
|
+
return this.cache.set(
|
|
21
|
+
e,
|
|
22
|
+
(/* @__PURE__ */ new Map()).set("typeMapper", {
|
|
23
|
+
id: s,
|
|
24
|
+
fn: t
|
|
25
|
+
})
|
|
26
|
+
), this.mappers[s] = t, this;
|
|
27
|
+
}
|
|
28
|
+
removeTypeMapper(e) {
|
|
29
|
+
const t = this.cache.get(e);
|
|
30
|
+
if (t) {
|
|
31
|
+
const { id: s } = t.get("typeMapper");
|
|
32
|
+
delete this.mappers[s], this.cache.delete(e);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
addGlobal(e, t) {
|
|
36
|
+
return this.globals[e] = t, this;
|
|
37
|
+
}
|
|
38
|
+
eval(mapper, { id, groupsId, model }) {
|
|
39
|
+
this.addGlobal("cache", this.cache);
|
|
40
|
+
const { globals, schemes } = this, injectGlobals = Object.keys(globals).map((e) => `const ${e} = globals.${e};`).join(`
|
|
41
|
+
`);
|
|
42
|
+
eval(`${injectGlobals};
|
|
43
|
+
|
|
44
|
+
cache.get(model).set(groupsId, { id: '${id}', fn: ${mapper} })`);
|
|
45
|
+
const store = this.cache.get(model).get(groupsId);
|
|
46
|
+
return this.mappers[id] = store.fn, store;
|
|
47
|
+
}
|
|
48
|
+
createContext(e) {
|
|
49
|
+
const { cache: t } = this;
|
|
50
|
+
return {
|
|
51
|
+
...e,
|
|
52
|
+
cache: t
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
compile(e, t, s = {}) {
|
|
56
|
+
const r = isString(e) ? e : this.getType(e), i = this.getGroupsId(t);
|
|
57
|
+
let a = this.cache.get(r) || this.cache.get(nameOf(r));
|
|
58
|
+
if (a || (a = /* @__PURE__ */ new Map(), this.cache.set(r, a)), a.has("typeMapper"))
|
|
59
|
+
return a.get("typeMapper");
|
|
60
|
+
if (!a.has(i)) {
|
|
61
|
+
const o = this.getId(r, i);
|
|
62
|
+
a.set(i, {
|
|
63
|
+
id: o
|
|
64
|
+
});
|
|
65
|
+
const n = s.mapper ? s.mapper(o, t) : this.createMapper(r, o, t);
|
|
66
|
+
try {
|
|
67
|
+
return this.eval(n, { id: o, model: r, groupsId: i });
|
|
68
|
+
} catch (c) {
|
|
69
|
+
throw new Error(`Fail to compile mapper for ${nameOf(e)}. See the error above: ${c.message}.
|
|
70
|
+
${n}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return a.get(i);
|
|
74
|
+
}
|
|
75
|
+
execMapper(e, t, s) {
|
|
76
|
+
return isObjectID(t) ? t.toString() : this.mappers[e || nameOf(classOf(t))](t, s);
|
|
77
|
+
}
|
|
78
|
+
getType(e) {
|
|
79
|
+
if (!e)
|
|
80
|
+
return Object;
|
|
81
|
+
if (isClass(e) && !isCollection(e)) {
|
|
82
|
+
const t = [Array, Map, Set].find((s) => ancestorsOf(e).includes(s));
|
|
83
|
+
if (t)
|
|
84
|
+
return t;
|
|
85
|
+
}
|
|
86
|
+
return e;
|
|
87
|
+
}
|
|
88
|
+
alterIgnore(e, t) {
|
|
89
|
+
var r, i;
|
|
90
|
+
let s = (i = (r = this.schemes[e]) == null ? void 0 : r.$hooks) == null ? void 0 : i.alter("ignore", !1, [t]);
|
|
91
|
+
if (s)
|
|
92
|
+
return s;
|
|
93
|
+
}
|
|
94
|
+
alterGroups(e, t) {
|
|
95
|
+
return t !== !1 ? e.$hooks.alter("groups", !1, [t]) : !1;
|
|
96
|
+
}
|
|
97
|
+
getGroupsId(e) {
|
|
98
|
+
return e === !1 ? "default" : e.length === 0 ? "-" : e.join(",");
|
|
99
|
+
}
|
|
100
|
+
getId(e, t) {
|
|
101
|
+
return `${isString(e) ? e : nameOf(e)}:${getRandomId()}:${t}`;
|
|
102
|
+
}
|
|
103
|
+
getSchemaId(e, t) {
|
|
104
|
+
return `${e}:${t}`;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
export {
|
|
108
|
+
JsonMapperCompiler
|
|
109
|
+
};
|
|
110
|
+
//# sourceMappingURL=JsonMapperCompiler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonMapperCompiler.js","sources":["../../../src/domain/JsonMapperCompiler.ts"],"sourcesContent":["import {\n ancestorsOf,\n classOf,\n getRandomId,\n hasJsonMethod,\n isClass,\n isCollection,\n isDate,\n isMomentObject,\n isMongooseObject,\n isNil,\n isObject,\n isObjectID,\n isString,\n nameOf,\n objectKeys,\n Type\n} from \"@tsed/core\";\nimport {JsonSchema} from \"@tsed/schema\";\n\nexport type JsonMapperCallback<Options> = (input: any, options?: Options) => any;\nexport type CachedJsonMapper<Options> = {\n id: string;\n fn: JsonMapperCallback<Options>;\n};\n\nexport type CachedGroupsJsonMapper<Options> = Map<string, CachedJsonMapper<Options>>;\n\nexport abstract class JsonMapperCompiler<Options extends Record<string, any> = any> {\n /**\n * Cached mappers metadata\n * @protected\n */\n protected cache = new Map<Type<any> | string, CachedGroupsJsonMapper<Options>>();\n /**\n * Cached executable mappers by his id\n * @protected\n */\n protected mappers: Record<string, JsonMapperCallback<Options>> = {};\n /**\n * Cached schemas\n * @protected\n */\n protected schemes: Record<string, any> = {};\n\n /**\n * Cached classes by his id\n * @protected\n */\n protected constructors: Record<string, Type<any>> = {};\n /**\n * Global variables available in the mapper\n * @protected\n */\n protected globals: Record<string, any> = {\n isCollection,\n isClass,\n isObject,\n classOf,\n nameOf,\n hasJsonMethod,\n isMongooseObject,\n isNil,\n isDate,\n objectKeys,\n isMomentObject\n };\n\n constructor() {\n this.addGlobal(\"alterIgnore\", this.alterIgnore.bind(this));\n this.addGlobal(\"alterValue\", this.alterValue.bind(this));\n this.addGlobal(\"execMapper\", this.execMapper.bind(this));\n this.addGlobal(\"compileAndMap\", this.map.bind(this));\n }\n\n addTypeMapper(model: Type<any> | string, fn: any) {\n const id = nameOf(model);\n\n this.cache.set(\n model,\n new Map().set(\"typeMapper\", {\n id,\n fn\n })\n );\n\n this.mappers[id] = fn;\n\n return this;\n }\n\n removeTypeMapper(model: Type<any> | string) {\n const store = this.cache.get(model);\n\n if (store) {\n const {id} = store.get(\"typeMapper\")!;\n\n delete this.mappers[id];\n this.cache.delete(model);\n }\n }\n\n addGlobal(key: string, value: any) {\n this.globals[key] = value;\n\n return this;\n }\n\n eval(mapper: string, {id, groupsId, model}: {id: string; model: Type<any> | string; groupsId: string}) {\n this.addGlobal(\"cache\", this.cache);\n\n const {globals, schemes} = this;\n\n const injectGlobals = Object.keys(globals)\n .map((name) => {\n return `const ${name} = globals.${name};`;\n })\n .join(\"\\n\");\n\n eval(`${injectGlobals};\n\n cache.get(model).set(groupsId, { id: '${id}', fn: ${mapper} })`);\n\n const store = this.cache.get(model)!.get(groupsId)!;\n\n this.mappers[id] = store.fn;\n\n return store;\n }\n\n createContext(options: Options) {\n const {cache} = this;\n\n return {\n ...options,\n cache\n };\n }\n\n compile(\n model: Type<any> | string,\n groups: false | string[],\n opts: {\n mapper?: any;\n } = {}\n ): CachedJsonMapper<Options> {\n const token = isString(model) ? model : this.getType(model);\n\n const groupsId = this.getGroupsId(groups);\n let storeGroups = this.cache.get(token) || this.cache.get(nameOf(token));\n\n if (!storeGroups) {\n storeGroups = new Map();\n this.cache.set(token, storeGroups);\n }\n\n if (storeGroups.has(\"typeMapper\")) {\n return storeGroups.get(\"typeMapper\")!;\n }\n\n // generate mapper for the given groups\n if (!storeGroups.has(groupsId)) {\n const id = this.getId(token, groupsId);\n\n // prevent circular dependencies\n storeGroups.set(groupsId, {\n id\n } as any);\n\n const mapper = opts.mapper ? opts.mapper(id, groups) : this.createMapper(token as Type<any>, id, groups);\n\n try {\n return this.eval(mapper, {id, model: token, groupsId});\n } catch (err) {\n throw new Error(`Fail to compile mapper for ${nameOf(model)}. See the error above: ${err.message}.\\n${mapper}`);\n }\n }\n\n return storeGroups!.get(groupsId)!;\n }\n\n protected execMapper(id: string, value: any, options: Options) {\n if (isObjectID(value)) {\n return value.toString();\n }\n\n return this.mappers[id || nameOf(classOf(value))](value, options);\n }\n\n protected abstract map(input: any, options: Options): any;\n\n protected abstract alterValue(schemaId: string, value: any, options: Options): any;\n\n protected abstract createMapper(model: Type<any>, id: string, groups: false | string[]): string;\n\n protected getType(model: Type<any>) {\n if (!model) {\n return Object;\n }\n\n if (isClass(model) && !isCollection(model)) {\n const type = [Array, Map, Set].find((t) => ancestorsOf(model).includes(t));\n\n if (type) {\n return type;\n }\n }\n\n return model;\n }\n\n protected alterIgnore(id: string, options: Options) {\n let result = this.schemes[id]?.$hooks?.alter(\"ignore\", false, [options]);\n\n if (result) {\n return result;\n }\n }\n\n protected alterGroups(schema: JsonSchema, groups: false | string[]) {\n if (groups !== false) {\n return schema.$hooks.alter(\"groups\", false, [groups]);\n }\n\n return false;\n }\n\n protected getGroupsId(groups: false | string[]) {\n if (groups === false) {\n return \"default\";\n }\n\n if (groups.length === 0) {\n return \"-\";\n }\n\n return groups.join(\",\");\n }\n\n protected getId(model: Type<any> | string, groupsId: string) {\n return `${isString(model) ? model : nameOf(model)}:${getRandomId()}:${groupsId}`;\n }\n\n protected getSchemaId(id: string, propertyKey: string) {\n return `${id}:${propertyKey}`;\n }\n}\n"],"names":["model","fn","id","store","key","value","name","options","cache","groups","opts","token","groupsId","storeGroups","mapper","err","type","t","result","_b","_a","schema","propertyKey"],"mappings":";AA4BO,MAAe,mBAA8D;AAAA,EAwClF,cAAc;AAnCJ,SAAA,4BAAY,IAAyD,GAK/E,KAAU,UAAuD,CAAC,GAKlE,KAAU,UAA+B,CAAC,GAM1C,KAAU,eAA0C,CAAC,GAKrD,KAAU,UAA+B;AAAA,MACvC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,GAGE,KAAK,UAAU,eAAe,KAAK,YAAY,KAAK,IAAI,CAAC,GACzD,KAAK,UAAU,cAAc,KAAK,WAAW,KAAK,IAAI,CAAC,GACvD,KAAK,UAAU,cAAc,KAAK,WAAW,KAAK,IAAI,CAAC,GACvD,KAAK,UAAU,iBAAiB,KAAK,IAAI,KAAK,IAAI,CAAC;AAAA,EAAA;AAAA,EAGrD,cAAcA,GAA2BC,GAAS;AAC1CC,UAAAA,IAAK,OAAOF,CAAK;AAEvB,gBAAK,MAAM;AAAA,MACTA;AAAAA,OACI,oBAAA,IAAA,GAAM,IAAI,cAAc;AAAA,QAC1B,IAAAE;AAAAA,QACA,IAAAD;AAAA,MACD,CAAA;AAAA,IACH,GAEK,KAAA,QAAQC,CAAE,IAAID,GAEZ;AAAA,EAAA;AAAA,EAGT,iBAAiBD,GAA2B;AAC1C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AAW,KACNY,EAAO,OAAO,MAAM,UAAU,IAAO,CAACZ,CAAM,CAAC,IAG/C;AAAA,EAAA;AAAA,EAGC,YAAYA,GAA0B;AAC9C,WAAIA,MAAW,KACN,YAGLA,EAAO,WAAW,IACb,MAGFA,EAAO,KAAK,GAAG;AAAA,EAAA;AAAA,EAGd,MAAMT,GAA2BY,GAAkB;AAC3D,WAAO,GAAG,SAASZ,CAAK,IAAIA,IAAQ,OAAOA,CAAK,CAAC,IAAI,YAAA,CAAa,IAAIY,CAAQ;AAAA,EAAA;AAAA,EAGtE,YAAYV,GAAYoB,GAAqB;AAC9C,WAAA,GAAGpB,CAAE,IAAIoB,CAAW;AAAA,EAAA;AAE/B;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonMapperGlobalOptions.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonMapperSettings.js","sources":["../../../src/domain/JsonMapperSettings.ts"],"sourcesContent":["import type {JsonMapperGlobalOptions} from \"./JsonMapperGlobalOptions.js\";\n\nexport const JsonMapperSettings: JsonMapperGlobalOptions = {\n disableUnsecureConstructor: true,\n additionalProperties: false,\n strictGroups: false\n};\n"],"names":["JsonMapperSettings"],"mappings":"AAEO,MAAMA,IAA8C;AAAA,EACzD,4BAA4B;AAAA,EAC5B,sBAAsB;AAAA,EACtB,cAAc;AAChB;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonMapperTypesContainer.js","sources":["../../../src/domain/JsonMapperTypesContainer.ts"],"sourcesContent":["import {Type} from \"@tsed/core\";\n\nimport {JsonMapperMethods} from \"../interfaces/JsonMapperMethods.js\";\n/**\n * @ignore\n */\n// tslint:disable-next-line:variable-name\nconst JsonMapperTypesContainer: Map<Type<any> | Symbol | string, JsonMapperMethods> = new Map();\n/**\n * @ignore\n */\nexport function registerJsonTypeMapper(type: Type<any> | Symbol | string, token: Type<JsonMapperMethods>) {\n JsonMapperTypesContainer.set(type, new token());\n}\n/**\n * @ignore\n */\nexport function getJsonMapperTypes(): Map<Type<any> | Symbol | string, JsonMapperMethods> {\n return JsonMapperTypesContainer;\n}\n"],"names":["JsonMapperTypesContainer","registerJsonTypeMapper","type","token","getJsonMapperTypes"],"mappings":"AAOA,MAAMA,wBAAoF,IAAI;AAI9E,SAAAC,EAAuBC,GAAmCC,GAAgC;AACxG,EAAAH,EAAyB,IAAIE,GAAM,IAAIC,EAAA,CAAO;AAChD;AAIO,SAASC,IAA0E;AACjF,SAAAJ;AACT;"}
|