levelfour 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.fernignore +9 -0
- package/BaseClient.ts +56 -0
- package/Client.ts +90 -0
- package/LevelFourClient.ts +50 -0
- package/api/errors/UnprocessableEntityError.ts +22 -0
- package/api/errors/index.ts +1 -0
- package/api/index.ts +3 -0
- package/api/resources/apiKeys/client/Client.ts +298 -0
- package/api/resources/apiKeys/client/index.ts +1 -0
- package/api/resources/apiKeys/client/requests/CreateApiKeyRequest.ts +23 -0
- package/api/resources/apiKeys/client/requests/ListApiKeysApiV1ApiKeysGetRequest.ts +11 -0
- package/api/resources/apiKeys/client/requests/RevokeApiKeyApiV1ApiKeysKeyIdDeleteRequest.ts +14 -0
- package/api/resources/apiKeys/client/requests/RotateApiKeyApiV1ApiKeysKeyIdRotatePostRequest.ts +14 -0
- package/api/resources/apiKeys/client/requests/index.ts +4 -0
- package/api/resources/apiKeys/exports.ts +4 -0
- package/api/resources/apiKeys/index.ts +1 -0
- package/api/resources/evaluation/client/Client.ts +71 -0
- package/api/resources/evaluation/client/index.ts +1 -0
- package/api/resources/evaluation/exports.ts +4 -0
- package/api/resources/evaluation/index.ts +1 -0
- package/api/resources/health/client/Client.ts +108 -0
- package/api/resources/health/client/index.ts +1 -0
- package/api/resources/health/exports.ts +4 -0
- package/api/resources/health/index.ts +1 -0
- package/api/resources/index.ts +24 -0
- package/api/resources/prAnalysis/client/Client.ts +100 -0
- package/api/resources/prAnalysis/client/index.ts +1 -0
- package/api/resources/prAnalysis/client/requests/AnalyzePrRequest.ts +30 -0
- package/api/resources/prAnalysis/client/requests/index.ts +1 -0
- package/api/resources/prAnalysis/exports.ts +4 -0
- package/api/resources/prAnalysis/index.ts +1 -0
- package/api/resources/prAnalysisActions/client/Client.ts +418 -0
- package/api/resources/prAnalysisActions/client/index.ts +1 -0
- package/api/resources/prAnalysisActions/client/requests/DismissSuggestionsApiV1PrAnalysisActionsDismissPostRequest.ts +21 -0
- package/api/resources/prAnalysisActions/client/requests/GetIgnoredResourcesApiV1PrAnalysisActionsIgnoreGetRequest.ts +15 -0
- package/api/resources/prAnalysisActions/client/requests/GetPrStatusApiV1PrAnalysisActionsStatusGetRequest.ts +15 -0
- package/api/resources/prAnalysisActions/client/requests/IgnoreRequest.ts +21 -0
- package/api/resources/prAnalysisActions/client/requests/SnoozeSuggestionsApiV1PrAnalysisActionsSnoozePostRequest.ts +21 -0
- package/api/resources/prAnalysisActions/client/requests/index.ts +5 -0
- package/api/resources/prAnalysisActions/exports.ts +4 -0
- package/api/resources/prAnalysisActions/index.ts +1 -0
- package/api/resources/prAnalysisInstallations/client/Client.ts +410 -0
- package/api/resources/prAnalysisInstallations/client/index.ts +1 -0
- package/api/resources/prAnalysisInstallations/client/requests/AddReposRequest.ts +17 -0
- package/api/resources/prAnalysisInstallations/client/requests/DeleteInstallationApiV1PrAnalysisInstallationsInstallationIdDeleteRequest.ts +15 -0
- package/api/resources/prAnalysisInstallations/client/requests/ListInstallationsApiV1PrAnalysisInstallationsGetRequest.ts +13 -0
- package/api/resources/prAnalysisInstallations/client/requests/RegisterInstallationRequest.ts +16 -0
- package/api/resources/prAnalysisInstallations/client/requests/RemoveReposRequest.ts +17 -0
- package/api/resources/prAnalysisInstallations/client/requests/index.ts +5 -0
- package/api/resources/prAnalysisInstallations/exports.ts +4 -0
- package/api/resources/prAnalysisInstallations/index.ts +1 -0
- package/api/resources/prAnalysisQuery/client/Client.ts +169 -0
- package/api/resources/prAnalysisQuery/client/index.ts +1 -0
- package/api/resources/prAnalysisQuery/client/requests/ExplainRequest.ts +17 -0
- package/api/resources/prAnalysisQuery/client/requests/WhatifRequest.ts +21 -0
- package/api/resources/prAnalysisQuery/client/requests/index.ts +2 -0
- package/api/resources/prAnalysisQuery/exports.ts +4 -0
- package/api/resources/prAnalysisQuery/index.ts +1 -0
- package/api/resources/providers/client/Client.ts +991 -0
- package/api/resources/providers/client/index.ts +1 -0
- package/api/resources/providers/client/requests/GetProviderFilterOptionsApiV1ProvidersProviderIdSpendingFilterOptionsGetRequest.ts +17 -0
- package/api/resources/providers/client/requests/GetProviderPotentialSavingsBreakdownApiV1ProvidersProviderIdPotentialSavingsBreakdownGetRequest.ts +19 -0
- package/api/resources/providers/client/requests/GetProviderPotentialSavingsSummaryApiV1ProvidersProviderIdPotentialSavingsSummaryGetRequest.ts +11 -0
- package/api/resources/providers/client/requests/GetProviderRecommendationFilterOptionsApiV1ProvidersProviderIdRecommendationsFilterOptionsGetRequest.ts +11 -0
- package/api/resources/providers/client/requests/GetProviderRecommendationsBreakdownApiV1ProvidersProviderIdRecommendationsGetRequest.ts +33 -0
- package/api/resources/providers/client/requests/GetProviderRecommendationsOverviewApiV1ProvidersProviderIdRecommendationsOverviewGetRequest.ts +11 -0
- package/api/resources/providers/client/requests/GetProviderRecommendationsSummaryApiV1ProvidersProviderIdRecommendationsSummaryGetRequest.ts +11 -0
- package/api/resources/providers/client/requests/GetProviderSavedSummaryApiV1ProvidersProviderIdSavingsSummaryGetRequest.ts +11 -0
- package/api/resources/providers/client/requests/GetProviderServiceBreakdownApiV1ProvidersProviderIdSpendingBreakdownGetRequest.ts +45 -0
- package/api/resources/providers/client/requests/GetProviderSpendingSummaryApiV1ProvidersProviderIdSpendingSummaryGetRequest.ts +11 -0
- package/api/resources/providers/client/requests/GetProviderSpendingTimelineApiV1ProvidersProviderIdSpendingTimelineGetRequest.ts +17 -0
- package/api/resources/providers/client/requests/GetSavedByProviderBreakdownApiV1ProvidersProviderIdSavingsBreakdownGetRequest.ts +31 -0
- package/api/resources/providers/client/requests/index.ts +12 -0
- package/api/resources/providers/exports.ts +4 -0
- package/api/resources/providers/index.ts +2 -0
- package/api/resources/providers/types/GetProviderServiceBreakdownApiV1ProvidersProviderIdSpendingBreakdownGetResponse.ts +8 -0
- package/api/resources/providers/types/index.ts +1 -0
- package/api/resources/recommendations/client/Client.ts +815 -0
- package/api/resources/recommendations/client/index.ts +1 -0
- package/api/resources/recommendations/client/requests/AcceptTermsApiV1RecommendationsRecommendationIdAcceptTermsPostRequest.ts +11 -0
- package/api/resources/recommendations/client/requests/CompleteWizardApiV1RecommendationsRecommendationIdCompletePostRequest.ts +11 -0
- package/api/resources/recommendations/client/requests/GetRecommendationDetailsApiV1RecommendationsRecommendationIdDetailsGetRequest.ts +11 -0
- package/api/resources/recommendations/client/requests/GetRecommendationForWizardApiV1RecommendationsRecommendationIdGetRequest.ts +11 -0
- package/api/resources/recommendations/client/requests/GetRecommendationsApiV1RecommendationsGetRequest.ts +16 -0
- package/api/resources/recommendations/client/requests/ImplementationMethodRequest.ts +14 -0
- package/api/resources/recommendations/client/requests/SavingsDecisionRequest.ts +18 -0
- package/api/resources/recommendations/client/requests/UpdateTagRequest.ts +13 -0
- package/api/resources/recommendations/client/requests/index.ts +8 -0
- package/api/resources/recommendations/exports.ts +4 -0
- package/api/resources/recommendations/index.ts +1 -0
- package/api/resources/savings/client/Client.ts +231 -0
- package/api/resources/savings/client/index.ts +1 -0
- package/api/resources/savings/client/requests/ExecutionRequestBody.ts +15 -0
- package/api/resources/savings/client/requests/GetSavedBreakdownApiV1SavingsBreakdownGetRequest.ts +30 -0
- package/api/resources/savings/client/requests/index.ts +2 -0
- package/api/resources/savings/exports.ts +4 -0
- package/api/resources/savings/index.ts +1 -0
- package/api/resources/spending/client/Client.ts +288 -0
- package/api/resources/spending/client/index.ts +1 -0
- package/api/resources/spending/client/requests/GetCostBreakdownApiV1SpendingBreakdownGetRequest.ts +30 -0
- package/api/resources/spending/client/requests/GetDailySpendingBreakdownApiV1SpendingDailyBreakdownGetRequest.ts +12 -0
- package/api/resources/spending/client/requests/index.ts +2 -0
- package/api/resources/spending/exports.ts +4 -0
- package/api/resources/spending/index.ts +2 -0
- package/api/resources/spending/types/GetCostBreakdownApiV1SpendingBreakdownGetResponse.ts +9 -0
- package/api/resources/spending/types/index.ts +1 -0
- package/api/resources/webhooks/client/Client.ts +232 -0
- package/api/resources/webhooks/client/index.ts +1 -0
- package/api/resources/webhooks/client/requests/DeleteEndpointApiV1WebhooksEndpointsEndpointIdDeleteRequest.ts +14 -0
- package/api/resources/webhooks/client/requests/ListEndpointsApiV1WebhooksEndpointsGetRequest.ts +11 -0
- package/api/resources/webhooks/client/requests/RegisterEndpointRequest.ts +18 -0
- package/api/resources/webhooks/client/requests/index.ts +3 -0
- package/api/resources/webhooks/exports.ts +4 -0
- package/api/resources/webhooks/index.ts +1 -0
- package/api/types/AcceptTermsData.ts +10 -0
- package/api/types/AcceptTermsResponse.ts +12 -0
- package/api/types/ActionRequest.ts +14 -0
- package/api/types/ApiKeyCreatedData.ts +13 -0
- package/api/types/ApiKeyData.ts +12 -0
- package/api/types/ComparisonItem.ts +10 -0
- package/api/types/CompleteWizardData.ts +12 -0
- package/api/types/CompleteWizardResponse.ts +12 -0
- package/api/types/CostBreakdownData.ts +14 -0
- package/api/types/CostBreakdownItem.ts +27 -0
- package/api/types/CostBreakdownRawData.ts +15 -0
- package/api/types/CostBreakdownRawResponse.ts +12 -0
- package/api/types/CostBreakdownResponse.ts +12 -0
- package/api/types/CostsBreakdownChartData.ts +19 -0
- package/api/types/CostsBreakdownChartResponse.ts +12 -0
- package/api/types/CostsBreakdownDataPoint.ts +17 -0
- package/api/types/CostsBreakdownGroupedChartData.ts +21 -0
- package/api/types/CostsBreakdownGroupedChartResponse.ts +12 -0
- package/api/types/CostsBreakdownGroupedDataPoint.ts +13 -0
- package/api/types/CostsBreakdownTotals.ts +15 -0
- package/api/types/CreateApiKeyResponse.ts +9 -0
- package/api/types/DailySpendingBreakdownData.ts +17 -0
- package/api/types/DailySpendingBreakdownResponse.ts +12 -0
- package/api/types/DailySpendingDataPoint.ts +11 -0
- package/api/types/DashboardSummaryData.ts +29 -0
- package/api/types/DashboardSummaryResponse.ts +12 -0
- package/api/types/DeleteEndpointData.ts +6 -0
- package/api/types/DeleteEndpointResponse.ts +9 -0
- package/api/types/EndpointData.ts +9 -0
- package/api/types/EvaluationStatusData.ts +27 -0
- package/api/types/EvaluationStatusResponse.ts +12 -0
- package/api/types/ExecutionLogCommand.ts +7 -0
- package/api/types/ExecutionLogEntry.ts +10 -0
- package/api/types/ExecutionStepSchema.ts +9 -0
- package/api/types/HttpValidationError.ts +7 -0
- package/api/types/ImplementationMethodData.ts +10 -0
- package/api/types/ImplementationMethodResponse.ts +12 -0
- package/api/types/ImplementationStep.ts +8 -0
- package/api/types/ListApiKeysData.ts +8 -0
- package/api/types/ListApiKeysResponse.ts +9 -0
- package/api/types/ListEndpointsResponse.ts +9 -0
- package/api/types/MetricDataPoint.ts +8 -0
- package/api/types/MetricSeries.ts +15 -0
- package/api/types/MetricSeriesEntry.ts +9 -0
- package/api/types/MonthlySpendingData.ts +11 -0
- package/api/types/MonthlySpendingDataPoint.ts +11 -0
- package/api/types/MonthlySpendingResponse.ts +12 -0
- package/api/types/PaginationMeta.ts +19 -0
- package/api/types/ProcessingRecommendationItem.ts +23 -0
- package/api/types/ProcessingRecommendationsData.ts +12 -0
- package/api/types/ProcessingRecommendationsResponse.ts +12 -0
- package/api/types/Provider.ts +17 -0
- package/api/types/ProviderBreakdownData.ts +13 -0
- package/api/types/ProviderBreakdownItem.ts +31 -0
- package/api/types/ProviderBreakdownResponse.ts +12 -0
- package/api/types/ProviderFilterOptionsData.ts +19 -0
- package/api/types/ProviderFilterOptionsResponse.ts +12 -0
- package/api/types/ProviderPotentialSavingsSummaryData.ts +17 -0
- package/api/types/ProviderPotentialSavingsSummaryResponse.ts +12 -0
- package/api/types/ProviderRecommendationsSummaryData.ts +15 -0
- package/api/types/ProviderRecommendationsSummaryResponse.ts +12 -0
- package/api/types/ProviderSavedSummaryData.ts +21 -0
- package/api/types/ProviderSavedSummaryResponse.ts +12 -0
- package/api/types/ProviderServiceBreakdownData.ts +26 -0
- package/api/types/ProviderServiceBreakdownItem.ts +29 -0
- package/api/types/ProviderServiceBreakdownRawData.ts +25 -0
- package/api/types/ProviderServiceBreakdownRawResponse.ts +12 -0
- package/api/types/ProviderServiceBreakdownResponse.ts +12 -0
- package/api/types/ProviderServiceCostsBreakdownData.ts +25 -0
- package/api/types/ProviderServiceCostsBreakdownResponse.ts +12 -0
- package/api/types/ProviderServiceCostsDataPoint.ts +13 -0
- package/api/types/ProviderSpending.ts +23 -0
- package/api/types/ProviderSpendingSummaryData.ts +27 -0
- package/api/types/ProviderSpendingSummaryResponse.ts +12 -0
- package/api/types/ProviderTimelineData.ts +23 -0
- package/api/types/ProviderTimelineResponse.ts +12 -0
- package/api/types/ProviderTopService.ts +13 -0
- package/api/types/ProvidersSummaryData.ts +10 -0
- package/api/types/ProvidersSummaryResponse.ts +12 -0
- package/api/types/RecommendationActions.ts +28 -0
- package/api/types/RecommendationDetail.ts +22 -0
- package/api/types/RecommendationDetailResponse.ts +12 -0
- package/api/types/RecommendationFilterOptionsData.ts +15 -0
- package/api/types/RecommendationFilterOptionsResponse.ts +12 -0
- package/api/types/RecommendationItem.ts +19 -0
- package/api/types/RecommendationWizardData.ts +83 -0
- package/api/types/RecommendationWizardResponse.ts +12 -0
- package/api/types/RecommendationsBreakdownData.ts +11 -0
- package/api/types/RecommendationsBreakdownResponse.ts +12 -0
- package/api/types/RecommendationsOverviewData.ts +19 -0
- package/api/types/RecommendationsOverviewResponse.ts +12 -0
- package/api/types/RegisterEndpointResponse.ts +9 -0
- package/api/types/ResourceChange.ts +14 -0
- package/api/types/ResourceSnapshot.ts +7 -0
- package/api/types/RevokeApiKeyData.ts +6 -0
- package/api/types/RevokeApiKeyResponse.ts +9 -0
- package/api/types/RiskAssessment.ts +11 -0
- package/api/types/RiskFactor.ts +8 -0
- package/api/types/SavedBreakdownData.ts +13 -0
- package/api/types/SavedBreakdownResponse.ts +12 -0
- package/api/types/SavedByProviderBreakdownData.ts +13 -0
- package/api/types/SavedByProviderBreakdownResponse.ts +12 -0
- package/api/types/SavedByProviderItem.ts +29 -0
- package/api/types/SavedItem.ts +20 -0
- package/api/types/SavedProviderSummary.ts +13 -0
- package/api/types/SavedSummaryData.ts +23 -0
- package/api/types/SavedSummaryResponse.ts +12 -0
- package/api/types/SavingsDecisionData.ts +13 -0
- package/api/types/SavingsDecisionResponse.ts +12 -0
- package/api/types/SpendingByDateItem.ts +13 -0
- package/api/types/TopRecommendation.ts +21 -0
- package/api/types/TriggerInfo.ts +8 -0
- package/api/types/UpdateTagData.ts +6 -0
- package/api/types/UpdateTagResponse.ts +9 -0
- package/api/types/ValidationError.ts +17 -0
- package/api/types/index.ts +115 -0
- package/core/exports.ts +1 -0
- package/core/fetcher/APIResponse.ts +23 -0
- package/core/fetcher/BinaryResponse.ts +34 -0
- package/core/fetcher/EndpointMetadata.ts +13 -0
- package/core/fetcher/EndpointSupplier.ts +14 -0
- package/core/fetcher/Fetcher.ts +398 -0
- package/core/fetcher/Headers.ts +93 -0
- package/core/fetcher/HttpResponsePromise.ts +116 -0
- package/core/fetcher/RawResponse.ts +61 -0
- package/core/fetcher/Supplier.ts +11 -0
- package/core/fetcher/createRequestUrl.ts +6 -0
- package/core/fetcher/getErrorResponseBody.ts +33 -0
- package/core/fetcher/getFetchFn.ts +3 -0
- package/core/fetcher/getHeader.ts +8 -0
- package/core/fetcher/getRequestBody.ts +20 -0
- package/core/fetcher/getResponseBody.ts +58 -0
- package/core/fetcher/index.ts +11 -0
- package/core/fetcher/makeRequest.ts +70 -0
- package/core/fetcher/requestWithRetries.ts +64 -0
- package/core/fetcher/signals.ts +26 -0
- package/core/headers.ts +33 -0
- package/core/index.ts +4 -0
- package/core/json.ts +27 -0
- package/core/logging/exports.ts +19 -0
- package/core/logging/index.ts +1 -0
- package/core/logging/logger.ts +203 -0
- package/core/runtime/index.ts +1 -0
- package/core/runtime/runtime.ts +134 -0
- package/core/url/encodePathParam.ts +18 -0
- package/core/url/index.ts +3 -0
- package/core/url/join.ts +79 -0
- package/core/url/qs.ts +74 -0
- package/errors/LevelFourError.ts +58 -0
- package/errors/LevelFourTimeoutError.ts +13 -0
- package/errors/handleNonStatusCodeError.ts +37 -0
- package/errors/index.ts +2 -0
- package/errors.ts +100 -0
- package/exports.ts +1 -0
- package/index.ts +22 -0
- package/jest.config.js +17 -0
- package/package.json +35 -0
- package/pagination.ts +54 -0
- package/telemetry.ts +64 -0
- package/tests/auth.test.ts +64 -0
- package/tests/errors.test.ts +92 -0
- package/tests/pagination.test.ts +72 -0
- package/tests/telemetry.test.ts +110 -0
- package/tsconfig.json +22 -0
- package/webhooks.ts +77 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
let Headers: typeof globalThis.Headers;
|
|
2
|
+
|
|
3
|
+
if (typeof globalThis.Headers !== "undefined") {
|
|
4
|
+
Headers = globalThis.Headers;
|
|
5
|
+
} else {
|
|
6
|
+
Headers = class Headers implements Headers {
|
|
7
|
+
private headers: Map<string, string[]>;
|
|
8
|
+
|
|
9
|
+
constructor(init?: HeadersInit) {
|
|
10
|
+
this.headers = new Map();
|
|
11
|
+
|
|
12
|
+
if (init) {
|
|
13
|
+
if (init instanceof Headers) {
|
|
14
|
+
init.forEach((value, key) => this.append(key, value));
|
|
15
|
+
} else if (Array.isArray(init)) {
|
|
16
|
+
for (const [key, value] of init) {
|
|
17
|
+
if (typeof key === "string" && typeof value === "string") {
|
|
18
|
+
this.append(key, value);
|
|
19
|
+
} else {
|
|
20
|
+
throw new TypeError("Each header entry must be a [string, string] tuple");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
} else {
|
|
24
|
+
for (const [key, value] of Object.entries(init)) {
|
|
25
|
+
if (typeof value === "string") {
|
|
26
|
+
this.append(key, value);
|
|
27
|
+
} else {
|
|
28
|
+
throw new TypeError("Header values must be strings");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
append(name: string, value: string): void {
|
|
36
|
+
const key = name.toLowerCase();
|
|
37
|
+
const existing = this.headers.get(key) || [];
|
|
38
|
+
this.headers.set(key, [...existing, value]);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
delete(name: string): void {
|
|
42
|
+
const key = name.toLowerCase();
|
|
43
|
+
this.headers.delete(key);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
get(name: string): string | null {
|
|
47
|
+
const key = name.toLowerCase();
|
|
48
|
+
const values = this.headers.get(key);
|
|
49
|
+
return values ? values.join(", ") : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
has(name: string): boolean {
|
|
53
|
+
const key = name.toLowerCase();
|
|
54
|
+
return this.headers.has(key);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
set(name: string, value: string): void {
|
|
58
|
+
const key = name.toLowerCase();
|
|
59
|
+
this.headers.set(key, [value]);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: unknown): void {
|
|
63
|
+
const boundCallback = thisArg ? callbackfn.bind(thisArg) : callbackfn;
|
|
64
|
+
this.headers.forEach((values, key) => boundCallback(values.join(", "), key, this));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
getSetCookie(): string[] {
|
|
68
|
+
return this.headers.get("set-cookie") || [];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
*entries(): HeadersIterator<[string, string]> {
|
|
72
|
+
for (const [key, values] of this.headers.entries()) {
|
|
73
|
+
yield [key, values.join(", ")];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
*keys(): HeadersIterator<string> {
|
|
78
|
+
yield* this.headers.keys();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
*values(): HeadersIterator<string> {
|
|
82
|
+
for (const values of this.headers.values()) {
|
|
83
|
+
yield values.join(", ");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
[Symbol.iterator](): HeadersIterator<[string, string]> {
|
|
88
|
+
return this.entries();
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export { Headers };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { WithRawResponse } from "./RawResponse.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A promise that returns the parsed response and lets you retrieve the raw response too.
|
|
5
|
+
*/
|
|
6
|
+
export class HttpResponsePromise<T> extends Promise<T> {
|
|
7
|
+
private innerPromise: Promise<WithRawResponse<T>>;
|
|
8
|
+
private unwrappedPromise: Promise<T> | undefined;
|
|
9
|
+
|
|
10
|
+
private constructor(promise: Promise<WithRawResponse<T>>) {
|
|
11
|
+
// Initialize with a no-op to avoid premature parsing
|
|
12
|
+
super((resolve) => {
|
|
13
|
+
resolve(undefined as unknown as T);
|
|
14
|
+
});
|
|
15
|
+
this.innerPromise = promise;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Creates an `HttpResponsePromise` from a function that returns a promise.
|
|
20
|
+
*
|
|
21
|
+
* @param fn - A function that returns a promise resolving to a `WithRawResponse` object.
|
|
22
|
+
* @param args - Arguments to pass to the function.
|
|
23
|
+
* @returns An `HttpResponsePromise` instance.
|
|
24
|
+
*/
|
|
25
|
+
public static fromFunction<F extends (...args: never[]) => Promise<WithRawResponse<T>>, T>(
|
|
26
|
+
fn: F,
|
|
27
|
+
...args: Parameters<F>
|
|
28
|
+
): HttpResponsePromise<T> {
|
|
29
|
+
return new HttpResponsePromise<T>(fn(...args));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Creates a function that returns an `HttpResponsePromise` from a function that returns a promise.
|
|
34
|
+
*
|
|
35
|
+
* @param fn - A function that returns a promise resolving to a `WithRawResponse` object.
|
|
36
|
+
* @returns A function that returns an `HttpResponsePromise` instance.
|
|
37
|
+
*/
|
|
38
|
+
public static interceptFunction<
|
|
39
|
+
F extends (...args: never[]) => Promise<WithRawResponse<T>>,
|
|
40
|
+
T = Awaited<ReturnType<F>>["data"],
|
|
41
|
+
>(fn: F): (...args: Parameters<F>) => HttpResponsePromise<T> {
|
|
42
|
+
return (...args: Parameters<F>): HttpResponsePromise<T> => {
|
|
43
|
+
return HttpResponsePromise.fromPromise<T>(fn(...args));
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Creates an `HttpResponsePromise` from an existing promise.
|
|
49
|
+
*
|
|
50
|
+
* @param promise - A promise resolving to a `WithRawResponse` object.
|
|
51
|
+
* @returns An `HttpResponsePromise` instance.
|
|
52
|
+
*/
|
|
53
|
+
public static fromPromise<T>(promise: Promise<WithRawResponse<T>>): HttpResponsePromise<T> {
|
|
54
|
+
return new HttpResponsePromise<T>(promise);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Creates an `HttpResponsePromise` from an executor function.
|
|
59
|
+
*
|
|
60
|
+
* @param executor - A function that takes resolve and reject callbacks to create a promise.
|
|
61
|
+
* @returns An `HttpResponsePromise` instance.
|
|
62
|
+
*/
|
|
63
|
+
public static fromExecutor<T>(
|
|
64
|
+
executor: (resolve: (value: WithRawResponse<T>) => void, reject: (reason?: unknown) => void) => void,
|
|
65
|
+
): HttpResponsePromise<T> {
|
|
66
|
+
const promise = new Promise<WithRawResponse<T>>(executor);
|
|
67
|
+
return new HttpResponsePromise<T>(promise);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Creates an `HttpResponsePromise` from a resolved result.
|
|
72
|
+
*
|
|
73
|
+
* @param result - A `WithRawResponse` object to resolve immediately.
|
|
74
|
+
* @returns An `HttpResponsePromise` instance.
|
|
75
|
+
*/
|
|
76
|
+
public static fromResult<T>(result: WithRawResponse<T>): HttpResponsePromise<T> {
|
|
77
|
+
const promise = Promise.resolve(result);
|
|
78
|
+
return new HttpResponsePromise<T>(promise);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private unwrap(): Promise<T> {
|
|
82
|
+
if (!this.unwrappedPromise) {
|
|
83
|
+
this.unwrappedPromise = this.innerPromise.then(({ data }) => data);
|
|
84
|
+
}
|
|
85
|
+
return this.unwrappedPromise;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** @inheritdoc */
|
|
89
|
+
public override then<TResult1 = T, TResult2 = never>(
|
|
90
|
+
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
|
|
91
|
+
onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
|
|
92
|
+
): Promise<TResult1 | TResult2> {
|
|
93
|
+
return this.unwrap().then(onfulfilled, onrejected);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** @inheritdoc */
|
|
97
|
+
public override catch<TResult = never>(
|
|
98
|
+
onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,
|
|
99
|
+
): Promise<T | TResult> {
|
|
100
|
+
return this.unwrap().catch(onrejected);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** @inheritdoc */
|
|
104
|
+
public override finally(onfinally?: (() => void) | null): Promise<T> {
|
|
105
|
+
return this.unwrap().finally(onfinally);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Retrieves the data and raw response.
|
|
110
|
+
*
|
|
111
|
+
* @returns A promise resolving to a `WithRawResponse` object.
|
|
112
|
+
*/
|
|
113
|
+
public async withRawResponse(): Promise<WithRawResponse<T>> {
|
|
114
|
+
return await this.innerPromise;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Headers } from "./Headers.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The raw response from the fetch call excluding the body.
|
|
5
|
+
*/
|
|
6
|
+
export type RawResponse = Omit<
|
|
7
|
+
{
|
|
8
|
+
[K in keyof Response as Response[K] extends Function ? never : K]: Response[K]; // strips out functions
|
|
9
|
+
},
|
|
10
|
+
"ok" | "body" | "bodyUsed"
|
|
11
|
+
>; // strips out body and bodyUsed
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A raw response indicating that the request was aborted.
|
|
15
|
+
*/
|
|
16
|
+
export const abortRawResponse: RawResponse = {
|
|
17
|
+
headers: new Headers(),
|
|
18
|
+
redirected: false,
|
|
19
|
+
status: 499,
|
|
20
|
+
statusText: "Client Closed Request",
|
|
21
|
+
type: "error",
|
|
22
|
+
url: "",
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A raw response indicating an unknown error.
|
|
27
|
+
*/
|
|
28
|
+
export const unknownRawResponse: RawResponse = {
|
|
29
|
+
headers: new Headers(),
|
|
30
|
+
redirected: false,
|
|
31
|
+
status: 0,
|
|
32
|
+
statusText: "Unknown Error",
|
|
33
|
+
type: "error",
|
|
34
|
+
url: "",
|
|
35
|
+
} as const;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Converts a `RawResponse` object into a `RawResponse` by extracting its properties,
|
|
39
|
+
* excluding the `body` and `bodyUsed` fields.
|
|
40
|
+
*
|
|
41
|
+
* @param response - The `RawResponse` object to convert.
|
|
42
|
+
* @returns A `RawResponse` object containing the extracted properties of the input response.
|
|
43
|
+
*/
|
|
44
|
+
export function toRawResponse(response: Response): RawResponse {
|
|
45
|
+
return {
|
|
46
|
+
headers: response.headers,
|
|
47
|
+
redirected: response.redirected,
|
|
48
|
+
status: response.status,
|
|
49
|
+
statusText: response.statusText,
|
|
50
|
+
type: response.type,
|
|
51
|
+
url: response.url,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Creates a `RawResponse` from a standard `Response` object.
|
|
57
|
+
*/
|
|
58
|
+
export interface WithRawResponse<T> {
|
|
59
|
+
readonly data: T;
|
|
60
|
+
readonly rawResponse: RawResponse;
|
|
61
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type Supplier<T> = T | Promise<T> | (() => T | Promise<T>);
|
|
2
|
+
|
|
3
|
+
export const Supplier = {
|
|
4
|
+
get: async <T>(supplier: Supplier<T>): Promise<T> => {
|
|
5
|
+
if (typeof supplier === "function") {
|
|
6
|
+
return (supplier as () => T)();
|
|
7
|
+
} else {
|
|
8
|
+
return supplier;
|
|
9
|
+
}
|
|
10
|
+
},
|
|
11
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { toQueryString } from "../url/qs.js";
|
|
2
|
+
|
|
3
|
+
export function createRequestUrl(baseUrl: string, queryParameters?: Record<string, unknown>): string {
|
|
4
|
+
const queryString = toQueryString(queryParameters, { arrayFormat: "repeat" });
|
|
5
|
+
return queryString ? `${baseUrl}?${queryString}` : baseUrl;
|
|
6
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { fromJson } from "../json.js";
|
|
2
|
+
import { getResponseBody } from "./getResponseBody.js";
|
|
3
|
+
|
|
4
|
+
export async function getErrorResponseBody(response: Response): Promise<unknown> {
|
|
5
|
+
let contentType = response.headers.get("Content-Type")?.toLowerCase();
|
|
6
|
+
if (contentType == null || contentType.length === 0) {
|
|
7
|
+
return getResponseBody(response);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
if (contentType.indexOf(";") !== -1) {
|
|
11
|
+
contentType = contentType.split(";")[0]?.trim() ?? "";
|
|
12
|
+
}
|
|
13
|
+
switch (contentType) {
|
|
14
|
+
case "application/hal+json":
|
|
15
|
+
case "application/json":
|
|
16
|
+
case "application/ld+json":
|
|
17
|
+
case "application/problem+json":
|
|
18
|
+
case "application/vnd.api+json":
|
|
19
|
+
case "text/json": {
|
|
20
|
+
const text = await response.text();
|
|
21
|
+
return text.length > 0 ? fromJson(text) : undefined;
|
|
22
|
+
}
|
|
23
|
+
default:
|
|
24
|
+
if (contentType.startsWith("application/vnd.") && contentType.endsWith("+json")) {
|
|
25
|
+
const text = await response.text();
|
|
26
|
+
return text.length > 0 ? fromJson(text) : undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Fallback to plain text if content type is not recognized
|
|
30
|
+
// Even if no body is present, the response will be an empty string
|
|
31
|
+
return await response.text();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function getHeader(headers: Record<string, any>, header: string): string | undefined {
|
|
2
|
+
for (const [headerKey, headerValue] of Object.entries(headers)) {
|
|
3
|
+
if (headerKey.toLowerCase() === header.toLowerCase()) {
|
|
4
|
+
return headerValue;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { toJson } from "../json.js";
|
|
2
|
+
import { toQueryString } from "../url/qs.js";
|
|
3
|
+
|
|
4
|
+
export declare namespace GetRequestBody {
|
|
5
|
+
interface Args {
|
|
6
|
+
body: unknown;
|
|
7
|
+
type: "json" | "file" | "bytes" | "form" | "other";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function getRequestBody({ body, type }: GetRequestBody.Args): Promise<BodyInit | undefined> {
|
|
12
|
+
if (type === "form") {
|
|
13
|
+
return toQueryString(body, { arrayFormat: "repeat", encode: true });
|
|
14
|
+
}
|
|
15
|
+
if (type.includes("json")) {
|
|
16
|
+
return toJson(body);
|
|
17
|
+
} else {
|
|
18
|
+
return body as BodyInit;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { fromJson } from "../json.js";
|
|
2
|
+
import { getBinaryResponse } from "./BinaryResponse.js";
|
|
3
|
+
|
|
4
|
+
export async function getResponseBody(response: Response, responseType?: string): Promise<unknown> {
|
|
5
|
+
switch (responseType) {
|
|
6
|
+
case "binary-response":
|
|
7
|
+
return getBinaryResponse(response);
|
|
8
|
+
case "blob":
|
|
9
|
+
return await response.blob();
|
|
10
|
+
case "arrayBuffer":
|
|
11
|
+
return await response.arrayBuffer();
|
|
12
|
+
case "sse":
|
|
13
|
+
if (response.body == null) {
|
|
14
|
+
return {
|
|
15
|
+
ok: false,
|
|
16
|
+
error: {
|
|
17
|
+
reason: "body-is-null",
|
|
18
|
+
statusCode: response.status,
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
return response.body;
|
|
23
|
+
case "streaming":
|
|
24
|
+
if (response.body == null) {
|
|
25
|
+
return {
|
|
26
|
+
ok: false,
|
|
27
|
+
error: {
|
|
28
|
+
reason: "body-is-null",
|
|
29
|
+
statusCode: response.status,
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return response.body;
|
|
35
|
+
|
|
36
|
+
case "text":
|
|
37
|
+
return await response.text();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// if responseType is "json" or not specified, try to parse as JSON
|
|
41
|
+
const text = await response.text();
|
|
42
|
+
if (text.length > 0) {
|
|
43
|
+
try {
|
|
44
|
+
const responseBody = fromJson(text);
|
|
45
|
+
return responseBody;
|
|
46
|
+
} catch (_err) {
|
|
47
|
+
return {
|
|
48
|
+
ok: false,
|
|
49
|
+
error: {
|
|
50
|
+
reason: "non-json",
|
|
51
|
+
statusCode: response.status,
|
|
52
|
+
rawBody: text,
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type { APIResponse } from "./APIResponse.js";
|
|
2
|
+
export type { BinaryResponse } from "./BinaryResponse.js";
|
|
3
|
+
export type { EndpointMetadata } from "./EndpointMetadata.js";
|
|
4
|
+
export { EndpointSupplier } from "./EndpointSupplier.js";
|
|
5
|
+
export type { Fetcher, FetchFunction } from "./Fetcher.js";
|
|
6
|
+
export { fetcher } from "./Fetcher.js";
|
|
7
|
+
export { getHeader } from "./getHeader.js";
|
|
8
|
+
export { HttpResponsePromise } from "./HttpResponsePromise.js";
|
|
9
|
+
export type { RawResponse, WithRawResponse } from "./RawResponse.js";
|
|
10
|
+
export { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse.js";
|
|
11
|
+
export { Supplier } from "./Supplier.js";
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { anySignal, getTimeoutSignal } from "./signals.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Cached result of checking whether the current runtime supports
|
|
5
|
+
* the `cache` option in `Request`. Some runtimes (e.g. Cloudflare Workers)
|
|
6
|
+
* throw a TypeError when this option is used.
|
|
7
|
+
*/
|
|
8
|
+
let _cacheNoStoreSupported: boolean | undefined;
|
|
9
|
+
export function isCacheNoStoreSupported(): boolean {
|
|
10
|
+
if (_cacheNoStoreSupported != null) {
|
|
11
|
+
return _cacheNoStoreSupported;
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
new Request("http://localhost", { cache: "no-store" });
|
|
15
|
+
_cacheNoStoreSupported = true;
|
|
16
|
+
} catch {
|
|
17
|
+
_cacheNoStoreSupported = false;
|
|
18
|
+
}
|
|
19
|
+
return _cacheNoStoreSupported;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Reset the cached result of `isCacheNoStoreSupported`. Exposed for testing only.
|
|
24
|
+
*/
|
|
25
|
+
export function resetCacheNoStoreSupported(): void {
|
|
26
|
+
_cacheNoStoreSupported = undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const makeRequest = async (
|
|
30
|
+
fetchFn: (url: string, init: RequestInit) => Promise<Response>,
|
|
31
|
+
url: string,
|
|
32
|
+
method: string,
|
|
33
|
+
headers: Headers | Record<string, string>,
|
|
34
|
+
requestBody: BodyInit | undefined,
|
|
35
|
+
timeoutMs?: number,
|
|
36
|
+
abortSignal?: AbortSignal,
|
|
37
|
+
withCredentials?: boolean,
|
|
38
|
+
duplex?: "half",
|
|
39
|
+
disableCache?: boolean,
|
|
40
|
+
): Promise<Response> => {
|
|
41
|
+
const signals: AbortSignal[] = [];
|
|
42
|
+
|
|
43
|
+
let timeoutAbortId: ReturnType<typeof setTimeout> | undefined;
|
|
44
|
+
if (timeoutMs != null) {
|
|
45
|
+
const { signal, abortId } = getTimeoutSignal(timeoutMs);
|
|
46
|
+
timeoutAbortId = abortId;
|
|
47
|
+
signals.push(signal);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (abortSignal != null) {
|
|
51
|
+
signals.push(abortSignal);
|
|
52
|
+
}
|
|
53
|
+
const newSignals = anySignal(signals);
|
|
54
|
+
const response = await fetchFn(url, {
|
|
55
|
+
method: method,
|
|
56
|
+
headers,
|
|
57
|
+
body: requestBody,
|
|
58
|
+
signal: newSignals,
|
|
59
|
+
credentials: withCredentials ? "include" : undefined,
|
|
60
|
+
// @ts-ignore
|
|
61
|
+
duplex,
|
|
62
|
+
...(disableCache && isCacheNoStoreSupported() ? { cache: "no-store" as RequestCache } : {}),
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
if (timeoutAbortId != null) {
|
|
66
|
+
clearTimeout(timeoutAbortId);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return response;
|
|
70
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const INITIAL_RETRY_DELAY = 1000; // in milliseconds
|
|
2
|
+
const MAX_RETRY_DELAY = 60000; // in milliseconds
|
|
3
|
+
const DEFAULT_MAX_RETRIES = 2;
|
|
4
|
+
const JITTER_FACTOR = 0.2; // 20% random jitter
|
|
5
|
+
|
|
6
|
+
function addPositiveJitter(delay: number): number {
|
|
7
|
+
const jitterMultiplier = 1 + Math.random() * JITTER_FACTOR;
|
|
8
|
+
return delay * jitterMultiplier;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function addSymmetricJitter(delay: number): number {
|
|
12
|
+
const jitterMultiplier = 1 + (Math.random() - 0.5) * JITTER_FACTOR;
|
|
13
|
+
return delay * jitterMultiplier;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function getRetryDelayFromHeaders(response: Response, retryAttempt: number): number {
|
|
17
|
+
const retryAfter = response.headers.get("Retry-After");
|
|
18
|
+
if (retryAfter) {
|
|
19
|
+
const retryAfterSeconds = parseInt(retryAfter, 10);
|
|
20
|
+
if (!Number.isNaN(retryAfterSeconds) && retryAfterSeconds > 0) {
|
|
21
|
+
return Math.min(retryAfterSeconds * 1000, MAX_RETRY_DELAY);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const retryAfterDate = new Date(retryAfter);
|
|
25
|
+
if (!Number.isNaN(retryAfterDate.getTime())) {
|
|
26
|
+
const delay = retryAfterDate.getTime() - Date.now();
|
|
27
|
+
if (delay > 0) {
|
|
28
|
+
return Math.min(Math.max(delay, 0), MAX_RETRY_DELAY);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const rateLimitReset = response.headers.get("X-RateLimit-Reset");
|
|
34
|
+
if (rateLimitReset) {
|
|
35
|
+
const resetTime = parseInt(rateLimitReset, 10);
|
|
36
|
+
if (!Number.isNaN(resetTime)) {
|
|
37
|
+
const delay = resetTime * 1000 - Date.now();
|
|
38
|
+
if (delay > 0) {
|
|
39
|
+
return addPositiveJitter(Math.min(delay, MAX_RETRY_DELAY));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return addSymmetricJitter(Math.min(INITIAL_RETRY_DELAY * 2 ** retryAttempt, MAX_RETRY_DELAY));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function requestWithRetries(
|
|
48
|
+
requestFn: () => Promise<Response>,
|
|
49
|
+
maxRetries: number = DEFAULT_MAX_RETRIES,
|
|
50
|
+
): Promise<Response> {
|
|
51
|
+
let response: Response = await requestFn();
|
|
52
|
+
|
|
53
|
+
for (let i = 0; i < maxRetries; ++i) {
|
|
54
|
+
if ([408, 429].includes(response.status) || response.status >= 500) {
|
|
55
|
+
const delay = getRetryDelayFromHeaders(response, i);
|
|
56
|
+
|
|
57
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
58
|
+
response = await requestFn();
|
|
59
|
+
} else {
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return response!;
|
|
64
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const TIMEOUT = "timeout";
|
|
2
|
+
|
|
3
|
+
export function getTimeoutSignal(timeoutMs: number): { signal: AbortSignal; abortId: ReturnType<typeof setTimeout> } {
|
|
4
|
+
const controller = new AbortController();
|
|
5
|
+
const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs);
|
|
6
|
+
return { signal: controller.signal, abortId };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function anySignal(...args: AbortSignal[] | [AbortSignal[]]): AbortSignal {
|
|
10
|
+
const signals = (args.length === 1 && Array.isArray(args[0]) ? args[0] : args) as AbortSignal[];
|
|
11
|
+
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
|
|
14
|
+
for (const signal of signals) {
|
|
15
|
+
if (signal.aborted) {
|
|
16
|
+
controller.abort((signal as any)?.reason);
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
signal.addEventListener("abort", () => controller.abort((signal as any)?.reason), {
|
|
21
|
+
signal: controller.signal,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return controller.signal;
|
|
26
|
+
}
|
package/core/headers.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export function mergeHeaders(...headersArray: (Record<string, unknown> | null | undefined)[]): Record<string, unknown> {
|
|
2
|
+
const result: Record<string, unknown> = {};
|
|
3
|
+
|
|
4
|
+
for (const [key, value] of headersArray
|
|
5
|
+
.filter((headers) => headers != null)
|
|
6
|
+
.flatMap((headers) => Object.entries(headers))) {
|
|
7
|
+
const insensitiveKey = key.toLowerCase();
|
|
8
|
+
if (value != null) {
|
|
9
|
+
result[insensitiveKey] = value;
|
|
10
|
+
} else if (insensitiveKey in result) {
|
|
11
|
+
delete result[insensitiveKey];
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function mergeOnlyDefinedHeaders(
|
|
19
|
+
...headersArray: (Record<string, unknown> | null | undefined)[]
|
|
20
|
+
): Record<string, unknown> {
|
|
21
|
+
const result: Record<string, unknown> = {};
|
|
22
|
+
|
|
23
|
+
for (const [key, value] of headersArray
|
|
24
|
+
.filter((headers) => headers != null)
|
|
25
|
+
.flatMap((headers) => Object.entries(headers))) {
|
|
26
|
+
const insensitiveKey = key.toLowerCase();
|
|
27
|
+
if (value != null) {
|
|
28
|
+
result[insensitiveKey] = value;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return result;
|
|
33
|
+
}
|
package/core/index.ts
ADDED
package/core/json.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serialize a value to JSON
|
|
3
|
+
* @param value A JavaScript value, usually an object or array, to be converted.
|
|
4
|
+
* @param replacer A function that transforms the results.
|
|
5
|
+
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
|
|
6
|
+
* @returns JSON string
|
|
7
|
+
*/
|
|
8
|
+
export const toJson = (
|
|
9
|
+
value: unknown,
|
|
10
|
+
replacer?: (this: unknown, key: string, value: unknown) => unknown,
|
|
11
|
+
space?: string | number,
|
|
12
|
+
): string => {
|
|
13
|
+
return JSON.stringify(value, replacer, space);
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Parse JSON string to object, array, or other type
|
|
18
|
+
* @param text A valid JSON string.
|
|
19
|
+
* @param reviver A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is.
|
|
20
|
+
* @returns Parsed object, array, or other type
|
|
21
|
+
*/
|
|
22
|
+
export function fromJson<T = unknown>(
|
|
23
|
+
text: string,
|
|
24
|
+
reviver?: (this: unknown, key: string, value: unknown) => unknown,
|
|
25
|
+
): T {
|
|
26
|
+
return JSON.parse(text, reviver);
|
|
27
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as logger from "./logger.js";
|
|
2
|
+
|
|
3
|
+
export namespace logging {
|
|
4
|
+
/**
|
|
5
|
+
* Configuration for logger instances.
|
|
6
|
+
*/
|
|
7
|
+
export type LogConfig = logger.LogConfig;
|
|
8
|
+
export type LogLevel = logger.LogLevel;
|
|
9
|
+
export const LogLevel: typeof logger.LogLevel = logger.LogLevel;
|
|
10
|
+
export type ILogger = logger.ILogger;
|
|
11
|
+
/**
|
|
12
|
+
* Console logger implementation that outputs to the console.
|
|
13
|
+
*/
|
|
14
|
+
export type ConsoleLogger = logger.ConsoleLogger;
|
|
15
|
+
/**
|
|
16
|
+
* Console logger implementation that outputs to the console.
|
|
17
|
+
*/
|
|
18
|
+
export const ConsoleLogger: typeof logger.ConsoleLogger = logger.ConsoleLogger;
|
|
19
|
+
}
|