@azure/core-client 1.10.2-alpha.20260306.4 → 1.10.2

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 (105) hide show
  1. package/dist/browser/authorizeRequestOnTenantChallenge.js +1 -2
  2. package/dist/browser/authorizeRequestOnTenantChallenge.js.map +1 -1
  3. package/dist/browser/base64.d.ts +1 -5
  4. package/dist/browser/base64.js +6 -14
  5. package/dist/browser/base64.js.map +1 -1
  6. package/dist/browser/interfaceHelpers.js +1 -2
  7. package/dist/browser/interfaceHelpers.js.map +1 -1
  8. package/dist/browser/operationHelpers.js +8 -4
  9. package/dist/browser/operationHelpers.js.map +1 -1
  10. package/dist/browser/serializationPolicy.js +1 -1
  11. package/dist/browser/serializationPolicy.js.map +1 -1
  12. package/dist/browser/serializer.js +32 -11
  13. package/dist/browser/serializer.js.map +1 -1
  14. package/dist/browser/serviceClient.js +2 -2
  15. package/dist/browser/serviceClient.js.map +1 -1
  16. package/dist/browser/{state.d.ts → state-web.d.mts} +1 -1
  17. package/dist/browser/{state.js → state-web.mjs} +1 -1
  18. package/dist/browser/state-web.mjs.map +1 -0
  19. package/dist/browser/urlHelpers.js +2 -1
  20. package/dist/browser/urlHelpers.js.map +1 -1
  21. package/dist/commonjs/authorizeRequestOnTenantChallenge.js +1 -2
  22. package/dist/commonjs/authorizeRequestOnTenantChallenge.js.map +1 -1
  23. package/dist/commonjs/base64.d.ts +1 -1
  24. package/dist/commonjs/base64.js +6 -6
  25. package/dist/commonjs/base64.js.map +1 -1
  26. package/dist/commonjs/interfaceHelpers.js +1 -2
  27. package/dist/commonjs/interfaceHelpers.js.map +1 -1
  28. package/dist/commonjs/operationHelpers.js +10 -6
  29. package/dist/commonjs/operationHelpers.js.map +1 -1
  30. package/dist/commonjs/serializationPolicy.js +1 -1
  31. package/dist/commonjs/serializationPolicy.js.map +1 -1
  32. package/dist/commonjs/serializer.js +32 -11
  33. package/dist/commonjs/serializer.js.map +1 -1
  34. package/dist/commonjs/serviceClient.js +2 -2
  35. package/dist/commonjs/serviceClient.js.map +1 -1
  36. package/dist/commonjs/{state.d.ts → state-cjs.d.ts} +1 -1
  37. package/dist/commonjs/{state.js → state-cjs.js} +1 -1
  38. package/dist/commonjs/state-cjs.js.map +1 -0
  39. package/dist/commonjs/tsdoc-metadata.json +1 -1
  40. package/dist/commonjs/urlHelpers.js +2 -1
  41. package/dist/commonjs/urlHelpers.js.map +1 -1
  42. package/dist/esm/authorizeRequestOnClaimChallenge.js +67 -44
  43. package/dist/esm/authorizeRequestOnClaimChallenge.js.map +1 -7
  44. package/dist/esm/authorizeRequestOnTenantChallenge.js +97 -72
  45. package/dist/esm/authorizeRequestOnTenantChallenge.js.map +1 -7
  46. package/dist/esm/base64.d.ts +1 -1
  47. package/dist/esm/base64.js +32 -15
  48. package/dist/esm/base64.js.map +1 -7
  49. package/dist/esm/deserializationPolicy.js +202 -205
  50. package/dist/esm/deserializationPolicy.js.map +1 -7
  51. package/dist/esm/httpClientCache.js +8 -8
  52. package/dist/esm/httpClientCache.js.map +1 -7
  53. package/dist/esm/index.js +11 -31
  54. package/dist/esm/index.js.map +1 -7
  55. package/dist/esm/interfaceHelpers.js +34 -23
  56. package/dist/esm/interfaceHelpers.js.map +1 -7
  57. package/dist/esm/interfaces.js +11 -6
  58. package/dist/esm/interfaces.js.map +1 -7
  59. package/dist/esm/log.js +4 -4
  60. package/dist/esm/log.js.map +1 -7
  61. package/dist/esm/operationHelpers.js +86 -73
  62. package/dist/esm/operationHelpers.js.map +1 -7
  63. package/dist/esm/pipeline.js +23 -22
  64. package/dist/esm/pipeline.js.map +1 -7
  65. package/dist/esm/serializationPolicy.js +134 -163
  66. package/dist/esm/serializationPolicy.js.map +1 -7
  67. package/dist/esm/serializer.js +877 -812
  68. package/dist/esm/serializer.js.map +1 -7
  69. package/dist/esm/serviceClient.js +150 -151
  70. package/dist/esm/serviceClient.js.map +1 -7
  71. package/dist/esm/state-cjs.d.ts +8 -0
  72. package/dist/esm/state-cjs.js +9 -0
  73. package/dist/esm/state-cjs.js.map +1 -0
  74. package/dist/esm/state.js +10 -5
  75. package/dist/esm/state.js.map +1 -7
  76. package/dist/esm/urlHelpers.js +207 -199
  77. package/dist/esm/urlHelpers.js.map +1 -7
  78. package/dist/esm/utils.js +118 -64
  79. package/dist/esm/utils.js.map +1 -7
  80. package/dist/react-native/authorizeRequestOnTenantChallenge.js +1 -2
  81. package/dist/react-native/authorizeRequestOnTenantChallenge.js.map +1 -1
  82. package/dist/react-native/base64.d.ts +1 -1
  83. package/dist/react-native/base64.js +6 -6
  84. package/dist/react-native/base64.js.map +1 -1
  85. package/dist/react-native/interfaceHelpers.js +1 -2
  86. package/dist/react-native/interfaceHelpers.js.map +1 -1
  87. package/dist/react-native/operationHelpers.js +8 -4
  88. package/dist/react-native/operationHelpers.js.map +1 -1
  89. package/dist/react-native/serializationPolicy.js +1 -1
  90. package/dist/react-native/serializationPolicy.js.map +1 -1
  91. package/dist/react-native/serializer.js +32 -11
  92. package/dist/react-native/serializer.js.map +1 -1
  93. package/dist/react-native/serviceClient.js +2 -2
  94. package/dist/react-native/serviceClient.js.map +1 -1
  95. package/dist/react-native/state-web.d.mts +8 -0
  96. package/dist/react-native/state-web.mjs +9 -0
  97. package/dist/react-native/state-web.mjs.map +1 -0
  98. package/dist/react-native/urlHelpers.js +2 -1
  99. package/dist/react-native/urlHelpers.js.map +1 -1
  100. package/package.json +33 -19
  101. package/dist/browser/state.js.map +0 -1
  102. package/dist/commonjs/state.js.map +0 -1
  103. package/dist/react-native/state.d.ts +0 -8
  104. package/dist/react-native/state.js +0 -10
  105. package/dist/react-native/state.js.map +0 -1
@@ -1,877 +1,942 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
1
3
  import * as base64 from "./base64.js";
2
4
  import { XML_ATTRKEY, XML_CHARKEY } from "./interfaces.js";
3
5
  import { isDuration, isValidUuid } from "./utils.js";
