hanzio 1.0.7 → 1.0.9

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.
@@ -1,3 +1,340 @@
1
+ // src/api-wrapper/index.ts
2
+ import { ZodError } from "zod";
3
+
4
+ class ResponseValidationError extends Error {
5
+ zodError;
6
+ rawResponse;
7
+ validationIssues;
8
+ constructor(zodError, rawResponse) {
9
+ const issues = zodError.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
10
+ super(`Response validation failed: ${issues}`);
11
+ this.name = "ResponseValidationError";
12
+ this.zodError = zodError;
13
+ this.rawResponse = rawResponse;
14
+ this.validationIssues = issues;
15
+ }
16
+ }
17
+
18
+ class HttpResponseError extends Error {
19
+ status;
20
+ body;
21
+ constructor(status, body) {
22
+ super(`HTTP error: ${status} - ${body}`);
23
+ this.name = "HttpResponseError";
24
+ this.status = status;
25
+ this.body = body;
26
+ }
27
+ }
28
+ function createApiClient(apiConfig) {
29
+ const request = async (endpointKey, input = {}) => {
30
+ const endpoint = apiConfig.endpoints[endpointKey];
31
+ if (!endpoint) {
32
+ throw new Error(`Unknown API endpoint: ${String(endpointKey)}`);
33
+ }
34
+ const { finalUrl, fullUrl } = buildUrl(endpoint, input.reqParams, input.reqQuery, apiConfig.baseApiUrls, apiConfig.defaultBaseApiUrl, input.url);
35
+ const endpointName = apiConfig.name ? `${apiConfig.name}.${String(endpointKey)}` : String(endpointKey);
36
+ const startedAt = Date.now();
37
+ let retryCount = 0;
38
+ let httpStatus = 0;
39
+ apiConfig.onRequestStart?.({ endpoint: endpointName, url: fullUrl });
40
+ try {
41
+ const config = {
42
+ method: endpoint.method,
43
+ url: finalUrl,
44
+ queryParams: buildQueryParams(endpoint, input.reqQuery),
45
+ body: buildRequestBody(endpoint, input.reqBody),
46
+ headers: buildHeaders(endpoint, input.reqHeaders, apiConfig.defaultHeaders ?? {}),
47
+ doNotEncodeQueryParams: endpoint.doNotEncodeQueryParams,
48
+ timeoutMs: apiConfig.timeoutMs,
49
+ fetchFn: apiConfig.fetch ?? fetch
50
+ };
51
+ const result = await makeRequestWithRetry(config, apiConfig.retries ?? 3, apiConfig.retryDelayMs ?? 300, (response) => validateAndTransformResponse(endpoint, response), apiConfig.shouldRetry ?? defaultShouldRetry, apiConfig.logger);
52
+ retryCount = result.retryCount;
53
+ httpStatus = result.httpStatus;
54
+ const responseTimeMs = Date.now() - startedAt;
55
+ const responseSizeMb = calculateSizeInMb(result.validatedData);
56
+ const requestSizeMb = calculateSizeInMb({
57
+ method: config.method,
58
+ url: fullUrl,
59
+ body: config.body,
60
+ headers: config.headers
61
+ });
62
+ apiConfig.onRequestEnd?.({
63
+ endpoint: endpointName,
64
+ url: fullUrl,
65
+ status: httpStatus,
66
+ retryCount,
67
+ responseTimeMs
68
+ });
69
+ return {
70
+ data: result.validatedData,
71
+ requestSizeMb,
72
+ responseSizeMb,
73
+ requestSizeTotalMb: requestSizeMb + responseSizeMb,
74
+ responseTimeMs,
75
+ httpStatus,
76
+ retryCount
77
+ };
78
+ } catch (error) {
79
+ apiConfig.logger?.error?.(error);
80
+ throw error;
81
+ }
82
+ };
83
+ return { request };
84
+ }
85
+ var createApiWrapper = createApiClient;
86
+ async function validateResponse(schema, data) {
87
+ try {
88
+ return await schema.parseAsync(data);
89
+ } catch (error) {
90
+ if (error instanceof ZodError) {
91
+ throw new ResponseValidationError(error, data);
92
+ }
93
+ throw error;
94
+ }
95
+ }
96
+ async function httpRequest(config) {
97
+ const queryString = config.doNotEncodeQueryParams ? Object.entries(config.queryParams).map(([key, value]) => `${key}=${value}`).join("&") : new URLSearchParams(config.queryParams).toString();
98
+ const fullUrl = queryString ? `${config.url}?${queryString}` : config.url;
99
+ const abortController = new AbortController;
100
+ const timeout = config.timeoutMs === undefined ? undefined : setTimeout(() => abortController.abort(), config.timeoutMs);
101
+ try {
102
+ return await config.fetchFn(fullUrl, {
103
+ method: config.method,
104
+ headers: config.headers,
105
+ body: buildFetchBody(config.body, config.headers),
106
+ signal: abortController.signal
107
+ });
108
+ } finally {
109
+ if (timeout)
110
+ clearTimeout(timeout);
111
+ }
112
+ }
113
+ async function makeRequestWithRetry(config, maxRetries, retryDelayMs, validateFn, shouldRetry, logger) {
114
+ let retryCount = 0;
115
+ while (true) {
116
+ try {
117
+ logger?.debug?.("API request", config);
118
+ const response = await httpRequest(config);
119
+ if (response.status >= 400) {
120
+ if (retryCount < maxRetries && shouldRetry({ response, retryCount, maxRetries })) {
121
+ retryCount++;
122
+ await delay(retryDelayMs);
123
+ continue;
124
+ }
125
+ throw new HttpResponseError(response.status, await response.text());
126
+ }
127
+ return {
128
+ validatedData: await validateFn(response),
129
+ retryCount,
130
+ httpStatus: response.status
131
+ };
132
+ } catch (error) {
133
+ if (error instanceof HttpResponseError)
134
+ throw error;
135
+ if (retryCount >= maxRetries || !shouldRetry({ error, retryCount, maxRetries })) {
136
+ throw error;
137
+ }
138
+ retryCount++;
139
+ await delay(retryDelayMs);
140
+ }
141
+ }
142
+ }
143
+ async function validateAndTransformResponse(endpoint, response) {
144
+ const responseHeaders = getHeadersAsObject(response.headers);
145
+ const contentType = responseHeaders["content-type"] ?? "";
146
+ const responseData = contentType.includes("application/json") ? await response.json() : await response.text();
147
+ const transformedData = endpoint.resFormatter ? endpoint.resFormatter(responseData, responseHeaders) : responseData;
148
+ return validateResponse(endpoint.resSchema, transformedData);
149
+ }
150
+ function buildUrl(endpoint, params, reqQuery, baseApiUrls, defaultBaseApiUrl, url) {
151
+ if (url) {
152
+ const finalUrl2 = replacePathParams(url, params);
153
+ const queryString2 = new URLSearchParams(buildQueryParams(endpoint, reqQuery)).toString();
154
+ return {
155
+ finalUrl: finalUrl2,
156
+ fullUrl: queryString2 ? `${finalUrl2}?${queryString2}` : finalUrl2
157
+ };
158
+ }
159
+ const defaultBaseUrl = defaultBaseApiUrl ?? Object.keys(baseApiUrls)[0];
160
+ if (!defaultBaseUrl) {
161
+ throw new Error("At least one base API URL is required");
162
+ }
163
+ const baseUrlKey = endpoint.baseApiUrl ?? defaultBaseUrl;
164
+ const configBaseUrl = baseApiUrls[baseUrlKey];
165
+ if (!configBaseUrl) {
166
+ throw new Error(`Unknown base API URL: ${baseUrlKey}`);
167
+ }
168
+ const baseUrl = typeof configBaseUrl === "function" ? configBaseUrl() : configBaseUrl;
169
+ const path = typeof endpoint.path === "function" ? endpoint.path(baseUrl) : endpoint.path;
170
+ const finalUrl = replacePathParams(`${baseUrl}${path}`, params);
171
+ const queryString = new URLSearchParams(buildQueryParams(endpoint, reqQuery)).toString();
172
+ return {
173
+ finalUrl,
174
+ fullUrl: queryString ? `${finalUrl}?${queryString}` : finalUrl
175
+ };
176
+ }
177
+ function buildQueryParams(endpoint, query) {
178
+ const defaultParams = endpoint.reqDefaultQueryParams ?? {};
179
+ const parsedQuery = endpoint.reqQuerySchema ? endpoint.reqQuerySchema.parse(query) : query ?? {};
180
+ const merged = { ...defaultParams, ...parsedQuery };
181
+ return Object.fromEntries(Object.entries(merged).filter(([, value]) => value !== undefined).map(([key, value]) => [key, String(value)]));
182
+ }
183
+ function buildRequestBody(endpoint, body) {
184
+ if (!endpoint.reqBodySchema)
185
+ return body;
186
+ const parsedBody = endpoint.reqBodySchema.parse(body);
187
+ if (endpoint.reqBodyFormat !== "form-data") {
188
+ return parsedBody;
189
+ }
190
+ const formData = new FormData;
191
+ for (const [key, value] of Object.entries(parsedBody)) {
192
+ if (value == null)
193
+ continue;
194
+ formData.set(key, value instanceof Blob ? value : String(value));
195
+ }
196
+ return formData;
197
+ }
198
+ function buildHeaders(endpoint, headers, defaultHeaders) {
199
+ const contentType = endpoint.reqBodyFormat === "json" ? "application/json" : undefined;
200
+ const parsedHeaders = endpoint.reqHeadersSchema ? endpoint.reqHeadersSchema.parse(headers) : headers ?? {};
201
+ return {
202
+ ...defaultHeaders,
203
+ ...contentType && { "Content-Type": contentType },
204
+ ...endpoint.defaultHeaders,
205
+ ...parsedHeaders
206
+ };
207
+ }
208
+ function buildFetchBody(body, headers) {
209
+ if (body === undefined || body === null)
210
+ return;
211
+ if (body instanceof FormData || body instanceof Blob)
212
+ return body;
213
+ if (headers["Content-Type"] === "application/json")
214
+ return JSON.stringify(body);
215
+ return body;
216
+ }
217
+ function replacePathParams(path, params) {
218
+ return path.replace(/:(\w+)/g, (_, key) => {
219
+ const value = params?.[key];
220
+ if (value === undefined) {
221
+ throw new Error(`Missing required path parameter: ${key}`);
222
+ }
223
+ return encodeURIComponent(String(value));
224
+ });
225
+ }
226
+ function getHeadersAsObject(headers) {
227
+ const result = {};
228
+ headers.forEach((value, key) => {
229
+ result[key] = value;
230
+ });
231
+ return result;
232
+ }
233
+ function calculateSizeInMb(data) {
234
+ const sizeInBytes = new TextEncoder().encode(JSON.stringify(data)).length;
235
+ return sizeInBytes / (1024 * 1024);
236
+ }
237
+ function defaultShouldRetry({ error, response }) {
238
+ if (error)
239
+ return true;
240
+ return response ? response.status >= 500 : false;
241
+ }
242
+ function delay(ms) {
243
+ return new Promise((resolve) => setTimeout(resolve, ms));
244
+ }
245
+
246
+ // src/secrets/infisical.ts
247
+ import { z } from "zod";
248
+ var defaultFetch = globalThis.fetch;
249
+ var infisicalAuthResponseSchema = z.object({
250
+ accessToken: z.string()
251
+ });
252
+ var infisicalSecretSchema = z.object({
253
+ secretKey: z.string(),
254
+ secretValue: z.string()
255
+ });
256
+ var infisicalSecretsResponseSchema = z.object({
257
+ secrets: z.array(infisicalSecretSchema)
258
+ });
259
+ async function loadInfisicalSecrets({
260
+ keys,
261
+ projectId,
262
+ environment,
263
+ siteUrl,
264
+ clientIdEnvKey,
265
+ clientSecretEnvKey
266
+ }) {
267
+ const clientId = process.env[clientIdEnvKey];
268
+ const clientSecret = process.env[clientSecretEnvKey];
269
+ if (!clientId || !clientSecret) {
270
+ throw new Error("Missing Infisical credentials");
271
+ }
272
+ const infisical = createInfisicalApiClient(siteUrl);
273
+ const { data: auth } = await infisical.request("login", {
274
+ reqBody: {
275
+ clientId,
276
+ clientSecret
277
+ }
278
+ });
279
+ const { data } = await infisical.request("listSecrets", {
280
+ reqHeaders: {
281
+ Authorization: `Bearer ${auth.accessToken}`
282
+ },
283
+ reqQuery: {
284
+ environment,
285
+ projectId,
286
+ secretPath: "/",
287
+ viewSecretValue: true,
288
+ expandSecretReferences: true,
289
+ includeImports: true
290
+ }
291
+ });
292
+ const wantedKeys = new Set(keys);
293
+ return Object.fromEntries(data.secrets.filter((secret) => wantedKeys.has(secret.secretKey)).map((secret) => [secret.secretKey, secret.secretValue]));
294
+ }
295
+ function createInfisicalApiClient(siteUrl) {
296
+ return createApiClient({
297
+ name: "infisical",
298
+ baseApiUrls: {
299
+ infisical: siteUrl
300
+ },
301
+ defaultBaseApiUrl: "infisical",
302
+ fetch: getFetch(),
303
+ retries: 1,
304
+ endpoints: {
305
+ login: {
306
+ method: "POST",
307
+ path: "/api/v1/auth/universal-auth/login",
308
+ reqBodySchema: z.object({
309
+ clientId: z.string(),
310
+ clientSecret: z.string()
311
+ }),
312
+ resSchema: infisicalAuthResponseSchema,
313
+ reqBodyFormat: "json"
314
+ },
315
+ listSecrets: {
316
+ method: "GET",
317
+ path: "/api/v4/secrets",
318
+ reqHeadersSchema: z.object({
319
+ Authorization: z.string()
320
+ }),
321
+ reqQuerySchema: z.object({
322
+ projectId: z.string(),
323
+ environment: z.string(),
324
+ secretPath: z.string(),
325
+ viewSecretValue: z.boolean(),
326
+ expandSecretReferences: z.boolean(),
327
+ includeImports: z.boolean()
328
+ }),
329
+ resSchema: infisicalSecretsResponseSchema
330
+ }
331
+ }
332
+ });
333
+ }
334
+ function getFetch() {
335
+ return globalThis.fetch ?? defaultFetch;
336
+ }
337
+
1
338
  // src/secrets/vite.ts
