@argos-ci/api-client 0.16.0 → 0.16.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.mjs ADDED
@@ -0,0 +1,233 @@
1
+ import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
2
+ import createFetchClient from "openapi-fetch";
3
+ import createDebug from "debug";
4
+ //#region ../../node_modules/.pnpm/is-network-error@1.3.1/node_modules/is-network-error/index.js
5
+ const objectToString = Object.prototype.toString;
6
+ const isError = (value) => objectToString.call(value) === "[object Error]";
7
+ const errorMessages = new Set([
8
+ "network error",
9
+ "NetworkError when attempting to fetch resource.",
10
+ "The Internet connection appears to be offline.",
11
+ "Network request failed",
12
+ "fetch failed",
13
+ "terminated",
14
+ " A network error occurred.",
15
+ "Network connection lost"
16
+ ]);
17
+ function isNetworkError(error) {
18
+ if (!(error && isError(error) && error.name === "TypeError" && typeof error.message === "string")) return false;
19
+ const { message, stack } = error;
20
+ if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error;
21
+ if (message.startsWith("error sending request for url")) return true;
22
+ if (message === "Failed to fetch" || message.startsWith("Failed to fetch (") && message.endsWith(")")) return true;
23
+ return errorMessages.has(message);
24
+ }
25
+ //#endregion
26
+ //#region ../../node_modules/.pnpm/p-retry@8.0.0/node_modules/p-retry/index.js
27
+ function validateRetries(retries) {
28
+ if (typeof retries === "number") {
29
+ if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number.");
30
+ if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");
31
+ } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity.");
32
+ }
33
+ function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) {
34
+ if (value === void 0) return;
35
+ if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`);
36
+ if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`);
37
+ if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`);
38
+ }
39
+ function validateFunctionOption(name, value) {
40
+ if (value === void 0) return;
41
+ if (typeof value !== "function") throw new TypeError(`Expected \`${name}\` to be a function.`);
42
+ }
43
+ var AbortError = class extends Error {
44
+ constructor(message) {
45
+ super();
46
+ if (message instanceof Error) {
47
+ this.originalError = message;
48
+ ({message} = message);
49
+ } else {
50
+ this.originalError = new Error(message);
51
+ this.originalError.stack = this.stack;
52
+ }
53
+ this.name = "AbortError";
54
+ this.message = message;
55
+ }
56
+ };
57
+ function calculateDelay(retriesConsumed, options) {
58
+ const attempt = Math.max(1, retriesConsumed + 1);
59
+ const random = options.randomize ? Math.random() + 1 : 1;
60
+ let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1));
61
+ timeout = Math.min(timeout, options.maxTimeout);
62
+ return timeout;
63
+ }
64
+ function calculateRemainingTime(start, max) {
65
+ if (!Number.isFinite(max)) return max;
66
+ return max - (performance.now() - start);
67
+ }
68
+ async function delayForRetry(delay, options) {
69
+ if (delay <= 0) return;
70
+ await new Promise((resolve, reject) => {
71
+ const onAbort = () => {
72
+ clearTimeout(timeoutToken);
73
+ options.signal?.removeEventListener("abort", onAbort);
74
+ reject(options.signal.reason);
75
+ };
76
+ const timeoutToken = setTimeout(() => {
77
+ options.signal?.removeEventListener("abort", onAbort);
78
+ resolve();
79
+ }, delay);
80
+ if (options.unref) timeoutToken.unref?.();
81
+ options.signal?.addEventListener("abort", onAbort, { once: true });
82
+ });
83
+ }
84
+ async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) {
85
+ const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
86
+ if (normalizedError instanceof AbortError) throw normalizedError.originalError;
87
+ const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
88
+ const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
89
+ const delayTime = calculateDelay(retriesConsumed, options);
90
+ if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {
91
+ const context = Object.freeze({
92
+ error: normalizedError,
93
+ attemptNumber,
94
+ retriesLeft,
95
+ retriesConsumed,
96
+ retryDelay: 0
97
+ });
98
+ await options.onFailedAttempt(context);
99
+ throw normalizedError;
100
+ }
101
+ const consumeRetryContext = Object.freeze({
102
+ error: normalizedError,
103
+ attemptNumber,
104
+ retriesLeft,
105
+ retriesConsumed,
106
+ retryDelay: retriesLeft > 0 ? delayTime : 0
107
+ });
108
+ const consumeRetry = await options.shouldConsumeRetry(consumeRetryContext);
109
+ const effectiveDelay = consumeRetry && retriesLeft > 0 ? delayTime : 0;
110
+ const context = Object.freeze({
111
+ error: normalizedError,
112
+ attemptNumber,
113
+ retriesLeft,
114
+ retriesConsumed,
115
+ retryDelay: effectiveDelay
116
+ });
117
+ await options.onFailedAttempt(context);
118
+ if (calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError;
119
+ if (calculateRemainingTime(startTime, maxRetryTime) <= 0 || retriesLeft <= 0) throw normalizedError;
120
+ if (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) throw normalizedError;
121
+ if (!await options.shouldRetry(context)) throw normalizedError;
122
+ const remainingTimeAfterShouldRetry = calculateRemainingTime(startTime, maxRetryTime);
123
+ if (remainingTimeAfterShouldRetry <= 0) throw normalizedError;
124
+ if (!consumeRetry) {
125
+ options.signal?.throwIfAborted();
126
+ return false;
127
+ }
128
+ const finalDelay = Math.min(effectiveDelay, remainingTimeAfterShouldRetry);
129
+ options.signal?.throwIfAborted();
130
+ await delayForRetry(finalDelay, options);
131
+ options.signal?.throwIfAborted();
132
+ return true;
133
+ }
134
+ async function pRetry(input, options = {}) {
135
+ options = { ...options };
136
+ validateRetries(options.retries);
137
+ if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");
138
+ options.retries ??= 10;
139
+ options.factor ??= 2;
140
+ options.minTimeout ??= 1e3;
141
+ options.maxTimeout ??= Number.POSITIVE_INFINITY;
142
+ options.maxRetryTime ??= Number.POSITIVE_INFINITY;
143
+ options.randomize ??= false;
144
+ options.onFailedAttempt ??= () => {};
145
+ options.shouldRetry ??= () => true;
146
+ options.shouldConsumeRetry ??= () => true;
147
+ validateFunctionOption("onFailedAttempt", options.onFailedAttempt);
148
+ validateFunctionOption("shouldRetry", options.shouldRetry);
149
+ validateFunctionOption("shouldConsumeRetry", options.shouldConsumeRetry);
150
+ validateNumberOption("factor", options.factor, {
151
+ min: 0,
152
+ allowInfinity: false
153
+ });
154
+ validateNumberOption("minTimeout", options.minTimeout, {
155
+ min: 0,
156
+ allowInfinity: false
157
+ });
158
+ validateNumberOption("maxTimeout", options.maxTimeout, {
159
+ min: 0,
160
+ allowInfinity: true
161
+ });
162
+ validateNumberOption("maxRetryTime", options.maxRetryTime, {
163
+ min: 0,
164
+ allowInfinity: true
165
+ });
166
+ if (!(options.factor > 0)) options.factor = 1;
167
+ options.signal?.throwIfAborted();
168
+ let attemptNumber = 0;
169
+ let retriesConsumed = 0;
170
+ const startTime = performance.now();
171
+ while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {
172
+ attemptNumber++;
173
+ try {
174
+ options.signal?.throwIfAborted();
175
+ const result = await input(attemptNumber);
176
+ options.signal?.throwIfAborted();
177
+ return result;
178
+ } catch (error) {
179
+ if (await onAttemptFailure({
180
+ error,
181
+ attemptNumber,
182
+ retriesConsumed,
183
+ startTime,
184
+ options
185
+ })) retriesConsumed++;
186
+ }
187
+ }
188
+ throw new Error("Retry attempts exhausted without throwing an error.");
189
+ }
190
+ const debug = createDebug("@argos-ci/api-client");
191
+ //#endregion
192
+ //#region src/schema.ts
193
+ var schema_exports = /* @__PURE__ */ __exportAll({});
194
+ //#endregion
195
+ //#region src/index.ts
196
+ /**
197
+ * Create Argos API client.
198
+ */
199
+ function createClient(options) {
200
+ const { baseUrl } = options || {};
201
+ return createFetchClient({
202
+ baseUrl: baseUrl || "https://api.argos-ci.com/v2/",
203
+ headers: { Authorization: `Bearer ${options.authToken}` },
204
+ fetch: (input) => {
205
+ return pRetry(async () => {
206
+ const response = await fetch(input.clone());
207
+ if (response.status >= 500) throw new APIError("Internal Server Error");
208
+ return response;
209
+ }, {
210
+ retries: 3,
211
+ onFailedAttempt: (context) => {
212
+ debug("API request failed", context.error.message);
213
+ if (context.retriesLeft > 0) debug(`Retrying API request... (${context.retriesLeft} left)`);
214
+ }
215
+ });
216
+ }
217
+ });
218
+ }
219
+ var APIError = class extends Error {
220
+ constructor(message) {
221
+ super(message);
222
+ }
223
+ };
224
+ /**
225
+ * Handle API errors.
226
+ */
227
+ function throwAPIError(error) {
228
+ debug("API error", error);
229
+ const detailMessage = error.details?.map((detail) => detail.message).join(", ");
230
+ throw new APIError(detailMessage ? `${error.error}: ${detailMessage}` : error.error);
231
+ }
232
+ //#endregion
233
+ export { APIError, schema_exports as ArgosAPISchema, createClient, throwAPIError };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@argos-ci/api-client",
3
3
  "description": "Argos API Client library.",
4
- "version": "0.16.0",
4
+ "version": "0.16.1",
5
5
  "author": "Smooth Code",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -24,33 +24,33 @@
24
24
  "type": "module",
25
25
  "exports": {
26
26
  ".": {
27
- "types": "./dist/index.d.ts",
28
- "import": "./dist/index.js",
29
- "default": "./dist/index.js"
27
+ "types": "./dist/index.d.mts",
28
+ "import": "./dist/index.mjs",
29
+ "default": "./dist/index.mjs"
30
30
  },
31
31
  "./package.json": "./package.json"
32
32
  },
33
- "types": "./dist/index.d.ts",
33
+ "types": "./dist/index.d.mts",
34
34
  "engines": {
35
35
  "node": ">=20.0.0"
36
36
  },
37
37
  "scripts": {
38
38
  "build-schema-types": "openapi-typescript https://api.argos-ci.com/v2/openapi.yaml -o src/schema.ts",
39
39
  "build-schema-types-dev": "NODE_TLS_REJECT_UNAUTHORIZED=0 openapi-typescript https://api.argos-ci.dev:4001/v2/openapi.yaml -o src/schema.ts",
40
- "build": "tsup",
40
+ "build": "tsdown",
41
41
  "check-types": "tsc",
42
42
  "check-format": "prettier --check --ignore-unknown --ignore-path=../../.gitignore --ignore-path=../../.prettierignore .",
43
43
  "lint": "eslint ."
44
44
  },
45
45
  "devDependencies": {
46
- "@types/debug": "^4.1.12",
46
+ "@types/debug": "^4.1.13",
47
47
  "@types/node": "catalog:",
48
- "openapi-typescript": "^7.10.1",
49
- "p-retry": "^7.1.1"
48
+ "openapi-typescript": "^7.13.0",
49
+ "p-retry": "^8.0.0"
50
50
  },
51
51
  "dependencies": {
52
52
  "debug": "^4.4.3",
53
- "openapi-fetch": "^0.15.0"
53
+ "openapi-fetch": "^0.17.0"
54
54
  },
55
- "gitHead": "6887164dc0ccd5b2a3dd1d7d9e778cdbbdd2d534"
55
+ "gitHead": "b49d186d5eb6e1338982a4cd5c3cb29e6cb0b7af"
56
56
  }