4
6
  class SerializerImpl {
5
- constructor(modelMappers = {}, isXML = false) {
6
- this.modelMappers = modelMappers;
7
- this.isXML = isXML;
8
- }
9
- /**
10
- * @deprecated Removing the constraints validation on client side.
11
- */
12
- validateConstraints(mapper, value, objectName) {
13
- const failValidation = (constraintName, constraintValue) => {
14
- throw new Error(
15
- `"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`
16
- );
17
- };
18
- if (mapper.constraints && value !== void 0 && value !== null) {
19
- const {
20
- ExclusiveMaximum,
21
- ExclusiveMinimum,
22
- InclusiveMaximum,
23
- InclusiveMinimum,
24
- MaxItems,
25
- MaxLength,
26
- MinItems,
27
- MinLength,
28
- MultipleOf,
29
- Pattern,
30
- UniqueItems
31
- } = mapper.constraints;
32
- if (ExclusiveMaximum !== void 0 && value >= ExclusiveMaximum) {
33
- failValidation("ExclusiveMaximum", ExclusiveMaximum);
34
- }
35
- if (ExclusiveMinimum !== void 0 && value <= ExclusiveMinimum) {
36
- failValidation("ExclusiveMinimum", ExclusiveMinimum);
37
- }
38
- if (InclusiveMaximum !== void 0 && value > InclusiveMaximum) {
39
- failValidation("InclusiveMaximum", InclusiveMaximum);
40
- }
41
- if (InclusiveMinimum !== void 0 && value < InclusiveMinimum) {
42
- failValidation("InclusiveMinimum", InclusiveMinimum);
43
- }
44
- if (MaxItems !== void 0 && value.length > MaxItems) {
45
- failValidation("MaxItems", MaxItems);
46
- }
47
- if (MaxLength !== void 0 && value.length > MaxLength) {
48
- failValidation("MaxLength", MaxLength);
49
- }
50
- if (MinItems !== void 0 && value.length < MinItems) {
51
- failValidation("MinItems", MinItems);
52
- }
53
- if (MinLength !== void 0 && value.length < MinLength) {
54
- failValidation("MinLength", MinLength);
55
- }
56
- if (MultipleOf !== void 0 && value % MultipleOf !== 0) {
57
- failValidation("MultipleOf", MultipleOf);
58
- }
59
- if (Pattern) {
60
- const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
61
- if (typeof value !== "string" || value.match(pattern) === null) {
62
- failValidation("Pattern", Pattern);
63
- }
64
- }
65
- if (UniqueItems && value.some((item, i, ar) => ar.indexOf(item) !== i)) {
66
- failValidation("UniqueItems", UniqueItems);
67
- }
68
- }
69
- }
70
- /**
71
- * Serialize the given object based on its metadata defined in the mapper
72
- *
73
- * @param mapper - The mapper which defines the metadata of the serializable object
74
- *
75
- * @param object - A valid Javascript object to be serialized
76
- *
77
- * @param objectName - Name of the serialized object
78
- *
79
- * @param options - additional options to serialization
80
- *
81
- * @returns A valid serialized Javascript object
82
- */
83
- serialize(mapper, object, objectName, options = { xml: {} }) {
84
- const updatedOptions = {
85
- xml: {
86
- rootName: options.xml.rootName ?? "",
87
- includeRoot: options.xml.includeRoot ?? false,
88
- xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY
89
- }
90
- };
91
- let payload = {};
92
- const mapperType = mapper.type.name;
93
- if (!objectName) {
94
- objectName = mapper.serializedName;
95
- }
96
- if (mapperType.match(/^Sequence$/i) !== null) {
97
- payload = [];
98
- }
99
- if (mapper.isConstant) {
100
- object = mapper.defaultValue;
101
- }
102
- const { required, nullable } = mapper;
103
- if (required && nullable && object === void 0) {
104
- throw new Error(`${objectName} cannot be undefined.`);
105
- }
106
- if (required && !nullable && (object === void 0 || object === null)) {
107
- throw new Error(`${objectName} cannot be null or undefined.`);
108
- }
109
- if (!required && nullable === false && object === null) {
110
- throw new Error(`${objectName} cannot be null.`);
111
- }
112
- if (object === void 0 || object === null) {
113
- payload = object;
114
- } else {
115
- if (mapperType.match(/^any$/i) !== null) {
116
- payload = object;
117
- } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
118
- payload = serializeBasicTypes(mapperType, objectName, object);
119
- } else if (mapperType.match(/^Enum$/i) !== null) {
120
- const enumMapper = mapper;
121
- payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
122
- } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
123
- payload = serializeDateTypes(mapperType, object, objectName);
124
- } else if (mapperType.match(/^ByteArray$/i) !== null) {
125
- payload = serializeByteArrayType(objectName, object);
126
- } else if (mapperType.match(/^Base64Url$/i) !== null) {
127
- payload = serializeBase64UrlType(objectName, object);
128
- } else if (mapperType.match(/^Sequence$/i) !== null) {
129
- payload = serializeSequenceType(
130
- this,
131
- mapper,
132
- object,
133
- objectName,
134
- Boolean(this.isXML),
135
- updatedOptions
136
- );
137
- } else if (mapperType.match(/^Dictionary$/i) !== null) {
138
- payload = serializeDictionaryType(
139
- this,
140
- mapper,
141
- object,
142
- objectName,
143
- Boolean(this.isXML),
144
- updatedOptions
145
- );
146
- } else if (mapperType.match(/^Composite$/i) !== null) {
147
- payload = serializeCompositeType(
148
- this,
149
- mapper,
150
- object,
151
- objectName,
152
- Boolean(this.isXML),
153
- updatedOptions
154
- );
155
- }
156
- }
157
- return payload;
158
- }
159
- /**
160
- * Deserialize the given object based on its metadata defined in the mapper
161
- *
162
- * @param mapper - The mapper which defines the metadata of the serializable object
163
- *
164
- * @param responseBody - A valid Javascript entity to be deserialized
165
- *
166
- * @param objectName - Name of the deserialized object
167
- *
168
- * @param options - Controls behavior of XML parser and builder.
169
- *
170
- * @returns A valid deserialized Javascript object
171
- */
172
- deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
173
- const updatedOptions = {
174
- xml: {
175
- rootName: options.xml.rootName ?? "",
176
- includeRoot: options.xml.includeRoot ?? false,
177
- xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY
178
- },
179
- ignoreUnknownProperties: options.ignoreUnknownProperties ?? false
180
- };
181
- if (responseBody === void 0 || responseBody === null) {
182
- if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
183
- responseBody = [];
184
- }
185
- if (mapper.defaultValue !== void 0) {
186
- responseBody = mapper.defaultValue;
187
- }
188
- return responseBody;
189
- }
190
- let payload;
191
- const mapperType = mapper.type.name;
192
- if (!objectName) {
193
- objectName = mapper.serializedName;
194
- }
195
- if (mapperType.match(/^Composite$/i) !== null) {
196
- payload = deserializeCompositeType(
197
- this,
198
- mapper,
199
- responseBody,
200
- objectName,
201
- updatedOptions
202
- );
203
- } else {
204
- if (this.isXML) {
205
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
206
- if (responseBody[XML_ATTRKEY] !== void 0 && responseBody[xmlCharKey] !== void 0) {
207
- responseBody = responseBody[xmlCharKey];
208
- }
209
- }
210
- if (mapperType.match(/^Number$/i) !== null) {
211
- payload = parseFloat(responseBody);
212
- if (isNaN(payload)) {
213
- payload = responseBody;
214
- }
215
- } else if (mapperType.match(/^Boolean$/i) !== null) {
216
- if (responseBody === "true") {
217
- payload = true;
218
- } else if (responseBody === "false") {
219
- payload = false;
220
- } else {
221
- payload = responseBody;
222
- }
223
- } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
224
- payload = responseBody;
225
- } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
226
- payload = new Date(responseBody);
227
- } else if (mapperType.match(/^UnixTime$/i) !== null) {
228
- payload = unixTimeToDate(responseBody);
229
- } else if (mapperType.match(/^ByteArray$/i) !== null) {
230
- payload = base64.decodeString(responseBody);
231
- } else if (mapperType.match(/^Base64Url$/i) !== null) {
232
- payload = base64UrlToByteArray(responseBody);
233
- } else if (mapperType.match(/^Sequence$/i) !== null) {
234
- payload = deserializeSequenceType(
235
- this,
236
- mapper,
237
- responseBody,
238
- objectName,
239
- updatedOptions
240
- );
241
- } else if (mapperType.match(/^Dictionary$/i) !== null) {
242
- payload = deserializeDictionaryType(
243
- this,
244
- mapper,
245
- responseBody,
246
- objectName,
247
- updatedOptions
248
- );
249
- }
250
- }
251
- if (mapper.isConstant) {
252
- payload = mapper.defaultValue;
253
- }
254
- return payload;
255
- }
7
+ modelMappers;
8
+ isXML;
9
+ constructor(modelMappers = {}, isXML = false) {
10
+ this.modelMappers = modelMappers;
11
+ this.isXML = isXML;
12
+ }
13
+ /**
14
+ * @deprecated Removing the constraints validation on client side.
15
+ */
16
+ validateConstraints(mapper, value, objectName) {
17
+ const failValidation = (constraintName, constraintValue) => {
18
+ throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
19
+ };
20
+ if (mapper.constraints && value !== undefined && value !== null) {
21
+ const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
22
+ if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
23
+ failValidation("ExclusiveMaximum", ExclusiveMaximum);
24
+ }
25
+ if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
26
+ failValidation("ExclusiveMinimum", ExclusiveMinimum);
27
+ }
28
+ if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
29
+ failValidation("InclusiveMaximum", InclusiveMaximum);
30
+ }
31
+ if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
32
+ failValidation("InclusiveMinimum", InclusiveMinimum);
33
+ }
34
+ if (MaxItems !== undefined && value.length > MaxItems) {
35
+ failValidation("MaxItems", MaxItems);
36
+ }
37
+ if (MaxLength !== undefined && value.length > MaxLength) {
38
+ failValidation("MaxLength", MaxLength);
39
+ }
40
+ if (MinItems !== undefined && value.length < MinItems) {
41
+ failValidation("MinItems", MinItems);
42
+ }
43
+ if (MinLength !== undefined && value.length < MinLength) {
44
+ failValidation("MinLength", MinLength);
45
+ }
46
+ if (MultipleOf !== undefined && value % MultipleOf !== 0) {
47
+ failValidation("MultipleOf", MultipleOf);
48
+ }
49
+ if (Pattern) {
50
+ const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
51
+ if (typeof value !== "string" || value.match(pattern) === null) {
52
+ failValidation("Pattern", Pattern);
53
+ }
54
+ }
55
+ if (UniqueItems &&
56
+ value.some((item, i, ar) => ar.indexOf(item) !== i)) {
57
+ failValidation("UniqueItems", UniqueItems);
58
+ }
59
+ }
60
+ }
61
+ /**
62
+ * Serialize the given object based on its metadata defined in the mapper
63
+ *
64
+ * @param mapper - The mapper which defines the metadata of the serializable object
65
+ *
66
+ * @param object - A valid Javascript object to be serialized
67
+ *
68
+ * @param objectName - Name of the serialized object
69
+ *
70
+ * @param options - additional options to serialization
71
+ *
72
+ * @returns A valid serialized Javascript object
73
+ */
74
+ serialize(mapper, object, objectName, options = { xml: {} }) {
75
+ const updatedOptions = {
76
+ xml: {
77
+ rootName: options.xml.rootName ?? "",
78
+ includeRoot: options.xml.includeRoot ?? false,
79
+ xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY,
80
+ },
81
+ };
82
+ let payload = {};
83
+ const mapperType = mapper.type.name;
84
+ if (!objectName) {
85
+ objectName = mapper.serializedName;
86
+ }
87
+ if (mapperType.match(/^Sequence$/i) !== null) {
88
+ payload = [];
89
+ }
90
+ if (mapper.isConstant) {
91
+ object = mapper.defaultValue;
92
+ }
93
+ // This table of allowed values should help explain
94
+ // the mapper.required and mapper.nullable properties.
95
+ // X means "neither undefined or null are allowed".
96
+ // || required
97
+ // || true | false
98
+ // nullable || ==========================
99
+ // true || null | undefined/null
100
+ // false || X | undefined
101
+ // undefined || X | undefined/null
102
+ const { required, nullable } = mapper;
103
+ if (required && nullable && object === undefined) {
104
+ throw new Error(`${objectName} cannot be undefined.`);
105
+ }
106
+ if (required && !nullable && (object === undefined || object === null)) {
107
+ throw new Error(`${objectName} cannot be null or undefined.`);
108
+ }
109
+ if (!required && nullable === false && object === null) {
110
+ throw new Error(`${objectName} cannot be null.`);
111
+ }
112
+ if (object === undefined || object === null) {
113
+ payload = object;
114
+ }
115
+ else {
116
+ if (mapperType.match(/^any$/i) !== null) {
117
+ payload = object;
118
+ }
119
+ else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
120
+ payload = serializeBasicTypes(mapperType, objectName, object);
121
+ }
122
+ else if (mapperType.match(/^Enum$/i) !== null) {
123
+ const enumMapper = mapper;
124
+ payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
125
+ }
126
+ else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
127
+ payload = serializeDateTypes(mapperType, object, objectName);
128
+ }
129
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
130
+ payload = serializeByteArrayType(objectName, object);
131
+ }
132
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
133
+ payload = serializeBase64UrlType(objectName, object);
134
+ }
135
+ else if (mapperType.match(/^Sequence$/i) !== null) {
136
+ payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
137
+ }
138
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
139
+ payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
140
+ }
141
+ else if (mapperType.match(/^Composite$/i) !== null) {
142
+ payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
143
+ }
144
+ }
145
+ return payload;
146
+ }
147
+ /**
148
+ * Deserialize the given object based on its metadata defined in the mapper
149
+ *
150
+ * @param mapper - The mapper which defines the metadata of the serializable object
151
+ *
152
+ * @param responseBody - A valid Javascript entity to be deserialized
153
+ *
154
+ * @param objectName - Name of the deserialized object
155
+ *
156
+ * @param options - Controls behavior of XML parser and builder.
157
+ *
158
+ * @returns A valid deserialized Javascript object
159
+ */
160
+ deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
161
+ const updatedOptions = {
162
+ xml: {
163
+ rootName: options.xml.rootName ?? "",
164
+ includeRoot: options.xml.includeRoot ?? false,
165
+ xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY,
166
+ },
167
+ ignoreUnknownProperties: options.ignoreUnknownProperties ?? false,
168
+ };
169
+ if (responseBody === undefined || responseBody === null) {
170
+ if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
171
+ // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
172
+ // between the list being empty versus being missing,
173
+ // so let's do the more user-friendly thing and return an empty list.
174
+ responseBody = [];
175
+ }
176
+ // specifically check for undefined as default value can be a falsey value `0, "", false, null`
177
+ if (mapper.defaultValue !== undefined) {
178
+ responseBody = mapper.defaultValue;
179
+ }
180
+ return responseBody;
181
+ }
182
+ let payload;
183
+ const mapperType = mapper.type.name;
184
+ if (!objectName) {
185
+ objectName = mapper.serializedName;
186
+ }
187
+ if (mapperType.match(/^Composite$/i) !== null) {
188
+ payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
189
+ }
190
+ else {
191
+ if (this.isXML) {
192
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
193
+ /**
194
+ * If the mapper specifies this as a non-composite type value but the responseBody contains
195
+ * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
196
+ * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
197
+ */
198
+ if (responseBody[XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
199
+ responseBody = responseBody[xmlCharKey];
200
+ }
201
+ }
202
+ if (mapperType.match(/^Number$/i) !== null) {
203
+ payload = parseFloat(responseBody);
204
+ if (isNaN(payload)) {
205
+ payload = responseBody;
206
+ }
207
+ }
208
+ else if (mapperType.match(/^Boolean$/i) !== null) {
209
+ if (responseBody === "true") {
210
+ payload = true;
211
+ }
212
+ else if (responseBody === "false") {
213
+ payload = false;
214
+ }
215
+ else {
216
+ payload = responseBody;
217
+ }
218
+ }
219
+ else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
220
+ payload = responseBody;
221
+ }
222
+ else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
223
+ payload = new Date(responseBody);
224
+ }
225
+ else if (mapperType.match(/^UnixTime$/i) !== null) {
226
+ payload = unixTimeToDate(responseBody);
227
+ }
228
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
229
+ payload = base64.decodeString(responseBody);
230
+ }
231
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
232
+ payload = base64UrlToByteArray(responseBody);
233
+ }
234
+ else if (mapperType.match(/^Sequence$/i) !== null) {
235
+ payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
236
+ }
237
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
238
+ payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
239
+ }
240
+ }
241
+ if (mapper.isConstant) {
242
+ payload = mapper.defaultValue;
243
+ }
244
+ return payload;
245
+ }
256
246
  }