2
339
  function getViteDefine(secretSet) {
3
340
  return Object.fromEntries(Object.entries(secretSet.secrets()).map(([key, value]) => [
@@ -15,7 +352,6 @@ function viteSecretSetPlugin(secretSet) {
15
352
  }
16
353
 
17
354
  // src/secrets/index.ts
18
- import { InfisicalSDK } from "@infisical/sdk";
19
355
  import { networkInterfaces } from "node:os";
20
356
 
21
357
  // src/cool-console-log/index.ts
@@ -195,31 +531,6 @@ async function defineSecretSet(keys, options) {
195
531
  await loadSecrets();
196
532
  return secretSet;
197
533
  }
198
- async function loadInfisicalSecrets({
199
- keys,
200
- projectId,
201
- environment,
202
- siteUrl,
203
- clientIdEnvKey,
204
- clientSecretEnvKey
205
- }) {
206
- const clientId = process.env[clientIdEnvKey];
207
- const clientSecret = process.env[clientSecretEnvKey];
208
- if (!clientId || !clientSecret) {
209
- throw new Error("Missing Infisical credentials");
210
- }
211
- const client = new InfisicalSDK({ siteUrl });
212
- await client.auth().universalAuth.login({
213
- clientId,
214
- clientSecret
215
- });
216
- const { secrets } = await client.secrets().listSecrets({
217
- environment,
218
- projectId
219
- });
220
- const wantedKeys = new Set(keys);
221
- return Object.fromEntries(secrets.filter((secret) => wantedKeys.has(secret.secretKey)).map((secret) => [secret.secretKey, secret.secretValue]));
222
- }
223
534
  function resolveEnvironment(environment) {
224
535
  if (typeof environment === "function")
225
536
  return environment();
@@ -255,6 +566,7 @@ function getLocalIpAddress() {
255
566
  }
256
567
  export {
257
568
  viteSecretSetPlugin,
569
+ loadInfisicalSecrets,
258
570
  getViteDefine,
259
571
  getSecretEnvironment,
260
572
  defineSecretSet