@terreno/api 0.24.0 → 0.26.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/.ai/guidelines/core.md +1 -0
- package/README.md +5 -3
- package/dist/__tests__/versionCheckPlugin.test.js +62 -2
- package/dist/api.query.test.js +99 -0
- package/dist/auth.compile.test.d.ts +1 -0
- package/dist/auth.compile.test.js +201 -0
- package/dist/auth.js +38 -7
- package/dist/auth.test.js +119 -1
- package/dist/betterAuthApp.test.js +1 -2
- package/dist/betterAuthSetup.test.js +76 -0
- package/dist/expressServer.js +6 -6
- package/dist/expressServer.test.js +37 -8
- package/dist/httpClient.d.ts +119 -0
- package/dist/httpClient.js +412 -0
- package/dist/httpClient.test.d.ts +1 -0
- package/dist/httpClient.test.js +1470 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.js +29 -3
- package/dist/openApi.test.js +51 -0
- package/dist/realtime/queryStore.d.ts +3 -3
- package/dist/realtime/queryStore.js +0 -1
- package/dist/realtime/realtime.test.js +22 -0
- package/dist/tests/fixtures/compileAuthEntry.d.ts +1 -0
- package/dist/tests/fixtures/compileAuthEntry.js +37 -0
- package/package.json +2 -2
- package/src/__tests__/versionCheckPlugin.test.ts +46 -2
- package/src/api.query.test.ts +59 -0
- package/src/auth.compile.test.ts +106 -0
- package/src/auth.test.ts +81 -1
- package/src/auth.ts +49 -7
- package/src/betterAuthApp.test.ts +3 -3
- package/src/betterAuthSetup.test.ts +65 -0
- package/src/expressServer.test.ts +29 -8
- package/src/expressServer.ts +1 -1
- package/src/httpClient.test.ts +979 -0
- package/src/httpClient.ts +464 -0
- package/src/index.ts +41 -2
- package/src/openApi.test.ts +53 -0
- package/src/realtime/queryStore.ts +6 -7
- package/src/realtime/realtime.test.ts +28 -2
- package/src/realtime/realtimeApp.ts +3 -3
- package/src/tests/fixtures/compileAuthEntry.ts +43 -0
- package/dist/notifiers/index.d.ts +0 -3
- package/dist/notifiers/index.js +0 -19
- package/dist/realtime/index.d.ts +0 -6
- package/dist/realtime/index.js +0 -27
- package/src/notifiers/index.ts +0 -3
- package/src/realtime/index.ts +0 -34
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __assign = (this && this.__assign) || function () {
|
|
3
|
+
__assign = Object.assign || function(t) {
|
|
4
|
+
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
5
|
+
s = arguments[i];
|
|
6
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
7
|
+
t[p] = s[p];
|
|
8
|
+
}
|
|
9
|
+
return t;
|
|
10
|
+
};
|
|
11
|
+
return __assign.apply(this, arguments);
|
|
12
|
+
};
|
|
13
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
14
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
15
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
16
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
17
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
18
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
19
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
20
|
+
});
|
|
21
|
+
};
|
|
22
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
23
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
24
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
25
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
26
|
+
function step(op) {
|
|
27
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
28
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
29
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
30
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
31
|
+
switch (op[0]) {
|
|
32
|
+
case 0: case 1: t = op; break;
|
|
33
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
34
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
35
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
36
|
+
default:
|
|
37
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
38
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
39
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
40
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
41
|
+
if (t[2]) _.ops.pop();
|
|
42
|
+
_.trys.pop(); continue;
|
|
43
|
+
}
|
|
44
|
+
op = body.call(thisArg, _);
|
|
45
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
46
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
var __values = (this && this.__values) || function(o) {
|
|
50
|
+
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
51
|
+
if (m) return m.call(o);
|
|
52
|
+
if (o && typeof o.length === "number") return {
|
|
53
|
+
next: function () {
|
|
54
|
+
if (o && i >= o.length) o = void 0;
|
|
55
|
+
return { value: o && o[i++], done: !o };
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
59
|
+
};
|
|
60
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
61
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
62
|
+
};
|
|
63
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
64
|
+
exports.createAuthenticatedClient = exports.withApiErrorHandling = exports.normalizeApiError = exports.markRetryUnsafe = void 0;
|
|
65
|
+
var axios_1 = __importDefault(require("axios"));
|
|
66
|
+
var errors_1 = require("./errors");
|
|
67
|
+
var logger_1 = require("./logger");
|
|
68
|
+
/**
|
|
69
|
+
* Opts a non-idempotent request (POST/PUT/PATCH/DELETE) into the retry policy of a
|
|
70
|
+
* createAuthenticatedClient instance: `client.axios.post(url, body, markRetryUnsafe())`.
|
|
71
|
+
* Callers must be sure the operation is safe to repeat, and the request body must be
|
|
72
|
+
* replayable — JSON objects are fine, but streams/FormData are consumed on first send.
|
|
73
|
+
* Has no effect on axios instances not created by createAuthenticatedClient.
|
|
74
|
+
*/
|
|
75
|
+
var markRetryUnsafe = function (config) {
|
|
76
|
+
if (config === void 0) { config = {}; }
|
|
77
|
+
return __assign(__assign({}, config), { retryUnsafe: true });
|
|
78
|
+
};
|
|
79
|
+
exports.markRetryUnsafe = markRetryUnsafe;
|
|
80
|
+
var classifyStatusCode = function (statusCode) {
|
|
81
|
+
if (statusCode === 429) {
|
|
82
|
+
return "rateLimited";
|
|
83
|
+
}
|
|
84
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
85
|
+
return "unauthorized";
|
|
86
|
+
}
|
|
87
|
+
if (statusCode === 404) {
|
|
88
|
+
return "notFound";
|
|
89
|
+
}
|
|
90
|
+
if (statusCode >= 400 && statusCode < 500) {
|
|
91
|
+
return "validation";
|
|
92
|
+
}
|
|
93
|
+
if (statusCode >= 500) {
|
|
94
|
+
return "server";
|
|
95
|
+
}
|
|
96
|
+
return "unknown";
|
|
97
|
+
};
|
|
98
|
+
// Plain-string bodies (HTML error pages, proxy text) are truncated to this length so an
|
|
99
|
+
// unbounded — and potentially sensitive — payload never reaches the logger whole.
|
|
100
|
+
var MAX_STRING_BODY_MESSAGE_LENGTH = 500;
|
|
101
|
+
/**
|
|
102
|
+
* Extracts human-readable messages from common API error response body shapes:
|
|
103
|
+
* plain strings (truncated), `{message}`, and JSONAPI-style `{errors: [{title, detail}]}`.
|
|
104
|
+
* Returns an empty array when the body has no recognizable message.
|
|
105
|
+
*/
|
|
106
|
+
var extractBodyMessages = function (data) {
|
|
107
|
+
var e_1, _a;
|
|
108
|
+
if (typeof data === "string" && data.length > 0) {
|
|
109
|
+
if (data.length > MAX_STRING_BODY_MESSAGE_LENGTH) {
|
|
110
|
+
return ["".concat(data.slice(0, MAX_STRING_BODY_MESSAGE_LENGTH), "\u2026")];
|
|
111
|
+
}
|
|
112
|
+
return [data];
|
|
113
|
+
}
|
|
114
|
+
if (data && typeof data === "object") {
|
|
115
|
+
var body = data;
|
|
116
|
+
if (typeof body.message === "string" && body.message.length > 0) {
|
|
117
|
+
return [body.message];
|
|
118
|
+
}
|
|
119
|
+
if (Array.isArray(body.errors)) {
|
|
120
|
+
var messages = [];
|
|
121
|
+
try {
|
|
122
|
+
for (var _b = __values(body.errors), _c = _b.next(); !_c.done; _c = _b.next()) {
|
|
123
|
+
var entry = _c.value;
|
|
124
|
+
if (entry && typeof entry === "object") {
|
|
125
|
+
var _d = entry, title = _d.title, detail = _d.detail;
|
|
126
|
+
if (typeof title === "string" && typeof detail === "string") {
|
|
127
|
+
messages.push("".concat(title, ": ").concat(detail));
|
|
128
|
+
}
|
|
129
|
+
else if (typeof title === "string") {
|
|
130
|
+
messages.push(title);
|
|
131
|
+
}
|
|
132
|
+
else if (typeof detail === "string") {
|
|
133
|
+
messages.push(detail);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
139
|
+
finally {
|
|
140
|
+
try {
|
|
141
|
+
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
|
142
|
+
}
|
|
143
|
+
finally { if (e_1) throw e_1.error; }
|
|
144
|
+
}
|
|
145
|
+
if (messages.length > 0) {
|
|
146
|
+
return messages;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return [];
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* Normalizes an unknown thrown value from an external API call into a stable shape:
|
|
154
|
+
* status code, human-readable messages, and a machine classification. Axios errors are
|
|
155
|
+
* unwrapped (response body messages extracted); axios errors without a response are
|
|
156
|
+
* classified as "network"; non-axios errors fall through to "unknown" with the error
|
|
157
|
+
* message preserved.
|
|
158
|
+
*
|
|
159
|
+
* Raw payload bodies are not carried on the normalized shape — only recognized message
|
|
160
|
+
* fields are extracted, and plain-string bodies are truncated. Consumers whose services
|
|
161
|
+
* put sensitive data inside those message fields should additionally use a redactError
|
|
162
|
+
* hook.
|
|
163
|
+
*/
|
|
164
|
+
var normalizeApiError = function (error, context) {
|
|
165
|
+
var _a, _b;
|
|
166
|
+
var base = { apiName: context.apiName, operation: context.operation };
|
|
167
|
+
if (axios_1.default.isAxiosError(error)) {
|
|
168
|
+
var statusCode = (_a = error.response) === null || _a === void 0 ? void 0 : _a.status;
|
|
169
|
+
if (statusCode === undefined) {
|
|
170
|
+
return __assign(__assign({}, base), { classification: "network", isAxios: true, messages: [error.message], statusCode: undefined });
|
|
171
|
+
}
|
|
172
|
+
var bodyMessages = extractBodyMessages((_b = error.response) === null || _b === void 0 ? void 0 : _b.data);
|
|
173
|
+
return __assign(__assign({}, base), { classification: classifyStatusCode(statusCode), isAxios: true, messages: bodyMessages.length > 0 ? bodyMessages : [error.message], statusCode: statusCode });
|
|
174
|
+
}
|
|
175
|
+
return __assign(__assign({}, base), { classification: "unknown", isAxios: false, messages: [error instanceof Error ? error.message : String(error)], statusCode: undefined });
|
|
176
|
+
};
|
|
177
|
+
exports.normalizeApiError = normalizeApiError;
|
|
178
|
+
/**
|
|
179
|
+
* Wraps an external API call with standardized error handling: failures are normalized
|
|
180
|
+
* via normalizeApiError, passed through the optional redactError hook, logged exactly
|
|
181
|
+
* once, and rethrown.
|
|
182
|
+
*
|
|
183
|
+
* In "raw" mode (default) the wrapper logs the normalized shape via the injected logger
|
|
184
|
+
* and rethrows the original error. In "apiError" mode the wrapper throws a terreno
|
|
185
|
+
* APIError — whose constructor already logs — so the wrapper itself stays silent to
|
|
186
|
+
* preserve the log-once contract. The APIError title is stable per JSONAPI convention;
|
|
187
|
+
* per-occurrence text goes in `detail`, built from the (redacted) normalized messages.
|
|
188
|
+
*/
|
|
189
|
+
var withApiErrorHandling = function (fn, options) { return __awaiter(void 0, void 0, void 0, function () {
|
|
190
|
+
var log, error_1, normalized, statusCode;
|
|
191
|
+
var _a, _b;
|
|
192
|
+
return __generator(this, function (_c) {
|
|
193
|
+
switch (_c.label) {
|
|
194
|
+
case 0:
|
|
195
|
+
log = (_a = options.logger) !== null && _a !== void 0 ? _a : logger_1.logger;
|
|
196
|
+
_c.label = 1;
|
|
197
|
+
case 1:
|
|
198
|
+
_c.trys.push([1, 3, , 4]);
|
|
199
|
+
return [4 /*yield*/, fn()];
|
|
200
|
+
case 2: return [2 /*return*/, _c.sent()];
|
|
201
|
+
case 3:
|
|
202
|
+
error_1 = _c.sent();
|
|
203
|
+
normalized = (0, exports.normalizeApiError)(error_1, {
|
|
204
|
+
apiName: options.apiName,
|
|
205
|
+
operation: options.operation,
|
|
206
|
+
});
|
|
207
|
+
if (options.redactError) {
|
|
208
|
+
normalized = options.redactError(normalized);
|
|
209
|
+
}
|
|
210
|
+
if (options.rethrowAs === "apiError") {
|
|
211
|
+
statusCode = normalized.statusCode;
|
|
212
|
+
throw new errors_1.APIError({
|
|
213
|
+
detail: (_b = normalized.messages[0]) !== null && _b !== void 0 ? _b : "unknown error",
|
|
214
|
+
error: error_1,
|
|
215
|
+
meta: { classification: normalized.classification },
|
|
216
|
+
status: statusCode !== undefined && statusCode >= 400 ? statusCode : 500,
|
|
217
|
+
title: "".concat(options.apiName, " ").concat(options.operation, " request failed"),
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
log.error("[".concat(options.apiName, "] ").concat(options.operation, " failed"), normalized);
|
|
221
|
+
throw error_1;
|
|
222
|
+
case 4: return [2 /*return*/];
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}); };
|
|
226
|
+
exports.withApiErrorHandling = withApiErrorHandling;
|
|
227
|
+
var DEFAULT_RETRY_POLICY = {
|
|
228
|
+
baseDelayMs: 250,
|
|
229
|
+
maxAttempts: 3,
|
|
230
|
+
maxDelayMs: 30000,
|
|
231
|
+
retryOn: ["rateLimited", "server", "network"],
|
|
232
|
+
};
|
|
233
|
+
// Retries apply only to these methods unless a request opts in via markRetryUnsafe() —
|
|
234
|
+
// repeating a failed POST against an external service can duplicate side effects.
|
|
235
|
+
var IDEMPOTENT_METHODS = ["get", "head", "options"];
|
|
236
|
+
var sleep = function (ms) { return new Promise(function (resolve) { return setTimeout(resolve, ms); }); };
|
|
237
|
+
var parseRetryAfterMs = function (headerValue) {
|
|
238
|
+
if (typeof headerValue !== "string" || headerValue.trim() === "") {
|
|
239
|
+
return undefined;
|
|
240
|
+
}
|
|
241
|
+
var seconds = Number(headerValue);
|
|
242
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
243
|
+
return seconds * 1000;
|
|
244
|
+
}
|
|
245
|
+
// HTTP-date form falls back to backoff rather than date math.
|
|
246
|
+
return undefined;
|
|
247
|
+
};
|
|
248
|
+
/**
|
|
249
|
+
* Creates an axios instance with a pluggable auth strategy, token caching, and a retry
|
|
250
|
+
* policy for transient failures.
|
|
251
|
+
*
|
|
252
|
+
* Auth: tokens/keys are fetched lazily on the first request and cached on the client;
|
|
253
|
+
* `invalidateToken()` drops the cache. The oauth2 strategy fetches a client-credentials
|
|
254
|
+
* token (HTTP Basic auth, form-encoded `grant_type=client_credentials`) and, with
|
|
255
|
+
* `refreshOn401`, refreshes and retries exactly once when a request returns 401.
|
|
256
|
+
*
|
|
257
|
+
* Retries: failures classified in `retry.retryOn` (default: rateLimited, server,
|
|
258
|
+
* network) are retried with exponential backoff and jitter up to `maxAttempts` total
|
|
259
|
+
* attempts, honoring a parseable Retry-After header. Only idempotent methods
|
|
260
|
+
* (GET/HEAD/OPTIONS) are retried unless the request opts in via markRetryUnsafe().
|
|
261
|
+
*
|
|
262
|
+
* Logging: the client logs retries and token refreshes at debug level only and always
|
|
263
|
+
* rejects with the original axios error — error-level logging is left to the call site
|
|
264
|
+
* (typically via withApiErrorHandling) so composed usage logs each failure exactly once.
|
|
265
|
+
*/
|
|
266
|
+
var createAuthenticatedClient = function (options) {
|
|
267
|
+
var _a, _b;
|
|
268
|
+
var log = (_a = options.logger) !== null && _a !== void 0 ? _a : logger_1.logger;
|
|
269
|
+
var apiName = (_b = options.apiName) !== null && _b !== void 0 ? _b : options.baseURL;
|
|
270
|
+
var retryPolicy = __assign(__assign({}, DEFAULT_RETRY_POLICY), options.retry);
|
|
271
|
+
// The in-flight promise is cached (not the resolved value) so concurrent first
|
|
272
|
+
// requests share a single token fetch. resolvedToken tracks the last issued token so
|
|
273
|
+
// a 401 only invalidates the cache if a newer token hasn't already replaced it.
|
|
274
|
+
var tokenPromise;
|
|
275
|
+
var resolvedToken;
|
|
276
|
+
var fetchToken = function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
277
|
+
var auth, response, accessToken;
|
|
278
|
+
var _a;
|
|
279
|
+
return __generator(this, function (_b) {
|
|
280
|
+
switch (_b.label) {
|
|
281
|
+
case 0:
|
|
282
|
+
auth = options.auth;
|
|
283
|
+
if (auth.type === "bearer") {
|
|
284
|
+
return [2 /*return*/, auth.getToken()];
|
|
285
|
+
}
|
|
286
|
+
if (auth.type === "apiKey") {
|
|
287
|
+
return [2 /*return*/, auth.getKey()];
|
|
288
|
+
}
|
|
289
|
+
return [4 /*yield*/, axios_1.default.post(auth.tokenUrl, new URLSearchParams({ grant_type: "client_credentials" }), {
|
|
290
|
+
auth: { password: auth.credentials.clientSecret, username: auth.credentials.clientId },
|
|
291
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
292
|
+
})];
|
|
293
|
+
case 1:
|
|
294
|
+
response = _b.sent();
|
|
295
|
+
accessToken = (_a = response.data) === null || _a === void 0 ? void 0 : _a.access_token;
|
|
296
|
+
if (typeof accessToken !== "string" || accessToken.length === 0) {
|
|
297
|
+
throw new Error("[httpClient] ".concat(apiName, " token response has no access_token"));
|
|
298
|
+
}
|
|
299
|
+
return [2 /*return*/, accessToken];
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}); };
|
|
303
|
+
var invalidateToken = function () {
|
|
304
|
+
tokenPromise = undefined;
|
|
305
|
+
resolvedToken = undefined;
|
|
306
|
+
};
|
|
307
|
+
var getCachedToken = function () {
|
|
308
|
+
if (!tokenPromise) {
|
|
309
|
+
// The promise-identity checks below keep an out-of-order resolution (a fetch that
|
|
310
|
+
// was invalidated and replaced while in flight) from clobbering the newer fetch's
|
|
311
|
+
// cache state.
|
|
312
|
+
var thisPromise_1 = fetchToken().then(function (token) {
|
|
313
|
+
if (tokenPromise === thisPromise_1) {
|
|
314
|
+
resolvedToken = token;
|
|
315
|
+
}
|
|
316
|
+
return token;
|
|
317
|
+
}, function (error) {
|
|
318
|
+
// Clear the failed fetch so the next request retries, and wrap the failure in
|
|
319
|
+
// a plain Error. The wrapping is what keeps the raw token-request AxiosError
|
|
320
|
+
// out of the response interceptor's refresh/retry logic (a wrapped error fails
|
|
321
|
+
// the isAxiosError guard); __httpClientManaged is defense-in-depth behind it.
|
|
322
|
+
if (tokenPromise === thisPromise_1) {
|
|
323
|
+
invalidateToken();
|
|
324
|
+
}
|
|
325
|
+
var normalized = (0, exports.normalizeApiError)(error, { apiName: apiName, operation: "token fetch" });
|
|
326
|
+
var wrapped = new Error("[httpClient] ".concat(apiName, " token fetch failed: ").concat(normalized.messages[0]));
|
|
327
|
+
wrapped.cause = error;
|
|
328
|
+
throw wrapped;
|
|
329
|
+
});
|
|
330
|
+
tokenPromise = thisPromise_1;
|
|
331
|
+
}
|
|
332
|
+
return tokenPromise;
|
|
333
|
+
};
|
|
334
|
+
var instance = axios_1.default.create({ baseURL: options.baseURL });
|
|
335
|
+
instance.interceptors.request.use(function (config) { return __awaiter(void 0, void 0, void 0, function () {
|
|
336
|
+
var token;
|
|
337
|
+
return __generator(this, function (_a) {
|
|
338
|
+
switch (_a.label) {
|
|
339
|
+
case 0:
|
|
340
|
+
config.__httpClientManaged = true;
|
|
341
|
+
return [4 /*yield*/, getCachedToken()];
|
|
342
|
+
case 1:
|
|
343
|
+
token = _a.sent();
|
|
344
|
+
if (options.auth.type === "apiKey") {
|
|
345
|
+
config.headers.set(options.auth.header, token);
|
|
346
|
+
}
|
|
347
|
+
else {
|
|
348
|
+
config.headers.set("Authorization", "Bearer ".concat(token));
|
|
349
|
+
}
|
|
350
|
+
return [2 /*return*/, config];
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
}); });
|
|
354
|
+
instance.interceptors.response.use(undefined, function (error) { return __awaiter(void 0, void 0, void 0, function () {
|
|
355
|
+
var config, normalized, sentAuthorization, method, isRetryableMethod, attemptsSoFar, backoffMs, retryAfterMs, delayMs;
|
|
356
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
357
|
+
return __generator(this, function (_h) {
|
|
358
|
+
switch (_h.label) {
|
|
359
|
+
case 0:
|
|
360
|
+
if (!axios_1.default.isAxiosError(error) || !error.config) {
|
|
361
|
+
throw error;
|
|
362
|
+
}
|
|
363
|
+
config = error.config;
|
|
364
|
+
// Errors from configs this client didn't manage (e.g. a failing token POST) must
|
|
365
|
+
// propagate untouched — refreshing or retrying them can loop forever.
|
|
366
|
+
if (!config.__httpClientManaged) {
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
normalized = (0, exports.normalizeApiError)(error, {
|
|
370
|
+
apiName: apiName,
|
|
371
|
+
operation: "".concat((_a = config.method) !== null && _a !== void 0 ? _a : "request", " ").concat((_b = config.url) !== null && _b !== void 0 ? _b : ""),
|
|
372
|
+
});
|
|
373
|
+
if (options.redactError) {
|
|
374
|
+
normalized = options.redactError(normalized);
|
|
375
|
+
}
|
|
376
|
+
// One-shot token refresh on 401 for oauth2 strategies.
|
|
377
|
+
if (options.auth.type === "oauth2" &&
|
|
378
|
+
options.auth.refreshOn401 &&
|
|
379
|
+
((_c = error.response) === null || _c === void 0 ? void 0 : _c.status) === 401 &&
|
|
380
|
+
!config.__httpClientDidAuthRefresh) {
|
|
381
|
+
config.__httpClientDidAuthRefresh = true;
|
|
382
|
+
sentAuthorization = config.headers.get("Authorization");
|
|
383
|
+
if (resolvedToken === undefined || sentAuthorization === "Bearer ".concat(resolvedToken)) {
|
|
384
|
+
invalidateToken();
|
|
385
|
+
}
|
|
386
|
+
log.debug("[".concat(apiName, "] ").concat(normalized.operation, " got 401, refreshing token and retrying"));
|
|
387
|
+
return [2 /*return*/, instance.request(config)];
|
|
388
|
+
}
|
|
389
|
+
method = ((_d = config.method) !== null && _d !== void 0 ? _d : "get").toLowerCase();
|
|
390
|
+
isRetryableMethod = IDEMPOTENT_METHODS.includes(method) || config.retryUnsafe === true;
|
|
391
|
+
attemptsSoFar = ((_e = config.__httpClientRetryCount) !== null && _e !== void 0 ? _e : 0) + 1;
|
|
392
|
+
if (!retryPolicy.retryOn.includes(normalized.classification) ||
|
|
393
|
+
!isRetryableMethod ||
|
|
394
|
+
attemptsSoFar >= retryPolicy.maxAttempts) {
|
|
395
|
+
throw error;
|
|
396
|
+
}
|
|
397
|
+
config.__httpClientRetryCount = attemptsSoFar;
|
|
398
|
+
backoffMs = retryPolicy.baseDelayMs * Math.pow(2, (attemptsSoFar - 1)) * (1 + Math.random() * 0.5);
|
|
399
|
+
retryAfterMs = parseRetryAfterMs((_g = (_f = error.response) === null || _f === void 0 ? void 0 : _f.headers) === null || _g === void 0 ? void 0 : _g["retry-after"]);
|
|
400
|
+
delayMs = Math.min(retryAfterMs !== null && retryAfterMs !== void 0 ? retryAfterMs : backoffMs, retryPolicy.maxDelayMs);
|
|
401
|
+
log.debug("[".concat(apiName, "] ").concat(normalized.operation, " failed (").concat(normalized.classification, "), ") +
|
|
402
|
+
"retrying attempt ".concat(attemptsSoFar + 1, "/").concat(retryPolicy.maxAttempts, " in ").concat(Math.round(delayMs), "ms"));
|
|
403
|
+
return [4 /*yield*/, sleep(delayMs)];
|
|
404
|
+
case 1:
|
|
405
|
+
_h.sent();
|
|
406
|
+
return [2 /*return*/, instance.request(config)];
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
}); });
|
|
410
|
+
return { axios: instance, invalidateToken: invalidateToken };
|
|
411
|
+
};
|
|
412
|
+
exports.createAuthenticatedClient = createAuthenticatedClient;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|