257
- function createSerializer(modelMappers = {}, isXML = false) {
258
- return new SerializerImpl(modelMappers, isXML);
247
+ /**
248
+ * Method that creates and returns a Serializer.
249
+ * @param modelMappers - Known models to map
250
+ * @param isXML - If XML should be supported
251
+ */
252
+ export function createSerializer(modelMappers = {}, isXML = false) {
253
+ return new SerializerImpl(modelMappers, isXML);
259
254
  }
260
255
  function trimEnd(str, ch) {
261
- let len = str.length;
262
- while (len - 1 >= 0 && str[len - 1] === ch) {
263
- --len;
264
- }
265
- return str.substr(0, len);
256
+ let len = str.length;
257
+ while (len - 1 >= 0 && str[len - 1] === ch) {
258
+ --len;
259
+ }
260
+ return str.substr(0, len);
266
261
  }
267
262
  function bufferToBase64Url(buffer) {
268
- if (!buffer) {
269
- return void 0;
270
- }
271
- if (!(buffer instanceof Uint8Array)) {
272
- throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
273
- }
274
- const str = base64.encodeByteArray(buffer);
275
- return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
263
+ if (!buffer) {
264
+ return undefined;
265
+ }
266
+ if (!(buffer instanceof Uint8Array)) {
267
+ throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
268
+ }
269
+ // Uint8Array to Base64.
270
+ const str = base64.encodeByteArray(buffer);
271
+ // Base64 to Base64Url.
272
+ return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
276
273
  }
277
274
  function base64UrlToByteArray(str) {
278
- if (!str) {
279
- return void 0;
280
- }
281
- if (str && typeof str.valueOf() !== "string") {
282
- throw new Error("Please provide an input of type string for converting to Uint8Array");
283
- }
284
- str = str.replace(/-/g, "+").replace(/_/g, "/");
285
- return base64.decodeString(str);
275
+ if (!str) {
276
+ return undefined;
277
+ }
278
+ if (str && typeof str.valueOf() !== "string") {
279
+ throw new Error("Please provide an input of type string for converting to Uint8Array");
280
+ }
281
+ // Base64Url to Base64.
282
+ str = str.replace(/-/g, "+").replace(/_/g, "/");
283
+ // Base64 to Uint8Array.
284
+ return base64.decodeString(str);
286
285
  }
287
286
  function splitSerializeName(prop) {
288
- const classes = [];
289
- let partialclass = "";
290
- if (prop) {
291
- const subwords = prop.split(".");
292
- for (const item of subwords) {
293
- if (item.charAt(item.length - 1) === "\\") {
294
- partialclass += item.substr(0, item.length - 1) + ".";
295
- } else {
296
- partialclass += item;
297
- classes.push(partialclass);
298
- partialclass = "";
299
- }
300
- }
301
- }
302
- return classes;
287
+ const classes = [];
288
+ let partialclass = "";
289
+ if (prop) {
290
+ const subwords = prop.split(".");
291
+ for (const item of subwords) {
292
+ if (item.charAt(item.length - 1) === "\\") {
293
+ partialclass += item.substr(0, item.length - 1) + ".";
294
+ }
295
+ else {
296
+ partialclass += item;
297
+ classes.push(partialclass);
298
+ partialclass = "";
299
+ }
300
+ }
301
+ }
302
+ return classes;
303
303
  }
304
304
  function dateToUnixTime(d) {
305
- if (!d) {
306
- return void 0;
307
- }
308
- if (typeof d.valueOf() === "string") {
309
- d = new Date(d);
310
- }
311
- return Math.floor(d.getTime() / 1e3);
305
+ if (!d) {
306
+ return undefined;
307
+ }
308
+ if (typeof d.valueOf() === "string") {
309
+ d = new Date(d);
310
+ }
311
+ return Math.floor(d.getTime() / 1000);
312
312
  }
313
313
  function unixTimeToDate(n) {
314
- if (!n) {
315
- return void 0;
316
- }
317
- return new Date(n * 1e3);
314
+ if (!n) {
315
+ return undefined;
316
+ }
317
+ return new Date(n * 1000);
318
318
  }
319
319
  function serializeBasicTypes(typeName, objectName, value) {
320
- if (value !== null && value !== void 0) {
321
- if (typeName.match(/^Number$/i) !== null) {
322
- if (typeof value !== "number") {
323
- throw new Error(`${objectName} with value ${value} must be of type number.`);
324
- }
325
- } else if (typeName.match(/^String$/i) !== null) {
326
- if (typeof value.valueOf() !== "string") {
327
- throw new Error(`${objectName} with value "${value}" must be of type string.`);
328
- }
329
- } else if (typeName.match(/^Uuid$/i) !== null) {
330
- if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
331
- throw new Error(
332
- `${objectName} with value "${value}" must be of type string and a valid uuid.`
333
- );
334
- }
335
- } else if (typeName.match(/^Boolean$/i) !== null) {
336
- if (typeof value !== "boolean") {
337
- throw new Error(`${objectName} with value ${value} must be of type boolean.`);
338
- }
339
- } else if (typeName.match(/^Stream$/i) !== null) {
340
- const objectType = typeof value;
341
- if (objectType !== "string" && typeof value.pipe !== "function" && // NodeJS.ReadableStream
342
- typeof value.tee !== "function" && // browser ReadableStream
343
- !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && // File objects count as a type of Blob, so we want to use instanceof explicitly
344
- !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) && objectType !== "function") {
345
- throw new Error(
346
- `${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`
347
- );
348
- }
349
- }
350
- }
351
- return value;
320
+ if (value !== null && value !== undefined) {
321
+ if (typeName.match(/^Number$/i) !== null) {
322
+ if (typeof value !== "number") {
323
+ throw new Error(`${objectName} with value ${value} must be of type number.`);
324
+ }
325
+ }
326
+ else if (typeName.match(/^String$/i) !== null) {
327
+ if (typeof value.valueOf() !== "string") {
328
+ throw new Error(`${objectName} with value "${value}" must be of type string.`);
329
+ }
330
+ }
331
+ else if (typeName.match(/^Uuid$/i) !== null) {
332
+ if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
333
+ throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
334
+ }
335
+ }
336
+ else if (typeName.match(/^Boolean$/i) !== null) {
337
+ if (typeof value !== "boolean") {
338
+ throw new Error(`${objectName} with value ${value} must be of type boolean.`);
339
+ }
340
+ }
341
+ else if (typeName.match(/^Stream$/i) !== null) {
342
+ const objectType = typeof value;
343
+ if (objectType !== "string" &&
344
+ typeof value.pipe !== "function" && // NodeJS.ReadableStream
345
+ typeof value.tee !== "function" && // browser ReadableStream
346
+ !(value instanceof ArrayBuffer) &&
347
+ !ArrayBuffer.isView(value) &&
348
+ // File objects count as a type of Blob, so we want to use instanceof explicitly
349
+ !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
350
+ objectType !== "function") {
351
+ throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
352
+ }
353
+ }
354
+ }
355
+ return value;
352
356
  }
