@adsk-platform/httpclient 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/_dist/index.es.js DELETED
@@ -1,3393 +0,0 @@
1
- class ParseNodeFactoryRegistry {
2
- constructor() {
3
- this.jsonContentType = "application/json";
4
- this.contentTypeAssociatedFactories = /* @__PURE__ */ new Map();
5
- }
6
- getValidContentType() {
7
- throw new Error("The registry supports multiple content types. Get the registered factory instead.");
8
- }
9
- /**
10
- * Creates a {@link ParseNode} from the given {@link ArrayBuffer} and content type.
11
- * @param contentType the content type of the {@link ArrayBuffer}.
12
- * @param content the {@link ArrayBuffer} to read from.
13
- * @returns a {@link ParseNode} that can deserialize the given {@link ArrayBuffer}.
14
- */
15
- getRootParseNode(contentType, content) {
16
- if (!contentType) {
17
- throw new Error("content type cannot be undefined or empty");
18
- }
19
- if (!content) {
20
- throw new Error("content cannot be undefined or empty");
21
- }
22
- const vendorSpecificContentType = contentType.split(";")[0];
23
- let factory = this.contentTypeAssociatedFactories.get(vendorSpecificContentType);
24
- if (factory) {
25
- return factory.getRootParseNode(vendorSpecificContentType, content);
26
- }
27
- const cleanedContentType = vendorSpecificContentType.replace(/[^/]+\+/gi, "");
28
- factory = this.contentTypeAssociatedFactories.get(cleanedContentType);
29
- if (factory) {
30
- return factory.getRootParseNode(cleanedContentType, content);
31
- }
32
- throw new Error(`Content type ${cleanedContentType} does not have a factory registered to be parsed`);
33
- }
34
- /**
35
- * Registers the default deserializer to the registry.
36
- * @param type the class of the factory to be registered.
37
- * @param backingStoreFactory The backing store factory to use.
38
- */
39
- registerDefaultDeserializer(type, backingStoreFactory) {
40
- if (!type)
41
- throw new Error("Type is required");
42
- const deserializer = new type(backingStoreFactory);
43
- this.contentTypeAssociatedFactories.set(deserializer.getValidContentType(), deserializer);
44
- }
45
- /**
46
- * Deserializes a buffer into a parsable object
47
- * @param bufferOrString the value to serialize
48
- * @param factory the factory for the model type
49
- * @returns the deserialized parsable object
50
- */
51
- deserializeFromJson(bufferOrString, factory) {
52
- return this.deserialize(this.jsonContentType, bufferOrString, factory);
53
- }
54
- /**
55
- * Deserializes a buffer into a collection of parsable object
56
- * @param bufferOrString the value to serialize
57
- * @param factory the factory for the model type
58
- * @returns the deserialized collection of parsable objects
59
- */
60
- deserializeCollectionFromJson(bufferOrString, factory) {
61
- return this.deserializeCollection(this.jsonContentType, bufferOrString, factory);
62
- }
63
- /**
64
- * Deserializes a buffer into a parsable object
65
- * @param contentType the content type to serialize to
66
- * @param bufferOrString the value to serialize
67
- * @param factory the factory for the model type
68
- * @returns the deserialized parsable object
69
- */
70
- deserialize(contentType, bufferOrString, factory) {
71
- if (typeof bufferOrString === "string") {
72
- bufferOrString = this.getBufferFromString(bufferOrString);
73
- }
74
- const reader = this.getParseNode(contentType, bufferOrString, factory);
75
- return reader.getObjectValue(factory);
76
- }
77
- /**
78
- * Deserializes a buffer into a parsable object
79
- * @param contentType the content type to serialize to
80
- * @param buffer the value to deserialize
81
- * @param factory the factory for the model type
82
- * @returns the deserialized parsable object
83
- */
84
- getParseNode(contentType, buffer, factory) {
85
- if (!contentType) {
86
- throw new Error("content type cannot be undefined or empty");
87
- }
88
- if (!buffer) {
89
- throw new Error("buffer cannot be undefined");
90
- }
91
- if (!factory) {
92
- throw new Error("factory cannot be undefined");
93
- }
94
- return this.getRootParseNode(contentType, buffer);
95
- }
96
- /**
97
- * Deserializes a buffer into a collection of parsable object
98
- * @param contentType the content type to serialize to
99
- * @param bufferOrString the value to serialize
100
- * @param factory the factory for the model type
101
- * @returns the deserialized collection of parsable objects
102
- */
103
- deserializeCollection(contentType, bufferOrString, factory) {
104
- if (typeof bufferOrString === "string") {
105
- bufferOrString = this.getBufferFromString(bufferOrString);
106
- }
107
- const reader = this.getParseNode(contentType, bufferOrString, factory);
108
- return reader.getCollectionOfObjectValues(factory);
109
- }
110
- /**
111
- * Deserializes a buffer into a a collection of parsable object
112
- * @param value the string to get a buffer from
113
- * @returns the ArrayBuffer representation of the string
114
- */
115
- getBufferFromString(value) {
116
- const encoder = new TextEncoder();
117
- return encoder.encode(value).buffer;
118
- }
119
- }
120
- class ParseNodeProxyFactory {
121
- getValidContentType() {
122
- return this._concrete.getValidContentType();
123
- }
124
- /**
125
- * Creates a new proxy factory that wraps the specified concrete factory while composing the before and after callbacks.
126
- * @param _concrete the concrete factory to wrap
127
- * @param _onBefore the callback to invoke before the deserialization of any model object.
128
- * @param _onAfter the callback to invoke after the deserialization of any model object.
129
- */
130
- constructor(_concrete, _onBefore, _onAfter) {
131
- this._concrete = _concrete;
132
- this._onBefore = _onBefore;
133
- this._onAfter = _onAfter;
134
- if (!_concrete) {
135
- throw new Error("_concrete cannot be undefined");
136
- }
137
- }
138
- getRootParseNode(contentType, content) {
139
- const node = this._concrete.getRootParseNode(contentType, content);
140
- const originalBefore = node.onBeforeAssignFieldValues;
141
- const originalAfter = node.onAfterAssignFieldValues;
142
- node.onBeforeAssignFieldValues = (value) => {
143
- if (this._onBefore)
144
- this._onBefore(value);
145
- if (originalBefore)
146
- originalBefore(value);
147
- };
148
- node.onAfterAssignFieldValues = (value) => {
149
- if (this._onAfter)
150
- this._onAfter(value);
151
- if (originalAfter)
152
- originalAfter(value);
153
- };
154
- return node;
155
- }
156
- }
157
- class SerializationWriterFactoryRegistry {
158
- constructor() {
159
- this.jsonContentType = "application/json";
160
- this.contentTypeAssociatedFactories = /* @__PURE__ */ new Map();
161
- }
162
- getValidContentType() {
163
- throw new Error("The registry supports multiple content types. Get the registered factory instead.");
164
- }
165
- getSerializationWriter(contentType) {
166
- if (!contentType) {
167
- throw new Error("content type cannot be undefined or empty");
168
- }
169
- const vendorSpecificContentType = contentType.split(";")[0];
170
- let factory = this.contentTypeAssociatedFactories.get(vendorSpecificContentType);
171
- if (factory) {
172
- return factory.getSerializationWriter(vendorSpecificContentType);
173
- }
174
- const cleanedContentType = vendorSpecificContentType.replace(/[^/]+\+/gi, "");
175
- factory = this.contentTypeAssociatedFactories.get(cleanedContentType);
176
- if (factory) {
177
- return factory.getSerializationWriter(cleanedContentType);
178
- }
179
- throw new Error(`Content type ${cleanedContentType} does not have a factory registered to be serialized`);
180
- }
181
- /**
182
- * Registers the default serializer to the registry.
183
- * @param type the class of the factory to be registered.
184
- */
185
- registerDefaultSerializer(type) {
186
- if (!type)
187
- throw new Error("Type is required");
188
- const serializer = new type();
189
- this.contentTypeAssociatedFactories.set(serializer.getValidContentType(), serializer);
190
- }
191
- /**
192
- * Serializes a parsable object into a buffer
193
- * @param value the value to serialize
194
- * @param serializationFunction the serialization function for the model type
195
- * @returns a buffer containing the serialized value
196
- */
197
- serializeToJson(value, serializationFunction) {
198
- return this.serialize(this.jsonContentType, value, serializationFunction);
199
- }
200
- /**
201
- * Serializes a parsable object into a string representation
202
- * @param value the value to serialize
203
- * @param serializationFunction the serialization function for the model type
204
- * @returns a string representing the serialized value
205
- */
206
- serializeToJsonAsString(value, serializationFunction) {
207
- return this.serializeToString(this.jsonContentType, value, serializationFunction);
208
- }
209
- /**
210
- * Serializes a collection of parsable objects into a buffer
211
- * @param values the value to serialize
212
- * @param serializationFunction the serialization function for the model type
213
- * @returns a string representing the serialized value
214
- */
215
- serializeCollectionToJson(values, serializationFunction) {
216
- return this.serializeCollection(this.jsonContentType, values, serializationFunction);
217
- }
218
- /**
219
- * Serializes a collection of parsable objects into a string representation
220
- * @param values the value to serialize
221
- * @param serializationFunction the serialization function for the model type
222
- * @returns a string representing the serialized value
223
- */
224
- serializeCollectionToJsonAsString(values, serializationFunction) {
225
- return this.serializeCollectionToString(this.jsonContentType, values, serializationFunction);
226
- }
227
- /**
228
- * Serializes a parsable object into a buffer
229
- * @param contentType the content type to serialize to
230
- * @param value the value to serialize
231
- * @param serializationFunction the serialization function for the model type
232
- * @returns a buffer containing the serialized value
233
- */
234
- serialize(contentType, value, serializationFunction) {
235
- const writer = this.getSerializationFactoryWriter(contentType, value, serializationFunction);
236
- writer.writeObjectValue(void 0, value, serializationFunction);
237
- return writer.getSerializedContent();
238
- }
239
- /**
240
- * Serializes a parsable object into a string representation
241
- * @param contentType the content type to serialize to
242
- * @param value the value to serialize
243
- * @param serializationFunction the serialization function for the model type
244
- * @returns a string representing the serialized value
245
- */
246
- serializeToString(contentType, value, serializationFunction) {
247
- const buffer = this.serialize(contentType, value, serializationFunction);
248
- return this.getStringValueFromBuffer(buffer);
249
- }
250
- /**
251
- * Serializes a collection of parsable objects into a buffer
252
- * @param contentType the content type to serialize to
253
- * @param values the value to serialize
254
- * @param serializationFunction the serialization function for the model type
255
- * @returns a string representing the serialized value
256
- */
257
- serializeCollection(contentType, values, serializationFunction) {
258
- const writer = this.getSerializationFactoryWriter(contentType, values, serializationFunction);
259
- writer.writeCollectionOfObjectValues(void 0, values, serializationFunction);
260
- return writer.getSerializedContent();
261
- }
262
- /**
263
- * Serializes a collection of parsable objects into a string representation
264
- * @param contentType the content type to serialize to
265
- * @param values the value to serialize
266
- * @param serializationFunction the serialization function for the model type
267
- * @returns a string representing the serialized value
268
- */
269
- serializeCollectionToString(contentType, values, serializationFunction) {
270
- const buffer = this.serializeCollection(contentType, values, serializationFunction);
271
- return this.getStringValueFromBuffer(buffer);
272
- }
273
- /**
274
- * Gets a serialization writer for a given content type
275
- * @param contentType the content type to serialize to
276
- * @param value the value to serialize
277
- * @param serializationFunction the serialization function for the model type
278
- * @returns the serialization writer for the given content type
279
- */
280
- getSerializationFactoryWriter(contentType, value, serializationFunction) {
281
- if (!contentType) {
282
- throw new Error("content type cannot be undefined or empty");
283
- }
284
- if (!value) {
285
- throw new Error("value cannot be undefined");
286
- }
287
- if (!serializationFunction) {
288
- throw new Error("serializationFunction cannot be undefined");
289
- }
290
- return this.getSerializationWriter(contentType);
291
- }
292
- /**
293
- * Gets a string value from a buffer
294
- * @param buffer the buffer to get a string from
295
- * @returns the string representation of the buffer
296
- */
297
- getStringValueFromBuffer(buffer) {
298
- const decoder = new TextDecoder();
299
- return decoder.decode(buffer);
300
- }
301
- }
302
- class SerializationWriterProxyFactory {
303
- getValidContentType() {
304
- return this._concrete.getValidContentType();
305
- }
306
- /**
307
- * Creates a new proxy factory that wraps the specified concrete factory while composing the before and after callbacks.
308
- * @param _concrete the concrete factory to wrap
309
- * @param _onBefore the callback to invoke before the serialization of any model object.
310
- * @param _onAfter the callback to invoke after the serialization of any model object.
311
- * @param _onStart the callback to invoke when the serialization of a model object starts
312
- */
313
- constructor(_concrete, _onBefore, _onAfter, _onStart) {
314
- this._concrete = _concrete;
315
- this._onBefore = _onBefore;
316
- this._onAfter = _onAfter;
317
- this._onStart = _onStart;
318
- if (!_concrete) {
319
- throw new Error("_concrete cannot be undefined");
320
- }
321
- }
322
- getSerializationWriter(contentType) {
323
- const writer = this._concrete.getSerializationWriter(contentType);
324
- const originalBefore = writer.onBeforeObjectSerialization;
325
- const originalAfter = writer.onAfterObjectSerialization;
326
- const originalStart = writer.onStartObjectSerialization;
327
- writer.onBeforeObjectSerialization = (value) => {
328
- if (this._onBefore)
329
- this._onBefore(value);
330
- if (originalBefore)
331
- originalBefore(value);
332
- };
333
- writer.onAfterObjectSerialization = (value) => {
334
- if (this._onAfter)
335
- this._onAfter(value);
336
- if (originalAfter)
337
- originalAfter(value);
338
- };
339
- writer.onStartObjectSerialization = (value, writer_) => {
340
- if (this._onStart)
341
- this._onStart(value, writer_);
342
- if (originalStart)
343
- originalStart(value, writer_);
344
- };
345
- return writer;
346
- }
347
- }
348
- class BackingStoreParseNodeFactory extends ParseNodeProxyFactory {
349
- /**
350
- * Initializes a new instance of the BackingStoreParseNodeFactory class given the concrete implementation.
351
- * @param concrete the concrete implementation of the ParseNodeFactory
352
- */
353
- constructor(concrete) {
354
- super(concrete, (value) => {
355
- const backedModel = value;
356
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
357
- backedModel.backingStore.initializationCompleted = false;
358
- }
359
- }, (value) => {
360
- const backedModel = value;
361
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
362
- backedModel.backingStore.initializationCompleted = true;
363
- }
364
- });
365
- }
366
- }
367
- class BackingStoreSerializationWriterProxyFactory extends SerializationWriterProxyFactory {
368
- /**
369
- * Initializes a new instance of the BackingStoreSerializationWriterProxyFactory class given a concrete implementation of SerializationWriterFactory.
370
- * @param concrete a concrete implementation of SerializationWriterFactory to wrap.
371
- */
372
- constructor(concrete) {
373
- super(concrete, (value) => {
374
- const backedModel = value;
375
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
376
- backedModel.backingStore.returnOnlyChangedValues = true;
377
- }
378
- }, (value) => {
379
- const backedModel = value;
380
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
381
- backedModel.backingStore.returnOnlyChangedValues = false;
382
- backedModel.backingStore.initializationCompleted = true;
383
- }
384
- }, (value, writer) => {
385
- const backedModel = value;
386
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
387
- const keys = backedModel.backingStore.enumerateKeysForValuesChangedToNull();
388
- for (const key of keys) {
389
- writer.writeNullValue(key);
390
- }
391
- }
392
- });
393
- }
394
- }
395
- const createGuid = () => [gen(2), gen(1), gen(1), gen(1), gen(3)].join("-");
396
- const gen = (count) => {
397
- let out = "";
398
- for (let i = 0; i < count; i++) {
399
- out += ((1 + Math.random()) * 65536 | 0).toString(16).substring(1);
400
- }
401
- return out;
402
- };
403
- const inNodeEnv = () => {
404
- try {
405
- return !!Buffer && !!process;
406
- } catch (err) {
407
- return !(err instanceof ReferenceError);
408
- }
409
- };
410
- class InMemoryBackingStore {
411
- constructor() {
412
- this.subscriptions = /* @__PURE__ */ new Map();
413
- this.store = /* @__PURE__ */ new Map();
414
- this.returnOnlyChangedValues = false;
415
- this._initializationCompleted = true;
416
- }
417
- get(key) {
418
- const wrapper = this.store.get(key);
419
- if (wrapper && (this.returnOnlyChangedValues && wrapper.changed || !this.returnOnlyChangedValues)) {
420
- return wrapper.value;
421
- }
422
- return void 0;
423
- }
424
- set(key, value) {
425
- const oldValueWrapper = this.store.get(key);
426
- const oldValue = oldValueWrapper === null || oldValueWrapper === void 0 ? void 0 : oldValueWrapper.value;
427
- if (oldValueWrapper) {
428
- oldValueWrapper.value = value;
429
- oldValueWrapper.changed = this.initializationCompleted;
430
- } else {
431
- this.store.set(key, {
432
- changed: this.initializationCompleted,
433
- value
434
- });
435
- }
436
- this.subscriptions.forEach((sub) => {
437
- sub(key, oldValue, value);
438
- });
439
- }
440
- enumerate() {
441
- let filterableArray = [...this.store.entries()];
442
- if (this.returnOnlyChangedValues) {
443
- filterableArray = filterableArray.filter(([_, v]) => v.changed);
444
- }
445
- return filterableArray.map(([key, value]) => {
446
- return { key, value };
447
- });
448
- }
449
- enumerateKeysForValuesChangedToNull() {
450
- const keys = [];
451
- for (const [key, entry] of this.store) {
452
- if (entry.changed && !entry.value) {
453
- keys.push(key);
454
- }
455
- }
456
- return keys;
457
- }
458
- subscribe(callback, subscriptionId) {
459
- if (!callback) {
460
- throw new Error("callback cannot be undefined");
461
- }
462
- subscriptionId = subscriptionId !== null && subscriptionId !== void 0 ? subscriptionId : createGuid();
463
- this.subscriptions.set(subscriptionId, callback);
464
- return subscriptionId;
465
- }
466
- unsubscribe(subscriptionId) {
467
- this.subscriptions.delete(subscriptionId);
468
- }
469
- clear() {
470
- this.store.clear();
471
- }
472
- set initializationCompleted(value) {
473
- this._initializationCompleted = value;
474
- this.store.forEach((v) => {
475
- v.changed = !value;
476
- });
477
- }
478
- get initializationCompleted() {
479
- return this._initializationCompleted;
480
- }
481
- }
482
- class InMemoryBackingStoreFactory {
483
- createBackingStore() {
484
- return new InMemoryBackingStore();
485
- }
486
- }
487
- function enableBackingStoreForSerializationWriterFactory(serializationWriterFactoryRegistry, parseNodeFactoryRegistry, original) {
488
- if (!original)
489
- throw new Error("Original must be specified");
490
- let result = original;
491
- if (original instanceof SerializationWriterFactoryRegistry) {
492
- enableBackingStoreForSerializationRegistry(original);
493
- } else {
494
- result = new BackingStoreSerializationWriterProxyFactory(original);
495
- }
496
- enableBackingStoreForSerializationRegistry(serializationWriterFactoryRegistry);
497
- enableBackingStoreForParseNodeRegistry(parseNodeFactoryRegistry);
498
- return result;
499
- }
500
- function enableBackingStoreForParseNodeFactory(parseNodeFactoryRegistry, original) {
501
- if (!original)
502
- throw new Error("Original must be specified");
503
- let result = original;
504
- if (original instanceof ParseNodeFactoryRegistry) {
505
- enableBackingStoreForParseNodeRegistry(original);
506
- } else {
507
- result = new BackingStoreParseNodeFactory(original);
508
- }
509
- enableBackingStoreForParseNodeRegistry(parseNodeFactoryRegistry);
510
- return result;
511
- }
512
- function enableBackingStoreForParseNodeRegistry(registry) {
513
- for (const [k, v] of registry.contentTypeAssociatedFactories) {
514
- if (!(v instanceof BackingStoreParseNodeFactory || v instanceof ParseNodeFactoryRegistry)) {
515
- registry.contentTypeAssociatedFactories.set(k, new BackingStoreParseNodeFactory(v));
516
- }
517
- }
518
- }
519
- function enableBackingStoreForSerializationRegistry(registry) {
520
- for (const [k, v] of registry.contentTypeAssociatedFactories) {
521
- if (!(v instanceof BackingStoreSerializationWriterProxyFactory || v instanceof SerializationWriterFactoryRegistry)) {
522
- registry.contentTypeAssociatedFactories.set(k, new BackingStoreSerializationWriterProxyFactory(v));
523
- }
524
- }
525
- }
526
- var _globalThis = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {};
527
- var VERSION = "1.9.0";
528
- var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
529
- function _makeCompatibilityCheck(ownVersion) {
530
- var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
531
- var rejectedVersions = /* @__PURE__ */ new Set();
532
- var myVersionMatch = ownVersion.match(re);
533
- if (!myVersionMatch) {
534
- return function() {
535
- return false;
536
- };
537
- }
538
- var ownVersionParsed = {
539
- major: +myVersionMatch[1],
540
- minor: +myVersionMatch[2],
541
- patch: +myVersionMatch[3],
542
- prerelease: myVersionMatch[4]
543
- };
544
- if (ownVersionParsed.prerelease != null) {
545
- return function isExactmatch(globalVersion) {
546
- return globalVersion === ownVersion;
547
- };
548
- }
549
- function _reject(v) {
550
- rejectedVersions.add(v);
551
- return false;
552
- }
553
- function _accept(v) {
554
- acceptedVersions.add(v);
555
- return true;
556
- }
557
- return function isCompatible2(globalVersion) {
558
- if (acceptedVersions.has(globalVersion)) {
559
- return true;
560
- }
561
- if (rejectedVersions.has(globalVersion)) {
562
- return false;
563
- }
564
- var globalVersionMatch = globalVersion.match(re);
565
- if (!globalVersionMatch) {
566
- return _reject(globalVersion);
567
- }
568
- var globalVersionParsed = {
569
- major: +globalVersionMatch[1],
570
- minor: +globalVersionMatch[2],
571
- patch: +globalVersionMatch[3],
572
- prerelease: globalVersionMatch[4]
573
- };
574
- if (globalVersionParsed.prerelease != null) {
575
- return _reject(globalVersion);
576
- }
577
- if (ownVersionParsed.major !== globalVersionParsed.major) {
578
- return _reject(globalVersion);
579
- }
580
- if (ownVersionParsed.major === 0) {
581
- if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
582
- return _accept(globalVersion);
583
- }
584
- return _reject(globalVersion);
585
- }
586
- if (ownVersionParsed.minor <= globalVersionParsed.minor) {
587
- return _accept(globalVersion);
588
- }
589
- return _reject(globalVersion);
590
- };
591
- }
592
- var isCompatible = _makeCompatibilityCheck(VERSION);
593
- var major = VERSION.split(".")[0];
594
- var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
595
- var _global = _globalThis;
596
- function registerGlobal(type, instance, diag, allowOverride) {
597
- var _a;
598
- if (allowOverride === void 0) {
599
- allowOverride = false;
600
- }
601
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
602
- version: VERSION
603
- };
604
- if (!allowOverride && api[type]) {
605
- var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
606
- diag.error(err.stack || err.message);
607
- return false;
608
- }
609
- if (api.version !== VERSION) {
610
- var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
611
- diag.error(err.stack || err.message);
612
- return false;
613
- }
614
- api[type] = instance;
615
- diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
616
- return true;
617
- }
618
- function getGlobal(type) {
619
- var _a, _b;
620
- var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
621
- if (!globalVersion || !isCompatible(globalVersion)) {
622
- return;
623
- }
624
- return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
625
- }
626
- function unregisterGlobal(type, diag) {
627
- diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
628
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
629
- if (api) {
630
- delete api[type];
631
- }
632
- }
633
- var __read$3 = function(o, n) {
634
- var m = typeof Symbol === "function" && o[Symbol.iterator];
635
- if (!m) return o;
636
- var i = m.call(o), r, ar = [], e;
637
- try {
638
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
639
- } catch (error) {
640
- e = { error };
641
- } finally {
642
- try {
643
- if (r && !r.done && (m = i["return"])) m.call(i);
644
- } finally {
645
- if (e) throw e.error;
646
- }
647
- }
648
- return ar;
649
- };
650
- var __spreadArray$3 = function(to, from, pack) {
651
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
652
- if (ar || !(i in from)) {
653
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
654
- ar[i] = from[i];
655
- }
656
- }
657
- return to.concat(ar || Array.prototype.slice.call(from));
658
- };
659
- var DiagComponentLogger = (
660
- /** @class */
661
- (function() {
662
- function DiagComponentLogger2(props) {
663
- this._namespace = props.namespace || "DiagComponentLogger";
664
- }
665
- DiagComponentLogger2.prototype.debug = function() {
666
- var args = [];
667
- for (var _i = 0; _i < arguments.length; _i++) {
668
- args[_i] = arguments[_i];
669
- }
670
- return logProxy("debug", this._namespace, args);
671
- };
672
- DiagComponentLogger2.prototype.error = function() {
673
- var args = [];
674
- for (var _i = 0; _i < arguments.length; _i++) {
675
- args[_i] = arguments[_i];
676
- }
677
- return logProxy("error", this._namespace, args);
678
- };
679
- DiagComponentLogger2.prototype.info = function() {
680
- var args = [];
681
- for (var _i = 0; _i < arguments.length; _i++) {
682
- args[_i] = arguments[_i];
683
- }
684
- return logProxy("info", this._namespace, args);
685
- };
686
- DiagComponentLogger2.prototype.warn = function() {
687
- var args = [];
688
- for (var _i = 0; _i < arguments.length; _i++) {
689
- args[_i] = arguments[_i];
690
- }
691
- return logProxy("warn", this._namespace, args);
692
- };
693
- DiagComponentLogger2.prototype.verbose = function() {
694
- var args = [];
695
- for (var _i = 0; _i < arguments.length; _i++) {
696
- args[_i] = arguments[_i];
697
- }
698
- return logProxy("verbose", this._namespace, args);
699
- };
700
- return DiagComponentLogger2;
701
- })()
702
- );
703
- function logProxy(funcName, namespace, args) {
704
- var logger = getGlobal("diag");
705
- if (!logger) {
706
- return;
707
- }
708
- args.unshift(namespace);
709
- return logger[funcName].apply(logger, __spreadArray$3([], __read$3(args), false));
710
- }
711
- var DiagLogLevel;
712
- (function(DiagLogLevel2) {
713
- DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
714
- DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
715
- DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
716
- DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
717
- DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
718
- DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
719
- DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
720
- })(DiagLogLevel || (DiagLogLevel = {}));
721
- function createLogLevelDiagLogger(maxLevel, logger) {
722
- if (maxLevel < DiagLogLevel.NONE) {
723
- maxLevel = DiagLogLevel.NONE;
724
- } else if (maxLevel > DiagLogLevel.ALL) {
725
- maxLevel = DiagLogLevel.ALL;
726
- }
727
- logger = logger || {};
728
- function _filterFunc(funcName, theLevel) {
729
- var theFunc = logger[funcName];
730
- if (typeof theFunc === "function" && maxLevel >= theLevel) {
731
- return theFunc.bind(logger);
732
- }
733
- return function() {
734
- };
735
- }
736
- return {
737
- error: _filterFunc("error", DiagLogLevel.ERROR),
738
- warn: _filterFunc("warn", DiagLogLevel.WARN),
739
- info: _filterFunc("info", DiagLogLevel.INFO),
740
- debug: _filterFunc("debug", DiagLogLevel.DEBUG),
741
- verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
742
- };
743
- }
744
- var __read$2 = function(o, n) {
745
- var m = typeof Symbol === "function" && o[Symbol.iterator];
746
- if (!m) return o;
747
- var i = m.call(o), r, ar = [], e;
748
- try {
749
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
750
- } catch (error) {
751
- e = { error };
752
- } finally {
753
- try {
754
- if (r && !r.done && (m = i["return"])) m.call(i);
755
- } finally {
756
- if (e) throw e.error;
757
- }
758
- }
759
- return ar;
760
- };
761
- var __spreadArray$2 = function(to, from, pack) {
762
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
763
- if (ar || !(i in from)) {
764
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
765
- ar[i] = from[i];
766
- }
767
- }
768
- return to.concat(ar || Array.prototype.slice.call(from));
769
- };
770
- var API_NAME$2 = "diag";
771
- var DiagAPI = (
772
- /** @class */
773
- (function() {
774
- function DiagAPI2() {
775
- function _logProxy(funcName) {
776
- return function() {
777
- var args = [];
778
- for (var _i = 0; _i < arguments.length; _i++) {
779
- args[_i] = arguments[_i];
780
- }
781
- var logger = getGlobal("diag");
782
- if (!logger)
783
- return;
784
- return logger[funcName].apply(logger, __spreadArray$2([], __read$2(args), false));
785
- };
786
- }
787
- var self2 = this;
788
- var setLogger = function(logger, optionsOrLogLevel) {
789
- var _a, _b, _c;
790
- if (optionsOrLogLevel === void 0) {
791
- optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
792
- }
793
- if (logger === self2) {
794
- var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
795
- self2.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
796
- return false;
797
- }
798
- if (typeof optionsOrLogLevel === "number") {
799
- optionsOrLogLevel = {
800
- logLevel: optionsOrLogLevel
801
- };
802
- }
803
- var oldLogger = getGlobal("diag");
804
- var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
805
- if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
806
- var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
807
- oldLogger.warn("Current logger will be overwritten from " + stack);
808
- newLogger.warn("Current logger will overwrite one already registered from " + stack);
809
- }
810
- return registerGlobal("diag", newLogger, self2, true);
811
- };
812
- self2.setLogger = setLogger;
813
- self2.disable = function() {
814
- unregisterGlobal(API_NAME$2, self2);
815
- };
816
- self2.createComponentLogger = function(options) {
817
- return new DiagComponentLogger(options);
818
- };
819
- self2.verbose = _logProxy("verbose");
820
- self2.debug = _logProxy("debug");
821
- self2.info = _logProxy("info");
822
- self2.warn = _logProxy("warn");
823
- self2.error = _logProxy("error");
824
- }
825
- DiagAPI2.instance = function() {
826
- if (!this._instance) {
827
- this._instance = new DiagAPI2();
828
- }
829
- return this._instance;
830
- };
831
- return DiagAPI2;
832
- })()
833
- );
834
- function createContextKey(description) {
835
- return Symbol.for(description);
836
- }
837
- var BaseContext = (
838
- /** @class */
839
- /* @__PURE__ */ (function() {
840
- function BaseContext2(parentContext) {
841
- var self2 = this;
842
- self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
843
- self2.getValue = function(key) {
844
- return self2._currentContext.get(key);
845
- };
846
- self2.setValue = function(key, value) {
847
- var context = new BaseContext2(self2._currentContext);
848
- context._currentContext.set(key, value);
849
- return context;
850
- };
851
- self2.deleteValue = function(key) {
852
- var context = new BaseContext2(self2._currentContext);
853
- context._currentContext.delete(key);
854
- return context;
855
- };
856
- }
857
- return BaseContext2;
858
- })()
859
- );
860
- var ROOT_CONTEXT = new BaseContext();
861
- var __read$1 = function(o, n) {
862
- var m = typeof Symbol === "function" && o[Symbol.iterator];
863
- if (!m) return o;
864
- var i = m.call(o), r, ar = [], e;
865
- try {
866
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
867
- } catch (error) {
868
- e = { error };
869
- } finally {
870
- try {
871
- if (r && !r.done && (m = i["return"])) m.call(i);
872
- } finally {
873
- if (e) throw e.error;
874
- }
875
- }
876
- return ar;
877
- };
878
- var __spreadArray$1 = function(to, from, pack) {
879
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
880
- if (ar || !(i in from)) {
881
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
882
- ar[i] = from[i];
883
- }
884
- }
885
- return to.concat(ar || Array.prototype.slice.call(from));
886
- };
887
- var NoopContextManager = (
888
- /** @class */
889
- (function() {
890
- function NoopContextManager2() {
891
- }
892
- NoopContextManager2.prototype.active = function() {
893
- return ROOT_CONTEXT;
894
- };
895
- NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
896
- var args = [];
897
- for (var _i = 3; _i < arguments.length; _i++) {
898
- args[_i - 3] = arguments[_i];
899
- }
900
- return fn.call.apply(fn, __spreadArray$1([thisArg], __read$1(args), false));
901
- };
902
- NoopContextManager2.prototype.bind = function(_context, target) {
903
- return target;
904
- };
905
- NoopContextManager2.prototype.enable = function() {
906
- return this;
907
- };
908
- NoopContextManager2.prototype.disable = function() {
909
- return this;
910
- };
911
- return NoopContextManager2;
912
- })()
913
- );
914
- var __read = function(o, n) {
915
- var m = typeof Symbol === "function" && o[Symbol.iterator];
916
- if (!m) return o;
917
- var i = m.call(o), r, ar = [], e;
918
- try {
919
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
920
- } catch (error) {
921
- e = { error };
922
- } finally {
923
- try {
924
- if (r && !r.done && (m = i["return"])) m.call(i);
925
- } finally {
926
- if (e) throw e.error;
927
- }
928
- }
929
- return ar;
930
- };
931
- var __spreadArray = function(to, from, pack) {
932
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
933
- if (ar || !(i in from)) {
934
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
935
- ar[i] = from[i];
936
- }
937
- }
938
- return to.concat(ar || Array.prototype.slice.call(from));
939
- };
940
- var API_NAME$1 = "context";
941
- var NOOP_CONTEXT_MANAGER = new NoopContextManager();
942
- var ContextAPI = (
943
- /** @class */
944
- (function() {
945
- function ContextAPI2() {
946
- }
947
- ContextAPI2.getInstance = function() {
948
- if (!this._instance) {
949
- this._instance = new ContextAPI2();
950
- }
951
- return this._instance;
952
- };
953
- ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
954
- return registerGlobal(API_NAME$1, contextManager, DiagAPI.instance());
955
- };
956
- ContextAPI2.prototype.active = function() {
957
- return this._getContextManager().active();
958
- };
959
- ContextAPI2.prototype.with = function(context, fn, thisArg) {
960
- var _a;
961
- var args = [];
962
- for (var _i = 3; _i < arguments.length; _i++) {
963
- args[_i - 3] = arguments[_i];
964
- }
965
- return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], __read(args), false));
966
- };
967
- ContextAPI2.prototype.bind = function(context, target) {
968
- return this._getContextManager().bind(context, target);
969
- };
970
- ContextAPI2.prototype._getContextManager = function() {
971
- return getGlobal(API_NAME$1) || NOOP_CONTEXT_MANAGER;
972
- };
973
- ContextAPI2.prototype.disable = function() {
974
- this._getContextManager().disable();
975
- unregisterGlobal(API_NAME$1, DiagAPI.instance());
976
- };
977
- return ContextAPI2;
978
- })()
979
- );
980
- var TraceFlags;
981
- (function(TraceFlags2) {
982
- TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
983
- TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
984
- })(TraceFlags || (TraceFlags = {}));
985
- var INVALID_SPANID = "0000000000000000";
986
- var INVALID_TRACEID = "00000000000000000000000000000000";
987
- var INVALID_SPAN_CONTEXT = {
988
- traceId: INVALID_TRACEID,
989
- spanId: INVALID_SPANID,
990
- traceFlags: TraceFlags.NONE
991
- };
992
- var NonRecordingSpan = (
993
- /** @class */
994
- (function() {
995
- function NonRecordingSpan2(_spanContext) {
996
- if (_spanContext === void 0) {
997
- _spanContext = INVALID_SPAN_CONTEXT;
998
- }
999
- this._spanContext = _spanContext;
1000
- }
1001
- NonRecordingSpan2.prototype.spanContext = function() {
1002
- return this._spanContext;
1003
- };
1004
- NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
1005
- return this;
1006
- };
1007
- NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
1008
- return this;
1009
- };
1010
- NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
1011
- return this;
1012
- };
1013
- NonRecordingSpan2.prototype.addLink = function(_link) {
1014
- return this;
1015
- };
1016
- NonRecordingSpan2.prototype.addLinks = function(_links) {
1017
- return this;
1018
- };
1019
- NonRecordingSpan2.prototype.setStatus = function(_status) {
1020
- return this;
1021
- };
1022
- NonRecordingSpan2.prototype.updateName = function(_name) {
1023
- return this;
1024
- };
1025
- NonRecordingSpan2.prototype.end = function(_endTime) {
1026
- };
1027
- NonRecordingSpan2.prototype.isRecording = function() {
1028
- return false;
1029
- };
1030
- NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
1031
- };
1032
- return NonRecordingSpan2;
1033
- })()
1034
- );
1035
- var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
1036
- function getSpan(context) {
1037
- return context.getValue(SPAN_KEY) || void 0;
1038
- }
1039
- function getActiveSpan() {
1040
- return getSpan(ContextAPI.getInstance().active());
1041
- }
1042
- function setSpan(context, span) {
1043
- return context.setValue(SPAN_KEY, span);
1044
- }
1045
- function deleteSpan(context) {
1046
- return context.deleteValue(SPAN_KEY);
1047
- }
1048
- function setSpanContext(context, spanContext) {
1049
- return setSpan(context, new NonRecordingSpan(spanContext));
1050
- }
1051
- function getSpanContext(context) {
1052
- var _a;
1053
- return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();
1054
- }
1055
- var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
1056
- var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
1057
- function isValidTraceId(traceId) {
1058
- return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
1059
- }
1060
- function isValidSpanId(spanId) {
1061
- return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
1062
- }
1063
- function isSpanContextValid(spanContext) {
1064
- return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
1065
- }
1066
- function wrapSpanContext(spanContext) {
1067
- return new NonRecordingSpan(spanContext);
1068
- }
1069
- var contextApi = ContextAPI.getInstance();
1070
- var NoopTracer = (
1071
- /** @class */
1072
- (function() {
1073
- function NoopTracer2() {
1074
- }
1075
- NoopTracer2.prototype.startSpan = function(name, options, context) {
1076
- if (context === void 0) {
1077
- context = contextApi.active();
1078
- }
1079
- var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
1080
- if (root) {
1081
- return new NonRecordingSpan();
1082
- }
1083
- var parentFromContext = context && getSpanContext(context);
1084
- if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
1085
- return new NonRecordingSpan(parentFromContext);
1086
- } else {
1087
- return new NonRecordingSpan();
1088
- }
1089
- };
1090
- NoopTracer2.prototype.startActiveSpan = function(name, arg2, arg3, arg4) {
1091
- var opts;
1092
- var ctx;
1093
- var fn;
1094
- if (arguments.length < 2) {
1095
- return;
1096
- } else if (arguments.length === 2) {
1097
- fn = arg2;
1098
- } else if (arguments.length === 3) {
1099
- opts = arg2;
1100
- fn = arg3;
1101
- } else {
1102
- opts = arg2;
1103
- ctx = arg3;
1104
- fn = arg4;
1105
- }
1106
- var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
1107
- var span = this.startSpan(name, opts, parentContext);
1108
- var contextWithSpanSet = setSpan(parentContext, span);
1109
- return contextApi.with(contextWithSpanSet, fn, void 0, span);
1110
- };
1111
- return NoopTracer2;
1112
- })()
1113
- );
1114
- function isSpanContext(spanContext) {
1115
- return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
1116
- }
1117
- var NOOP_TRACER = new NoopTracer();
1118
- var ProxyTracer = (
1119
- /** @class */
1120
- (function() {
1121
- function ProxyTracer2(_provider, name, version, options) {
1122
- this._provider = _provider;
1123
- this.name = name;
1124
- this.version = version;
1125
- this.options = options;
1126
- }
1127
- ProxyTracer2.prototype.startSpan = function(name, options, context) {
1128
- return this._getTracer().startSpan(name, options, context);
1129
- };
1130
- ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
1131
- var tracer = this._getTracer();
1132
- return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
1133
- };
1134
- ProxyTracer2.prototype._getTracer = function() {
1135
- if (this._delegate) {
1136
- return this._delegate;
1137
- }
1138
- var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
1139
- if (!tracer) {
1140
- return NOOP_TRACER;
1141
- }
1142
- this._delegate = tracer;
1143
- return this._delegate;
1144
- };
1145
- return ProxyTracer2;
1146
- })()
1147
- );
1148
- var NoopTracerProvider = (
1149
- /** @class */
1150
- (function() {
1151
- function NoopTracerProvider2() {
1152
- }
1153
- NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
1154
- return new NoopTracer();
1155
- };
1156
- return NoopTracerProvider2;
1157
- })()
1158
- );
1159
- var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
1160
- var ProxyTracerProvider = (
1161
- /** @class */
1162
- (function() {
1163
- function ProxyTracerProvider2() {
1164
- }
1165
- ProxyTracerProvider2.prototype.getTracer = function(name, version, options) {
1166
- var _a;
1167
- return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);
1168
- };
1169
- ProxyTracerProvider2.prototype.getDelegate = function() {
1170
- var _a;
1171
- return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
1172
- };
1173
- ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
1174
- this._delegate = delegate;
1175
- };
1176
- ProxyTracerProvider2.prototype.getDelegateTracer = function(name, version, options) {
1177
- var _a;
1178
- return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
1179
- };
1180
- return ProxyTracerProvider2;
1181
- })()
1182
- );
1183
- var SpanStatusCode;
1184
- (function(SpanStatusCode2) {
1185
- SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
1186
- SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
1187
- SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
1188
- })(SpanStatusCode || (SpanStatusCode = {}));
1189
- var API_NAME = "trace";
1190
- var TraceAPI = (
1191
- /** @class */
1192
- (function() {
1193
- function TraceAPI2() {
1194
- this._proxyTracerProvider = new ProxyTracerProvider();
1195
- this.wrapSpanContext = wrapSpanContext;
1196
- this.isSpanContextValid = isSpanContextValid;
1197
- this.deleteSpan = deleteSpan;
1198
- this.getSpan = getSpan;
1199
- this.getActiveSpan = getActiveSpan;
1200
- this.getSpanContext = getSpanContext;
1201
- this.setSpan = setSpan;
1202
- this.setSpanContext = setSpanContext;
1203
- }
1204
- TraceAPI2.getInstance = function() {
1205
- if (!this._instance) {
1206
- this._instance = new TraceAPI2();
1207
- }
1208
- return this._instance;
1209
- };
1210
- TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
1211
- var success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());
1212
- if (success) {
1213
- this._proxyTracerProvider.setDelegate(provider);
1214
- }
1215
- return success;
1216
- };
1217
- TraceAPI2.prototype.getTracerProvider = function() {
1218
- return getGlobal(API_NAME) || this._proxyTracerProvider;
1219
- };
1220
- TraceAPI2.prototype.getTracer = function(name, version) {
1221
- return this.getTracerProvider().getTracer(name, version);
1222
- };
1223
- TraceAPI2.prototype.disable = function() {
1224
- unregisterGlobal(API_NAME, DiagAPI.instance());
1225
- this._proxyTracerProvider = new ProxyTracerProvider();
1226
- };
1227
- return TraceAPI2;
1228
- })()
1229
- );
1230
- var trace = TraceAPI.getInstance();
1231
- var dist = {};
1232
- var hasRequiredDist;
1233
- function requireDist() {
1234
- if (hasRequiredDist) return dist;
1235
- hasRequiredDist = 1;
1236
- (function(exports) {
1237
- Object.defineProperty(exports, "__esModule", { value: true });
1238
- exports.serialize = exports.parse = exports.MultipleFractionsError = exports.InvalidDurationError = void 0;
1239
- const DEFAULT_PARSE_CONFIG = {
1240
- allowMultipleFractions: true
1241
- };
1242
- const units = [
1243
- { unit: "years", symbol: "Y" },
1244
- { unit: "months", symbol: "M" },
1245
- { unit: "weeks", symbol: "W" },
1246
- { unit: "days", symbol: "D" },
1247
- { unit: "hours", symbol: "H" },
1248
- { unit: "minutes", symbol: "M" },
1249
- { unit: "seconds", symbol: "S" }
1250
- ];
1251
- const r = (name, unit) => `((?<${name}>-?\\d*[\\.,]?\\d+)${unit})?`;
1252
- const durationRegex = new RegExp([
1253
- "(?<negative>-)?P",
1254
- r("years", "Y"),
1255
- r("months", "M"),
1256
- r("weeks", "W"),
1257
- r("days", "D"),
1258
- "(T",
1259
- r("hours", "H"),
1260
- r("minutes", "M"),
1261
- r("seconds", "S"),
1262
- ")?"
1263
- // end optional time
1264
- ].join(""));
1265
- function parseNum(s2) {
1266
- if (s2 === "" || s2 === void 0 || s2 === null) {
1267
- return void 0;
1268
- }
1269
- return parseFloat(s2.replace(",", "."));
1270
- }
1271
- exports.InvalidDurationError = new Error("Invalid duration");
1272
- exports.MultipleFractionsError = new Error("Multiple fractions specified");
1273
- function parse(durationStr, config = DEFAULT_PARSE_CONFIG) {
1274
- const match = durationRegex.exec(durationStr);
1275
- if (!match || !match.groups) {
1276
- throw exports.InvalidDurationError;
1277
- }
1278
- let empty = true;
1279
- let decimalFractionCount = 0;
1280
- const values = {};
1281
- for (const { unit } of units) {
1282
- if (match.groups[unit]) {
1283
- empty = false;
1284
- values[unit] = parseNum(match.groups[unit]);
1285
- if (!config.allowMultipleFractions && !Number.isInteger(values[unit])) {
1286
- decimalFractionCount++;
1287
- if (decimalFractionCount > 1) {
1288
- throw exports.MultipleFractionsError;
1289
- }
1290
- }
1291
- }
1292
- }
1293
- if (empty) {
1294
- throw exports.InvalidDurationError;
1295
- }
1296
- const duration = values;
1297
- if (match.groups.negative) {
1298
- duration.negative = true;
1299
- }
1300
- return duration;
1301
- }
1302
- exports.parse = parse;
1303
- const s = (number, component) => {
1304
- if (!number) {
1305
- return void 0;
1306
- }
1307
- let numberAsString = number.toString();
1308
- const exponentIndex = numberAsString.indexOf("e");
1309
- if (exponentIndex > -1) {
1310
- const magnitude = parseInt(numberAsString.slice(exponentIndex + 2), 10);
1311
- numberAsString = number.toFixed(magnitude + exponentIndex - 2);
1312
- }
1313
- return numberAsString + component;
1314
- };
1315
- function serialize(duration) {
1316
- if (!duration.years && !duration.months && !duration.weeks && !duration.days && !duration.hours && !duration.minutes && !duration.seconds) {
1317
- return "PT0S";
1318
- }
1319
- return [
1320
- duration.negative && "-",
1321
- "P",
1322
- s(duration.years, "Y"),
1323
- s(duration.months, "M"),
1324
- s(duration.weeks, "W"),
1325
- s(duration.days, "D"),
1326
- (duration.hours || duration.minutes || duration.seconds) && "T",
1327
- s(duration.hours, "H"),
1328
- s(duration.minutes, "M"),
1329
- s(duration.seconds, "S")
1330
- ].filter(Boolean).join("");
1331
- }
1332
- exports.serialize = serialize;
1333
- })(dist);
1334
- return dist;
1335
- }
1336
- requireDist();
1337
- function dictionaryWithCanonicalKeys(canon) {
1338
- const keysNormalizationMap = /* @__PURE__ */ new Map();
1339
- return new Proxy({}, {
1340
- /**
1341
- * Intercept the get operation on the dictionary object and forward it to the target object using Reflect.get.
1342
- * @param target The target object.
1343
- * @param prop The property to get.
1344
- * @returns The value of the property.
1345
- */
1346
- get(target, prop) {
1347
- const normalKey = canon(prop);
1348
- return Reflect.get(target, normalKey);
1349
- },
1350
- /**
1351
- * Intercept the set operation on the dictionary object and forward it to the target object using Reflect.set.
1352
- * @param target The target object.
1353
- * @param prop The property to set.
1354
- * @param value The value to set.
1355
- * @returns A boolean indicating whether the property was set.
1356
- */
1357
- set(target, prop, value) {
1358
- const nonNormalKey = prop.toString();
1359
- const normalKey = canon(prop);
1360
- keysNormalizationMap.set(normalKey, nonNormalKey);
1361
- return Reflect.set(target, normalKey, value);
1362
- },
1363
- /**
1364
- * Intercept the has operation on the dictionary object and forward it to the target object using Reflect.has.
1365
- * @param _ the target object.
1366
- * @param prop The property to check.
1367
- * @returns A boolean indicating whether the property exists.
1368
- */
1369
- has(_, prop) {
1370
- const normalKey = canon(prop);
1371
- return keysNormalizationMap.has(normalKey);
1372
- },
1373
- /**
1374
- * Intercept the defineProperty operation on the dictionary object and forward it to the target object using Reflect.defineProperty.
1375
- * @param target The target object.
1376
- * @param prop The property to define.
1377
- * @param attribs The attributes of the property.
1378
- * @returns A boolean indicating whether the property was defined.
1379
- */
1380
- defineProperty(target, prop, attribs) {
1381
- const nonNormalKey = prop.toString();
1382
- const normalKey = canon(prop);
1383
- keysNormalizationMap.set(normalKey, nonNormalKey);
1384
- return Reflect.defineProperty(target, normalKey, attribs);
1385
- },
1386
- /**
1387
- * Intercept the deleteProperty operation on the dictionary object and forward it to the target object using Reflect.deleteProperty.
1388
- * @param target The target object.
1389
- * @param prop The property to delete.
1390
- * @returns A boolean indicating whether the property was deleted.
1391
- */
1392
- deleteProperty(target, prop) {
1393
- const normalKey = canon(prop);
1394
- keysNormalizationMap.delete(normalKey);
1395
- return Reflect.deleteProperty(target, normalKey);
1396
- },
1397
- /**
1398
- * Intercept the getOwnPropertyDescriptor operation on the dictionary object and forward it to the target object using Reflect.getOwnPropertyDescriptor.
1399
- * @param target The target object.
1400
- * @param prop The property to gets its descriptor.
1401
- * @returns The property descriptor.
1402
- */
1403
- getOwnPropertyDescriptor(target, prop) {
1404
- return Reflect.getOwnPropertyDescriptor(target, canon(prop));
1405
- },
1406
- ownKeys() {
1407
- return [...keysNormalizationMap.values()];
1408
- }
1409
- });
1410
- }
1411
- function createRecordWithCaseInsensitiveKeys() {
1412
- const record = dictionaryWithCanonicalKeys((p) => typeof p === "string" ? p.toLowerCase() : p.toString().toLowerCase());
1413
- return record;
1414
- }
1415
- class Headers extends Map {
1416
- /**
1417
- * Creates a new Headers object.
1418
- * @param entries An iterable object that contains key-value pairs. Each key-value pair must be an array with two elements: the key of the header, and the value of the header.
1419
- * @example
1420
- * ```typescript
1421
- * const entries: [string, Set<string>][] = [
1422
- * ['header1', new Set(['value1'])],
1423
- * ['header2', new Set(['value2', 'value3'])]
1424
- * ];
1425
- * const headers = new Headers(entries);
1426
- * ```
1427
- */
1428
- constructor(entries) {
1429
- super();
1430
- this.headers = createRecordWithCaseInsensitiveKeys();
1431
- this.singleValueHeaders = /* @__PURE__ */ new Set(["Content-Type", "Content-Encoding", "Content-Length"]);
1432
- if (entries) {
1433
- entries.forEach(([key, value]) => {
1434
- this.headers[key] = value;
1435
- });
1436
- }
1437
- }
1438
- /**
1439
- * Sets a header with the specified name and value. If a header with the same name already exists, its value is appended with the specified value.
1440
- * @param headerName the name of the header to set
1441
- * @param headerValue the value of the header to set
1442
- * @returns Headers object
1443
- */
1444
- set(headerName, headerValue) {
1445
- this.add(headerName, ...headerValue);
1446
- return this;
1447
- }
1448
- /**
1449
- * Gets the values for the header with the specified name.
1450
- * @param headerName The name of the header to get the values for.
1451
- * @returns The values for the header with the specified name.
1452
- * @throws Error if headerName is null or empty
1453
- */
1454
- get(headerName) {
1455
- if (!headerName) {
1456
- throw new Error("headerName cannot be null or empty");
1457
- }
1458
- return this.headers[headerName];
1459
- }
1460
- /**
1461
- * Checks if a header exists.
1462
- * @param key The name of the header to check for.
1463
- * @returns whether or not a header with the given name/key exists.
1464
- */
1465
- has(key) {
1466
- return !!key && !!this.headers[key];
1467
- }
1468
- /**
1469
- * Delete the header with the specified name.
1470
- * @param headerName The name of the header to delete.
1471
- * @returns Whether or not the header existed and was deleted.
1472
- * @throws Error if headerName is null or empty
1473
- */
1474
- delete(headerName) {
1475
- if (!headerName) {
1476
- throw new Error("headerName cannot be null or empty");
1477
- }
1478
- if (this.headers[headerName]) {
1479
- delete this.headers[headerName];
1480
- return true;
1481
- }
1482
- return false;
1483
- }
1484
- /**
1485
- * clear the headers collection
1486
- */
1487
- clear() {
1488
- for (const header in this.headers) {
1489
- if (Object.prototype.hasOwnProperty.call(this.headers, header)) {
1490
- delete this.headers[header];
1491
- }
1492
- }
1493
- }
1494
- /**
1495
- * execute a provided function once per each header
1496
- * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each header in the dictionary.
1497
- * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
1498
- */
1499
- forEach(callbackfn, thisArg) {
1500
- for (const header in this.headers) {
1501
- if (Object.prototype.hasOwnProperty.call(this.headers, header)) {
1502
- callbackfn.call(thisArg, this.headers[header], header, this);
1503
- }
1504
- }
1505
- }
1506
- /**
1507
- * Adds values to the header with the specified name.
1508
- * @param headerName The name of the header to add values to.
1509
- * @param headerValues The values to add to the header.
1510
- * @returns Whether or not the values were added to the header.
1511
- */
1512
- add(headerName, ...headerValues) {
1513
- if (!headerName) {
1514
- console.error("headerName cannot be null or empty");
1515
- return false;
1516
- }
1517
- if (!headerValues) {
1518
- console.error("headerValues cannot be null");
1519
- return false;
1520
- }
1521
- if (headerValues.length === 0) {
1522
- return false;
1523
- }
1524
- if (this.singleValueHeaders.has(headerName)) {
1525
- this.headers[headerName] = /* @__PURE__ */ new Set([headerValues[0]]);
1526
- } else if (this.headers[headerName]) {
1527
- headerValues.forEach((headerValue) => this.headers[headerName].add(headerValue));
1528
- } else {
1529
- this.headers[headerName] = new Set(headerValues);
1530
- }
1531
- return true;
1532
- }
1533
- /**
1534
- * Adds values to the header with the specified name if it's not already present
1535
- * @param headerName The name of the header to add values to.
1536
- * @param headerValue The values to add to the header.
1537
- * @returns If the headerValue have been added to the Dictionary.
1538
- */
1539
- tryAdd(headerName, headerValue) {
1540
- if (!headerName) {
1541
- throw new Error("headerName cannot be null or empty");
1542
- }
1543
- if (!headerValue) {
1544
- throw new Error("headerValue cannot be null");
1545
- }
1546
- if (!this.headers[headerName]) {
1547
- this.headers[headerName] = /* @__PURE__ */ new Set([headerValue]);
1548
- return true;
1549
- }
1550
- return false;
1551
- }
1552
- /**
1553
- * Removes the specified value from the header with the specified name.
1554
- * @param headerName The name of the header to remove the value from.
1555
- * @param headerValue The value to remove from the header.
1556
- * @returns Whether or not the header existed and was removed.
1557
- * @throws Error if headerName is null or empty
1558
- * @throws Error if headerValue is null
1559
- */
1560
- remove(headerName, headerValue) {
1561
- if (!headerName) {
1562
- throw new Error("headerName cannot be null or empty");
1563
- }
1564
- if (!headerValue) {
1565
- throw new Error("headerValue cannot be null");
1566
- }
1567
- if (this.headers[headerName]) {
1568
- const result = this.headers[headerName].delete(headerValue);
1569
- if (this.headers[headerName].size === 0) {
1570
- delete this.headers[headerName];
1571
- }
1572
- return result;
1573
- }
1574
- return false;
1575
- }
1576
- /**
1577
- * Adds all the headers values from the specified headers collection.
1578
- * @param headers The headers to update the current headers with.
1579
- * @throws Error if headers is null
1580
- */
1581
- addAll(headers) {
1582
- if (!headers) {
1583
- throw new Error("headers cannot be null");
1584
- }
1585
- for (const header in headers.headers) {
1586
- if (Object.prototype.hasOwnProperty.call(headers.headers, header)) {
1587
- headers.headers[header].forEach((value) => this.add(header, value));
1588
- }
1589
- }
1590
- }
1591
- /**
1592
- * Adds all headers from the request configuration value to the current headers collection.
1593
- * Replaces any existing headers with the same key.
1594
- * @param headers The headers to update the current headers with.
1595
- * @throws Error if headers is null
1596
- */
1597
- addAllRaw(headers) {
1598
- if (!headers) {
1599
- throw new Error("headers cannot be null");
1600
- }
1601
- for (const header in headers) {
1602
- if (Object.prototype.hasOwnProperty.call(headers, header)) {
1603
- const headerValues = headers[header];
1604
- if (Array.isArray(headerValues)) {
1605
- this.add(header, ...headerValues);
1606
- } else {
1607
- this.add(header, headerValues);
1608
- }
1609
- }
1610
- }
1611
- }
1612
- /**
1613
- * Gets the values for the header with the specified name.
1614
- * @param key The name of the header to get the values for.
1615
- * @returns The values for the header with the specified name.
1616
- * @throws Error if key is null or empty
1617
- */
1618
- tryGetValue(key) {
1619
- if (!key) {
1620
- throw new Error("key cannot be null or empty");
1621
- }
1622
- return this.headers[key] ? Array.from(this.headers[key]) : null;
1623
- }
1624
- /**
1625
- * Override toString method for the headers collection
1626
- * @returns a string representation of the headers collection
1627
- */
1628
- toString() {
1629
- return JSON.stringify(this.headers, (_key, value) => value instanceof Set ? [...value] : value);
1630
- }
1631
- /**
1632
- * check if the headers collection is empty
1633
- * @returns a boolean indicating if the headers collection is empty
1634
- */
1635
- isEmpty() {
1636
- return Object.keys(this.headers).length === 0;
1637
- }
1638
- /**
1639
- * get keys of the headers collection
1640
- * @returns an iterator of keys
1641
- */
1642
- keys() {
1643
- return Object.keys(this.headers)[Symbol.iterator]();
1644
- }
1645
- /**
1646
- * get entries
1647
- * @returns an iterator of entries
1648
- */
1649
- entries() {
1650
- return Object.entries(this.headers)[Symbol.iterator]();
1651
- }
1652
- }
1653
- var HttpMethod;
1654
- (function(HttpMethod2) {
1655
- HttpMethod2["GET"] = "GET";
1656
- HttpMethod2["POST"] = "POST";
1657
- HttpMethod2["PATCH"] = "PATCH";
1658
- HttpMethod2["DELETE"] = "DELETE";
1659
- HttpMethod2["OPTIONS"] = "OPTIONS";
1660
- HttpMethod2["CONNECT"] = "CONNECT";
1661
- HttpMethod2["TRACE"] = "TRACE";
1662
- HttpMethod2["HEAD"] = "HEAD";
1663
- HttpMethod2["PUT"] = "PUT";
1664
- })(HttpMethod || (HttpMethod = {}));
1665
- class DefaultApiError extends Error {
1666
- constructor(message) {
1667
- super(message);
1668
- this.responseHeaders = {};
1669
- }
1670
- }
1671
- var ApiKeyLocation;
1672
- (function(ApiKeyLocation2) {
1673
- ApiKeyLocation2[ApiKeyLocation2["QueryParameter"] = 0] = "QueryParameter";
1674
- ApiKeyLocation2[ApiKeyLocation2["Header"] = 1] = "Header";
1675
- })(ApiKeyLocation || (ApiKeyLocation = {}));
1676
- class BaseBearerTokenAuthenticationProvider {
1677
- /**
1678
- * The constructor for the BaseBearerTokenAuthenticationProvider
1679
- * @param accessTokenProvider The AccessTokenProvider instance that this provider will use to authenticate requests.
1680
- */
1681
- constructor(accessTokenProvider) {
1682
- this.accessTokenProvider = accessTokenProvider;
1683
- this.authenticateRequest = async (request, additionalAuthenticationContext) => {
1684
- var _a;
1685
- if (!request) {
1686
- throw new Error("request info cannot be null");
1687
- }
1688
- if ((additionalAuthenticationContext === null || additionalAuthenticationContext === void 0 ? void 0 : additionalAuthenticationContext.claims) && request.headers.has(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey)) {
1689
- request.headers.delete(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey);
1690
- }
1691
- if (!((_a = request.headers) === null || _a === void 0 ? void 0 : _a.has(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey))) {
1692
- const token = await this.accessTokenProvider.getAuthorizationToken(request.URL, additionalAuthenticationContext);
1693
- if (!request.headers) {
1694
- request.headers = new Headers();
1695
- }
1696
- if (token) {
1697
- request.headers.add(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey, `Bearer ${token}`);
1698
- }
1699
- }
1700
- };
1701
- }
1702
- }
1703
- BaseBearerTokenAuthenticationProvider.authorizationHeaderKey = "Authorization";
1704
- class NativeResponseHandler {
1705
- handleResponse(response, errorMappings) {
1706
- this.value = response;
1707
- this.errorMappings = errorMappings;
1708
- return Promise.resolve(void 0);
1709
- }
1710
- }
1711
- class NativeResponseWrapper {
1712
- }
1713
- NativeResponseWrapper.CallAndGetNative = async (originalCall, q, h, o) => {
1714
- const responseHandler = new NativeResponseHandler();
1715
- await originalCall(q, h, o, responseHandler);
1716
- return responseHandler.value;
1717
- };
1718
- NativeResponseWrapper.CallAndGetNativeWithBody = async (originalCall, requestBody, q, h, o) => {
1719
- const responseHandler = new NativeResponseHandler();
1720
- await originalCall(requestBody, q, h, o, responseHandler);
1721
- return responseHandler.value;
1722
- };
1723
- const ResponseHandlerOptionKey = "ResponseHandlerOptionKey";
1724
- class CustomFetchHandler {
1725
- constructor(customFetch) {
1726
- this.customFetch = customFetch;
1727
- }
1728
- /**
1729
- * @inheritdoc
1730
- */
1731
- async execute(url, requestInit) {
1732
- return await this.customFetch(url, requestInit);
1733
- }
1734
- }
1735
- class HttpClient {
1736
- /**
1737
- *
1738
- * Creates an instance of a HttpClient which contains the middlewares and fetch implementation for request execution.
1739
- * @param customFetch - custom fetch function - a Fetch API implementation
1740
- * @param middlewares - an array of Middleware handlers
1741
- */
1742
- constructor(customFetch, ...middlewares) {
1743
- this.customFetch = customFetch;
1744
- middlewares = (middlewares === null || middlewares === void 0 ? void 0 : middlewares.length) && middlewares[0] ? middlewares : MiddlewareFactory.getDefaultMiddlewares(customFetch);
1745
- if (this.customFetch) {
1746
- middlewares.push(new CustomFetchHandler(customFetch));
1747
- }
1748
- this.setMiddleware(...middlewares);
1749
- }
1750
- /**
1751
- * Processes the middleware parameter passed to set this.middleware property
1752
- * The calling function should validate if middleware is not undefined or not empty.
1753
- * @param middleware - The middleware passed
1754
- */
1755
- setMiddleware(...middleware) {
1756
- for (let i = 0; i < middleware.length - 1; i++) {
1757
- middleware[i].next = middleware[i + 1];
1758
- }
1759
- this.middleware = middleware[0];
1760
- }
1761
- /**
1762
- * Executes a request and returns a promise resolving the response.
1763
- * @param url the request url.
1764
- * @param requestInit the RequestInit object.
1765
- * @param requestOptions the request options.
1766
- * @returns the promise resolving the response.
1767
- */
1768
- async executeFetch(url, requestInit, requestOptions) {
1769
- if (this.middleware) {
1770
- return await this.middleware.execute(url, requestInit, requestOptions);
1771
- } else if (this.customFetch) {
1772
- return this.customFetch(url, requestInit);
1773
- }
1774
- throw new Error("Please provide middlewares or a custom fetch function to execute the request");
1775
- }
1776
- }
1777
- const ObservabilityOptionKey = "ObservabilityOptionKey";
1778
- class ObservabilityOptionsImpl {
1779
- constructor(originalOptions) {
1780
- this._originalOptions = originalOptions !== null && originalOptions !== void 0 ? originalOptions : {};
1781
- }
1782
- getKey() {
1783
- return ObservabilityOptionKey;
1784
- }
1785
- get includeEUIIAttributes() {
1786
- return this._originalOptions.includeEUIIAttributes;
1787
- }
1788
- set includeEUIIAttributes(value) {
1789
- this._originalOptions.includeEUIIAttributes = value;
1790
- }
1791
- getTracerInstrumentationName() {
1792
- return "@microsoft/kiota-http-fetchlibrary";
1793
- }
1794
- }
1795
- function getObservabilityOptionsFromRequest(requestOptions) {
1796
- if (requestOptions) {
1797
- const observabilityOptions = requestOptions[ObservabilityOptionKey];
1798
- if (observabilityOptions instanceof ObservabilityOptionsImpl) {
1799
- return observabilityOptions;
1800
- }
1801
- }
1802
- return void 0;
1803
- }
1804
- class FetchRequestAdapter {
1805
- getSerializationWriterFactory() {
1806
- return this.serializationWriterFactory;
1807
- }
1808
- getParseNodeFactory() {
1809
- return this.parseNodeFactory;
1810
- }
1811
- getBackingStoreFactory() {
1812
- return this.backingStoreFactory;
1813
- }
1814
- /**
1815
- * Instantiates a new request adapter.
1816
- * @param authenticationProvider the authentication provider to use.
1817
- * @param parseNodeFactory the parse node factory to deserialize responses.
1818
- * @param serializationWriterFactory the serialization writer factory to use to serialize request bodies.
1819
- * @param httpClient the http client to use to execute requests.
1820
- * @param observabilityOptions the observability options to use.
1821
- * @param backingStoreFactory the backing store factory to use.
1822
- */
1823
- constructor(authenticationProvider, parseNodeFactory = new ParseNodeFactoryRegistry(), serializationWriterFactory = new SerializationWriterFactoryRegistry(), httpClient = new HttpClient(), observabilityOptions = new ObservabilityOptionsImpl(), backingStoreFactory = new InMemoryBackingStoreFactory()) {
1824
- this.authenticationProvider = authenticationProvider;
1825
- this.parseNodeFactory = parseNodeFactory;
1826
- this.serializationWriterFactory = serializationWriterFactory;
1827
- this.httpClient = httpClient;
1828
- this.backingStoreFactory = backingStoreFactory;
1829
- this.baseUrl = "";
1830
- this.getResponseContentType = (response) => {
1831
- var _a;
1832
- const header = (_a = response.headers.get("content-type")) === null || _a === void 0 ? void 0 : _a.toLowerCase();
1833
- if (!header)
1834
- return void 0;
1835
- const segments = header.split(";");
1836
- if (segments.length === 0)
1837
- return void 0;
1838
- else
1839
- return segments[0];
1840
- };
1841
- this.getResponseHandler = (response) => {
1842
- const options = response.getRequestOptions();
1843
- const responseHandlerOption = options[ResponseHandlerOptionKey];
1844
- return responseHandlerOption === null || responseHandlerOption === void 0 ? void 0 : responseHandlerOption.responseHandler;
1845
- };
1846
- this.sendCollectionOfPrimitive = (requestInfo, responseType, errorMappings) => {
1847
- if (!requestInfo) {
1848
- throw new Error("requestInfo cannot be null");
1849
- }
1850
- return this.startTracingSpan(requestInfo, "sendCollectionOfPrimitive", async (span) => {
1851
- const response = await this.getHttpResponseMessage(requestInfo, span);
1852
- const responseHandler = this.getResponseHandler(requestInfo);
1853
- if (responseHandler) {
1854
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
1855
- return await responseHandler.handleResponse(response, errorMappings);
1856
- } else {
1857
- try {
1858
- await this.throwIfFailedResponse(response, errorMappings, span);
1859
- if (this.shouldReturnUndefined(response))
1860
- return void 0;
1861
- switch (responseType) {
1862
- case "string":
1863
- case "number":
1864
- case "boolean":
1865
- case "Date":
1866
- const rootNode = await this.getRootParseNode(response);
1867
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan(`getCollectionOf${responseType}Value`, (deserializeSpan) => {
1868
- try {
1869
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, responseType);
1870
- if (responseType === "string") {
1871
- return rootNode.getCollectionOfPrimitiveValues();
1872
- } else if (responseType === "number") {
1873
- return rootNode.getCollectionOfPrimitiveValues();
1874
- } else if (responseType === "boolean") {
1875
- return rootNode.getCollectionOfPrimitiveValues();
1876
- } else if (responseType === "Date") {
1877
- return rootNode.getCollectionOfPrimitiveValues();
1878
- } else if (responseType === "Duration") {
1879
- return rootNode.getCollectionOfPrimitiveValues();
1880
- } else if (responseType === "DateOnly") {
1881
- return rootNode.getCollectionOfPrimitiveValues();
1882
- } else if (responseType === "TimeOnly") {
1883
- return rootNode.getCollectionOfPrimitiveValues();
1884
- } else {
1885
- throw new Error("unexpected type to deserialize");
1886
- }
1887
- } finally {
1888
- deserializeSpan.end();
1889
- }
1890
- });
1891
- }
1892
- } finally {
1893
- await this.purgeResponseBody(response);
1894
- }
1895
- }
1896
- });
1897
- };
1898
- this.sendCollection = (requestInfo, deserialization, errorMappings) => {
1899
- if (!requestInfo) {
1900
- throw new Error("requestInfo cannot be null");
1901
- }
1902
- return this.startTracingSpan(requestInfo, "sendCollection", async (span) => {
1903
- const response = await this.getHttpResponseMessage(requestInfo, span);
1904
- const responseHandler = this.getResponseHandler(requestInfo);
1905
- if (responseHandler) {
1906
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
1907
- return await responseHandler.handleResponse(response, errorMappings);
1908
- } else {
1909
- try {
1910
- await this.throwIfFailedResponse(response, errorMappings, span);
1911
- if (this.shouldReturnUndefined(response))
1912
- return void 0;
1913
- const rootNode = await this.getRootParseNode(response);
1914
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getCollectionOfObjectValues", (deserializeSpan) => {
1915
- try {
1916
- const result = rootNode.getCollectionOfObjectValues(deserialization);
1917
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "object[]");
1918
- return result;
1919
- } finally {
1920
- deserializeSpan.end();
1921
- }
1922
- });
1923
- } finally {
1924
- await this.purgeResponseBody(response);
1925
- }
1926
- }
1927
- });
1928
- };
1929
- this.startTracingSpan = (requestInfo, methodName, callback) => {
1930
- var _a;
1931
- const urlTemplate = decodeURIComponent((_a = requestInfo.urlTemplate) !== null && _a !== void 0 ? _a : "");
1932
- const telemetryPathValue = urlTemplate.replace(/\{\?[^}]+\}/gi, "");
1933
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan(`${methodName} - ${telemetryPathValue}`, async (span) => {
1934
- try {
1935
- span.setAttribute("url.uri_template", urlTemplate);
1936
- return await callback(span);
1937
- } finally {
1938
- span.end();
1939
- }
1940
- });
1941
- };
1942
- this.send = (requestInfo, deserializer, errorMappings) => {
1943
- if (!requestInfo) {
1944
- throw new Error("requestInfo cannot be null");
1945
- }
1946
- return this.startTracingSpan(requestInfo, "send", async (span) => {
1947
- const response = await this.getHttpResponseMessage(requestInfo, span);
1948
- const responseHandler = this.getResponseHandler(requestInfo);
1949
- if (responseHandler) {
1950
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
1951
- return await responseHandler.handleResponse(response, errorMappings);
1952
- } else {
1953
- try {
1954
- await this.throwIfFailedResponse(response, errorMappings, span);
1955
- if (this.shouldReturnUndefined(response))
1956
- return void 0;
1957
- const rootNode = await this.getRootParseNode(response);
1958
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getObjectValue", (deserializeSpan) => {
1959
- try {
1960
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "object");
1961
- const result = rootNode.getObjectValue(deserializer);
1962
- return result;
1963
- } finally {
1964
- deserializeSpan.end();
1965
- }
1966
- });
1967
- } finally {
1968
- await this.purgeResponseBody(response);
1969
- }
1970
- }
1971
- });
1972
- };
1973
- this.sendPrimitive = (requestInfo, responseType, errorMappings) => {
1974
- if (!requestInfo) {
1975
- throw new Error("requestInfo cannot be null");
1976
- }
1977
- return this.startTracingSpan(requestInfo, "sendPrimitive", async (span) => {
1978
- const response = await this.getHttpResponseMessage(requestInfo, span);
1979
- const responseHandler = this.getResponseHandler(requestInfo);
1980
- if (responseHandler) {
1981
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
1982
- return await responseHandler.handleResponse(response, errorMappings);
1983
- } else {
1984
- try {
1985
- await this.throwIfFailedResponse(response, errorMappings, span);
1986
- if (this.shouldReturnUndefined(response))
1987
- return void 0;
1988
- switch (responseType) {
1989
- case "ArrayBuffer":
1990
- if (!response.body) {
1991
- return void 0;
1992
- }
1993
- return await response.arrayBuffer();
1994
- case "string":
1995
- case "number":
1996
- case "boolean":
1997
- case "Date":
1998
- const rootNode = await this.getRootParseNode(response);
1999
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, responseType);
2000
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan(`get${responseType}Value`, (deserializeSpan) => {
2001
- try {
2002
- if (responseType === "string") {
2003
- return rootNode.getStringValue();
2004
- } else if (responseType === "number") {
2005
- return rootNode.getNumberValue();
2006
- } else if (responseType === "boolean") {
2007
- return rootNode.getBooleanValue();
2008
- } else if (responseType === "Date") {
2009
- return rootNode.getDateValue();
2010
- } else if (responseType === "Duration") {
2011
- return rootNode.getDurationValue();
2012
- } else if (responseType === "DateOnly") {
2013
- return rootNode.getDateOnlyValue();
2014
- } else if (responseType === "TimeOnly") {
2015
- return rootNode.getTimeOnlyValue();
2016
- } else {
2017
- throw new Error("unexpected type to deserialize");
2018
- }
2019
- } finally {
2020
- deserializeSpan.end();
2021
- }
2022
- });
2023
- }
2024
- } finally {
2025
- await this.purgeResponseBody(response);
2026
- }
2027
- }
2028
- });
2029
- };
2030
- this.sendNoResponseContent = (requestInfo, errorMappings) => {
2031
- if (!requestInfo) {
2032
- throw new Error("requestInfo cannot be null");
2033
- }
2034
- return this.startTracingSpan(requestInfo, "sendNoResponseContent", async (span) => {
2035
- const response = await this.getHttpResponseMessage(requestInfo, span);
2036
- const responseHandler = this.getResponseHandler(requestInfo);
2037
- if (responseHandler) {
2038
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2039
- return await responseHandler.handleResponse(response, errorMappings);
2040
- }
2041
- try {
2042
- await this.throwIfFailedResponse(response, errorMappings, span);
2043
- } finally {
2044
- await this.purgeResponseBody(response);
2045
- }
2046
- });
2047
- };
2048
- this.sendEnum = (requestInfo, enumObject, errorMappings) => {
2049
- if (!requestInfo) {
2050
- throw new Error("requestInfo cannot be null");
2051
- }
2052
- return this.startTracingSpan(requestInfo, "sendEnum", async (span) => {
2053
- const response = await this.getHttpResponseMessage(requestInfo, span);
2054
- const responseHandler = this.getResponseHandler(requestInfo);
2055
- if (responseHandler) {
2056
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2057
- return await responseHandler.handleResponse(response, errorMappings);
2058
- } else {
2059
- try {
2060
- await this.throwIfFailedResponse(response, errorMappings, span);
2061
- if (this.shouldReturnUndefined(response))
2062
- return void 0;
2063
- const rootNode = await this.getRootParseNode(response);
2064
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getEnumValue", (deserializeSpan) => {
2065
- try {
2066
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "enum");
2067
- const result = rootNode.getEnumValue(enumObject);
2068
- return result;
2069
- } finally {
2070
- deserializeSpan.end();
2071
- }
2072
- });
2073
- } finally {
2074
- await this.purgeResponseBody(response);
2075
- }
2076
- }
2077
- });
2078
- };
2079
- this.sendCollectionOfEnum = (requestInfo, enumObject, errorMappings) => {
2080
- if (!requestInfo) {
2081
- throw new Error("requestInfo cannot be null");
2082
- }
2083
- return this.startTracingSpan(requestInfo, "sendCollectionOfEnum", async (span) => {
2084
- const response = await this.getHttpResponseMessage(requestInfo, span);
2085
- const responseHandler = this.getResponseHandler(requestInfo);
2086
- if (responseHandler) {
2087
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2088
- return await responseHandler.handleResponse(response, errorMappings);
2089
- } else {
2090
- try {
2091
- await this.throwIfFailedResponse(response, errorMappings, span);
2092
- if (this.shouldReturnUndefined(response))
2093
- return void 0;
2094
- const rootNode = await this.getRootParseNode(response);
2095
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getCollectionOfEnumValues", (deserializeSpan) => {
2096
- try {
2097
- const result = rootNode.getCollectionOfEnumValues(enumObject);
2098
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "enum[]");
2099
- return result;
2100
- } finally {
2101
- deserializeSpan.end();
2102
- }
2103
- });
2104
- } finally {
2105
- await this.purgeResponseBody(response);
2106
- }
2107
- }
2108
- });
2109
- };
2110
- this.enableBackingStore = (backingStoreFactory2) => {
2111
- if (this.parseNodeFactory instanceof ParseNodeFactoryRegistry) {
2112
- this.parseNodeFactory = enableBackingStoreForParseNodeFactory(this.parseNodeFactory, this.parseNodeFactory);
2113
- } else {
2114
- throw new Error("parseNodeFactory is not a ParseNodeFactoryRegistry");
2115
- }
2116
- if (this.serializationWriterFactory instanceof SerializationWriterFactoryRegistry && this.parseNodeFactory instanceof ParseNodeFactoryRegistry) {
2117
- this.serializationWriterFactory = enableBackingStoreForSerializationWriterFactory(this.serializationWriterFactory, this.parseNodeFactory, this.serializationWriterFactory);
2118
- } else {
2119
- throw new Error("serializationWriterFactory is not a SerializationWriterFactoryRegistry or parseNodeFactory is not a ParseNodeFactoryRegistry");
2120
- }
2121
- if (!this.serializationWriterFactory || !this.parseNodeFactory)
2122
- throw new Error("unable to enable backing store");
2123
- if (backingStoreFactory2) {
2124
- this.backingStoreFactory = backingStoreFactory2;
2125
- }
2126
- };
2127
- this.getRootParseNode = (response) => {
2128
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getRootParseNode", async (span) => {
2129
- try {
2130
- const payload = await response.arrayBuffer();
2131
- const responseContentType = this.getResponseContentType(response);
2132
- if (!responseContentType)
2133
- throw new Error("no response content type found for deserialization");
2134
- return this.parseNodeFactory.getRootParseNode(responseContentType, payload);
2135
- } finally {
2136
- span.end();
2137
- }
2138
- });
2139
- };
2140
- this.shouldReturnUndefined = (response) => {
2141
- return response.status === 204 || response.status === 304 || !response.body;
2142
- };
2143
- this.purgeResponseBody = async (response) => {
2144
- if (!response.bodyUsed && response.body) {
2145
- await response.arrayBuffer();
2146
- }
2147
- };
2148
- this.throwIfFailedResponse = (response, errorMappings, spanForAttributes) => {
2149
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("throwIfFailedResponse", async (span) => {
2150
- var _a, _b, _c;
2151
- try {
2152
- if (response.ok || response.status >= 300 && response.status < 400 && !response.headers.has(FetchRequestAdapter.locationHeaderName))
2153
- return;
2154
- spanForAttributes.setStatus({
2155
- code: SpanStatusCode.ERROR,
2156
- message: "received_error_response"
2157
- });
2158
- const statusCode = response.status;
2159
- const responseHeaders = {};
2160
- response.headers.forEach((value, key) => {
2161
- responseHeaders[key] = value.split(",");
2162
- });
2163
- const factory = errorMappings ? (_c = (_b = (_a = errorMappings[statusCode]) !== null && _a !== void 0 ? _a : statusCode >= 400 && statusCode < 500 ? errorMappings._4XX : void 0) !== null && _b !== void 0 ? _b : statusCode >= 500 && statusCode < 600 ? errorMappings._5XX : void 0) !== null && _c !== void 0 ? _c : errorMappings.XXX : void 0;
2164
- if (!factory) {
2165
- spanForAttributes.setAttribute(FetchRequestAdapter.errorMappingFoundAttributeName, false);
2166
- const error = new DefaultApiError("the server returned an unexpected status code and no error class is registered for this code " + statusCode);
2167
- error.responseStatusCode = statusCode;
2168
- error.responseHeaders = responseHeaders;
2169
- spanForAttributes.recordException(error);
2170
- throw error;
2171
- }
2172
- spanForAttributes.setAttribute(FetchRequestAdapter.errorMappingFoundAttributeName, true);
2173
- const rootNode = await this.getRootParseNode(response);
2174
- let deserializedError = trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getObjectValue", (deserializeSpan) => {
2175
- try {
2176
- return rootNode.getObjectValue(factory);
2177
- } finally {
2178
- deserializeSpan.end();
2179
- }
2180
- });
2181
- spanForAttributes.setAttribute(FetchRequestAdapter.errorBodyFoundAttributeName, !!deserializedError);
2182
- if (!deserializedError)
2183
- deserializedError = new DefaultApiError("unexpected error type" + typeof deserializedError);
2184
- const errorObject = deserializedError;
2185
- errorObject.responseStatusCode = statusCode;
2186
- errorObject.responseHeaders = responseHeaders;
2187
- spanForAttributes.recordException(errorObject);
2188
- throw errorObject;
2189
- } finally {
2190
- span.end();
2191
- }
2192
- });
2193
- };
2194
- this.getHttpResponseMessage = (requestInfo, spanForAttributes, claims) => {
2195
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getHttpResponseMessage", async (span) => {
2196
- try {
2197
- if (!requestInfo) {
2198
- throw new Error("requestInfo cannot be null");
2199
- }
2200
- this.setBaseUrlForRequestInformation(requestInfo);
2201
- const additionalContext = {};
2202
- if (claims) {
2203
- additionalContext.claims = claims;
2204
- }
2205
- await this.authenticationProvider.authenticateRequest(requestInfo, additionalContext);
2206
- const request = await this.getRequestFromRequestInformation(requestInfo, spanForAttributes);
2207
- if (this.observabilityOptions) {
2208
- requestInfo.addRequestOptions([this.observabilityOptions]);
2209
- }
2210
- let response = await this.httpClient.executeFetch(requestInfo.URL, request, requestInfo.getRequestOptions());
2211
- response = await this.retryCAEResponseIfRequired(requestInfo, response, spanForAttributes, claims);
2212
- if (response) {
2213
- const responseContentLength = response.headers.get("Content-Length");
2214
- if (responseContentLength) {
2215
- spanForAttributes.setAttribute("http.response.body.size", parseInt(responseContentLength, 10));
2216
- }
2217
- const responseContentType = response.headers.get("Content-Type");
2218
- if (responseContentType) {
2219
- spanForAttributes.setAttribute("http.response.header.content-type", responseContentType);
2220
- }
2221
- spanForAttributes.setAttribute("http.response.status_code", response.status);
2222
- }
2223
- return response;
2224
- } finally {
2225
- span.end();
2226
- }
2227
- });
2228
- };
2229
- this.retryCAEResponseIfRequired = async (requestInfo, response, spanForAttributes, claims) => {
2230
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("retryCAEResponseIfRequired", async (span) => {
2231
- try {
2232
- const responseClaims = this.getClaimsFromResponse(response, claims);
2233
- if (responseClaims) {
2234
- span.addEvent(FetchRequestAdapter.authenticateChallengedEventKey);
2235
- spanForAttributes.setAttribute("http.request.resend_count", 1);
2236
- await this.purgeResponseBody(response);
2237
- return await this.getHttpResponseMessage(requestInfo, spanForAttributes, responseClaims);
2238
- }
2239
- return response;
2240
- } finally {
2241
- span.end();
2242
- }
2243
- });
2244
- };
2245
- this.getClaimsFromResponse = (response, claims) => {
2246
- if (response.status === 401 && !claims) {
2247
- const rawAuthenticateHeader = response.headers.get("WWW-Authenticate");
2248
- if (rawAuthenticateHeader && /^Bearer /gi.test(rawAuthenticateHeader)) {
2249
- const rawParameters = rawAuthenticateHeader.replace(/^Bearer /gi, "").split(",");
2250
- for (const rawParameter of rawParameters) {
2251
- const trimmedParameter = rawParameter.trim();
2252
- if (/claims="[^"]+"/gi.test(trimmedParameter)) {
2253
- return trimmedParameter.replace(/claims="([^"]+)"/gi, "$1");
2254
- }
2255
- }
2256
- }
2257
- }
2258
- return void 0;
2259
- };
2260
- this.setBaseUrlForRequestInformation = (requestInfo) => {
2261
- requestInfo.pathParameters.baseurl = this.baseUrl;
2262
- };
2263
- this.getRequestFromRequestInformation = (requestInfo, spanForAttributes) => {
2264
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getRequestFromRequestInformation", async (span) => {
2265
- var _a, _b;
2266
- try {
2267
- const method = (_a = requestInfo.httpMethod) === null || _a === void 0 ? void 0 : _a.toString();
2268
- const uri = requestInfo.URL;
2269
- spanForAttributes.setAttribute("http.request.method", method !== null && method !== void 0 ? method : "");
2270
- const uriContainsScheme = uri.includes("://");
2271
- const schemeSplatUri = uri.split("://");
2272
- if (uriContainsScheme) {
2273
- spanForAttributes.setAttribute("server.address", schemeSplatUri[0]);
2274
- }
2275
- const uriWithoutScheme = uriContainsScheme ? schemeSplatUri[1] : uri;
2276
- spanForAttributes.setAttribute("url.scheme", uriWithoutScheme.split("/")[0]);
2277
- if (this.observabilityOptions.includeEUIIAttributes) {
2278
- spanForAttributes.setAttribute("url.full", decodeURIComponent(uri));
2279
- }
2280
- const requestContentLength = requestInfo.headers.tryGetValue("Content-Length");
2281
- if (requestContentLength) {
2282
- spanForAttributes.setAttribute("http.response.body.size", parseInt(requestContentLength[0], 10));
2283
- }
2284
- const requestContentType = requestInfo.headers.tryGetValue("Content-Type");
2285
- if (requestContentType) {
2286
- spanForAttributes.setAttribute("http.request.header.content-type", requestContentType);
2287
- }
2288
- const headers = {};
2289
- (_b = requestInfo.headers) === null || _b === void 0 ? void 0 : _b.forEach((_, key) => {
2290
- headers[key.toString().toLocaleLowerCase()] = this.foldHeaderValue(requestInfo.headers.tryGetValue(key));
2291
- });
2292
- const request = {
2293
- method,
2294
- headers,
2295
- body: requestInfo.content
2296
- };
2297
- return request;
2298
- } finally {
2299
- span.end();
2300
- }
2301
- });
2302
- };
2303
- this.foldHeaderValue = (value) => {
2304
- if (!value || value.length < 1) {
2305
- return "";
2306
- } else if (value.length === 1) {
2307
- return value[0];
2308
- } else {
2309
- return value.reduce((acc, val) => acc + val, ",");
2310
- }
2311
- };
2312
- this.convertToNativeRequest = async (requestInfo) => {
2313
- if (!requestInfo) {
2314
- throw new Error("requestInfo cannot be null");
2315
- }
2316
- await this.authenticationProvider.authenticateRequest(requestInfo, void 0);
2317
- return this.startTracingSpan(requestInfo, "convertToNativeRequest", async (span) => {
2318
- const request = await this.getRequestFromRequestInformation(requestInfo, span);
2319
- return request;
2320
- });
2321
- };
2322
- if (!authenticationProvider) {
2323
- throw new Error("authentication provider cannot be null");
2324
- }
2325
- if (!parseNodeFactory) {
2326
- throw new Error("parse node factory cannot be null");
2327
- }
2328
- if (!serializationWriterFactory) {
2329
- throw new Error("serialization writer factory cannot be null");
2330
- }
2331
- if (!httpClient) {
2332
- throw new Error("http client cannot be null");
2333
- }
2334
- if (!observabilityOptions) {
2335
- throw new Error("observability options cannot be null");
2336
- } else {
2337
- this.observabilityOptions = new ObservabilityOptionsImpl(observabilityOptions);
2338
- }
2339
- }
2340
- }
2341
- FetchRequestAdapter.responseTypeAttributeKey = "com.microsoft.kiota.response.type";
2342
- FetchRequestAdapter.eventResponseHandlerInvokedKey = "com.microsoft.kiota.response_handler_invoked";
2343
- FetchRequestAdapter.errorMappingFoundAttributeName = "com.microsoft.kiota.error.mapping_found";
2344
- FetchRequestAdapter.errorBodyFoundAttributeName = "com.microsoft.kiota.error.body_found";
2345
- FetchRequestAdapter.locationHeaderName = "Location";
2346
- FetchRequestAdapter.authenticateChallengedEventKey = "com.microsoft.kiota.authenticate_challenge_received";
2347
- const getRequestHeader = (options, key) => {
2348
- if (options && options.headers) {
2349
- return options.headers[key];
2350
- }
2351
- return void 0;
2352
- };
2353
- const setRequestHeader = (options, key, value) => {
2354
- if (options) {
2355
- if (!options.headers) {
2356
- options.headers = {};
2357
- }
2358
- options.headers[key] = value;
2359
- }
2360
- };
2361
- const deleteRequestHeader = (options, key) => {
2362
- if (options) {
2363
- if (!options.headers) {
2364
- options.headers = {};
2365
- }
2366
- delete options.headers[key];
2367
- }
2368
- };
2369
- const appendRequestHeader = (options, key, value, separator = ", ") => {
2370
- if (options) {
2371
- if (!options.headers) {
2372
- options.headers = {};
2373
- }
2374
- if (!options.headers[key]) {
2375
- options.headers[key] = value;
2376
- } else {
2377
- options.headers[key] += `${separator}${value}`;
2378
- }
2379
- }
2380
- };
2381
- var ChaosStrategy;
2382
- (function(ChaosStrategy2) {
2383
- ChaosStrategy2[ChaosStrategy2["MANUAL"] = 0] = "MANUAL";
2384
- ChaosStrategy2[ChaosStrategy2["RANDOM"] = 1] = "RANDOM";
2385
- })(ChaosStrategy || (ChaosStrategy = {}));
2386
- const CompressionHandlerOptionsKey = "CompressionHandlerOptionsKey";
2387
- class CompressionHandlerOptions {
2388
- /**
2389
- * Create a new instance of the CompressionHandlerOptions class
2390
- * @param config the configuration to apply to the compression handler options.
2391
- */
2392
- constructor(config) {
2393
- var _a;
2394
- this._enableCompression = (_a = config === null || config === void 0 ? void 0 : config.enableCompression) !== null && _a !== void 0 ? _a : true;
2395
- }
2396
- /**
2397
- * @inheritdoc
2398
- */
2399
- getKey() {
2400
- return CompressionHandlerOptionsKey;
2401
- }
2402
- /**
2403
- * Returns whether the compression handler is enabled or not.
2404
- * @returns whether the compression handler is enabled or not.
2405
- */
2406
- get ShouldCompress() {
2407
- return this._enableCompression;
2408
- }
2409
- }
2410
- class CompressionHandler {
2411
- /**
2412
- * Creates a new instance of the CompressionHandler class
2413
- * @param handlerOptions The options for the compression handler.
2414
- * @returns An instance of the CompressionHandler class
2415
- */
2416
- constructor(handlerOptions = new CompressionHandlerOptions()) {
2417
- this.handlerOptions = handlerOptions;
2418
- if (!handlerOptions) {
2419
- throw new Error("handlerOptions cannot be undefined");
2420
- }
2421
- }
2422
- /**
2423
- * @inheritdoc
2424
- */
2425
- execute(url, requestInit, requestOptions) {
2426
- let currentOptions = this.handlerOptions;
2427
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[CompressionHandlerOptionsKey]) {
2428
- currentOptions = requestOptions[CompressionHandlerOptionsKey];
2429
- }
2430
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
2431
- if (obsOptions) {
2432
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("compressionHandler - execute", (span) => {
2433
- try {
2434
- span.setAttribute("com.microsoft.kiota.handler.compression.enable", currentOptions.ShouldCompress);
2435
- return this.executeInternal(currentOptions, url, requestInit, requestOptions, span);
2436
- } finally {
2437
- span.end();
2438
- }
2439
- });
2440
- }
2441
- return this.executeInternal(currentOptions, url, requestInit, requestOptions);
2442
- }
2443
- async executeInternal(options, url, requestInit, requestOptions, span) {
2444
- var _a, _b, _c, _d;
2445
- if (!options.ShouldCompress || this.contentRangeBytesIsPresent(requestInit.headers) || this.contentEncodingIsPresent(requestInit.headers) || requestInit.body === null || requestInit.body === void 0) {
2446
- return (_b = (_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, requestInit, requestOptions)) !== null && _b !== void 0 ? _b : Promise.reject(new Error("Response is undefined"));
2447
- }
2448
- span === null || span === void 0 ? void 0 : span.setAttribute("http.request.body.compressed", true);
2449
- const unCompressedBody = requestInit.body;
2450
- const unCompressedBodySize = this.getRequestBodySize(unCompressedBody);
2451
- const compressedBody = await this.compressRequestBody(unCompressedBody);
2452
- setRequestHeader(requestInit, CompressionHandler.CONTENT_ENCODING_HEADER, "gzip");
2453
- requestInit.body = compressedBody.compressedBody;
2454
- span === null || span === void 0 ? void 0 : span.setAttribute("http.request.body.size", compressedBody.size);
2455
- let response = await ((_c = this.next) === null || _c === void 0 ? void 0 : _c.execute(url, requestInit, requestOptions));
2456
- if (!response) {
2457
- throw new Error("Response is undefined");
2458
- }
2459
- if (response.status === 415) {
2460
- deleteRequestHeader(requestInit, CompressionHandler.CONTENT_ENCODING_HEADER);
2461
- requestInit.body = unCompressedBody;
2462
- span === null || span === void 0 ? void 0 : span.setAttribute("http.request.body.compressed", false);
2463
- span === null || span === void 0 ? void 0 : span.setAttribute("http.request.body.size", unCompressedBodySize);
2464
- response = await ((_d = this.next) === null || _d === void 0 ? void 0 : _d.execute(url, requestInit, requestOptions));
2465
- }
2466
- return response !== void 0 && response !== null ? Promise.resolve(response) : Promise.reject(new Error("Response is undefined"));
2467
- }
2468
- contentRangeBytesIsPresent(header) {
2469
- var _a;
2470
- if (!header) {
2471
- return false;
2472
- }
2473
- const contentRange = getRequestHeader(header, CompressionHandler.CONTENT_RANGE_HEADER);
2474
- return (_a = contentRange === null || contentRange === void 0 ? void 0 : contentRange.toLowerCase().includes("bytes")) !== null && _a !== void 0 ? _a : false;
2475
- }
2476
- contentEncodingIsPresent(header) {
2477
- if (!header) {
2478
- return false;
2479
- }
2480
- return getRequestHeader(header, CompressionHandler.CONTENT_ENCODING_HEADER) !== void 0;
2481
- }
2482
- getRequestBodySize(body) {
2483
- if (!body) {
2484
- return 0;
2485
- }
2486
- if (typeof body === "string") {
2487
- return body.length;
2488
- }
2489
- if (body instanceof Blob) {
2490
- return body.size;
2491
- }
2492
- if (body instanceof ArrayBuffer) {
2493
- return body.byteLength;
2494
- }
2495
- if (ArrayBuffer.isView(body)) {
2496
- return body.byteLength;
2497
- }
2498
- if (inNodeEnv() && Buffer.isBuffer(body)) {
2499
- return body.byteLength;
2500
- }
2501
- throw new Error("Unsupported body type");
2502
- }
2503
- readBodyAsBytes(body) {
2504
- if (!body) {
2505
- return { stream: new ReadableStream(), size: 0 };
2506
- }
2507
- const uint8ArrayToStream = (uint8Array) => {
2508
- return new ReadableStream({
2509
- start(controller) {
2510
- controller.enqueue(uint8Array);
2511
- controller.close();
2512
- }
2513
- });
2514
- };
2515
- if (typeof body === "string") {
2516
- return { stream: uint8ArrayToStream(new TextEncoder().encode(body)), size: body.length };
2517
- }
2518
- if (body instanceof Blob) {
2519
- return { stream: body.stream(), size: body.size };
2520
- }
2521
- if (body instanceof ArrayBuffer) {
2522
- return { stream: uint8ArrayToStream(new Uint8Array(body)), size: body.byteLength };
2523
- }
2524
- if (ArrayBuffer.isView(body)) {
2525
- return { stream: uint8ArrayToStream(new Uint8Array(body.buffer, body.byteOffset, body.byteLength)), size: body.byteLength };
2526
- }
2527
- throw new Error("Unsupported body type");
2528
- }
2529
- async compressRequestBody(body) {
2530
- const compressionData = this.readBodyAsBytes(body);
2531
- const compressedBody = await this.compressUsingCompressionStream(compressionData.stream);
2532
- return {
2533
- compressedBody: compressedBody.body,
2534
- size: compressedBody.size
2535
- };
2536
- }
2537
- async compressUsingCompressionStream(uint8ArrayStream) {
2538
- const compressionStream = new CompressionStream("gzip");
2539
- const compressedStream = uint8ArrayStream.pipeThrough(compressionStream);
2540
- const reader = compressedStream.getReader();
2541
- const compressedChunks = [];
2542
- let totalLength = 0;
2543
- let result = await reader.read();
2544
- while (!result.done) {
2545
- const chunk = result.value;
2546
- compressedChunks.push(chunk);
2547
- totalLength += chunk.length;
2548
- result = await reader.read();
2549
- }
2550
- const compressedArray = new Uint8Array(totalLength);
2551
- let offset = 0;
2552
- for (const chunk of compressedChunks) {
2553
- compressedArray.set(chunk, offset);
2554
- offset += chunk.length;
2555
- }
2556
- return {
2557
- body: compressedArray.buffer,
2558
- size: compressedArray.length
2559
- };
2560
- }
2561
- }
2562
- CompressionHandler.CONTENT_RANGE_HEADER = "Content-Range";
2563
- CompressionHandler.CONTENT_ENCODING_HEADER = "Content-Encoding";
2564
- const HeadersInspectionOptionsKey = "HeadersInspectionOptionsKey";
2565
- class HeadersInspectionOptions {
2566
- /**
2567
- * Gets the request headers
2568
- * @returns the request headers
2569
- */
2570
- getRequestHeaders() {
2571
- return this.requestHeaders;
2572
- }
2573
- /**
2574
- * Gets the response headers
2575
- * @returns the response headers
2576
- */
2577
- getResponseHeaders() {
2578
- return this.responseHeaders;
2579
- }
2580
- /**
2581
- *
2582
- * To create an instance of HeadersInspectionOptions
2583
- * @param [options] - The headers inspection options value
2584
- * @returns An instance of HeadersInspectionOptions
2585
- * @example const options = new HeadersInspectionOptions({ inspectRequestHeaders: true, inspectResponseHeaders: true });
2586
- */
2587
- constructor(options = {}) {
2588
- var _a, _b;
2589
- this.requestHeaders = new Headers();
2590
- this.responseHeaders = new Headers();
2591
- this.inspectRequestHeaders = (_a = options.inspectRequestHeaders) !== null && _a !== void 0 ? _a : false;
2592
- this.inspectResponseHeaders = (_b = options.inspectResponseHeaders) !== null && _b !== void 0 ? _b : false;
2593
- }
2594
- getKey() {
2595
- return HeadersInspectionOptionsKey;
2596
- }
2597
- }
2598
- class HeadersInspectionHandler {
2599
- /**
2600
- *
2601
- * Creates new instance of HeadersInspectionHandler
2602
- * @param _options The options for inspecting the headers
2603
- */
2604
- constructor(_options = new HeadersInspectionOptions()) {
2605
- this._options = _options;
2606
- }
2607
- execute(url, requestInit, requestOptions) {
2608
- let currentOptions = this._options;
2609
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[HeadersInspectionOptionsKey]) {
2610
- currentOptions = requestOptions[HeadersInspectionOptionsKey];
2611
- }
2612
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
2613
- if (obsOptions) {
2614
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("retryHandler - execute", (span) => {
2615
- try {
2616
- span.setAttribute("com.microsoft.kiota.handler.headersInspection.enable", true);
2617
- return this.executeInternal(url, requestInit, requestOptions, currentOptions);
2618
- } finally {
2619
- span.end();
2620
- }
2621
- });
2622
- }
2623
- return this.executeInternal(url, requestInit, requestOptions, currentOptions);
2624
- }
2625
- async executeInternal(url, requestInit, requestOptions, currentOptions) {
2626
- if (!this.next) {
2627
- throw new Error("next middleware is undefined.");
2628
- }
2629
- if (currentOptions.inspectRequestHeaders && requestInit.headers) {
2630
- for (const [key, value] of requestInit.headers) {
2631
- currentOptions.getRequestHeaders().add(key, value);
2632
- }
2633
- }
2634
- const response = await this.next.execute(url, requestInit, requestOptions);
2635
- if (currentOptions.inspectResponseHeaders && response.headers) {
2636
- for (const [key, value] of response.headers.entries()) {
2637
- currentOptions.getResponseHeaders().add(key, value);
2638
- }
2639
- }
2640
- return response;
2641
- }
2642
- }
2643
- const ParametersNameDecodingHandlerOptionsKey = "RetryHandlerOptionKey";
2644
- class ParametersNameDecodingHandlerOptions {
2645
- getKey() {
2646
- return ParametersNameDecodingHandlerOptionsKey;
2647
- }
2648
- /**
2649
- *
2650
- * To create an instance of ParametersNameDecodingHandlerOptions
2651
- * @param [options] - The optional parameters
2652
- * @returns An instance of ParametersNameDecodingHandlerOptions
2653
- * @example ParametersNameDecodingHandlerOptions({ enable: true, charactersToDecode: [".", "-", "~", "$"] });
2654
- */
2655
- constructor(options = {}) {
2656
- var _a, _b;
2657
- this.enable = (_a = options.enable) !== null && _a !== void 0 ? _a : true;
2658
- this.charactersToDecode = (_b = options.charactersToDecode) !== null && _b !== void 0 ? _b : [".", "-", "~", "$"];
2659
- }
2660
- }
2661
- class ParametersNameDecodingHandler {
2662
- /**
2663
- *
2664
- * To create an instance of ParametersNameDecodingHandler
2665
- * @param [options] - The parameters name decoding handler options value
2666
- */
2667
- constructor(options = new ParametersNameDecodingHandlerOptions()) {
2668
- this.options = options;
2669
- if (!options) {
2670
- throw new Error("The options parameter is required.");
2671
- }
2672
- }
2673
- /**
2674
- * To execute the current middleware
2675
- * @param url - The url to be fetched
2676
- * @param requestInit - The request init object
2677
- * @param requestOptions - The request options
2678
- * @returns A Promise that resolves to nothing
2679
- */
2680
- execute(url, requestInit, requestOptions) {
2681
- let currentOptions = this.options;
2682
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[ParametersNameDecodingHandlerOptionsKey]) {
2683
- currentOptions = requestOptions[ParametersNameDecodingHandlerOptionsKey];
2684
- }
2685
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
2686
- if (obsOptions) {
2687
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("parametersNameDecodingHandler - execute", (span) => {
2688
- try {
2689
- span.setAttribute("com.microsoft.kiota.handler.parameters_name_decoding.enable", currentOptions.enable);
2690
- return this.decodeParameters(url, requestInit, currentOptions, requestOptions);
2691
- } finally {
2692
- span.end();
2693
- }
2694
- });
2695
- }
2696
- return this.decodeParameters(url, requestInit, currentOptions, requestOptions);
2697
- }
2698
- decodeParameters(url, requestInit, currentOptions, requestOptions) {
2699
- var _a, _b;
2700
- let updatedUrl = url;
2701
- if (currentOptions && currentOptions.enable && url.includes("%") && currentOptions.charactersToDecode && currentOptions.charactersToDecode.length > 0) {
2702
- currentOptions.charactersToDecode.forEach((character) => {
2703
- updatedUrl = updatedUrl.replace(new RegExp(`%${character.charCodeAt(0).toString(16)}`, "gi"), character);
2704
- });
2705
- }
2706
- return (_b = (_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(updatedUrl, requestInit, requestOptions)) !== null && _b !== void 0 ? _b : Promise.reject(new Error("The next middleware is not set."));
2707
- }
2708
- }
2709
- const RedirectHandlerOptionKey = "RedirectHandlerOption";
2710
- class RedirectHandlerOptions {
2711
- /**
2712
- *
2713
- * To create an instance of RedirectHandlerOptions
2714
- * @param [options] - The redirect handler options instance
2715
- * @returns An instance of RedirectHandlerOptions
2716
- * @throws Error if maxRedirects is more than 20 or less than 0
2717
- * @example const options = new RedirectHandlerOptions({ maxRedirects: 5 });
2718
- */
2719
- constructor(options = {}) {
2720
- var _a, _b;
2721
- if (options.maxRedirects && options.maxRedirects > RedirectHandlerOptions.MAX_MAX_REDIRECTS) {
2722
- const error = new Error(`MaxRedirects should not be more than ${RedirectHandlerOptions.MAX_MAX_REDIRECTS}`);
2723
- error.name = "MaxLimitExceeded";
2724
- throw error;
2725
- }
2726
- if (options.maxRedirects !== void 0 && options.maxRedirects < 0) {
2727
- const error = new Error(`MaxRedirects should not be negative`);
2728
- error.name = "MinExpectationNotMet";
2729
- throw error;
2730
- }
2731
- this.maxRedirects = (_a = options.maxRedirects) !== null && _a !== void 0 ? _a : RedirectHandlerOptions.DEFAULT_MAX_REDIRECTS;
2732
- this.shouldRedirect = (_b = options.shouldRedirect) !== null && _b !== void 0 ? _b : RedirectHandlerOptions.defaultShouldRetry;
2733
- }
2734
- getKey() {
2735
- return RedirectHandlerOptionKey;
2736
- }
2737
- }
2738
- RedirectHandlerOptions.DEFAULT_MAX_REDIRECTS = 5;
2739
- RedirectHandlerOptions.MAX_MAX_REDIRECTS = 20;
2740
- RedirectHandlerOptions.defaultShouldRetry = () => true;
2741
- class RedirectHandler {
2742
- /**
2743
- *
2744
- *
2745
- * To create an instance of RedirectHandler
2746
- * @param [options] - The redirect handler options instance
2747
- * @returns An instance of RedirectHandler
2748
- */
2749
- constructor(options = new RedirectHandlerOptions()) {
2750
- this.options = options;
2751
- if (!options) {
2752
- throw new Error("The options parameter is required.");
2753
- }
2754
- }
2755
- /**
2756
- *
2757
- * To check whether the response has the redirect status code or not
2758
- * @param response - The response object
2759
- * @returns A boolean representing whether the response contains the redirect status code or not
2760
- */
2761
- isRedirect(response) {
2762
- return RedirectHandler.REDIRECT_STATUS_CODES.has(response.status);
2763
- }
2764
- /**
2765
- *
2766
- * To check whether the response has location header or not
2767
- * @param response - The response object
2768
- * @returns A boolean representing the whether the response has location header or not
2769
- */
2770
- hasLocationHeader(response) {
2771
- return response.headers.has(RedirectHandler.LOCATION_HEADER);
2772
- }
2773
- /**
2774
- *
2775
- * To get the redirect url from location header in response object
2776
- * @param response - The response object
2777
- * @returns A redirect url from location header
2778
- */
2779
- getLocationHeader(response) {
2780
- return response.headers.get(RedirectHandler.LOCATION_HEADER);
2781
- }
2782
- /**
2783
- *
2784
- * To check whether the given url is a relative url or not
2785
- * @param url - The url string value
2786
- * @returns A boolean representing whether the given url is a relative url or not
2787
- */
2788
- isRelativeURL(url) {
2789
- return !url.includes("://");
2790
- }
2791
- /**
2792
- *
2793
- * To check whether the authorization header in the request should be dropped for consequent redirected requests
2794
- * @param requestUrl - The request url value
2795
- * @param redirectUrl - The redirect url value
2796
- * @returns A boolean representing whether the authorization header in the request should be dropped for consequent redirected requests
2797
- */
2798
- shouldDropAuthorizationHeader(requestUrl, redirectUrl) {
2799
- const schemeHostRegex = /^[A-Za-z].+?:\/\/.+?(?=\/|$)/;
2800
- const requestMatches = schemeHostRegex.exec(requestUrl);
2801
- let requestAuthority;
2802
- let redirectAuthority;
2803
- if (requestMatches !== null) {
2804
- requestAuthority = requestMatches[0];
2805
- }
2806
- const redirectMatches = schemeHostRegex.exec(redirectUrl);
2807
- if (redirectMatches !== null) {
2808
- redirectAuthority = redirectMatches[0];
2809
- }
2810
- return typeof requestAuthority !== "undefined" && typeof redirectAuthority !== "undefined" && requestAuthority !== redirectAuthority;
2811
- }
2812
- /**
2813
- * To execute the next middleware and to handle in case of redirect response returned by the server
2814
- * @param url - The url string value
2815
- * @param fetchRequestInit - The Fetch RequestInit object
2816
- * @param redirectCount - The redirect count value
2817
- * @param currentOptions - The redirect handler options instance
2818
- * @param requestOptions - The request options
2819
- * @param tracerName - The name to use for the tracer
2820
- * @returns A promise that resolves to nothing
2821
- */
2822
- async executeWithRedirect(url, fetchRequestInit, redirectCount, currentOptions, requestOptions, tracerName) {
2823
- var _a;
2824
- const response = await ((_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, fetchRequestInit, requestOptions));
2825
- if (!response) {
2826
- throw new Error("Response is undefined");
2827
- }
2828
- if (redirectCount < currentOptions.maxRedirects && this.isRedirect(response) && this.hasLocationHeader(response) && currentOptions.shouldRedirect(response)) {
2829
- ++redirectCount;
2830
- if (response.status === RedirectHandler.STATUS_CODE_SEE_OTHER) {
2831
- fetchRequestInit.method = HttpMethod.GET;
2832
- delete fetchRequestInit.body;
2833
- } else {
2834
- const redirectUrl = this.getLocationHeader(response);
2835
- if (redirectUrl) {
2836
- if (fetchRequestInit.headers && !this.isRelativeURL(redirectUrl) && this.shouldDropAuthorizationHeader(url, redirectUrl)) {
2837
- delete fetchRequestInit.headers[RedirectHandler.AUTHORIZATION_HEADER];
2838
- }
2839
- url = redirectUrl;
2840
- }
2841
- }
2842
- if (tracerName) {
2843
- return trace.getTracer(tracerName).startActiveSpan(`redirectHandler - redirect ${redirectCount}`, (span) => {
2844
- try {
2845
- span.setAttribute("com.microsoft.kiota.handler.redirect.count", redirectCount);
2846
- span.setAttribute("http.response.status_code", response.status);
2847
- return this.executeWithRedirect(url, fetchRequestInit, redirectCount, currentOptions, requestOptions);
2848
- } finally {
2849
- span.end();
2850
- }
2851
- });
2852
- }
2853
- return await this.executeWithRedirect(url, fetchRequestInit, redirectCount, currentOptions, requestOptions);
2854
- } else {
2855
- return response;
2856
- }
2857
- }
2858
- /**
2859
- * Executes the request and returns a promise resolving the response.
2860
- * @param url - The url for the request
2861
- * @param requestInit - The Fetch RequestInit object.
2862
- * @param requestOptions - The request options.
2863
- * @returns A Promise that resolves to the response.
2864
- */
2865
- execute(url, requestInit, requestOptions) {
2866
- const redirectCount = 0;
2867
- let currentOptions = this.options;
2868
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[RedirectHandlerOptionKey]) {
2869
- currentOptions = requestOptions[RedirectHandlerOptionKey];
2870
- }
2871
- requestInit.redirect = RedirectHandler.MANUAL_REDIRECT;
2872
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
2873
- if (obsOptions) {
2874
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("redirectHandler - execute", (span) => {
2875
- try {
2876
- span.setAttribute("com.microsoft.kiota.handler.redirect.enable", true);
2877
- return this.executeWithRedirect(url, requestInit, redirectCount, currentOptions, requestOptions, obsOptions.getTracerInstrumentationName());
2878
- } finally {
2879
- span.end();
2880
- }
2881
- });
2882
- }
2883
- return this.executeWithRedirect(url, requestInit, redirectCount, currentOptions, requestOptions);
2884
- }
2885
- }
2886
- RedirectHandler.REDIRECT_STATUS_CODES = /* @__PURE__ */ new Set([
2887
- 301,
2888
- // Moved Permanently
2889
- 302,
2890
- // Found
2891
- 303,
2892
- // See Other
2893
- 307,
2894
- // Temporary Permanently
2895
- 308
2896
- // Moved Permanently
2897
- ]);
2898
- RedirectHandler.STATUS_CODE_SEE_OTHER = 303;
2899
- RedirectHandler.LOCATION_HEADER = "Location";
2900
- RedirectHandler.AUTHORIZATION_HEADER = "Authorization";
2901
- RedirectHandler.MANUAL_REDIRECT = "manual";
2902
- const RetryHandlerOptionKey = "RetryHandlerOptionKey";
2903
- class RetryHandlerOptions {
2904
- /**
2905
- *
2906
- * To create an instance of RetryHandlerOptions
2907
- * @param options - The RetryHandlerOptionsParams object
2908
- * @returns An instance of RetryHandlerOptions
2909
- * @example const options = new RetryHandlerOptions({ maxRetries: 4 });
2910
- */
2911
- constructor(options = {}) {
2912
- var _a, _b, _c;
2913
- if (options.delay !== void 0 && options.delay > RetryHandlerOptions.MAX_DELAY) {
2914
- throw this.createError(`Delay should not be more than ${RetryHandlerOptions.MAX_DELAY}`, "MaxLimitExceeded");
2915
- }
2916
- if (options.maxRetries !== void 0 && options.maxRetries > RetryHandlerOptions.MAX_MAX_RETRIES) {
2917
- throw this.createError(`MaxRetries should not be more than ${RetryHandlerOptions.MAX_MAX_RETRIES}`, "MaxLimitExceeded");
2918
- }
2919
- if (options.delay !== void 0 && options.delay < 0) {
2920
- throw this.createError(`Delay should not be negative`, "MinExpectationNotMet");
2921
- }
2922
- if (options.maxRetries !== void 0 && options.maxRetries < 0) {
2923
- throw this.createError(`MaxRetries should not be negative`, "MinExpectationNotMet");
2924
- }
2925
- this.delay = Math.min((_a = options.delay) !== null && _a !== void 0 ? _a : RetryHandlerOptions.DEFAULT_DELAY, RetryHandlerOptions.MAX_DELAY);
2926
- this.maxRetries = Math.min((_b = options.maxRetries) !== null && _b !== void 0 ? _b : RetryHandlerOptions.DEFAULT_MAX_RETRIES, RetryHandlerOptions.MAX_MAX_RETRIES);
2927
- this.shouldRetry = (_c = options.shouldRetry) !== null && _c !== void 0 ? _c : RetryHandlerOptions.defaultShouldRetry;
2928
- }
2929
- /**
2930
- *
2931
- * Creates an error object with a message and name
2932
- * @param message - The error message
2933
- * @param name - The error name
2934
- * @returns An error object
2935
- */
2936
- createError(message, name) {
2937
- const error = new Error(message);
2938
- error.name = name;
2939
- return error;
2940
- }
2941
- /**
2942
- *
2943
- * To get the maximum delay
2944
- * @returns A maximum delay
2945
- */
2946
- getMaxDelay() {
2947
- return RetryHandlerOptions.MAX_DELAY;
2948
- }
2949
- getKey() {
2950
- return RetryHandlerOptionKey;
2951
- }
2952
- }
2953
- RetryHandlerOptions.DEFAULT_DELAY = 3;
2954
- RetryHandlerOptions.DEFAULT_MAX_RETRIES = 3;
2955
- RetryHandlerOptions.MAX_DELAY = 180;
2956
- RetryHandlerOptions.MAX_MAX_RETRIES = 10;
2957
- RetryHandlerOptions.defaultShouldRetry = () => true;
2958
- class RetryHandler {
2959
- /**
2960
- *
2961
- * To create an instance of RetryHandler
2962
- * @param [options] - The retry handler options value
2963
- * @returns An instance of RetryHandler
2964
- */
2965
- constructor(options = new RetryHandlerOptions()) {
2966
- this.options = options;
2967
- if (!options) {
2968
- throw new Error("The options parameter is required.");
2969
- }
2970
- }
2971
- /**
2972
- *
2973
- *
2974
- * To check whether the response has the retry status code
2975
- * @param response - The response object
2976
- * @returns Whether the response has retry status code or not
2977
- */
2978
- isRetry(response) {
2979
- return RetryHandler.RETRY_STATUS_CODES.has(response.status);
2980
- }
2981
- /**
2982
- *
2983
- * To check whether the payload is buffered or not
2984
- * @param options - The options of a request
2985
- * @returns Whether the payload is buffered or not
2986
- */
2987
- isBuffered(options) {
2988
- var _a;
2989
- const method = options.method;
2990
- const isPutPatchOrPost = method === HttpMethod.PUT || method === HttpMethod.PATCH || method === HttpMethod.POST;
2991
- if (isPutPatchOrPost) {
2992
- const isStream = ((_a = getRequestHeader(options, "content-type")) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === "application/octet-stream";
2993
- if (isStream) {
2994
- return false;
2995
- }
2996
- }
2997
- return true;
2998
- }
2999
- /**
3000
- *
3001
- * To get the delay for a retry
3002
- * @param response - The response object
3003
- * @param retryAttempts - The current attempt count
3004
- * @param delay - The delay value in seconds
3005
- * @returns A delay for a retry
3006
- */
3007
- getDelay(response, retryAttempts, delay) {
3008
- const getRandomness = () => Number(Math.random().toFixed(3));
3009
- const retryAfter = response.headers !== void 0 ? response.headers.get(RetryHandler.RETRY_AFTER_HEADER) : null;
3010
- let newDelay;
3011
- if (retryAfter !== null) {
3012
- if (Number.isNaN(Number(retryAfter))) {
3013
- newDelay = Math.round((new Date(retryAfter).getTime() - Date.now()) / 1e3);
3014
- } else {
3015
- newDelay = Number(retryAfter);
3016
- }
3017
- } else {
3018
- newDelay = retryAttempts >= 2 ? this.getExponentialBackOffTime(retryAttempts) + delay + getRandomness() : delay + getRandomness();
3019
- }
3020
- return Math.min(newDelay, this.options.getMaxDelay() + getRandomness());
3021
- }
3022
- /**
3023
- *
3024
- * To get an exponential back off value
3025
- * @param attempts - The current attempt count
3026
- * @returns An exponential back off value
3027
- */
3028
- getExponentialBackOffTime(attempts) {
3029
- return Math.round(1 / 2 * (2 ** attempts - 1));
3030
- }
3031
- /**
3032
- * To add delay for the execution
3033
- * @param delaySeconds - The delay value in seconds
3034
- * @returns A Promise that resolves to nothing
3035
- */
3036
- async sleep(delaySeconds) {
3037
- const delayMilliseconds = delaySeconds * 1e3;
3038
- return new Promise((resolve) => setTimeout(resolve, delayMilliseconds));
3039
- }
3040
- /**
3041
- * To execute the middleware with retries
3042
- * @param url - The request url
3043
- * @param fetchRequestInit - The request options
3044
- * @param retryAttempts - The current attempt count
3045
- * @param currentOptions - The current request options for the retry handler.
3046
- * @param requestOptions - The retry middleware options instance
3047
- * @param tracerName - The name to use for the tracer
3048
- * @returns A Promise that resolves to nothing
3049
- */
3050
- async executeWithRetry(url, fetchRequestInit, retryAttempts, currentOptions, requestOptions, tracerName) {
3051
- var _a;
3052
- const response = await ((_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, fetchRequestInit, requestOptions));
3053
- if (!response) {
3054
- throw new Error("Response is undefined");
3055
- }
3056
- if (retryAttempts < currentOptions.maxRetries && this.isRetry(response) && this.isBuffered(fetchRequestInit) && currentOptions.shouldRetry(currentOptions.delay, retryAttempts, url, fetchRequestInit, response)) {
3057
- ++retryAttempts;
3058
- setRequestHeader(fetchRequestInit, RetryHandler.RETRY_ATTEMPT_HEADER, retryAttempts.toString());
3059
- let delay = null;
3060
- if (response) {
3061
- delay = this.getDelay(response, retryAttempts, currentOptions.delay);
3062
- await this.sleep(delay);
3063
- }
3064
- if (tracerName) {
3065
- return await trace.getTracer(tracerName).startActiveSpan(`retryHandler - attempt ${retryAttempts}`, (span) => {
3066
- try {
3067
- span.setAttribute("http.request.resend_count", retryAttempts);
3068
- if (delay) {
3069
- span.setAttribute("http.request.resend_delay", delay);
3070
- }
3071
- span.setAttribute("http.response.status_code", response.status);
3072
- return this.executeWithRetry(url, fetchRequestInit, retryAttempts, currentOptions, requestOptions);
3073
- } finally {
3074
- span.end();
3075
- }
3076
- });
3077
- }
3078
- return await this.executeWithRetry(url, fetchRequestInit, retryAttempts, currentOptions, requestOptions);
3079
- } else {
3080
- return response;
3081
- }
3082
- }
3083
- /**
3084
- * To execute the current middleware
3085
- * @param url - The request url
3086
- * @param requestInit - The request options
3087
- * @param requestOptions - The request options
3088
- * @returns A Promise that resolves to nothing
3089
- */
3090
- execute(url, requestInit, requestOptions) {
3091
- const retryAttempts = 0;
3092
- let currentOptions = this.options;
3093
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[RetryHandlerOptionKey]) {
3094
- currentOptions = requestOptions[RetryHandlerOptionKey];
3095
- }
3096
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3097
- if (obsOptions) {
3098
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("retryHandler - execute", (span) => {
3099
- try {
3100
- span.setAttribute("com.microsoft.kiota.handler.retry.enable", true);
3101
- return this.executeWithRetry(url, requestInit, retryAttempts, currentOptions, requestOptions, obsOptions.getTracerInstrumentationName());
3102
- } finally {
3103
- span.end();
3104
- }
3105
- });
3106
- }
3107
- return this.executeWithRetry(url, requestInit, retryAttempts, currentOptions, requestOptions);
3108
- }
3109
- }
3110
- RetryHandler.RETRY_STATUS_CODES = /* @__PURE__ */ new Set([
3111
- 429,
3112
- // Too many requests
3113
- 503,
3114
- // Service unavailable
3115
- 504
3116
- // Gateway timeout
3117
- ]);
3118
- RetryHandler.RETRY_ATTEMPT_HEADER = "Retry-Attempt";
3119
- RetryHandler.RETRY_AFTER_HEADER = "Retry-After";
3120
- const libraryVersion = "1.0.0-preview.24";
3121
- const UserAgentHandlerOptionsKey = "UserAgentHandlerOptionKey";
3122
- class UserAgentHandlerOptions {
3123
- getKey() {
3124
- return UserAgentHandlerOptionsKey;
3125
- }
3126
- /**
3127
- *
3128
- * To create an instance of UserAgentHandlerOptions
3129
- * @param [options] - The options for the UserAgentHandler
3130
- * @example const options = new UserAgentHandlerOptions({ enable: false });
3131
- */
3132
- constructor(options = {}) {
3133
- var _a, _b, _c;
3134
- this.enable = (_a = options.enable) !== null && _a !== void 0 ? _a : true;
3135
- this.productName = (_b = options.productName) !== null && _b !== void 0 ? _b : "kiota-typescript";
3136
- this.productVersion = (_c = options.productVersion) !== null && _c !== void 0 ? _c : libraryVersion;
3137
- }
3138
- }
3139
- const USER_AGENT_HEADER_KEY = "User-Agent";
3140
- class UserAgentHandler {
3141
- /**
3142
- * To create an instance of UserAgentHandler
3143
- * @param _options - The options for the middleware
3144
- */
3145
- constructor(_options = new UserAgentHandlerOptions()) {
3146
- this._options = _options;
3147
- }
3148
- /** @inheritdoc */
3149
- execute(url, requestInit, requestOptions) {
3150
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3151
- if (obsOptions) {
3152
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("userAgentHandler - execute", (span) => {
3153
- try {
3154
- span.setAttribute("com.microsoft.kiota.handler.useragent.enable", true);
3155
- return this.addValue(url, requestInit, requestOptions);
3156
- } finally {
3157
- span.end();
3158
- }
3159
- });
3160
- } else {
3161
- return this.addValue(url, requestInit, requestOptions);
3162
- }
3163
- }
3164
- async addValue(url, requestInit, requestOptions) {
3165
- var _a;
3166
- let currentOptions = this._options;
3167
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[UserAgentHandlerOptionsKey]) {
3168
- currentOptions = requestOptions[UserAgentHandlerOptionsKey];
3169
- }
3170
- if (currentOptions.enable) {
3171
- const additionalValue = `${currentOptions.productName}/${currentOptions.productVersion}`;
3172
- const currentValue = getRequestHeader(requestInit, USER_AGENT_HEADER_KEY);
3173
- if (!(currentValue === null || currentValue === void 0 ? void 0 : currentValue.includes(additionalValue))) {
3174
- appendRequestHeader(requestInit, USER_AGENT_HEADER_KEY, additionalValue, " ");
3175
- }
3176
- }
3177
- const response = await ((_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, requestInit, requestOptions));
3178
- if (!response)
3179
- throw new Error("No response returned by the next middleware");
3180
- return response;
3181
- }
3182
- }
3183
- const UrlReplaceHandlerOptionsKey = "UrlReplaceHandlerOptionsKey";
3184
- class UrlReplaceHandlerOptions {
3185
- /**
3186
- * Create a new instance of the UrlReplaceHandlerOptions class
3187
- * @param config the configuration to apply to the url replace handler options.
3188
- */
3189
- constructor(config) {
3190
- var _a, _b;
3191
- if (config) {
3192
- this._urlReplacements = (_a = config.urlReplacements) !== null && _a !== void 0 ? _a : {};
3193
- this._enabled = (_b = config.enabled) !== null && _b !== void 0 ? _b : true;
3194
- } else {
3195
- this._urlReplacements = {};
3196
- this._enabled = true;
3197
- }
3198
- }
3199
- /**
3200
- * @inheritdoc
3201
- */
3202
- getKey() {
3203
- return UrlReplaceHandlerOptionsKey;
3204
- }
3205
- /**
3206
- * Returns whether the url replace handler is enabled or not.
3207
- * @returns whether the url replace handler is enabled or not.
3208
- */
3209
- get enabled() {
3210
- return this._enabled;
3211
- }
3212
- /**
3213
- * Returns the url replacements combinations.
3214
- * @returns the url replacements combinations.
3215
- */
3216
- get urlReplacements() {
3217
- return this._urlReplacements;
3218
- }
3219
- }
3220
- class UrlReplaceHandler {
3221
- /**
3222
- *
3223
- * Creates a new instance of the UrlReplaceHandler class
3224
- * @param handlerOptions The options for the url replace handler.
3225
- * @returns An instance of the UrlReplaceHandler class
3226
- */
3227
- constructor(handlerOptions = new UrlReplaceHandlerOptions()) {
3228
- this.handlerOptions = handlerOptions;
3229
- if (!handlerOptions) {
3230
- throw new Error("handlerOptions cannot be undefined");
3231
- }
3232
- }
3233
- /**
3234
- * @inheritdoc
3235
- */
3236
- execute(url, requestInit, requestOptions) {
3237
- let currentOptions = this.handlerOptions;
3238
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[UrlReplaceHandlerOptionsKey]) {
3239
- currentOptions = requestOptions[UrlReplaceHandlerOptionsKey];
3240
- }
3241
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3242
- if (obsOptions) {
3243
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("urlReplaceHandler - execute", (span) => {
3244
- try {
3245
- span.setAttribute("com.microsoft.kiota.handler.urlReplace.enable", currentOptions.enabled);
3246
- return this.replaceTokensInUrl(currentOptions, url, requestInit, requestOptions);
3247
- } finally {
3248
- span.end();
3249
- }
3250
- });
3251
- }
3252
- return this.replaceTokensInUrl(currentOptions, url, requestInit, requestOptions);
3253
- }
3254
- replaceTokensInUrl(options, url, requestInit, requestOptions) {
3255
- var _a;
3256
- if (options.enabled) {
3257
- Object.keys(options.urlReplacements).forEach((replacementKey) => {
3258
- url = url.replace(replacementKey, options.urlReplacements[replacementKey]);
3259
- });
3260
- }
3261
- const response = (_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, requestInit, requestOptions);
3262
- if (!response) {
3263
- throw new Error("Response is undefined");
3264
- }
3265
- return response;
3266
- }
3267
- }
3268
- class MiddlewareFactory {
3269
- /**
3270
- * @param customFetch - The custom fetch implementation
3271
- * Returns the default middleware chain an array with the middleware handlers
3272
- * @returns an array of the middleware handlers of the default middleware chain
3273
- */
3274
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
3275
- static getDefaultMiddlewares(customFetch = (...args) => fetch(...args)) {
3276
- return [new RetryHandler(), new RedirectHandler(), new ParametersNameDecodingHandler(), new UserAgentHandler(), new HeadersInspectionHandler(), new UrlReplaceHandler(), new CustomFetchHandler(customFetch)];
3277
- }
3278
- /**
3279
- * @param customFetch - The custom fetch implementation
3280
- * Returns the default middleware chain + performance middleware
3281
- * @returns an array of the middleware handlers of the default + performance middleware chain
3282
- */
3283
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
3284
- static getPerformanceMiddlewares(customFetch = (...args) => fetch(...args)) {
3285
- const middlewares = MiddlewareFactory.getDefaultMiddlewares(customFetch);
3286
- middlewares.splice(middlewares.length - 3, 0, new CompressionHandler());
3287
- return middlewares;
3288
- }
3289
- }
3290
- const ErrorHandlerOptionKey = "ErrorHandlerOptionKey";
3291
- class ErrorHandlerOptions {
3292
- constructor(enabled = true) {
3293
- this.enabled = enabled;
3294
- }
3295
- getKey() {
3296
- return ErrorHandlerOptionKey;
3297
- }
3298
- }
3299
- class ErrorHandler {
3300
- /**
3301
- *
3302
- * To create an instance of ErrorHandler
3303
- * @param [options] - The error handler options value
3304
- * @returns An instance of ErrorHandler
3305
- */
3306
- constructor(options = new ErrorHandlerOptions()) {
3307
- this.options = options;
3308
- }
3309
- /**
3310
- *
3311
- * The next middleware in the middleware chain
3312
- */
3313
- next;
3314
- /**
3315
- * To execute the current middleware
3316
- * @param url - The request url
3317
- * @param requestInit - The request options
3318
- * @param requestOptions - The request options
3319
- * @returns A Promise that resolves to nothing
3320
- */
3321
- async execute(url, requestInit, requestOptions) {
3322
- const response = await this.next?.execute(url, requestInit, requestOptions);
3323
- if (!response) {
3324
- throw new Error("Response is undefined");
3325
- }
3326
- let currentOptions = this.options;
3327
- if (requestOptions?.[ErrorHandlerOptionKey]) {
3328
- currentOptions = requestOptions[ErrorHandlerOptionKey];
3329
- }
3330
- if (currentOptions.enabled === false || this.isSuccessStatusCode(response)) {
3331
- return response;
3332
- }
3333
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3334
- if (obsOptions) {
3335
- trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("retryHandler - execute", (span) => {
3336
- span.setAttribute("com.microsoft.kiota.handler.error.enable", true);
3337
- span.setAttribute("http.response.status_code", response.status);
3338
- span.setAttribute("http.response.status_text", response.statusText);
3339
- span.setAttribute("http.response.url", response.url);
3340
- span.end();
3341
- });
3342
- }
3343
- const err = new HttpRequestError(
3344
- `Request to ${url} failed with status code ${response.status}`,
3345
- response.status,
3346
- { url, request: requestInit, response }
3347
- );
3348
- throw err;
3349
- }
3350
- isSuccessStatusCode(response) {
3351
- return response.status >= 200 && response.status < 300;
3352
- }
3353
- }
3354
- class HttpRequestError extends Error {
3355
- constructor(message, statusCode, context) {
3356
- super(message);
3357
- this.statusCode = statusCode;
3358
- this.name = "HttpRequestError";
3359
- if (Error.captureStackTrace) {
3360
- Error.captureStackTrace(this, HttpRequestError);
3361
- }
3362
- }
3363
- }
3364
- class AccessTokenProvider {
3365
- constructor(getAccessToken) {
3366
- this.getAccessToken = getAccessToken;
3367
- }
3368
- async getAuthorizationToken(url, additionalAuthenticationContext) {
3369
- return await this.getAccessToken();
3370
- }
3371
- getAllowedHostsValidator() {
3372
- throw new Error("Method not implemented.");
3373
- }
3374
- }
3375
- class HttpClientFactory {
3376
- static create(customFetch) {
3377
- const middlewares = [new ErrorHandler(), ...MiddlewareFactory.getDefaultMiddlewares(customFetch)];
3378
- return new HttpClient(customFetch, ...middlewares);
3379
- }
3380
- static createFetchRequestAdapter(getAccessToken, httpClient) {
3381
- const auth = new BaseBearerTokenAuthenticationProvider(new AccessTokenProvider(getAccessToken));
3382
- return new FetchRequestAdapter(
3383
- auth,
3384
- void 0,
3385
- void 0,
3386
- httpClient
3387
- );
3388
- }
3389
- }
3390
- export {
3391
- HttpClientFactory
3392
- };
3393
- //# sourceMappingURL=index.es.js.map