353
357
  function serializeEnumType(objectName, allowedValues, value) {
354
- if (!allowedValues) {
355
- throw new Error(
356
- `Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`
357
- );
358
- }
359
- const isPresent = allowedValues.some((item) => {
360
- if (typeof item.valueOf() === "string") {
361
- return item.toLowerCase() === value.toLowerCase();
362
- }
363
- return item === value;
364
- });
365
- if (!isPresent) {
366
- throw new Error(
367
- `${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(
368
- allowedValues
369
- )}.`
370
- );
371
- }
372
- return value;
358
+ if (!allowedValues) {
359
+ throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
360
+ }
361
+ const isPresent = allowedValues.some((item) => {
362
+ if (typeof item.valueOf() === "string") {
363
+ return item.toLowerCase() === value.toLowerCase();
364
+ }
365
+ return item === value;
366
+ });
367
+ if (!isPresent) {
368
+ throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
369
+ }
370
+ return value;
373
371
  }
374
372
  function serializeByteArrayType(objectName, value) {
375
- if (value !== void 0 && value !== null) {
376
- if (!(value instanceof Uint8Array)) {
377
- throw new Error(`${objectName} must be of type Uint8Array.`);
373
+ if (value !== undefined && value !== null) {
374
+ if (!(value instanceof Uint8Array)) {
375
+ throw new Error(`${objectName} must be of type Uint8Array.`);
376
+ }
377
+ value = base64.encodeByteArray(value);
378
378
  }
379
- value = base64.encodeByteArray(value);
380
- }
381
- return value;
379
+ return value;
382
380
  }
383
381
  function serializeBase64UrlType(objectName, value) {
384
- if (value !== void 0 && value !== null) {
385
- if (!(value instanceof Uint8Array)) {
386
- throw new Error(`${objectName} must be of type Uint8Array.`);
382
+ if (value !== undefined && value !== null) {
383
+ if (!(value instanceof Uint8Array)) {
384
+ throw new Error(`${objectName} must be of type Uint8Array.`);
385
+ }
386
+ value = bufferToBase64Url(value);
387
387
  }
388
- value = bufferToBase64Url(value);
389
- }
390
- return value;
388
+ return value;
391
389
  }
392
390
  function serializeDateTypes(typeName, value, objectName) {
393
- if (value !== void 0 && value !== null) {
394
- if (typeName.match(/^Date$/i) !== null) {
395
- if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) {
396
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
397
- }
398
- value = value instanceof Date ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10);
399
- } else if (typeName.match(/^DateTime$/i) !== null) {
400
- if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) {
401
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
402
- }
403
- value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
404
- } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
405
- if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) {
406
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
407
- }
408
- value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
409
- } else if (typeName.match(/^UnixTime$/i) !== null) {
410
- if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) {
411
- throw new Error(
412
- `${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format for it to be serialized in UnixTime/Epoch format.`
413
- );
414
- }
415
- value = dateToUnixTime(value);
416
- } else if (typeName.match(/^TimeSpan$/i) !== null) {
417
- if (!isDuration(value)) {
418
- throw new Error(
419
- `${objectName} must be a string in ISO 8601 format. Instead was "${value}".`
420
- );
421
- }
422
- }
423
- }
424
- return value;
391
+ if (value !== undefined && value !== null) {
392
+ if (typeName.match(/^Date$/i) !== null) {
393
+ if (!(value instanceof Date ||
394
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
395
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
396
+ }
397
+ value =
398
+ value instanceof Date
399
+ ? value.toISOString().substring(0, 10)
400
+ : new Date(value).toISOString().substring(0, 10);
401
+ }
402
+ else if (typeName.match(/^DateTime$/i) !== null) {
403
+ if (!(value instanceof Date ||
404
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
405
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
406
+ }
407
+ value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
408
+ }
409
+ else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
410
+ if (!(value instanceof Date ||
411
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
412
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
413
+ }
414
+ value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
415
+ }
416
+ else if (typeName.match(/^UnixTime$/i) !== null) {
417
+ if (!(value instanceof Date ||
418
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
419
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
420
+ `for it to be serialized in UnixTime/Epoch format.`);
421
+ }
422
+ value = dateToUnixTime(value);
423
+ }
424
+ else if (typeName.match(/^TimeSpan$/i) !== null) {
425
+ if (!isDuration(value)) {
426
+ throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
427
+ }
428
+ }
429
+ }
430
+ return value;
425
431
  }
426
432
  function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
427
- if (!Array.isArray(object)) {
428
- throw new Error(`${objectName} must be of type Array.`);
429
- }
430
- let elementType = mapper.type.element;
431
- if (!elementType || typeof elementType !== "object") {
432
- throw new Error(
433
- `element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}.`
434
- );
435
- }
436
- if (elementType.type.name === "Composite" && elementType.type.className) {
437
- elementType = serializer.modelMappers[elementType.type.className] ?? elementType;
438
- }
439
- const tempArray = [];
440
- for (let i = 0; i < object.length; i++) {
441
- const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
442
- if (isXml && elementType.xmlNamespace) {
443
- const xmlnsKey = elementType.xmlNamespacePrefix ? `xmlns:${elementType.xmlNamespacePrefix}` : "xmlns";
444
- if (elementType.type.name === "Composite") {
445
- tempArray[i] = { ...serializedValue };
446
- tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
447
- } else {
448
- tempArray[i] = {};
449
- tempArray[i][options.xml.xmlCharKey] = serializedValue;
450
- tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
451
- }
452
- } else {
453
- tempArray[i] = serializedValue;
454
- }
455
- }
456
- return tempArray;
433
+ if (!Array.isArray(object)) {
434
+ throw new Error(`${objectName} must be of type Array.`);
435
+ }
436
+ let elementType = mapper.type.element;
437
+ if (!elementType || typeof elementType !== "object") {
438
+ throw new Error(`"element" metadata for an Array must be defined in the ` +
439
+ `mapper and it must be of type "object" in ${objectName}.`);
440
+ }
441
+ // Quirk: Composite mappers referenced by `element` might
442
+ // not have *all* properties declared (like uberParent),
443
+ // so let's try to look up the full definition by name.
444
+ if (elementType.type.name === "Composite" && elementType.type.className) {
445
+ elementType = serializer.modelMappers[elementType.type.className] ?? elementType;
446
+ }
447
+ const tempArray = [];
448
+ for (let i = 0; i < object.length; i++) {
449
+ const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
450
+ if (isXml && elementType.xmlNamespace) {
451
+ const xmlnsKey = elementType.xmlNamespacePrefix
452
+ ? `xmlns:${elementType.xmlNamespacePrefix}`
453
+ : "xmlns";
454
+ if (elementType.type.name === "Composite") {
455
+ tempArray[i] = { ...serializedValue };
456
+ tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
457
+ }
458
+ else {
459
+ tempArray[i] = {};
460
+ tempArray[i][options.xml.xmlCharKey] = serializedValue;
461
+ tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
462
+ }
463
+ }
464
+ else {
465
+ tempArray[i] = serializedValue;
466
+ }
467
+ }
468
+ return tempArray;
457
469
  }
458
470
  function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
459
- if (typeof object !== "object") {
460
- throw new Error(`${objectName} must be of type object.`);
461
- }
462
- const valueType = mapper.type.value;
463
- if (!valueType || typeof valueType !== "object") {
464
- throw new Error(
465
- `"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}.`
466
- );
467
- }
468
- const tempDictionary = {};
469
- for (const key of Object.keys(object)) {
470
- const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
471
- tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
472
- }
473
- if (isXml && mapper.xmlNamespace) {
474
- const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
475
- const result = tempDictionary;
476
- result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
477
- return result;
478
- }
479
- return tempDictionary;
471
+ if (typeof object !== "object") {
472
+ throw new Error(`${objectName} must be of type object.`);
473
+ }
474
+ const valueType = mapper.type.value;
475
+ if (!valueType || typeof valueType !== "object") {
476
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
477
+ `mapper and it must of type "object" in ${objectName}.`);
478
+ }
479
+ const tempDictionary = {};
480
+ for (const key of Object.keys(object)) {
481
+ const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
482
+ // If the element needs an XML namespace we need to add it within the $ property
483
+ tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
484
+ }
485
+ // Add the namespace to the root element if needed
486
+ if (isXml && mapper.xmlNamespace) {
487
+ const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
488
+ const result = tempDictionary;
489
+ result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
490
+ return result;
491
+ }
492
+ return tempDictionary;
480
493
  }
494
+ /**
495
+ * Resolves the additionalProperties property from a referenced mapper
496
+ * @param serializer - the serializer containing the entire set of mappers
497
+ * @param mapper - the composite mapper to resolve
498
+ * @param objectName - name of the object being serialized
499
+ */
481
500
  function resolveAdditionalProperties(serializer, mapper, objectName) {
482
- const additionalProperties = mapper.type.additionalProperties;
483
- if (!additionalProperties && mapper.type.className) {
484
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
485
- return modelMapper?.type.additionalProperties;
486
- }
487
- return additionalProperties;
501
+ const additionalProperties = mapper.type.additionalProperties;
502
+ if (!additionalProperties && mapper.type.className) {
503
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
504
+ return modelMapper?.type.additionalProperties;
505
+ }
506
+ return additionalProperties;
488
507
  }
508
+ /**
509
+ * Finds the mapper referenced by className
510
+ * @param serializer - the serializer containing the entire set of mappers
511
+ * @param mapper - the composite mapper to resolve
512
+ * @param objectName - name of the object being serialized
513
+ */
489
514
  function resolveReferencedMapper(serializer, mapper, objectName) {
490
- const className = mapper.type.className;
491
- if (!className) {
492
- throw new Error(
493
- `Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(
494
- mapper,
495
- void 0,
496
- 2
497
- )}".`
498
- );
499
- }
500
- return serializer.modelMappers[className];
515
+ const className = mapper.type.className;
516
+ if (!className) {
517
+ throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
518
+ }
519
+ return serializer.modelMappers[className];
501
520
  }
521
+ /**
522
+ * Resolves a composite mapper's modelProperties.
523
+ * @param serializer - the serializer containing the entire set of mappers
524
+ * @param mapper - the composite mapper to resolve
525
+ */
502
526
  function resolveModelProperties(serializer, mapper, objectName) {
503
- let modelProps = mapper.type.modelProperties;
504
- if (!modelProps) {
505
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
506
- if (!modelMapper) {
507
- throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
508
- }
509
- modelProps = modelMapper?.type.modelProperties;
527
+ let modelProps = mapper.type.modelProperties;
510
528
  if (!modelProps) {
511
- throw new Error(
512
- `modelProperties cannot be null or undefined in the mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`
513
- );
529
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
530
+ if (!modelMapper) {
531
+ throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
532
+ }
533
+ modelProps = modelMapper?.type.modelProperties;
534
+ if (!modelProps) {
535
+ throw new Error(`modelProperties cannot be null or undefined in the ` +
536
+ `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
537
+ }
514
538
  }
515
- }
516
- return modelProps;
539
+ return modelProps;
517
540
  }
518
541
  function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
519
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
520
- mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
521
- }
522
- if (object !== void 0 && object !== null) {
523
- const payload = {};
524
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
525
- for (const key of Object.keys(modelProps)) {
526
- const propertyMapper = modelProps[key];
527
- if (propertyMapper.readOnly) {
528
- continue;
529
- }
530
- let propName;
531
- let parentObject = payload;
532
- if (serializer.isXML) {
533
- if (propertyMapper.xmlIsWrapped) {
534
- propName = propertyMapper.xmlName;
535
- } else {
536
- propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
537
- }
538
- } else {
539
- const paths = splitSerializeName(propertyMapper.serializedName);
540
- propName = paths.pop();
541
- for (const pathName of paths) {
542
- const childObject = parentObject[pathName];
543
- if ((childObject === void 0 || childObject === null) && (object[key] !== void 0 && object[key] !== null || propertyMapper.defaultValue !== void 0)) {
544
- parentObject[pathName] = {};
545
- }
546
- parentObject = parentObject[pathName];
547
- }
548
- }
549
- if (parentObject !== void 0 && parentObject !== null) {
550
- if (isXml && mapper.xmlNamespace) {
551
- const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
552
- parentObject[XML_ATTRKEY] = {
553
- ...parentObject[XML_ATTRKEY],
554
- [xmlnsKey]: mapper.xmlNamespace
555
- };
556
- }
557
- const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName;
558
- let toSerialize = object[key];
559
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
560
- if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && (toSerialize === void 0 || toSerialize === null)) {
561
- toSerialize = mapper.serializedName;
562
- }
563
- const serializedValue = serializer.serialize(
564
- propertyMapper,
565
- toSerialize,
566
- propertyObjectName,
567
- options
568
- );
569
- if (serializedValue !== void 0 && propName !== void 0 && propName !== null) {
570
- const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
571
- if (isXml && propertyMapper.xmlIsAttribute) {
572
- parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {};
573
- parentObject[XML_ATTRKEY][propName] = serializedValue;
574
- } else if (isXml && propertyMapper.xmlIsWrapped) {
575
- parentObject[propName] = { [propertyMapper.xmlElementName]: value };
576
- } else {
577
- parentObject[propName] = value;
578
- }
579
- }
580
- }
581
- }
582
- const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
583
- if (additionalPropertiesMapper) {
584
- const propNames = Object.keys(modelProps);
585
- for (const clientPropName in object) {
586
- const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
587
- if (isAdditionalProperty) {
588
- payload[clientPropName] = serializer.serialize(
589
- additionalPropertiesMapper,
590
- object[clientPropName],
591
- objectName + '["' + clientPropName + '"]',
592
- options
593
- );
594
- }
595
- }
596
- }
597
- return payload;
598
- }
599
- return object;
542
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
543
+ mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
544
+ }
545
+ if (object !== undefined && object !== null) {
546
+ const payload = {};
547
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
548
+ for (const key of Object.keys(modelProps)) {
549
+ const propertyMapper = modelProps[key];
550
+ if (propertyMapper.readOnly) {
551
+ continue;
552
+ }
553
+ let propName;
554
+ let parentObject = payload;
555
+ if (serializer.isXML) {
556
+ if (propertyMapper.xmlIsWrapped) {
557
+ propName = propertyMapper.xmlName;
558
+ }
559
+ else {
560
+ propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
561
+ }
562
+ }
563
+ else {
564
+ const paths = splitSerializeName(propertyMapper.serializedName);
565
+ propName = paths.pop();
566
+ for (const pathName of paths) {
567
+ const childObject = parentObject[pathName];
568
+ if ((childObject === undefined || childObject === null) &&
569
+ ((object[key] !== undefined && object[key] !== null) ||
570
+ propertyMapper.defaultValue !== undefined)) {
571
+ parentObject[pathName] = {};
572
+ }
573
+ parentObject = parentObject[pathName];
574
+ }
575
+ }
576
+ if (parentObject !== undefined && parentObject !== null) {
577
+ if (isXml && mapper.xmlNamespace) {
578
+ const xmlnsKey = mapper.xmlNamespacePrefix
579
+ ? `xmlns:${mapper.xmlNamespacePrefix}`
580
+ : "xmlns";
581
+ parentObject[XML_ATTRKEY] = {
582
+ ...parentObject[XML_ATTRKEY],
583
+ [xmlnsKey]: mapper.xmlNamespace,
584
+ };
585
+ }
586
+ const propertyObjectName = propertyMapper.serializedName !== ""
587
+ ? objectName + "." + propertyMapper.serializedName
588
+ : objectName;
589
+ let toSerialize = object[key];
590
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
591
+ if (polymorphicDiscriminator &&
592
+ polymorphicDiscriminator.clientName === key &&
593
+ (toSerialize === undefined || toSerialize === null)) {
594
+ toSerialize = mapper.serializedName;
595
+ }
596
+ const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
597
+ if (serializedValue !== undefined && propName !== undefined && propName !== null) {
598
+ const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
599
+ if (isXml && propertyMapper.xmlIsAttribute) {
600
+ // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
601
+ // This keeps things simple while preventing name collision
602
+ // with names in user documents.
603
+ parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {};
604
+ parentObject[XML_ATTRKEY][propName] = serializedValue;
605
+ }
606
+ else if (isXml && propertyMapper.xmlIsWrapped) {
607
+ parentObject[propName] = { [propertyMapper.xmlElementName]: value };
608
+ }
609
+ else {
610
+ parentObject[propName] = value;
611
+ }
612
+ }
613
+ }
614
+ }
615
+ const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
616
+ if (additionalPropertiesMapper) {
617
+ const propNames = Object.keys(modelProps);
618
+ for (const clientPropName of Object.keys(object)) {
619
+ const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
620
+ if (isAdditionalProperty) {
621
+ Object.defineProperty(payload, clientPropName, {
622
+ value: serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options),
623
+ enumerable: true,
624
+ configurable: true,
625
+ writable: true,
626
+ });
627
+ }
628
+ }
629
+ }
630
+ return payload;
631
+ }
632
+ return object;
600
633
  }
601
634
  function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
602
- if (!isXml || !propertyMapper.xmlNamespace) {
603
- return serializedValue;
604
- }
605
- const xmlnsKey = propertyMapper.xmlNamespacePrefix ? `xmlns:${propertyMapper.xmlNamespacePrefix}` : "xmlns";
606
- const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
607
- if (["Composite"].includes(propertyMapper.type.name)) {
608
- if (serializedValue[XML_ATTRKEY]) {
609
- return serializedValue;
610
- } else {
611
- const result2 = { ...serializedValue };
612
- result2[XML_ATTRKEY] = xmlNamespace;
613
- return result2;
614
- }
615
- }
616
- const result = {};
617
- result[options.xml.xmlCharKey] = serializedValue;
618
- result[XML_ATTRKEY] = xmlNamespace;
619
- return result;
635
+ if (!isXml || !propertyMapper.xmlNamespace) {
636
+ return serializedValue;
637
+ }
638
+ const xmlnsKey = propertyMapper.xmlNamespacePrefix
639
+ ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
640
+ : "xmlns";
641
+ const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
642
+ if (["Composite"].includes(propertyMapper.type.name)) {
643
+ if (serializedValue[XML_ATTRKEY]) {
644
+ return serializedValue;
645
+ }
646
+ else {
647
+ const result = { ...serializedValue };
648
+ result[XML_ATTRKEY] = xmlNamespace;
649
+ return result;
650
+ }
651
+ }
652
+ const result = {};
653
+ result[options.xml.xmlCharKey] = serializedValue;
654
+ result[XML_ATTRKEY] = xmlNamespace;
655
+ return result;
620
656
  }
621
657
  function isSpecialXmlProperty(propertyName, options) {
622
- return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
658
+ return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
623
659
  }
624
660
  function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
625
- const xmlCharKey = options.xml.xmlCharKey ?? XML_CHARKEY;
626
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
627
- mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
628
- }
629
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
630
- let instance = {};
631
- const handledPropertyNames = [];
632
- for (const key of Object.keys(modelProps)) {
633
- const propertyMapper = modelProps[key];
634
- const paths = splitSerializeName(modelProps[key].serializedName);
635
- handledPropertyNames.push(paths[0]);
636
- const { serializedName, xmlName, xmlElementName } = propertyMapper;
637
- let propertyObjectName = objectName;
638
- if (serializedName !== "" && serializedName !== void 0) {
639
- propertyObjectName = objectName + "." + serializedName;
640
- }
641
- const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
642
- if (headerCollectionPrefix) {
643
- const dictionary = {};
644
- for (const headerKey of Object.keys(responseBody)) {
645
- if (headerKey.startsWith(headerCollectionPrefix)) {
646
- dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(
647
- propertyMapper.type.value,
648
- responseBody[headerKey],
649
- propertyObjectName,
650
- options
651
- );
652
- }
653
- handledPropertyNames.push(headerKey);
654
- }
655
- instance[key] = dictionary;
656
- } else if (serializer.isXML) {
657
- if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) {
658
- instance[key] = serializer.deserialize(
659
- propertyMapper,
660
- responseBody[XML_ATTRKEY][xmlName],
661
- propertyObjectName,
662
- options
663
- );
664
- } else if (propertyMapper.xmlIsMsText) {
665
- if (responseBody[xmlCharKey] !== void 0) {
666
- instance[key] = responseBody[xmlCharKey];
667
- } else if (typeof responseBody === "string") {
668
- instance[key] = responseBody;
669
- }
670
- } else {
671
- const propertyName = xmlElementName || xmlName || serializedName;
672
- if (propertyMapper.xmlIsWrapped) {
673
- const wrapped = responseBody[xmlName];
674
- const elementList = wrapped?.[xmlElementName] ?? [];
675
- instance[key] = serializer.deserialize(
676
- propertyMapper,
677
- elementList,
678
- propertyObjectName,
679
- options
680
- );
681
- handledPropertyNames.push(xmlName);
682
- } else {
683
- const property = responseBody[propertyName];
684
- instance[key] = serializer.deserialize(
685
- propertyMapper,
686
- property,
687
- propertyObjectName,
688
- options
689
- );
690
- handledPropertyNames.push(propertyName);
691
- }
692
- }
693
- } else {
694
- let propertyInstance;
695
- let res = responseBody;
696
- let steps = 0;
697
- for (const item of paths) {
698
- if (!res) break;
699
- steps++;
700
- res = res[item];
701
- }
702
- if (res === null && steps < paths.length) {
703
- res = void 0;
704
- }
705
- propertyInstance = res;
706
- const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
707
- if (polymorphicDiscriminator && key === polymorphicDiscriminator.clientName && (propertyInstance === void 0 || propertyInstance === null)) {
708
- propertyInstance = mapper.serializedName;
709
- }
710
- let serializedValue;
711
- if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
712
- propertyInstance = responseBody[key];
713
- const arrayInstance = serializer.deserialize(
714
- propertyMapper,
715
- propertyInstance,
716
- propertyObjectName,
717
- options
718
- );
719
- for (const [k, v] of Object.entries(instance)) {
720
- if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
721
- arrayInstance[k] = v;
722
- }
723
- }
724
- instance = arrayInstance;
725
- } else if (propertyInstance !== void 0 || propertyMapper.defaultValue !== void 0) {
726
- serializedValue = serializer.deserialize(
727
- propertyMapper,
728
- propertyInstance,
729
- propertyObjectName,
730
- options
731
- );
732
- instance[key] = serializedValue;
733
- }
734
- }
735
- }
736
- const additionalPropertiesMapper = mapper.type.additionalProperties;
737
- if (additionalPropertiesMapper) {
738
- const isAdditionalProperty = (responsePropName) => {
739
- for (const clientPropName in modelProps) {
740
- const paths = splitSerializeName(modelProps[clientPropName].serializedName);
741
- if (paths[0] === responsePropName) {
742
- return false;
743
- }
744
- }
745
- return true;
746
- };
747
- for (const responsePropName in responseBody) {
748
- if (isAdditionalProperty(responsePropName)) {
749
- instance[responsePropName] = serializer.deserialize(
750
- additionalPropertiesMapper,
751
- responseBody[responsePropName],
752
- objectName + '["' + responsePropName + '"]',
753
- options
754
- );
755
- }
756
- }
757
- } else if (responseBody && !options.ignoreUnknownProperties) {
758
- for (const key of Object.keys(responseBody)) {
759
- if (instance[key] === void 0 && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) {
760
- instance[key] = responseBody[key];
761
- }
762
- }
763
- }
764
- return instance;
661
+ const xmlCharKey = options.xml.xmlCharKey ?? XML_CHARKEY;
662
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
663
+ mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
664
+ }
665
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
666
+ let instance = {};
667
+ const handledPropertyNames = [];
668
+ for (const key of Object.keys(modelProps)) {
669
+ const propertyMapper = modelProps[key];
670
+ const paths = splitSerializeName(modelProps[key].serializedName);
671
+ handledPropertyNames.push(paths[0]);
672
+ const { serializedName, xmlName, xmlElementName } = propertyMapper;
673
+ let propertyObjectName = objectName;
674
+ if (serializedName !== "" && serializedName !== undefined) {
675
+ propertyObjectName = objectName + "." + serializedName;
676
+ }
677
+ const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
678
+ if (headerCollectionPrefix) {
679
+ const dictionary = {};
680
+ for (const headerKey of Object.keys(responseBody)) {
681
+ if (headerKey.startsWith(headerCollectionPrefix)) {
682
+ dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
683
+ }
684
+ handledPropertyNames.push(headerKey);
685
+ }
686
+ instance[key] = dictionary;
687
+ }
688
+ else if (serializer.isXML) {
689
+ if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) {
690
+ instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options);
691
+ }
692
+ else if (propertyMapper.xmlIsMsText) {
693
+ if (responseBody[xmlCharKey] !== undefined) {
694
+ instance[key] = responseBody[xmlCharKey];
695
+ }
696
+ else if (typeof responseBody === "string") {
697
+ // The special case where xml parser parses "<Name>content</Name>" into JSON of
698
+ // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
699
+ instance[key] = responseBody;
700
+ }
701
+ }
702
+ else {
703
+ const propertyName = xmlElementName || xmlName || serializedName;
704
+ if (propertyMapper.xmlIsWrapped) {
705
+ /* a list of <xmlElementName> wrapped by <xmlName>
706
+ For the xml example below
707
+ <Cors>
708
+ <CorsRule>...</CorsRule>
709
+ <CorsRule>...</CorsRule>
710
+ </Cors>
711
+ the responseBody has
712
+ {
713
+ Cors: {
714
+ CorsRule: [{...}, {...}]
715
+ }
716
+ }
717
+ xmlName is "Cors" and xmlElementName is"CorsRule".
718
+ */
719
+ const wrapped = responseBody[xmlName];
720
+ const elementList = wrapped?.[xmlElementName] ?? [];
721
+ Object.defineProperty(instance, key, {
722
+ value: serializer.deserialize(propertyMapper, elementList, propertyObjectName, options),
723
+ enumerable: true,
724
+ configurable: true,
725
+ writable: true,
726
+ });
727
+ handledPropertyNames.push(xmlName);
728
+ }
729
+ else {
730
+ const property = responseBody[propertyName];
731
+ instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
732
+ handledPropertyNames.push(propertyName);
733
+ }
734
+ }
735
+ }
736
+ else {
737
+ // deserialize the property if it is present in the provided responseBody instance
738
+ let propertyInstance;
739
+ let res = responseBody;
740
+ // traversing the object step by step.
741
+ let steps = 0;
742
+ for (const item of paths) {
743
+ if (!res)
744
+ break;
745
+ steps++;
746
+ res = res[item];
747
+ }
748
+ // only accept null when reaching the last position of object otherwise it would be undefined
749
+ if (res === null && steps < paths.length) {
750
+ res = undefined;
751
+ }
752
+ propertyInstance = res;
753
+ const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
754
+ // checking that the model property name (key)(ex: "fishtype") and the
755
+ // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
756
+ // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
757
+ // is a better approach. The generator is not consistent with escaping '\.' in the
758
+ // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
759
+ // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
760
+ // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
761
+ // the transformation of model property name (ex: "fishtype") is done consistently.
762
+ // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
763
+ if (polymorphicDiscriminator &&
764
+ key === polymorphicDiscriminator.clientName &&
765
+ (propertyInstance === undefined || propertyInstance === null)) {
766
+ propertyInstance = mapper.serializedName;
767
+ }
768
+ let serializedValue;
769
+ // paging
770
+ if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
771
+ propertyInstance = responseBody[key];
772
+ const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
773
+ // Copy over any properties that have already been added into the instance, where they do
774
+ // not exist on the newly de-serialized array
775
+ for (const [k, v] of Object.entries(instance)) {
776
+ if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
777
+ arrayInstance[k] = v;
778
+ }
779
+ }
780
+ instance = arrayInstance;
781
+ }
782
+ else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
783
+ serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
784
+ instance[key] = serializedValue;
785
+ }
786
+ }
787
+ }
788
+ const additionalPropertiesMapper = mapper.type.additionalProperties;
789
+ if (additionalPropertiesMapper) {
790
+ const isAdditionalProperty = (responsePropName) => {
791
+ for (const clientPropName of Object.keys(modelProps)) {
792
+ const paths = splitSerializeName(modelProps[clientPropName].serializedName);
793
+ if (paths[0] === responsePropName) {
794
+ return false;
795
+ }
796
+ }
797
+ return true;
798
+ };
799
+ for (const responsePropName of Object.keys(responseBody)) {
800
+ if (isAdditionalProperty(responsePropName)) {
801
+ const deserializedValue = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
802
+ Object.defineProperty(instance, responsePropName, {
803
+ value: deserializedValue,
804
+ enumerable: true,
805
+ configurable: true,
806
+ writable: true,
807
+ });
808
+ }
809
+ }
810
+ }
811
+ else if (responseBody && !options.ignoreUnknownProperties) {
812
+ for (const key of Object.keys(responseBody)) {
813
+ if (instance[key] === undefined &&
814
+ !handledPropertyNames.includes(key) &&
815
+ !isSpecialXmlProperty(key, options)) {
816
+ Object.defineProperty(instance, key, {
817
+ value: responseBody[key],
818
+ enumerable: true,
819
+ configurable: true,
820
+ writable: true,
821
+ });
822
+ }
823
+ }
824
+ }
825
+ return instance;
765
826
  }
766
827
  function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
767
- const value = mapper.type.value;
768
- if (!value || typeof value !== "object") {
769
- throw new Error(
770
- `"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}`
771
- );
772
- }
773
- if (responseBody) {
774
- const tempDictionary = {};
775
- for (const key of Object.keys(responseBody)) {
776
- tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
828
+ /* jshint validthis: true */
829
+ const value = mapper.type.value;
830
+ if (!value || typeof value !== "object") {
831
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
832
+ `mapper and it must of type "object" in ${objectName}`);
833
+ }
834
+ if (responseBody) {
835
+ const tempDictionary = {};
836
+ for (const key of Object.keys(responseBody)) {
837
+ tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
838
+ }
839
+ return tempDictionary;
777
840
  }
778
- return tempDictionary;
779
- }
780
- return responseBody;
841
+ return responseBody;
781
842
  }
782
843
  function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
783
- let element = mapper.type.element;
784
- if (!element || typeof element !== "object") {
785
- throw new Error(
786
- `element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}`
787
- );
788
- }
789
- if (responseBody) {
790
- if (!Array.isArray(responseBody)) {
791
- responseBody = [responseBody];
792
- }
793
- if (element.type.name === "Composite" && element.type.className) {
794
- element = serializer.modelMappers[element.type.className] ?? element;
795
- }
796
- const tempArray = [];
797
- for (let i = 0; i < responseBody.length; i++) {
798
- tempArray[i] = serializer.deserialize(
799
- element,
800
- responseBody[i],
801
- `${objectName}[${i}]`,
802
- options
803
- );
844
+ let element = mapper.type.element;
845
+ if (!element || typeof element !== "object") {
846
+ throw new Error(`"element" metadata for an Array must be defined in the ` +
847
+ `mapper and it must be of type "object" in ${objectName}`);
848
+ }
849
+ if (responseBody) {
850
+ if (!Array.isArray(responseBody)) {
851
+ // xml2js will interpret a single element array as just the element, so force it to be an array
852
+ responseBody = [responseBody];
853
+ }
854
+ // Quirk: Composite mappers referenced by `element` might
855
+ // not have *all* properties declared (like uberParent),
856
+ // so let's try to look up the full definition by name.
857
+ if (element.type.name === "Composite" && element.type.className) {
858
+ element = serializer.modelMappers[element.type.className] ?? element;
859
+ }
860
+ const tempArray = [];
861
+ for (let i = 0; i < responseBody.length; i++) {
862
+ tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
863
+ }
864
+ return tempArray;
804
865
  }
805
- return tempArray;
806
- }
807
- return responseBody;
866
+ return responseBody;
808
867
  }
809
868
  function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
810
- const typeNamesToCheck = [typeName];
811
- while (typeNamesToCheck.length) {
812
- const currentName = typeNamesToCheck.shift();
813
- const indexDiscriminator = discriminatorValue === currentName ? discriminatorValue : currentName + "." + discriminatorValue;
814
- if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
815
- return discriminators[indexDiscriminator];
816
- } else {
817
- for (const [name, mapper] of Object.entries(discriminators)) {
818
- if (name.startsWith(currentName + ".") && mapper.type.uberParent === currentName && mapper.type.className) {
819
- typeNamesToCheck.push(mapper.type.className);
820
- }
821
- }
822
- }
823
- }
824
- return void 0;
869
+ const typeNamesToCheck = [typeName];
870
+ while (typeNamesToCheck.length) {
871
+ const currentName = typeNamesToCheck.shift();
872
+ const indexDiscriminator = discriminatorValue === currentName
873
+ ? discriminatorValue
874
+ : currentName + "." + discriminatorValue;
875
+ if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
876
+ return discriminators[indexDiscriminator];
877
+ }
878
+ else {
879
+ for (const [name, mapper] of Object.entries(discriminators)) {
880
+ if (name.startsWith(currentName + ".") &&
881
+ mapper.type.uberParent === currentName &&
882
+ mapper.type.className) {
883
+ typeNamesToCheck.push(mapper.type.className);
884
+ }
885
+ }
886
+ }
887
+ }
888
+ return undefined;
825
889
  }
826
890
  function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
827
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
828
- if (polymorphicDiscriminator) {
829
- let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
830
- if (discriminatorName) {
831
- if (polymorphicPropertyName === "serializedName") {
832
- discriminatorName = discriminatorName.replace(/\\/gi, "");
833
- }
834
- const discriminatorValue = object[discriminatorName];
835
- const typeName = mapper.type.uberParent ?? mapper.type.className;
836
- if (typeof discriminatorValue === "string" && typeName) {
837
- const polymorphicMapper = getIndexDiscriminator(
838
- serializer.modelMappers.discriminators,
839
- discriminatorValue,
840
- typeName
841
- );
842
- if (polymorphicMapper) {
843
- mapper = polymorphicMapper;
844
- }
845
- }
846
- }
847
- }
848
- return mapper;
891
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
892
+ if (polymorphicDiscriminator) {
893
+ let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
894
+ if (discriminatorName) {
895
+ // The serializedName might have \\, which we just want to ignore
896
+ if (polymorphicPropertyName === "serializedName") {
897
+ discriminatorName = discriminatorName.replace(/\\/gi, "");
898
+ }
899
+ const discriminatorValue = object[discriminatorName];
900
+ const typeName = mapper.type.uberParent ?? mapper.type.className;
901
+ if (typeof discriminatorValue === "string" && typeName) {
902
+ const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
903
+ if (polymorphicMapper) {
904
+ mapper = polymorphicMapper;
905
+ }
906
+ }
907
+ }
908
+ }
909
+ return mapper;
849
910
  }
850
911
  function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
851
- return mapper.type.polymorphicDiscriminator || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className);
912
+ return (mapper.type.polymorphicDiscriminator ||
913
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
914
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
852
915
  }
853
916
  function getPolymorphicDiscriminatorSafely(serializer, typeName) {
854
- return typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator;
917
+ return (typeName &&
918
+ serializer.modelMappers[typeName] &&
919
+ serializer.modelMappers[typeName].type.polymorphicDiscriminator);
855
920
  }
856
- const MapperTypeNames = {
857
- Base64Url: "Base64Url",
858
- Boolean: "Boolean",
859
- ByteArray: "ByteArray",
860
- Composite: "Composite",
861
- Date: "Date",
862
- DateTime: "DateTime",
863
- DateTimeRfc1123: "DateTimeRfc1123",
864
- Dictionary: "Dictionary",
865
- Enum: "Enum",
866
- Number: "Number",
867
- Object: "Object",
868
- Sequence: "Sequence",
869
- String: "String",
870
- Stream: "Stream",
871
- TimeSpan: "TimeSpan",
872
- UnixTime: "UnixTime"
873
- };
874
- export {
875
- MapperTypeNames,
876
- createSerializer
921
+ /**
922
+ * Known types of Mappers
923
+ */
924
+ export const MapperTypeNames = {
925
+ Base64Url: "Base64Url",
926
+ Boolean: "Boolean",
927
+ ByteArray: "ByteArray",
928
+ Composite: "Composite",
929
+ Date: "Date",
930
+ DateTime: "DateTime",
931
+ DateTimeRfc1123: "DateTimeRfc1123",
932
+ Dictionary: "Dictionary",
933
+ Enum: "Enum",
934
+ Number: "Number",
935
+ Object: "Object",
936
+ Sequence: "Sequence",
937
+ String: "String",
938
+ Stream: "Stream",
939
+ TimeSpan: "TimeSpan",
940
+ UnixTime: "UnixTime",
877
941
  };
942
+ //# sourceMappingURL=serializer.js.map