@grow-codes/aws-secrets-manager 0.0.0-stage → 0.1.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/lib/index.cjs ADDED
@@ -0,0 +1,2956 @@
1
+ 'use strict';
2
+
3
+ var chunk5AEPFQD7_cjs = require('./chunk-5AEPFQD7.cjs');
4
+ var fs = require('fs');
5
+ var undici = require('undici');
6
+ var clientSecretsManager = require('@aws-sdk/client-secrets-manager');
7
+ var credentialProviders = require('@aws-sdk/credential-providers');
8
+
9
+ // src/core/health.ts
10
+ var HEALTHY_WORDS = /* @__PURE__ */ new Set([
11
+ "ok",
12
+ "up",
13
+ "healthy",
14
+ "pass",
15
+ "passing",
16
+ "green",
17
+ "ready",
18
+ "available",
19
+ "running",
20
+ "serving"
21
+ ]);
22
+ function isHealthyWord(status) {
23
+ return HEALTHY_WORDS.has(status.trim().toLowerCase());
24
+ }
25
+ function healthStatus(status, details = {}, healthy = isHealthyWord(status)) {
26
+ const flat = {};
27
+ for (const [k, v] of Object.entries(details)) {
28
+ if (v === void 0 || v === null) continue;
29
+ if (typeof v === "string") flat[k] = v;
30
+ else if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint")
31
+ flat[k] = String(v);
32
+ else if (typeof v === "object") flat[k] = JSON.stringify(v);
33
+ }
34
+ return { healthy, status, details: flat };
35
+ }
36
+ async function probeHealth(probe) {
37
+ try {
38
+ return await probe();
39
+ } catch (err) {
40
+ if (err instanceof chunk5AEPFQD7_cjs.AwsSecretsManagerError) {
41
+ if (err.code === chunk5AEPFQD7_cjs.ErrorCode.Cancelled || err.code === chunk5AEPFQD7_cjs.ErrorCode.Config) throw err;
42
+ if (err.httpStatus !== void 0) {
43
+ return healthStatus("unhealthy", { httpStatus: err.httpStatus, error: err.code }, false);
44
+ }
45
+ return healthStatus("unreachable", { error: err.code }, false);
46
+ }
47
+ return healthStatus("unreachable", { error: chunk5AEPFQD7_cjs.ErrorCode.Unavailable }, false);
48
+ }
49
+ }
50
+
51
+ // src/core/hooks.ts
52
+ var silentLogger = Object.freeze({
53
+ debug: () => void 0,
54
+ info: () => void 0,
55
+ warn: () => void 0,
56
+ error: () => void 0
57
+ });
58
+ function safeCall(fn, ...args) {
59
+ if (fn === void 0) return;
60
+ try {
61
+ const result = fn(...args);
62
+ if (result instanceof Promise) result.catch(() => void 0);
63
+ } catch {
64
+ }
65
+ }
66
+ function safeLogger(logger) {
67
+ if (logger === void 0) return silentLogger;
68
+ return {
69
+ debug: (m, f) => {
70
+ safeCall(
71
+ (a, b) => {
72
+ logger.debug(a, b);
73
+ },
74
+ m,
75
+ f
76
+ );
77
+ },
78
+ info: (m, f) => {
79
+ safeCall(
80
+ (a, b) => {
81
+ logger.info(a, b);
82
+ },
83
+ m,
84
+ f
85
+ );
86
+ },
87
+ warn: (m, f) => {
88
+ safeCall(
89
+ (a, b) => {
90
+ logger.warn(a, b);
91
+ },
92
+ m,
93
+ f
94
+ );
95
+ },
96
+ error: (m, f) => {
97
+ safeCall(
98
+ (a, b) => {
99
+ logger.error(a, b);
100
+ },
101
+ m,
102
+ f
103
+ );
104
+ }
105
+ };
106
+ }
107
+
108
+ // src/core/retry.ts
109
+ var RetryPolicy = class _RetryPolicy {
110
+ static DEFAULTS = Object.freeze({
111
+ maxRetries: 3,
112
+ initialBackoffMs: 100,
113
+ maxBackoffMs: 1e4,
114
+ multiplier: 2,
115
+ maxRetryAfterMs: 6e4
116
+ });
117
+ maxRetries;
118
+ initialBackoffMs;
119
+ maxBackoffMs;
120
+ multiplier;
121
+ maxRetryAfterMs;
122
+ random;
123
+ constructor(options = {}) {
124
+ const d = _RetryPolicy.DEFAULTS;
125
+ this.maxRetries = options.maxRetries ?? d.maxRetries;
126
+ this.initialBackoffMs = options.initialBackoffMs ?? d.initialBackoffMs;
127
+ this.maxBackoffMs = options.maxBackoffMs ?? d.maxBackoffMs;
128
+ this.multiplier = options.multiplier ?? d.multiplier;
129
+ this.maxRetryAfterMs = options.maxRetryAfterMs ?? d.maxRetryAfterMs;
130
+ this.random = options.random ?? Math.random;
131
+ Object.freeze(this);
132
+ }
133
+ /** Returns a policy from options, keeping an existing instance as is. */
134
+ static from(value) {
135
+ return value instanceof _RetryPolicy ? value : new _RetryPolicy(value);
136
+ }
137
+ /** Upper bound of the backoff before retry `n` (0-based): `min(max, initial * multiplier^n)`. */
138
+ backoffCapMs(retry) {
139
+ return Math.min(this.maxBackoffMs, this.initialBackoffMs * this.multiplier ** retry);
140
+ }
141
+ /** Full-jitter backoff before retry `n` (0-based): `random(0, backoffCapMs(n))`. */
142
+ backoffMs(retry) {
143
+ return this.random() * this.backoffCapMs(retry);
144
+ }
145
+ /** Validation problems (empty when valid). */
146
+ problems() {
147
+ const out = [];
148
+ if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0)
149
+ out.push("retry.maxRetries must be an integer >= 0");
150
+ if (!(this.initialBackoffMs >= 0)) out.push("retry.initialBackoffMs must be >= 0");
151
+ if (!(this.maxBackoffMs >= 0)) out.push("retry.maxBackoffMs must be >= 0");
152
+ if (!(this.multiplier >= 1)) out.push("retry.multiplier must be >= 1");
153
+ if (!(this.maxRetryAfterMs >= 0)) out.push("retry.maxRetryAfterMs must be >= 0");
154
+ return out;
155
+ }
156
+ toJSON() {
157
+ return {
158
+ maxRetries: this.maxRetries,
159
+ initialBackoffMs: this.initialBackoffMs,
160
+ maxBackoffMs: this.maxBackoffMs,
161
+ multiplier: this.multiplier,
162
+ maxRetryAfterMs: this.maxRetryAfterMs
163
+ };
164
+ }
165
+ };
166
+ function parseRetryAfter(value, now = Date.now()) {
167
+ if (value === null || value === void 0) return void 0;
168
+ const text = value.trim();
169
+ if (text === "") return void 0;
170
+ if (/^\d+(\.\d+)?$/.test(text)) return Math.round(Number(text) * 1e3);
171
+ if (!/[a-z]/i.test(text)) return void 0;
172
+ const at = Date.parse(text);
173
+ if (Number.isNaN(at)) return void 0;
174
+ return Math.max(0, at - now);
175
+ }
176
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
177
+ "GET",
178
+ "HEAD",
179
+ "OPTIONS",
180
+ "PUT",
181
+ "DELETE"
182
+ ]);
183
+ function isIdempotentMethod(method) {
184
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
185
+ }
186
+ function isRetryableStatus(status, idempotent) {
187
+ if (status === 429) return true;
188
+ if (!idempotent) return false;
189
+ return status === 408 || status === 500 || status === 502 || status === 503 || status === 504;
190
+ }
191
+
192
+ // src/core/options.ts
193
+ var DEFAULT_TIMEOUTS = Object.freeze({
194
+ connectTimeoutMs: 1e4,
195
+ requestTimeoutMs: 3e4,
196
+ totalTimeoutMs: 12e4
197
+ });
198
+ function resolveCommonConfig(options, defaultUrl) {
199
+ const out = {
200
+ url: options.url ?? defaultUrl,
201
+ connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_TIMEOUTS.connectTimeoutMs,
202
+ requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_TIMEOUTS.requestTimeoutMs,
203
+ totalTimeoutMs: options.totalTimeoutMs ?? DEFAULT_TIMEOUTS.totalTimeoutMs,
204
+ retry: RetryPolicy.from(options.retry),
205
+ tls: Object.freeze({ ...options.tls }),
206
+ headers: Object.freeze({ ...options.headers })
207
+ };
208
+ if (options.proxy !== void 0) out.proxy = options.proxy;
209
+ if (options.userAgentSuffix !== void 0) out.userAgentSuffix = options.userAgentSuffix;
210
+ if (options.hooks !== void 0) out.hooks = options.hooks;
211
+ if (options.logger !== void 0) out.logger = options.logger;
212
+ return out;
213
+ }
214
+ function isHttpUrl(value) {
215
+ try {
216
+ const u = new URL(value);
217
+ return u.protocol === "http:" || u.protocol === "https:";
218
+ } catch {
219
+ return false;
220
+ }
221
+ }
222
+ function validateCommonConfig(config) {
223
+ const problems = [];
224
+ if (!isHttpUrl(config.url)) problems.push("url must be an http or https URL");
225
+ for (const key of ["connectTimeoutMs", "requestTimeoutMs", "totalTimeoutMs"]) {
226
+ const v = config[key];
227
+ if (!Number.isFinite(v) || v <= 0) problems.push(`${key} must be a positive number`);
228
+ }
229
+ problems.push(...config.retry.problems());
230
+ const tls = config.tls;
231
+ if (tls.clientCertPath === void 0 !== (tls.clientKeyPath === void 0)) {
232
+ problems.push("tls.clientCertPath and tls.clientKeyPath must be given together");
233
+ }
234
+ if (config.proxy !== void 0 && !isHttpUrl(config.proxy)) {
235
+ problems.push("proxy must be an http or https URL");
236
+ }
237
+ if (problems.length > 0) throw new chunk5AEPFQD7_cjs.ConfigError(`invalid configuration: ${problems.join("; ")}`);
238
+ }
239
+ function readCommonEnv(reader, vendor = {}) {
240
+ const out = {};
241
+ const url = reader.string("URL", vendor.url);
242
+ if (url !== void 0) out.url = url;
243
+ const connect = reader.duration("CONNECT_TIMEOUT");
244
+ if (connect !== void 0) out.connectTimeoutMs = connect;
245
+ const request = reader.duration("REQUEST_TIMEOUT");
246
+ if (request !== void 0) out.requestTimeoutMs = request;
247
+ const total = reader.duration("TOTAL_TIMEOUT");
248
+ if (total !== void 0) out.totalTimeoutMs = total;
249
+ const maxRetries = reader.int("MAX_RETRIES");
250
+ if (maxRetries !== void 0) out.retry = { maxRetries };
251
+ const tls = {};
252
+ const ca = reader.string("CA_CERT", vendor.caCert);
253
+ if (ca !== void 0) tls.caCertPath = ca;
254
+ const cert = reader.string("CLIENT_CERT", vendor.clientCert);
255
+ if (cert !== void 0) tls.clientCertPath = cert;
256
+ const key = reader.string("CLIENT_KEY", vendor.clientKey);
257
+ if (key !== void 0) tls.clientKeyPath = key;
258
+ const insecure = reader.bool("INSECURE_SKIP_VERIFY", vendor.insecureSkipVerify);
259
+ if (insecure !== void 0) tls.insecureSkipVerify = insecure;
260
+ if (Object.keys(tls).length > 0) out.tls = tls;
261
+ const proxy = reader.string("PROXY", vendor.proxy);
262
+ if (proxy !== void 0) out.proxy = proxy;
263
+ return out;
264
+ }
265
+ function definedOnly(value) {
266
+ const out = {};
267
+ for (const [k, v] of Object.entries(value)) {
268
+ if (v !== void 0) out[k] = v;
269
+ }
270
+ return out;
271
+ }
272
+ function mergeOptions(...layers) {
273
+ const out = {};
274
+ for (const layer of layers) {
275
+ if (layer === void 0) continue;
276
+ for (const [k, v] of Object.entries(definedOnly(layer))) {
277
+ const prev = out[k];
278
+ if ((k === "tls" || k === "headers" || k === "retry" && !(v instanceof RetryPolicy)) && typeof prev === "object" && prev !== null) {
279
+ const base = prev instanceof RetryPolicy ? prev.toJSON() : prev;
280
+ out[k] = { ...base, ...definedOnly(v) };
281
+ } else {
282
+ out[k] = v;
283
+ }
284
+ }
285
+ }
286
+ return out;
287
+ }
288
+ function describeCommonConfig(config) {
289
+ const headers = {};
290
+ for (const k of Object.keys(config.headers)) headers[k] = chunk5AEPFQD7_cjs.REDACTED;
291
+ const out = {
292
+ url: chunk5AEPFQD7_cjs.redactUrl(config.url),
293
+ connectTimeoutMs: config.connectTimeoutMs,
294
+ requestTimeoutMs: config.requestTimeoutMs,
295
+ totalTimeoutMs: config.totalTimeoutMs,
296
+ retry: config.retry.toJSON(),
297
+ tls: {
298
+ ...config.tls,
299
+ ...config.tls.caCertPem === void 0 ? {} : { caCertPem: chunk5AEPFQD7_cjs.REDACTED }
300
+ },
301
+ headers
302
+ };
303
+ if (config.proxy !== void 0) out.proxy = chunk5AEPFQD7_cjs.redactUrl(config.proxy);
304
+ if (config.userAgentSuffix !== void 0) out.userAgentSuffix = config.userAgentSuffix;
305
+ return out;
306
+ }
307
+ function secretValues(...values) {
308
+ return values.filter((v) => v instanceof chunk5AEPFQD7_cjs.Secret).map((s) => s.reveal());
309
+ }
310
+
311
+ // src/core/version.ts
312
+ var SDK_VERSION = "0.1.0";
313
+ var PACKAGE_KEY = "aws-secrets-manager";
314
+ var LANGUAGE = "typescript";
315
+ var SDK_KIT_VERSION = "0.2.0";
316
+
317
+ // src/core/transport.ts
318
+ var DEFAULT_REQUEST_ID_HEADERS = [
319
+ "x-request-id",
320
+ "x-amzn-requestid",
321
+ "x-amz-request-id",
322
+ "x-datadog-request-id",
323
+ "request-id",
324
+ "x-correlation-id"
325
+ ];
326
+ var MAX_VENDOR_TEXT = 300;
327
+ var PRE_SEND_CODES = /* @__PURE__ */ new Set([
328
+ "ECONNREFUSED",
329
+ "ENOTFOUND",
330
+ "EAI_AGAIN",
331
+ "EHOSTUNREACH",
332
+ "ENETUNREACH",
333
+ "EADDRNOTAVAIL",
334
+ "UND_ERR_CONNECT_TIMEOUT"
335
+ ]);
336
+ var TLS_CODE = /CERT|SELF_SIGNED|UNABLE_TO_|ERR_TLS|ERR_SSL|DEPTH_ZERO/;
337
+ var CANCEL = /* @__PURE__ */ Symbol("cancel");
338
+ var ATTEMPT_TIMEOUT = /* @__PURE__ */ Symbol("attempt-timeout");
339
+ var insecureWarned = false;
340
+ var AbortedAttempt = class extends Error {
341
+ kind;
342
+ constructor(kind) {
343
+ super("aborted");
344
+ this.kind = kind;
345
+ }
346
+ };
347
+ function errorCode(err) {
348
+ let current = err;
349
+ for (let depth = 0; depth < 5 && current !== void 0 && current !== null; depth++) {
350
+ const code = current.code;
351
+ if (typeof code === "string") return code;
352
+ current = current.cause;
353
+ }
354
+ return void 0;
355
+ }
356
+ function readPem(path) {
357
+ return path === void 0 ? void 0 : fs.readFileSync(path, "utf8");
358
+ }
359
+ function createDispatcher(config, logger = safeLogger(config.logger)) {
360
+ const tls = config.tls;
361
+ if (tls.insecureSkipVerify === true && !insecureWarned) {
362
+ insecureWarned = true;
363
+ logger.warn("TLS certificate verification is disabled (insecureSkipVerify); use only in tests");
364
+ }
365
+ const caParts = [tls.caCertPem, readPem(tls.caCertPath)].filter(
366
+ (v) => v !== void 0
367
+ );
368
+ const tlsOptions = {
369
+ timeout: config.connectTimeoutMs,
370
+ rejectUnauthorized: tls.insecureSkipVerify !== true,
371
+ ...caParts.length > 0 ? { ca: caParts } : {},
372
+ ...tls.clientCertPath === void 0 ? {} : { cert: readPem(tls.clientCertPath) },
373
+ ...tls.clientKeyPath === void 0 ? {} : { key: readPem(tls.clientKeyPath) }
374
+ };
375
+ if (config.proxy !== void 0) {
376
+ return new undici.ProxyAgent({
377
+ uri: config.proxy,
378
+ connect: { timeout: config.connectTimeoutMs },
379
+ requestTls: tlsOptions
380
+ });
381
+ }
382
+ return new undici.Agent({ connect: tlsOptions });
383
+ }
384
+ var HttpTransport = class {
385
+ /** `grow-codes-<key>/<version> (typescript)[ <suffix>]`. */
386
+ userAgent;
387
+ retry;
388
+ #config;
389
+ #options;
390
+ #logger;
391
+ #hooks;
392
+ #fetch;
393
+ #sleep;
394
+ #now;
395
+ #requestIdHeaders;
396
+ #dispatcher;
397
+ #closed = false;
398
+ constructor(options) {
399
+ this.#options = options;
400
+ this.#config = options.config;
401
+ this.retry = options.config.retry;
402
+ this.#logger = safeLogger(options.config.logger);
403
+ this.#hooks = options.config.hooks ?? {};
404
+ this.#fetch = undici.fetch;
405
+ this.#sleep = options.sleep ?? chunk5AEPFQD7_cjs.sleep;
406
+ this.#now = options.now ?? Date.now;
407
+ this.#requestIdHeaders = options.requestIdHeaders ?? DEFAULT_REQUEST_ID_HEADERS;
408
+ this.#dispatcher = options.dispatcher;
409
+ const suffix = options.config.userAgentSuffix;
410
+ this.userAgent = `grow-codes-${PACKAGE_KEY}/${SDK_VERSION} (${LANGUAGE})` + (suffix !== void 0 && suffix !== "" ? ` ${suffix}` : "");
411
+ }
412
+ /** Whether {@link close} was called. */
413
+ get closed() {
414
+ return this.#closed;
415
+ }
416
+ /** Builds the absolute URL for a path and query. */
417
+ buildUrl(path, query) {
418
+ let url;
419
+ if (/^https?:\/\//i.test(path)) {
420
+ url = new URL(path);
421
+ } else {
422
+ const base = this.#config.url.endsWith("/") ? this.#config.url : this.#config.url + "/";
423
+ url = new URL(path.replace(/^\/+/, ""), base);
424
+ }
425
+ for (const [k, v] of Object.entries(query ?? {})) {
426
+ if (v === void 0 || v === null) continue;
427
+ if (Array.isArray(v)) {
428
+ for (const item of v)
429
+ url.searchParams.append(k, String(item));
430
+ } else {
431
+ url.searchParams.append(k, String(v));
432
+ }
433
+ }
434
+ return url;
435
+ }
436
+ /** Redacts known secrets from a text (error messages, vendor text). */
437
+ redact(text) {
438
+ return chunk5AEPFQD7_cjs.redactText(text, this.#knownSecrets());
439
+ }
440
+ #knownSecrets() {
441
+ return [...this.#options.knownSecrets?.() ?? []];
442
+ }
443
+ #getDispatcher() {
444
+ this.#dispatcher ??= createDispatcher(this.#config, this.#logger);
445
+ return this.#dispatcher;
446
+ }
447
+ /** `GET` shortcut. */
448
+ get(path, options = {}) {
449
+ return this.request({ ...options, method: "GET", path });
450
+ }
451
+ /** `POST` shortcut. */
452
+ post(path, options = {}) {
453
+ return this.request({ ...options, method: "POST", path });
454
+ }
455
+ /** `PUT` shortcut. */
456
+ put(path, options = {}) {
457
+ return this.request({ ...options, method: "PUT", path });
458
+ }
459
+ /** `DELETE` shortcut. */
460
+ delete(path, options = {}) {
461
+ return this.request({ ...options, method: "DELETE", path });
462
+ }
463
+ /**
464
+ * Sends a request with retries; throws an SDK error on failure. Every error message passes
465
+ * through {@link redact} with the known secrets.
466
+ */
467
+ async request(options) {
468
+ try {
469
+ return await this.#request(options);
470
+ } catch (err) {
471
+ if (err instanceof chunk5AEPFQD7_cjs.AwsSecretsManagerError) err.message = this.redact(err.message);
472
+ throw err;
473
+ }
474
+ }
475
+ async #request(options) {
476
+ const method = (options.method ?? "GET").toUpperCase();
477
+ const operation = options.operation ?? `${method} ${options.path.split("?")[0] ?? ""}`;
478
+ if (this.#closed) throw new chunk5AEPFQD7_cjs.CancelledError(`${operation}: client is closed`);
479
+ const signal = options.signal;
480
+ if (signal?.aborted === true) throw new chunk5AEPFQD7_cjs.CancelledError(`${operation}: cancelled`);
481
+ const url = this.buildUrl(options.path, options.query);
482
+ const safeUrl = chunk5AEPFQD7_cjs.redactUrl(url);
483
+ const headers = this.#buildHeaders(options);
484
+ const body = options.json !== void 0 ? JSON.stringify(options.json) : options.body;
485
+ const idempotent = options.idempotent ?? isIdempotentMethod(method);
486
+ const requestTimeout = options.requestTimeoutMs ?? this.#config.requestTimeoutMs;
487
+ const totalTimeout = options.totalTimeoutMs ?? this.#config.totalTimeoutMs;
488
+ const start = this.#now();
489
+ const deadline = start + totalTimeout;
490
+ const policy = this.retry;
491
+ for (let attempt = 1; ; attempt++) {
492
+ const remaining = deadline - this.#now();
493
+ if (remaining <= 0) {
494
+ throw new chunk5AEPFQD7_cjs.TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`);
495
+ }
496
+ const attemptTimeout = Math.min(requestTimeout, remaining);
497
+ const isTotal = attemptTimeout < requestTimeout;
498
+ safeCall(this.#hooks.onRequest, {
499
+ method,
500
+ url: safeUrl,
501
+ headers: chunk5AEPFQD7_cjs.redactHeaders(headers),
502
+ attempt
503
+ });
504
+ this.#logger.debug("http request", { method, url: safeUrl, attempt });
505
+ const attemptStart = this.#now();
506
+ let failure;
507
+ let willRetry = false;
508
+ let waitMs = 0;
509
+ try {
510
+ const res = await this.#attempt(
511
+ url,
512
+ method,
513
+ headers,
514
+ body,
515
+ attemptTimeout,
516
+ signal,
517
+ options.responseType ?? "json",
518
+ options.allowStatus ?? []
519
+ );
520
+ const durationMs = this.#now() - attemptStart;
521
+ const requestId = this.#requestId(res.headers);
522
+ safeCall(this.#hooks.onResponse, {
523
+ method,
524
+ url: safeUrl,
525
+ status: res.status,
526
+ durationMs,
527
+ attempt,
528
+ ...requestId === void 0 ? {} : { requestId }
529
+ });
530
+ this.#logger.debug("http response", {
531
+ method,
532
+ url: safeUrl,
533
+ status: res.status,
534
+ durationMs,
535
+ attempt
536
+ });
537
+ if (res.status < 400 || options.allowStatus?.includes(res.status) === true) {
538
+ return {
539
+ status: res.status,
540
+ headers: res.headers,
541
+ data: res.data,
542
+ ...requestId === void 0 ? {} : { requestId },
543
+ durationMs: this.#now() - start,
544
+ attempts: attempt,
545
+ ...res.status >= 400 ? { text: res.text } : {}
546
+ };
547
+ }
548
+ const retryAfter = res.status === 429 || res.status === 503 ? parseRetryAfter(res.headers.get("retry-after"), this.#now()) : void 0;
549
+ const reason = this.vendorText(res.text);
550
+ const defaultError = chunk5AEPFQD7_cjs.errorForStatus(operation, res.status, {
551
+ ...reason === void 0 ? {} : { reason },
552
+ ...requestId === void 0 ? {} : { requestId },
553
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter }
554
+ });
555
+ const classified = this.#classifyResponse(options.classifyError, {
556
+ operation,
557
+ method,
558
+ status: res.status,
559
+ headers: res.headers,
560
+ body: res.text,
561
+ ...reason === void 0 ? {} : { reason },
562
+ ...requestId === void 0 ? {} : { requestId },
563
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter },
564
+ attempt,
565
+ defaultError
566
+ });
567
+ failure = classified ?? defaultError;
568
+ if (isRetryableStatus(res.status, idempotent) && (classified === void 0 || classified.retryable) && attempt <= policy.maxRetries) {
569
+ const backoff = policy.backoffMs(attempt - 1);
570
+ if (retryAfter !== void 0) {
571
+ if (retryAfter > policy.maxRetryAfterMs || retryAfter >= deadline - this.#now()) {
572
+ willRetry = false;
573
+ } else {
574
+ willRetry = true;
575
+ waitMs = Math.max(retryAfter, backoff);
576
+ }
577
+ } else {
578
+ willRetry = true;
579
+ waitMs = backoff;
580
+ }
581
+ }
582
+ } catch (err) {
583
+ failure = this.#classify(err, operation, attemptTimeout, isTotal, totalTimeout);
584
+ const preSend = PRE_SEND_CODES.has(errorCode(err) ?? "");
585
+ willRetry = failure.retryable && !(failure.code === "TIMEOUT" && isTotal) && (idempotent || preSend) && attempt <= policy.maxRetries;
586
+ waitMs = willRetry ? policy.backoffMs(attempt - 1) : 0;
587
+ }
588
+ if (willRetry && waitMs >= deadline - this.#now()) {
589
+ safeCall(this.#hooks.onError, {
590
+ method,
591
+ url: safeUrl,
592
+ error: failure,
593
+ attempt,
594
+ willRetry: false
595
+ });
596
+ throw new chunk5AEPFQD7_cjs.TimeoutError(
597
+ `${operation}: total timeout of ${totalTimeout} ms exceeded after ${attempt} attempts`,
598
+ {
599
+ cause: failure,
600
+ ...failure.httpStatus === void 0 ? {} : { httpStatus: failure.httpStatus },
601
+ ...failure.requestId === void 0 ? {} : { requestId: failure.requestId }
602
+ }
603
+ );
604
+ }
605
+ safeCall(this.#hooks.onError, { method, url: safeUrl, error: failure, attempt, willRetry });
606
+ if (!willRetry) {
607
+ this.#logger.debug("http call failed", {
608
+ method,
609
+ url: safeUrl,
610
+ attempt,
611
+ code: failure.code
612
+ });
613
+ throw failure;
614
+ }
615
+ this.#logger.warn("http call failed, retrying", {
616
+ method,
617
+ url: safeUrl,
618
+ attempt,
619
+ code: failure.code,
620
+ waitMs: Math.round(waitMs)
621
+ });
622
+ await this.#sleep(waitMs, signal).catch((err) => {
623
+ throw err instanceof chunk5AEPFQD7_cjs.AwsSecretsManagerError ? err : new chunk5AEPFQD7_cjs.CancelledError(`${operation}: cancelled`);
624
+ });
625
+ }
626
+ }
627
+ #buildHeaders(options) {
628
+ const headers = {
629
+ accept: "application/json",
630
+ "user-agent": this.userAgent
631
+ };
632
+ const layers = [
633
+ this.#config.headers,
634
+ this.#options.defaultHeaders?.() ?? {},
635
+ options.headers ?? {}
636
+ ];
637
+ for (const layer of layers) {
638
+ for (const [k, v] of Object.entries(layer)) headers[k.toLowerCase()] = v;
639
+ }
640
+ if (options.json !== void 0 && headers["content-type"] === void 0) {
641
+ headers["content-type"] = "application/json";
642
+ }
643
+ return headers;
644
+ }
645
+ async #attempt(url, method, headers, body, timeoutMs, signal, responseType, allowStatus) {
646
+ const controller = new AbortController();
647
+ const timer = setTimeout(() => {
648
+ controller.abort(ATTEMPT_TIMEOUT);
649
+ }, timeoutMs);
650
+ timer.unref();
651
+ const onAbort = () => {
652
+ controller.abort(CANCEL);
653
+ };
654
+ signal?.addEventListener("abort", onAbort, { once: true });
655
+ try {
656
+ const init = {
657
+ method,
658
+ headers,
659
+ signal: controller.signal,
660
+ dispatcher: this.#getDispatcher(),
661
+ redirect: "follow"
662
+ };
663
+ if (body !== void 0) init.body = body;
664
+ const res = await this.#fetch(url, init);
665
+ const bytes = new Uint8Array(await res.arrayBuffer());
666
+ const isError = res.status >= 400;
667
+ const allowed = isError && allowStatus.includes(res.status);
668
+ const text = isError || responseType === "json" || responseType === "text" ? new TextDecoder().decode(bytes) : "";
669
+ let data;
670
+ if (isError && !allowed || responseType === "none") {
671
+ data = void 0;
672
+ } else if (responseType === "bytes") {
673
+ data = bytes;
674
+ } else if (responseType === "text") {
675
+ data = text;
676
+ } else if (allowed) {
677
+ data = parseJsonOrUndefined(text);
678
+ } else {
679
+ data = this.#parseJson(text, res.status);
680
+ }
681
+ return { status: res.status, headers: res.headers, data, text };
682
+ } catch (err) {
683
+ const reason = controller.signal.reason;
684
+ if (controller.signal.aborted && (reason === CANCEL || reason === ATTEMPT_TIMEOUT)) {
685
+ throw new AbortedAttempt(reason);
686
+ }
687
+ throw err;
688
+ } finally {
689
+ clearTimeout(timer);
690
+ signal?.removeEventListener("abort", onAbort);
691
+ }
692
+ }
693
+ #parseJson(text, status) {
694
+ if (text.trim() === "") return void 0;
695
+ try {
696
+ return JSON.parse(text);
697
+ } catch {
698
+ throw new chunk5AEPFQD7_cjs.UnavailableError(`invalid JSON in response (HTTP ${status})`, {
699
+ retryable: false,
700
+ httpStatus: status
701
+ });
702
+ }
703
+ }
704
+ #classify(err, operation, timeoutMs, isTotal, totalTimeout) {
705
+ if (err instanceof chunk5AEPFQD7_cjs.AwsSecretsManagerError) return err;
706
+ if (err instanceof AbortedAttempt) {
707
+ if (err.kind === CANCEL) return new chunk5AEPFQD7_cjs.CancelledError(`${operation}: cancelled`);
708
+ return isTotal ? new chunk5AEPFQD7_cjs.TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`) : new chunk5AEPFQD7_cjs.TimeoutError(`${operation}: request timed out after ${timeoutMs} ms`);
709
+ }
710
+ const cause = chunk5AEPFQD7_cjs.redactError(err, this.#knownSecrets());
711
+ const code = errorCode(err);
712
+ if (code === "UND_ERR_CONNECT_TIMEOUT") {
713
+ return new chunk5AEPFQD7_cjs.TimeoutError(
714
+ `${operation}: connect timeout after ${this.#config.connectTimeoutMs} ms`,
715
+ { cause }
716
+ );
717
+ }
718
+ if (code !== void 0 && TLS_CODE.test(code)) {
719
+ return new chunk5AEPFQD7_cjs.UnavailableError(`${operation}: TLS error (${code})`, { cause, retryable: false });
720
+ }
721
+ return new chunk5AEPFQD7_cjs.UnavailableError(
722
+ `${operation}: network error${code === void 0 ? "" : ` (${code})`}`,
723
+ { cause }
724
+ );
725
+ }
726
+ #classifyResponse(perRequest, response) {
727
+ for (const classify of [perRequest, this.#options.classifyError]) {
728
+ if (classify === void 0) continue;
729
+ let mapped;
730
+ try {
731
+ mapped = classify(response);
732
+ } catch (err) {
733
+ mapped = err instanceof chunk5AEPFQD7_cjs.AwsSecretsManagerError ? err : void 0;
734
+ }
735
+ if (mapped instanceof chunk5AEPFQD7_cjs.AwsSecretsManagerError) return mapped;
736
+ }
737
+ return void 0;
738
+ }
739
+ /**
740
+ * Extracts the vendor error message from a response body (JSON `message`, `error`, … or plain
741
+ * text; HTML is ignored), collapses whitespace, trims, redacts secrets and truncates it to
742
+ * {@link MAX_VENDOR_TEXT} characters. Returns `undefined` when there is nothing useful.
743
+ */
744
+ vendorText(text) {
745
+ const trimmed = text.trim();
746
+ if (trimmed === "") return void 0;
747
+ let extracted;
748
+ try {
749
+ extracted = extractMessage(JSON.parse(trimmed));
750
+ } catch {
751
+ extracted = /^\s*</.test(trimmed) ? void 0 : trimmed;
752
+ }
753
+ const collapsed = extracted?.replace(/\s+/g, " ").trim();
754
+ if (collapsed === void 0 || collapsed === "") return void 0;
755
+ const redacted = redactSecretsInText(this.redact(collapsed));
756
+ return redacted.length > MAX_VENDOR_TEXT ? redacted.slice(0, MAX_VENDOR_TEXT - 1).trimEnd() + "\u2026" : redacted;
757
+ }
758
+ #requestId(headers) {
759
+ for (const name of this.#requestIdHeaders) {
760
+ const v = headers.get(name);
761
+ if (v !== null && v !== "") return v;
762
+ }
763
+ return void 0;
764
+ }
765
+ /** Releases connections. Idempotent. */
766
+ async close() {
767
+ if (this.#closed) return;
768
+ this.#closed = true;
769
+ const dispatcher = this.#dispatcher;
770
+ this.#dispatcher = void 0;
771
+ if (dispatcher !== void 0 && this.#options.dispatcher === void 0) {
772
+ await dispatcher.close().catch(() => void 0);
773
+ }
774
+ }
775
+ };
776
+ function parseJsonOrUndefined(text) {
777
+ if (text.trim() === "") return void 0;
778
+ try {
779
+ return JSON.parse(text);
780
+ } catch {
781
+ return void 0;
782
+ }
783
+ }
784
+ function extractMessage(body) {
785
+ if (typeof body === "string") return body;
786
+ if (body === null || typeof body !== "object") return void 0;
787
+ if (Array.isArray(body)) return body.length > 0 ? extractMessage(body[0]) : void 0;
788
+ const obj = body;
789
+ for (const key of [
790
+ "message",
791
+ "error_description",
792
+ "error",
793
+ "errors",
794
+ "detail",
795
+ "msg",
796
+ "title",
797
+ "reason"
798
+ ]) {
799
+ const found = extractMessage(obj[key]);
800
+ if (found !== void 0 && found !== "") return found;
801
+ }
802
+ return void 0;
803
+ }
804
+ var SECRET_ASSIGNMENT = /((?:password|passwd|secret|token|authorization|api[_-]?key|access[_-]?key|private[_-]?key|credential|session|signature)["']?\s*[:=]\s*["']?)([^"'\s,;&}]+)/gi;
805
+ var BEARER = /\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi;
806
+ function redactSecretsInText(text) {
807
+ return text.replace(BEARER, "$1 [REDACTED]").replace(SECRET_ASSIGNMENT, "$1[REDACTED]");
808
+ }
809
+
810
+ // src/config.ts
811
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
812
+ var DEFAULT_RECOVERY_WINDOW_DAYS = 30;
813
+ var DEFAULT_ROLE_SESSION_NAME = "grow-sdk";
814
+ var VENDOR_ENV = {
815
+ url: ["AWS_ENDPOINT_URL_SECRETS_MANAGER", "AWS_ENDPOINT_URL"],
816
+ region: ["AWS_REGION", "AWS_DEFAULT_REGION"],
817
+ accessKeyId: ["AWS_ACCESS_KEY_ID"],
818
+ secretAccessKey: ["AWS_SECRET_ACCESS_KEY"],
819
+ sessionToken: ["AWS_SESSION_TOKEN"],
820
+ profile: ["AWS_PROFILE"]
821
+ };
822
+ var AwsSecretsManagerConfig = class _AwsSecretsManagerConfig {
823
+ /** Prefix of every environment variable. */
824
+ static ENV_PREFIX = "GROW_AWS_SECRETS_MANAGER_";
825
+ /**
826
+ * Effective endpoint: {@link endpoint} when set, otherwise the public AWS endpoint of
827
+ * {@link region} (`us-east-1` when the region is left to the SDK). Informational.
828
+ */
829
+ url;
830
+ /** Explicit endpoint override passed to the AWS SDK (`undefined` = SDK resolves it). */
831
+ endpoint;
832
+ connectTimeoutMs;
833
+ requestTimeoutMs;
834
+ totalTimeoutMs;
835
+ retry;
836
+ tls;
837
+ proxy;
838
+ headers;
839
+ userAgentSuffix;
840
+ hooks;
841
+ logger;
842
+ /** AWS region (`undefined` = SDK chain: env, shared config). */
843
+ region;
844
+ /** Access key id. */
845
+ accessKeyId;
846
+ /** Secret access key. */
847
+ secretAccessKey;
848
+ /** Session token. */
849
+ sessionToken;
850
+ /** Shared config profile. */
851
+ profile;
852
+ /** Explicit SDK credentials. */
853
+ credentials;
854
+ /** Role assumed with STS. */
855
+ roleArn;
856
+ /** STS session name. */
857
+ roleSessionName;
858
+ /** STS external id. */
859
+ externalId;
860
+ /** Assumed-role session duration in ms. */
861
+ roleDurationMs;
862
+ /** Recovery window of deletes in days. */
863
+ recoveryWindowDays;
864
+ /** Caller-supplied AWS SDK client. */
865
+ sdkClient;
866
+ /** Applies defaults, validates (throws {@link ConfigError}) and freezes. */
867
+ constructor(options = {}) {
868
+ const region = blankToUndefined(options.region);
869
+ const fallbackUrl = `https://secretsmanager.${region ?? "us-east-1"}.amazonaws.com`;
870
+ const endpointOption = blankToUndefined(options.url);
871
+ const common = resolveCommonConfig(
872
+ endpointOption === void 0 ? { ...options, url: fallbackUrl } : options,
873
+ fallbackUrl
874
+ );
875
+ this.url = common.url;
876
+ if (endpointOption !== void 0) this.endpoint = endpointOption;
877
+ this.connectTimeoutMs = common.connectTimeoutMs;
878
+ this.requestTimeoutMs = common.requestTimeoutMs;
879
+ this.totalTimeoutMs = common.totalTimeoutMs;
880
+ this.retry = common.retry;
881
+ this.tls = common.tls;
882
+ this.headers = common.headers;
883
+ if (common.proxy !== void 0) this.proxy = common.proxy;
884
+ if (common.userAgentSuffix !== void 0) this.userAgentSuffix = common.userAgentSuffix;
885
+ if (common.hooks !== void 0) this.hooks = common.hooks;
886
+ if (common.logger !== void 0) this.logger = common.logger;
887
+ if (region !== void 0) this.region = region;
888
+ const accessKeyId = blankToUndefined(options.accessKeyId);
889
+ if (accessKeyId !== void 0) this.accessKeyId = accessKeyId;
890
+ const secretAccessKey = chunk5AEPFQD7_cjs.Secret.from(options.secretAccessKey);
891
+ if (secretAccessKey !== void 0) this.secretAccessKey = secretAccessKey;
892
+ const sessionToken = chunk5AEPFQD7_cjs.Secret.from(options.sessionToken);
893
+ if (sessionToken !== void 0) this.sessionToken = sessionToken;
894
+ const profile = blankToUndefined(options.profile);
895
+ if (profile !== void 0) this.profile = profile;
896
+ if (options.credentials !== void 0) this.credentials = options.credentials;
897
+ const roleArn = blankToUndefined(options.roleArn);
898
+ if (roleArn !== void 0) this.roleArn = roleArn;
899
+ this.roleSessionName = blankToUndefined(options.roleSessionName) ?? DEFAULT_ROLE_SESSION_NAME;
900
+ const externalId = blankToUndefined(options.externalId);
901
+ if (externalId !== void 0) this.externalId = externalId;
902
+ if (options.roleDurationMs !== void 0) this.roleDurationMs = options.roleDurationMs;
903
+ this.recoveryWindowDays = options.recoveryWindowDays ?? DEFAULT_RECOVERY_WINDOW_DAYS;
904
+ if (options.sdkClient !== void 0) this.sdkClient = options.sdkClient;
905
+ this.validate();
906
+ Object.freeze(this);
907
+ }
908
+ /** Returns `options` when it already is a config, otherwise builds one. */
909
+ static from(options = {}) {
910
+ if (options instanceof _AwsSecretsManagerConfig) return options;
911
+ return new _AwsSecretsManagerConfig(options);
912
+ }
913
+ /**
914
+ * Builds a config from the environment. Precedence: explicit `overrides` >
915
+ * `GROW_AWS_SECRETS_MANAGER_<NAME>` > standard AWS variables ({@link VENDOR_ENV}) > defaults.
916
+ * Credentials left unset use the AWS SDK default chain.
917
+ */
918
+ static fromEnv(overrides = {}, env = process.env) {
919
+ const reader = new chunk5AEPFQD7_cjs.EnvReader(_AwsSecretsManagerConfig.ENV_PREFIX, env);
920
+ const fromEnv = readCommonEnv(reader, VENDOR_ENV);
921
+ const set = (key, value) => {
922
+ if (value !== void 0) fromEnv[key] = value;
923
+ };
924
+ set("region", reader.string("REGION", VENDOR_ENV.region));
925
+ const growKey = reader.string("ACCESS_KEY_ID");
926
+ if (growKey !== void 0) {
927
+ set("accessKeyId", growKey);
928
+ set("secretAccessKey", reader.secret("SECRET_ACCESS_KEY"));
929
+ set("sessionToken", reader.secret("SESSION_TOKEN"));
930
+ } else {
931
+ set("accessKeyId", firstEnv(env, VENDOR_ENV.accessKeyId));
932
+ set("secretAccessKey", chunk5AEPFQD7_cjs.Secret.from(firstEnv(env, VENDOR_ENV.secretAccessKey)));
933
+ set("sessionToken", chunk5AEPFQD7_cjs.Secret.from(firstEnv(env, VENDOR_ENV.sessionToken)));
934
+ }
935
+ set("profile", reader.string("PROFILE", VENDOR_ENV.profile));
936
+ set("roleArn", reader.string("ROLE_ARN"));
937
+ set("roleSessionName", reader.string("ROLE_SESSION_NAME"));
938
+ set("externalId", reader.string("EXTERNAL_ID"));
939
+ set("recoveryWindowDays", reader.int("RECOVERY_WINDOW_DAYS"));
940
+ const merged = mergeOptions(fromEnv, overrides);
941
+ if (overrides.sdkClient !== void 0 || overrides.credentials !== void 0) {
942
+ delete merged.accessKeyId;
943
+ delete merged.secretAccessKey;
944
+ delete merged.sessionToken;
945
+ if (overrides.sdkClient !== void 0) {
946
+ if (overrides.region === void 0) delete merged.region;
947
+ if (overrides.url === void 0) delete merged.url;
948
+ if (overrides.profile === void 0) delete merged.profile;
949
+ if (overrides.roleArn === void 0) delete merged.roleArn;
950
+ }
951
+ }
952
+ return new _AwsSecretsManagerConfig(merged);
953
+ }
954
+ /** Throws {@link ConfigError} when a setting is invalid. */
955
+ validate() {
956
+ validateCommonConfig(this);
957
+ const problems = [];
958
+ if (this.endpoint !== void 0 && !/^https?:\/\//i.test(this.endpoint)) {
959
+ problems.push("url must be an http or https URL");
960
+ }
961
+ if (this.region !== void 0 && !/^[a-z0-9-]+$/.test(this.region)) {
962
+ problems.push("region must look like us-east-1");
963
+ }
964
+ if (this.accessKeyId !== void 0 && this.secretAccessKey === void 0) {
965
+ problems.push("accessKeyId requires secretAccessKey");
966
+ }
967
+ if (this.accessKeyId === void 0 && this.secretAccessKey !== void 0) {
968
+ problems.push("secretAccessKey requires accessKeyId");
969
+ }
970
+ if (this.sessionToken !== void 0 && this.accessKeyId === void 0) {
971
+ problems.push("sessionToken requires accessKeyId and secretAccessKey");
972
+ }
973
+ if (this.credentials !== void 0 && this.accessKeyId !== void 0) {
974
+ problems.push("credentials and accessKeyId/secretAccessKey are mutually exclusive");
975
+ }
976
+ if (this.sdkClient !== void 0) {
977
+ const clash = [
978
+ ["accessKeyId", this.accessKeyId],
979
+ ["credentials", this.credentials],
980
+ ["profile", this.profile],
981
+ ["roleArn", this.roleArn],
982
+ ["region", this.region],
983
+ ["url", this.endpoint]
984
+ ].filter(([, v]) => v !== void 0);
985
+ if (clash.length > 0) {
986
+ problems.push(`sdkClient is mutually exclusive with ${clash.map(([k]) => k).join(", ")}`);
987
+ }
988
+ }
989
+ if (this.roleArn !== void 0 && !this.roleArn.startsWith("arn:")) {
990
+ problems.push("roleArn must be an ARN");
991
+ }
992
+ if (this.roleDurationMs !== void 0 && !(this.roleDurationMs >= 9e5 && this.roleDurationMs <= 432e5)) {
993
+ problems.push("roleDurationMs must be between 900000 and 43200000");
994
+ }
995
+ if (!Number.isInteger(this.recoveryWindowDays) || this.recoveryWindowDays < 7 || this.recoveryWindowDays > 30) {
996
+ problems.push("recoveryWindowDays must be an integer from 7 to 30");
997
+ }
998
+ if (problems.length > 0) {
999
+ throw new chunk5AEPFQD7_cjs.ConfigError(`invalid configuration: ${problems.join("; ")}`);
1000
+ }
1001
+ }
1002
+ /** Credential values to redact from error messages and logs. */
1003
+ knownSecrets() {
1004
+ return secretValues(this.secretAccessKey, this.sessionToken);
1005
+ }
1006
+ /** Debug form with every credential redacted. */
1007
+ toJSON() {
1008
+ const out = {
1009
+ ...describeCommonConfig(this),
1010
+ endpoint: this.endpoint ?? null,
1011
+ region: this.region ?? null,
1012
+ accessKeyId: this.accessKeyId ?? null,
1013
+ secretAccessKey: this.secretAccessKey === void 0 ? null : chunk5AEPFQD7_cjs.REDACTED,
1014
+ sessionToken: this.sessionToken === void 0 ? null : chunk5AEPFQD7_cjs.REDACTED,
1015
+ profile: this.profile ?? null,
1016
+ credentials: this.credentials === void 0 ? null : chunk5AEPFQD7_cjs.REDACTED,
1017
+ roleArn: this.roleArn ?? null,
1018
+ roleSessionName: this.roleSessionName,
1019
+ externalId: this.externalId === void 0 ? null : chunk5AEPFQD7_cjs.REDACTED,
1020
+ recoveryWindowDays: this.recoveryWindowDays,
1021
+ sdkClient: this.sdkClient === void 0 ? null : "SecretsManagerClient"
1022
+ };
1023
+ if (this.roleDurationMs !== void 0) out.roleDurationMs = this.roleDurationMs;
1024
+ return out;
1025
+ }
1026
+ toString() {
1027
+ return `AwsSecretsManagerConfig(${JSON.stringify(this.toJSON())})`;
1028
+ }
1029
+ [INSPECT]() {
1030
+ return this.toString();
1031
+ }
1032
+ };
1033
+ function firstEnv(env, names) {
1034
+ for (const name of names) {
1035
+ const value = env[name];
1036
+ if (value !== void 0 && value !== "") return value;
1037
+ }
1038
+ return void 0;
1039
+ }
1040
+ function blankToUndefined(value) {
1041
+ return value === void 0 || value.trim() === "" ? void 0 : value;
1042
+ }
1043
+
1044
+ // src/errors-map.ts
1045
+ var AWS_ERROR_CODES = Object.freeze({
1046
+ ResourceNotFoundException: chunk5AEPFQD7_cjs.ErrorCode.NotFound,
1047
+ ResourceExistsException: chunk5AEPFQD7_cjs.ErrorCode.Conflict,
1048
+ PreconditionNotMetException: chunk5AEPFQD7_cjs.ErrorCode.Conflict,
1049
+ InvalidRequestException: chunk5AEPFQD7_cjs.ErrorCode.Conflict,
1050
+ InvalidParameterException: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1051
+ InvalidParameterValue: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1052
+ ValidationException: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1053
+ InvalidNextTokenException: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1054
+ MalformedPolicyDocumentException: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1055
+ PublicPolicyException: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1056
+ LimitExceededException: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1057
+ EncryptionFailure: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1058
+ DecryptionFailure: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1059
+ SerializationException: chunk5AEPFQD7_cjs.ErrorCode.Validation,
1060
+ AccessDeniedException: chunk5AEPFQD7_cjs.ErrorCode.PermissionDenied,
1061
+ AccessDenied: chunk5AEPFQD7_cjs.ErrorCode.PermissionDenied,
1062
+ UnrecognizedClientException: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1063
+ InvalidClientTokenId: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1064
+ InvalidSignatureException: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1065
+ SignatureDoesNotMatch: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1066
+ IncompleteSignature: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1067
+ IncompleteSignatureException: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1068
+ MissingAuthenticationToken: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1069
+ MissingAuthenticationTokenException: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1070
+ ExpiredToken: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1071
+ ExpiredTokenException: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1072
+ InvalidAccessKeyId: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1073
+ CredentialsProviderError: chunk5AEPFQD7_cjs.ErrorCode.Authentication,
1074
+ ThrottlingException: chunk5AEPFQD7_cjs.ErrorCode.RateLimited,
1075
+ Throttling: chunk5AEPFQD7_cjs.ErrorCode.RateLimited,
1076
+ TooManyRequestsException: chunk5AEPFQD7_cjs.ErrorCode.RateLimited,
1077
+ RequestLimitExceeded: chunk5AEPFQD7_cjs.ErrorCode.RateLimited,
1078
+ InternalServiceError: chunk5AEPFQD7_cjs.ErrorCode.Unavailable,
1079
+ InternalServiceErrorException: chunk5AEPFQD7_cjs.ErrorCode.Unavailable,
1080
+ InternalFailure: chunk5AEPFQD7_cjs.ErrorCode.Unavailable,
1081
+ ServiceUnavailable: chunk5AEPFQD7_cjs.ErrorCode.Unavailable,
1082
+ ServiceUnavailableException: chunk5AEPFQD7_cjs.ErrorCode.Unavailable,
1083
+ RequestTimeout: chunk5AEPFQD7_cjs.ErrorCode.Timeout,
1084
+ RequestTimeoutException: chunk5AEPFQD7_cjs.ErrorCode.Timeout,
1085
+ TimeoutError: chunk5AEPFQD7_cjs.ErrorCode.Timeout
1086
+ });
1087
+ var NETWORK_TIMEOUT_CODES = /* @__PURE__ */ new Set([
1088
+ "ETIMEDOUT",
1089
+ "UND_ERR_CONNECT_TIMEOUT",
1090
+ "UND_ERR_HEADERS_TIMEOUT",
1091
+ "UND_ERR_BODY_TIMEOUT"
1092
+ ]);
1093
+ function bodyText(body) {
1094
+ if (typeof body === "string") return body;
1095
+ if (body instanceof Uint8Array) return new TextDecoder().decode(body);
1096
+ return "";
1097
+ }
1098
+ function errorCodeFromBody(text) {
1099
+ const xml = /<Code>\s*([^<\s]+)\s*<\/Code>/.exec(text)?.[1];
1100
+ if (xml !== void 0) return xml;
1101
+ try {
1102
+ const parsed = JSON.parse(text);
1103
+ const raw = typeof parsed.__type === "string" ? parsed.__type : parsed.code;
1104
+ if (typeof raw === "string") return raw.split("#").pop()?.split(":")[0];
1105
+ } catch {
1106
+ }
1107
+ return void 0;
1108
+ }
1109
+ function cleanVendorText(text, knownSecrets) {
1110
+ const collapsed = text.replace(/\s+/g, " ").trim();
1111
+ const redacted = redactSecretsInText(chunk5AEPFQD7_cjs.redactText(collapsed, knownSecrets));
1112
+ return redacted.length > MAX_VENDOR_TEXT ? `${redacted.slice(0, MAX_VENDOR_TEXT)}\u2026` : redacted;
1113
+ }
1114
+ function nodeCode(err) {
1115
+ let current = err;
1116
+ for (let depth = 0; depth < 5 && current !== void 0 && current !== null; depth++) {
1117
+ const code = current.code;
1118
+ if (typeof code === "string") return code;
1119
+ current = current.cause;
1120
+ }
1121
+ return void 0;
1122
+ }
1123
+ function mapAwsError(err, operation, options = {}) {
1124
+ if (chunk5AEPFQD7_cjs.isAwsSecretsManagerError(err)) return err;
1125
+ const known = [...options.knownSecrets ?? []];
1126
+ const e = typeof err === "object" && err !== null ? err : {};
1127
+ const name = typeof e.name === "string" ? e.name : "";
1128
+ const message = typeof e.message === "string" ? e.message : String(err);
1129
+ const status = e.$metadata?.httpStatusCode ?? e.$response?.statusCode;
1130
+ const requestId = e.$metadata?.requestId;
1131
+ const details = {
1132
+ ...status === void 0 ? {} : { httpStatus: status },
1133
+ ...requestId === void 0 ? {} : { requestId },
1134
+ cause: err
1135
+ };
1136
+ const suffix = status === void 0 ? "" : ` (HTTP ${String(status)})`;
1137
+ if (name === "AbortError") {
1138
+ return chunk5AEPFQD7_cjs.errorForCode(chunk5AEPFQD7_cjs.ErrorCode.Cancelled, `${operation}: cancelled`, { cause: err });
1139
+ }
1140
+ if (/Region is missing|Region not accepted/i.test(message)) {
1141
+ return chunk5AEPFQD7_cjs.errorForCode(
1142
+ chunk5AEPFQD7_cjs.ErrorCode.Config,
1143
+ `${operation}: no AWS region configured (set region or AWS_REGION)`,
1144
+ { cause: err }
1145
+ );
1146
+ }
1147
+ if (status !== void 0) {
1148
+ const parsed = e.$fault !== void 0 && name !== "" ? name : void 0;
1149
+ const raw = bodyText(e.$response?.body);
1150
+ const awsCode = parsed ?? errorCodeFromBody(raw);
1151
+ let code = awsCode === void 0 ? void 0 : AWS_ERROR_CODES[awsCode];
1152
+ if (code === void 0) {
1153
+ if (status === 403) {
1154
+ code = /InvalidClientTokenId|SignatureDoesNotMatch|security token/i.test(raw) ? chunk5AEPFQD7_cjs.ErrorCode.Authentication : chunk5AEPFQD7_cjs.ErrorCode.PermissionDenied;
1155
+ } else if (status === 500 && options.unsupportedOnHtml500 === true && /<html/i.test(raw)) {
1156
+ code = chunk5AEPFQD7_cjs.ErrorCode.Unsupported;
1157
+ } else {
1158
+ code = chunk5AEPFQD7_cjs.codeForStatus(status);
1159
+ }
1160
+ }
1161
+ const vendor = parsed !== void 0 ? cleanVendorText(message, known) : "";
1162
+ const reason = awsCode === void 0 ? chunk5AEPFQD7_cjs.reasonForCode(code) : vendor === "" ? awsCode : `${awsCode}: ${vendor}`;
1163
+ const retryAfterRaw = e.$response?.headers?.["retry-after"];
1164
+ const retryAfterMs = code === chunk5AEPFQD7_cjs.ErrorCode.RateLimited && retryAfterRaw !== void 0 ? parseRetryAfter(retryAfterRaw) : void 0;
1165
+ return chunk5AEPFQD7_cjs.errorForCode(code, `${operation}: ${reason}${suffix}`, {
1166
+ ...details,
1167
+ ...retryAfterMs === void 0 ? {} : { retryAfterMs }
1168
+ });
1169
+ }
1170
+ const mappedByName = AWS_ERROR_CODES[name];
1171
+ if (mappedByName !== void 0) {
1172
+ const text2 = cleanVendorText(message, known);
1173
+ return chunk5AEPFQD7_cjs.errorForCode(
1174
+ mappedByName,
1175
+ `${operation}: ${chunk5AEPFQD7_cjs.reasonForCode(mappedByName)}: ${text2}`,
1176
+ details
1177
+ );
1178
+ }
1179
+ const net = nodeCode(err);
1180
+ if (net !== void 0 && NETWORK_TIMEOUT_CODES.has(net)) {
1181
+ return chunk5AEPFQD7_cjs.errorForCode(chunk5AEPFQD7_cjs.ErrorCode.Timeout, `${operation}: timed out (${net})`, details);
1182
+ }
1183
+ const text = cleanVendorText(message, known);
1184
+ return chunk5AEPFQD7_cjs.errorForCode(
1185
+ chunk5AEPFQD7_cjs.ErrorCode.Unavailable,
1186
+ `${operation}: service unavailable: ${net === void 0 ? text : `${net}: ${text}`}`,
1187
+ details
1188
+ );
1189
+ }
1190
+ var GROW_USER_AGENT = `grow-codes-${PACKAGE_KEY}/${SDK_VERSION} (${LANGUAGE})`;
1191
+ var AttemptTimeoutError = class extends Error {
1192
+ /** Node-style code, recognised by the SDK retry strategy as a transient error. */
1193
+ code = "ETIMEDOUT";
1194
+ constructor(ms) {
1195
+ super(`request timed out after ${ms} ms`);
1196
+ this.name = "TimeoutError";
1197
+ }
1198
+ };
1199
+ function parseAttemptHeader(value) {
1200
+ const attempt = /attempt=(\d+)/.exec(value ?? "")?.[1];
1201
+ const max = /max=(\d+)/.exec(value ?? "")?.[1];
1202
+ return {
1203
+ attempt: attempt === void 0 ? 1 : Number(attempt),
1204
+ max: max === void 0 ? 1 : Number(max)
1205
+ };
1206
+ }
1207
+ function buildUrl(request) {
1208
+ const port = request.port === void 0 ? "" : `:${String(request.port)}`;
1209
+ const path = request.path.startsWith("/") ? request.path : `/${request.path}`;
1210
+ const params = new URLSearchParams();
1211
+ for (const [k, v] of Object.entries(request.query ?? {})) {
1212
+ if (v === null) continue;
1213
+ for (const item of Array.isArray(v) ? v : [v]) params.append(k, item);
1214
+ }
1215
+ const qs = params.toString();
1216
+ return `${request.protocol}//${request.hostname}${port}${path}${qs === "" ? "" : `?${qs}`}`;
1217
+ }
1218
+ var GrowHttpHandler = class {
1219
+ #config;
1220
+ #hooks;
1221
+ #logger;
1222
+ #userAgent;
1223
+ #dispatcher;
1224
+ #ownsDispatcher;
1225
+ #destroyed = false;
1226
+ constructor(options) {
1227
+ this.#config = options.config;
1228
+ this.#hooks = options.config.hooks ?? {};
1229
+ this.#logger = safeLogger(options.config.logger);
1230
+ this.#dispatcher = options.dispatcher;
1231
+ this.#ownsDispatcher = options.dispatcher === void 0;
1232
+ const suffix = options.config.userAgentSuffix;
1233
+ this.#userAgent = GROW_USER_AGENT + (suffix !== void 0 && suffix !== "" ? ` ${suffix}` : "");
1234
+ }
1235
+ /** The User-Agent token appended to the SDK's own User-Agent. */
1236
+ get userAgent() {
1237
+ return this.#userAgent;
1238
+ }
1239
+ /** Smithy handler metadata. */
1240
+ metadata = { handlerProtocol: "http/1.1" };
1241
+ #getDispatcher() {
1242
+ this.#dispatcher ??= createDispatcher(this.#config, this.#logger);
1243
+ return this.#dispatcher;
1244
+ }
1245
+ /** Sends one attempt. Called by the SDK (after signing) for every attempt. */
1246
+ async handle(request, options = {}) {
1247
+ const url = buildUrl(request);
1248
+ const safeUrl = chunk5AEPFQD7_cjs.redactUrl(url);
1249
+ const headers = {};
1250
+ for (const [k, v] of Object.entries(this.#config.headers)) headers[k.toLowerCase()] = v;
1251
+ for (const [k, v] of Object.entries(request.headers)) headers[k.toLowerCase()] = v;
1252
+ headers["user-agent"] = headers["user-agent"] === void 0 ? this.#userAgent : `${headers["user-agent"]} ${this.#userAgent}`;
1253
+ const { attempt, max } = parseAttemptHeader(headers["amz-sdk-request"]);
1254
+ const method = request.method.toUpperCase();
1255
+ safeCall(this.#hooks.onRequest, {
1256
+ method,
1257
+ url: safeUrl,
1258
+ headers: chunk5AEPFQD7_cjs.redactHeaders(headers),
1259
+ attempt
1260
+ });
1261
+ this.#logger.debug("aws-secrets-manager request", { method, url: safeUrl, attempt });
1262
+ const timeoutMs = options.requestTimeout ?? this.#config.requestTimeoutMs;
1263
+ const controller = new AbortController();
1264
+ const external = options.abortSignal;
1265
+ const onAbort = () => {
1266
+ controller.abort(external?.reason);
1267
+ };
1268
+ if (external?.aborted === true) onAbort();
1269
+ else external?.addEventListener("abort", onAbort, { once: true });
1270
+ const state = { timedOut: false };
1271
+ const timer = setTimeout(() => {
1272
+ state.timedOut = true;
1273
+ controller.abort();
1274
+ }, timeoutMs);
1275
+ timer.unref();
1276
+ const start = performance.now();
1277
+ try {
1278
+ const res = await undici.fetch(url, {
1279
+ method,
1280
+ headers,
1281
+ ...request.body === void 0 || request.body === null ? {} : { body: request.body },
1282
+ signal: controller.signal,
1283
+ dispatcher: this.#getDispatcher()
1284
+ });
1285
+ const body = new Uint8Array(await res.arrayBuffer());
1286
+ const responseHeaders = {};
1287
+ res.headers.forEach((value, key) => {
1288
+ responseHeaders[key] = value;
1289
+ });
1290
+ const requestId = responseHeaders["x-amzn-requestid"] ?? responseHeaders["x-amz-request-id"];
1291
+ safeCall(this.#hooks.onResponse, {
1292
+ method,
1293
+ url: safeUrl,
1294
+ status: res.status,
1295
+ durationMs: performance.now() - start,
1296
+ attempt,
1297
+ ...requestId === void 0 ? {} : { requestId }
1298
+ });
1299
+ return {
1300
+ response: {
1301
+ statusCode: res.status,
1302
+ reason: res.statusText,
1303
+ headers: responseHeaders,
1304
+ body
1305
+ }
1306
+ };
1307
+ } catch (err) {
1308
+ const error = state.timedOut && external?.aborted !== true ? new AttemptTimeoutError(timeoutMs) : external?.aborted === true ? abortError() : toError(err);
1309
+ safeCall(this.#hooks.onError, {
1310
+ method,
1311
+ url: safeUrl,
1312
+ error,
1313
+ attempt,
1314
+ willRetry: external?.aborted !== true && attempt < max
1315
+ });
1316
+ throw error;
1317
+ } finally {
1318
+ clearTimeout(timer);
1319
+ external?.removeEventListener("abort", onAbort);
1320
+ }
1321
+ }
1322
+ /** Smithy handler API (no runtime-updatable settings). */
1323
+ updateHttpClientConfig() {
1324
+ }
1325
+ /** Smithy handler API. */
1326
+ httpHandlerConfigs() {
1327
+ return {};
1328
+ }
1329
+ /** Closes the dispatcher (only when this handler created it). Idempotent. */
1330
+ destroy() {
1331
+ if (this.#destroyed) return;
1332
+ this.#destroyed = true;
1333
+ const dispatcher = this.#dispatcher;
1334
+ this.#dispatcher = void 0;
1335
+ if (dispatcher !== void 0 && this.#ownsDispatcher) {
1336
+ dispatcher.close().catch(() => void 0);
1337
+ }
1338
+ }
1339
+ };
1340
+ function abortError() {
1341
+ const err = new Error("Request aborted");
1342
+ err.name = "AbortError";
1343
+ return err;
1344
+ }
1345
+ function toError(err) {
1346
+ if (err instanceof Error) {
1347
+ const cause = err.cause;
1348
+ if (typeof cause?.code === "string") {
1349
+ const wrapped = new Error(typeof cause.message === "string" ? cause.message : err.message, {
1350
+ cause: err
1351
+ });
1352
+ wrapped.code = cause.code;
1353
+ wrapped.name = cause.code;
1354
+ return wrapped;
1355
+ }
1356
+ return err;
1357
+ }
1358
+ return new Error(String(err));
1359
+ }
1360
+
1361
+ // src/secrets/cache.ts
1362
+ var SecretCache = class extends chunk5AEPFQD7_cjs.BaseSecretsProvider {
1363
+ #provider;
1364
+ #ttl;
1365
+ #max;
1366
+ #refreshAt;
1367
+ #swr;
1368
+ #clock;
1369
+ #onRefreshError;
1370
+ #entries = /* @__PURE__ */ new Map();
1371
+ #inflight = /* @__PURE__ */ new Map();
1372
+ #hits = 0;
1373
+ #misses = 0;
1374
+ #evictions = 0;
1375
+ #refreshes = 0;
1376
+ #generation = 0;
1377
+ constructor(provider, options = {}) {
1378
+ super();
1379
+ this.#provider = provider;
1380
+ this.#ttl = options.ttlMs ?? 6e4;
1381
+ this.#max = options.maxEntries ?? 1e3;
1382
+ const factor = options.refreshAheadFactor ?? 0.8;
1383
+ this.#swr = options.staleWhileRevalidateMs ?? 0;
1384
+ this.#clock = options.clock ?? Date.now;
1385
+ this.#onRefreshError = options.onRefreshError;
1386
+ if (!(this.#ttl > 0)) throw new chunk5AEPFQD7_cjs.ValidationError("SecretCache: ttlMs must be > 0");
1387
+ if (!Number.isInteger(this.#max) || this.#max < 1)
1388
+ throw new chunk5AEPFQD7_cjs.ValidationError("SecretCache: maxEntries must be >= 1");
1389
+ if (!(factor > 0)) throw new chunk5AEPFQD7_cjs.ValidationError("SecretCache: refreshAheadFactor must be > 0");
1390
+ if (!(this.#swr >= 0))
1391
+ throw new chunk5AEPFQD7_cjs.ValidationError("SecretCache: staleWhileRevalidateMs must be >= 0");
1392
+ this.#refreshAt = this.#ttl * factor;
1393
+ }
1394
+ /** The wrapped provider. */
1395
+ get provider() {
1396
+ return this.#provider;
1397
+ }
1398
+ async fetchSecret(name, options) {
1399
+ const key = cacheKey(name, options);
1400
+ const entry = this.#entries.get(key);
1401
+ if (entry !== void 0) {
1402
+ const age = this.#clock() - entry.storedAt;
1403
+ if (age < this.#ttl + this.#swr) {
1404
+ this.#hits++;
1405
+ this.#touch(key, entry);
1406
+ if (age >= this.#refreshAt) this.#refresh(key, name, options, entry);
1407
+ return entry.value;
1408
+ }
1409
+ this.#entries.delete(key);
1410
+ }
1411
+ this.#misses++;
1412
+ return this.#load(key, name, options);
1413
+ }
1414
+ #touch(key, entry) {
1415
+ this.#entries.delete(key);
1416
+ this.#entries.set(key, entry);
1417
+ }
1418
+ #load(key, name, options) {
1419
+ const pending = this.#inflight.get(key);
1420
+ if (pending !== void 0) return pending;
1421
+ const generation = this.#generation;
1422
+ const promise = this.#provider.get(name, stripSignal(options)).then((value) => {
1423
+ if (generation === this.#generation) this.#store(key, name, value);
1424
+ return value;
1425
+ }).finally(() => {
1426
+ if (this.#inflight.get(key) === promise) this.#inflight.delete(key);
1427
+ });
1428
+ this.#inflight.set(key, promise);
1429
+ return promise;
1430
+ }
1431
+ #refresh(key, name, options, entry) {
1432
+ if (entry.refreshing || this.#inflight.has(key)) return;
1433
+ entry.refreshing = true;
1434
+ this.#refreshes++;
1435
+ this.#load(key, name, options).catch((err) => {
1436
+ entry.refreshing = false;
1437
+ try {
1438
+ this.#onRefreshError?.(err);
1439
+ } catch {
1440
+ }
1441
+ });
1442
+ }
1443
+ #store(key, name, value) {
1444
+ this.#entries.delete(key);
1445
+ this.#entries.set(key, { name, value, storedAt: this.#clock(), refreshing: false });
1446
+ while (this.#entries.size > this.#max) {
1447
+ const oldest = this.#entries.keys().next().value;
1448
+ this.#entries.delete(oldest);
1449
+ this.#evictions++;
1450
+ }
1451
+ }
1452
+ listSecrets(prefixOrPath, options) {
1453
+ return this.#provider.list(prefixOrPath, options);
1454
+ }
1455
+ async putSecret(name, value, options) {
1456
+ try {
1457
+ return await this.#provider.set(name, value, options);
1458
+ } finally {
1459
+ this.invalidate(name);
1460
+ }
1461
+ }
1462
+ async removeSecret(name, options) {
1463
+ try {
1464
+ await this.#provider.delete(name, options);
1465
+ } finally {
1466
+ this.invalidate(name);
1467
+ }
1468
+ }
1469
+ fetchMetadata(name, options) {
1470
+ return this.#provider.metadata(name, options);
1471
+ }
1472
+ /** Drops every cached entry of `name` (all versions and paths). */
1473
+ invalidate(name) {
1474
+ for (const [key, entry] of this.#entries) {
1475
+ if (entry.name === name) this.#entries.delete(key);
1476
+ }
1477
+ for (const key of [...this.#inflight.keys()]) {
1478
+ if (keyName(key) === name) {
1479
+ this.#inflight.delete(key);
1480
+ this.#generation++;
1481
+ }
1482
+ }
1483
+ }
1484
+ /** Drops every cached entry. */
1485
+ clear() {
1486
+ this.#entries.clear();
1487
+ this.#inflight.clear();
1488
+ this.#generation++;
1489
+ }
1490
+ /** Counters and current size. */
1491
+ stats() {
1492
+ return {
1493
+ hits: this.#hits,
1494
+ misses: this.#misses,
1495
+ evictions: this.#evictions,
1496
+ refreshes: this.#refreshes,
1497
+ size: this.#entries.size
1498
+ };
1499
+ }
1500
+ };
1501
+ function cacheKey(name, options) {
1502
+ return JSON.stringify([name, options.path ?? null, options.version ?? null]);
1503
+ }
1504
+ function keyName(key) {
1505
+ return JSON.parse(key)[0];
1506
+ }
1507
+ function stripSignal(options) {
1508
+ const { signal: _signal, ...rest } = options;
1509
+ return rest;
1510
+ }
1511
+
1512
+ // src/models.ts
1513
+ var API_VERSION = "2017-10-17";
1514
+ var AWSCURRENT = "AWSCURRENT";
1515
+ var AWSPREVIOUS = "AWSPREVIOUS";
1516
+ var AWSPENDING = "AWSPENDING";
1517
+ var BATCH_GET_MAX_IDS = 20;
1518
+ function toAwsTags(tags) {
1519
+ return Object.entries(tags).map(([Key, Value]) => ({ Key, Value }));
1520
+ }
1521
+ function fromAwsTags(tags) {
1522
+ const out = {};
1523
+ for (const t of tags ?? []) if (t.Key !== void 0) out[t.Key] = t.Value ?? "";
1524
+ return out;
1525
+ }
1526
+ function encodeValue(value) {
1527
+ if (typeof value === "string") return { SecretString: value };
1528
+ if (value instanceof Uint8Array) return { SecretBinary: value };
1529
+ let json;
1530
+ try {
1531
+ json = JSON.stringify(value);
1532
+ } catch {
1533
+ json = void 0;
1534
+ }
1535
+ if (json === void 0) throw new chunk5AEPFQD7_cjs.ValidationError("secret value must be JSON-serialisable");
1536
+ return { SecretString: json };
1537
+ }
1538
+ function encodeBytes(bytes) {
1539
+ try {
1540
+ return { SecretString: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
1541
+ } catch {
1542
+ return { SecretBinary: bytes };
1543
+ }
1544
+ }
1545
+ function opt(key, value) {
1546
+ return value === void 0 || value === null ? {} : { [key]: value };
1547
+ }
1548
+ function toSecretValue(out) {
1549
+ const binary = out.SecretBinary !== void 0;
1550
+ const raw = binary ? out.SecretBinary : out.SecretString ?? "";
1551
+ return {
1552
+ arn: out.ARN ?? "",
1553
+ name: out.Name ?? "",
1554
+ ...opt("versionId", out.VersionId),
1555
+ versionStages: [...out.VersionStages ?? []],
1556
+ ...opt("createdDate", out.CreatedDate),
1557
+ binary,
1558
+ value: new chunk5AEPFQD7_cjs.SecretValue(raw, out.VersionId ?? void 0)
1559
+ };
1560
+ }
1561
+ function toRotationRules(r) {
1562
+ if (r === void 0 || r === null) return void 0;
1563
+ return {
1564
+ ...opt("automaticallyAfterDays", r.AutomaticallyAfterDays),
1565
+ ...opt("duration", r.Duration),
1566
+ ...opt("scheduleExpression", r.ScheduleExpression)
1567
+ };
1568
+ }
1569
+ function toReplication(r) {
1570
+ return {
1571
+ ...opt("region", r.Region),
1572
+ ...opt("kmsKeyId", r.KmsKeyId),
1573
+ ...opt("status", r.Status),
1574
+ ...opt("statusMessage", r.StatusMessage),
1575
+ ...opt("lastAccessedDate", r.LastAccessedDate)
1576
+ };
1577
+ }
1578
+ function toDescription(out) {
1579
+ const stages = {};
1580
+ for (const [id, list] of Object.entries(out.SecretVersionsToStages ?? {})) stages[id] = [...list];
1581
+ for (const [id, list] of Object.entries(out.VersionIdsToStages ?? {})) stages[id] = [...list];
1582
+ return {
1583
+ arn: out.ARN ?? "",
1584
+ name: out.Name ?? "",
1585
+ ...opt("description", out.Description),
1586
+ ...opt("kmsKeyId", out.KmsKeyId),
1587
+ rotationEnabled: out.RotationEnabled === true,
1588
+ ...opt("rotationLambdaArn", out.RotationLambdaARN),
1589
+ ...opt("rotationRules", toRotationRules(out.RotationRules)),
1590
+ ...opt("lastRotatedDate", out.LastRotatedDate),
1591
+ ...opt("lastChangedDate", out.LastChangedDate),
1592
+ ...opt("lastAccessedDate", out.LastAccessedDate),
1593
+ ...opt("deletedDate", out.DeletedDate),
1594
+ ...opt("nextRotationDate", out.NextRotationDate),
1595
+ ...opt("createdDate", out.CreatedDate),
1596
+ ...opt("primaryRegion", out.PrimaryRegion),
1597
+ ...opt("owningService", out.OwningService),
1598
+ tags: fromAwsTags(out.Tags),
1599
+ versionIdsToStages: stages,
1600
+ replicationStatus: (out.ReplicationStatus ?? []).map(toReplication)
1601
+ };
1602
+ }
1603
+ function toVersion(v) {
1604
+ return {
1605
+ versionId: v.VersionId ?? "",
1606
+ versionStages: [...v.VersionStages ?? []],
1607
+ ...opt("createdDate", v.CreatedDate),
1608
+ ...opt("lastAccessedDate", v.LastAccessedDate),
1609
+ kmsKeyIds: [...v.KmsKeyIds ?? []]
1610
+ };
1611
+ }
1612
+ function toBatchError(e) {
1613
+ return {
1614
+ ...opt("secretId", e.SecretId),
1615
+ ...opt("errorCode", e.ErrorCode),
1616
+ ...opt("message", e.Message)
1617
+ };
1618
+ }
1619
+ function toPolicyError(e) {
1620
+ return { ...opt("checkName", e.CheckName), ...opt("errorMessage", e.ErrorMessage) };
1621
+ }
1622
+ function parsePolicy(text) {
1623
+ if (text === void 0 || text === "") return void 0;
1624
+ try {
1625
+ const parsed = JSON.parse(text);
1626
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : void 0;
1627
+ } catch {
1628
+ return void 0;
1629
+ }
1630
+ }
1631
+ function toAwsFilters(filters) {
1632
+ return filters.map((f) => ({ Key: f.key, Values: [...f.values] }));
1633
+ }
1634
+ function hasMore(token) {
1635
+ return token !== void 0 && token !== null && token !== "";
1636
+ }
1637
+
1638
+ // src/paginator.ts
1639
+ var Paginator = class {
1640
+ #fetch;
1641
+ constructor(fetch) {
1642
+ this.#fetch = fetch;
1643
+ }
1644
+ /** Yields one array per page. */
1645
+ async *pages() {
1646
+ let token;
1647
+ const seen = /* @__PURE__ */ new Set();
1648
+ do {
1649
+ const page = await this.#fetch(token);
1650
+ yield page.items;
1651
+ token = page.nextToken;
1652
+ if (token !== void 0) {
1653
+ if (seen.has(token)) return;
1654
+ seen.add(token);
1655
+ }
1656
+ } while (token !== void 0);
1657
+ }
1658
+ async *[Symbol.asyncIterator]() {
1659
+ for await (const page of this.pages()) yield* page;
1660
+ }
1661
+ /** Collects every item of every page. */
1662
+ async toArray() {
1663
+ const out = [];
1664
+ for await (const page of this.pages()) out.push(...page);
1665
+ return out;
1666
+ }
1667
+ };
1668
+
1669
+ // src/secret-cache.ts
1670
+ var AWS_SECRET_CACHE_DEFAULTS = Object.freeze({ ttlMs: 36e5, maxEntries: 1024 });
1671
+ var REFRESH_RETRY_MS = 1e3;
1672
+ var AwsSecretCache = class {
1673
+ /** The AWS caching-client defaults (TTL 1 h, 1 024 entries). */
1674
+ static awsDefaults() {
1675
+ return { ...AWS_SECRET_CACHE_DEFAULTS };
1676
+ }
1677
+ #source;
1678
+ #ttl;
1679
+ #max;
1680
+ #stage;
1681
+ #clock;
1682
+ #onRefreshError;
1683
+ #entries = /* @__PURE__ */ new Map();
1684
+ #inflight = /* @__PURE__ */ new Map();
1685
+ #hits = 0;
1686
+ #misses = 0;
1687
+ #refreshes = 0;
1688
+ #versionChanges = 0;
1689
+ #evictions = 0;
1690
+ constructor(source, options = {}) {
1691
+ this.#source = source;
1692
+ this.#ttl = options.ttlMs ?? AWS_SECRET_CACHE_DEFAULTS.ttlMs;
1693
+ this.#max = options.maxEntries ?? AWS_SECRET_CACHE_DEFAULTS.maxEntries;
1694
+ this.#stage = options.versionStage ?? AWSCURRENT;
1695
+ this.#clock = options.clock ?? Date.now;
1696
+ this.#onRefreshError = options.onRefreshError;
1697
+ if (!(this.#ttl > 0)) throw new chunk5AEPFQD7_cjs.ValidationError("AwsSecretCache: ttlMs must be > 0");
1698
+ if (!Number.isInteger(this.#max) || this.#max < 1) {
1699
+ throw new chunk5AEPFQD7_cjs.ValidationError("AwsSecretCache: maxEntries must be >= 1");
1700
+ }
1701
+ if (this.#stage.trim() === "") {
1702
+ throw new chunk5AEPFQD7_cjs.ValidationError("AwsSecretCache: versionStage must not be empty");
1703
+ }
1704
+ }
1705
+ /** The cached value of `secretId` at the stage (default `AWSCURRENT`). */
1706
+ async getSecretValue(secretId, options = {}) {
1707
+ const stage = options.versionStage ?? this.#stage;
1708
+ const key = keyOf(secretId, stage);
1709
+ const entry = this.#entries.get(key);
1710
+ if (entry !== void 0) {
1711
+ this.#hits++;
1712
+ this.#entries.delete(key);
1713
+ this.#entries.set(key, entry);
1714
+ if (this.#clock() - entry.checkedAt < this.#nextCheckAfter(entry)) return entry.value;
1715
+ return this.#coalesce(key, () => this.#refresh(key, entry, stage, options));
1716
+ }
1717
+ this.#misses++;
1718
+ return this.#coalesce(key, async () => {
1719
+ const value = await this.#source.getSecretValue(secretId, withStage(options, stage));
1720
+ this.#store(key, { secretId, value, checkedAt: this.#clock(), failures: 0 });
1721
+ return value;
1722
+ });
1723
+ }
1724
+ /** The value as text (`SecretString`, or UTF-8 of the binary). */
1725
+ async getSecretString(secretId, options = {}) {
1726
+ return (await this.getSecretValue(secretId, options)).value.reveal();
1727
+ }
1728
+ /** The value as bytes. */
1729
+ async getSecretBinary(secretId, options = {}) {
1730
+ return (await this.getSecretValue(secretId, options)).value.revealBytes();
1731
+ }
1732
+ /** Forces a refresh check now (and a fetch when the stage moved); returns the value. */
1733
+ async refreshNow(secretId, options = {}) {
1734
+ const stage = options.versionStage ?? this.#stage;
1735
+ const key = keyOf(secretId, stage);
1736
+ const entry = this.#entries.get(key);
1737
+ if (entry === void 0) return this.getSecretValue(secretId, options);
1738
+ entry.checkedAt = Number.NEGATIVE_INFINITY;
1739
+ entry.failures = 0;
1740
+ return this.getSecretValue(secretId, options);
1741
+ }
1742
+ /** Drops every cached stage of `secretId`. */
1743
+ invalidate(secretId) {
1744
+ for (const [key, entry] of this.#entries) {
1745
+ if (entry.secretId === secretId) this.#entries.delete(key);
1746
+ }
1747
+ }
1748
+ /** Drops every entry. */
1749
+ clear() {
1750
+ this.#entries.clear();
1751
+ }
1752
+ /** Counters and current size. */
1753
+ stats() {
1754
+ return {
1755
+ hits: this.#hits,
1756
+ misses: this.#misses,
1757
+ refreshes: this.#refreshes,
1758
+ versionChanges: this.#versionChanges,
1759
+ evictions: this.#evictions,
1760
+ size: this.#entries.size
1761
+ };
1762
+ }
1763
+ #nextCheckAfter(entry) {
1764
+ if (entry.failures === 0) return this.#ttl;
1765
+ return Math.min(this.#ttl, REFRESH_RETRY_MS * 2 ** (entry.failures - 1));
1766
+ }
1767
+ async #refresh(key, entry, stage, options) {
1768
+ this.#refreshes++;
1769
+ try {
1770
+ const described = await this.#source.describeSecret(entry.secretId, signalOnly(options));
1771
+ const current = Object.entries(described.versionIdsToStages).find(
1772
+ ([, stages]) => stages.includes(stage)
1773
+ )?.[0];
1774
+ let value = entry.value;
1775
+ if (current === void 0 || current !== entry.value.versionId) {
1776
+ value = await this.#source.getSecretValue(entry.secretId, withStage(options, stage));
1777
+ this.#versionChanges++;
1778
+ }
1779
+ this.#store(key, { secretId: entry.secretId, value, checkedAt: this.#clock(), failures: 0 });
1780
+ return value;
1781
+ } catch (err) {
1782
+ entry.failures++;
1783
+ entry.checkedAt = this.#clock();
1784
+ try {
1785
+ this.#onRefreshError?.(err);
1786
+ } catch {
1787
+ }
1788
+ return entry.value;
1789
+ }
1790
+ }
1791
+ #coalesce(key, load) {
1792
+ const pending = this.#inflight.get(key);
1793
+ if (pending !== void 0) return pending;
1794
+ const promise = load().finally(() => {
1795
+ this.#inflight.delete(key);
1796
+ });
1797
+ this.#inflight.set(key, promise);
1798
+ return promise;
1799
+ }
1800
+ #store(key, entry) {
1801
+ this.#entries.delete(key);
1802
+ this.#entries.set(key, entry);
1803
+ while (this.#entries.size > this.#max) {
1804
+ const oldest = this.#entries.keys().next().value;
1805
+ this.#entries.delete(oldest);
1806
+ this.#evictions++;
1807
+ }
1808
+ }
1809
+ };
1810
+ function keyOf(secretId, stage) {
1811
+ return JSON.stringify([secretId, stage]);
1812
+ }
1813
+ function signalOnly(options) {
1814
+ return options.signal === void 0 ? {} : { signal: options.signal };
1815
+ }
1816
+ function withStage(options, stage) {
1817
+ return { ...signalOnly(options), versionStage: stage };
1818
+ }
1819
+
1820
+ // src/provider.ts
1821
+ var MISSING_BATCH_CODES = /* @__PURE__ */ new Set([
1822
+ "ResourceNotFoundException",
1823
+ "InvalidRequestException"
1824
+ ]);
1825
+ function trimSlashes(path) {
1826
+ return path.replace(/^\/+|\/+$/g, "");
1827
+ }
1828
+ function fullName(name, path) {
1829
+ const p = path === void 0 ? "" : trimSlashes(path);
1830
+ return p === "" ? name : `${p}/${name}`;
1831
+ }
1832
+ function signalOnly2(options) {
1833
+ return options.signal === void 0 ? {} : { signal: options.signal };
1834
+ }
1835
+ function isMissing(err) {
1836
+ return chunk5AEPFQD7_cjs.isAwsSecretsManagerError(err, chunk5AEPFQD7_cjs.ErrorCode.NotFound) || // InvalidRequestException: the secret is scheduled for deletion.
1837
+ chunk5AEPFQD7_cjs.isAwsSecretsManagerError(err, chunk5AEPFQD7_cjs.ErrorCode.Conflict) && err.message.includes("InvalidRequestException");
1838
+ }
1839
+ function toMetadata(d) {
1840
+ const current = Object.entries(d.versionIdsToStages).find(
1841
+ ([, stages]) => stages.includes("AWSCURRENT")
1842
+ )?.[0];
1843
+ const slash = d.name.lastIndexOf("/");
1844
+ const extra = { arn: d.arn, rotationEnabled: String(d.rotationEnabled) };
1845
+ if (d.description !== void 0) extra.description = d.description;
1846
+ if (d.kmsKeyId !== void 0) extra.kmsKeyId = d.kmsKeyId;
1847
+ if (d.nextRotationDate !== void 0) extra.nextRotationDate = d.nextRotationDate.toISOString();
1848
+ if (d.deletedDate !== void 0) extra.deletedDate = d.deletedDate.toISOString();
1849
+ if (d.primaryRegion !== void 0) extra.primaryRegion = d.primaryRegion;
1850
+ return {
1851
+ name: d.name,
1852
+ ...slash > 0 ? { path: d.name.slice(0, slash) } : {},
1853
+ ...current === void 0 ? {} : { version: current },
1854
+ ...d.createdDate === void 0 ? {} : { createdAt: d.createdDate },
1855
+ ...d.lastChangedDate === void 0 ? {} : { updatedAt: d.lastChangedDate },
1856
+ tags: { ...d.tags },
1857
+ versions: Object.keys(d.versionIdsToStages).length,
1858
+ extra
1859
+ };
1860
+ }
1861
+ var AwsSecretsManagerSecretsProvider = class extends chunk5AEPFQD7_cjs.BaseSecretsProvider {
1862
+ /** Capabilities declared to the conformance runner. */
1863
+ static capabilities = ["write", "versions", "delete"];
1864
+ #client;
1865
+ #recoveryWindowDays;
1866
+ #onClose;
1867
+ constructor(client, options = {}, onClose) {
1868
+ super();
1869
+ this.#client = client;
1870
+ const days = options.recoveryWindowDays ?? client.config.recoveryWindowDays;
1871
+ if (!Number.isInteger(days) || days < 7 || days > 30) {
1872
+ throw new chunk5AEPFQD7_cjs.ValidationError("secrets: recoveryWindowDays must be an integer from 7 to 30");
1873
+ }
1874
+ this.#recoveryWindowDays = days;
1875
+ this.#onClose = onClose;
1876
+ }
1877
+ /** The client this provider uses. */
1878
+ get client() {
1879
+ return this.#client;
1880
+ }
1881
+ async fetchSecret(name, options) {
1882
+ try {
1883
+ const out = await this.#client.getSecretValue(fullName(name, options.path), {
1884
+ ...signalOnly2(options),
1885
+ ...options.version === void 0 ? {} : { versionId: options.version }
1886
+ });
1887
+ return out.value;
1888
+ } catch (err) {
1889
+ if (isMissing(err)) return null;
1890
+ throw err;
1891
+ }
1892
+ }
1893
+ async listSecrets(prefixOrPath, options) {
1894
+ const prefix = prefixOrPath ?? "";
1895
+ return (await this.#listDescriptions(prefix, options)).map(toMetadata);
1896
+ }
1897
+ async #listDescriptions(prefix, options) {
1898
+ const all = await this.#client.listSecrets({
1899
+ ...signalOnly2(options),
1900
+ ...prefix === "" ? {} : { filters: [{ key: "name", values: [prefix] }] }
1901
+ }).toArray();
1902
+ return all.filter((d) => d.name.startsWith(prefix) && d.deletedDate === void 0);
1903
+ }
1904
+ /** Every secret directly under `path` (non-recursive), keyed by full name. */
1905
+ async getAll(path, options = {}) {
1906
+ chunk5AEPFQD7_cjs.throwIfAborted(options.signal, "secrets.getAll");
1907
+ const base = path === void 0 ? "" : trimSlashes(path);
1908
+ const prefix = base === "" ? "" : `${base}/`;
1909
+ const names = (await this.#listDescriptions(prefix, options)).map((d) => d.name).filter((n) => !n.slice(prefix.length).includes("/")).sort();
1910
+ return this.getMany(names, options);
1911
+ }
1912
+ /**
1913
+ * Present secrets in request order (`BatchGetSecretValue` in chunks of 20; per-name reads when
1914
+ * a `version` is requested).
1915
+ */
1916
+ async getMany(names, options = {}) {
1917
+ if (options.version !== void 0) return super.getMany(names, options);
1918
+ chunk5AEPFQD7_cjs.throwIfAborted(options.signal, "secrets.getMany");
1919
+ const unique = [...new Set(names)];
1920
+ const byFull = /* @__PURE__ */ new Map();
1921
+ for (const n of unique) byFull.set(fullName(n, options.path), n);
1922
+ const found = /* @__PURE__ */ new Map();
1923
+ const ids = [...byFull.keys()];
1924
+ for (let i = 0; i < ids.length; i += BATCH_GET_MAX_IDS) {
1925
+ const chunk = ids.slice(i, i + BATCH_GET_MAX_IDS);
1926
+ const result = await this.#client.batchGetSecretValue(chunk, signalOnly2(options));
1927
+ for (const e of result.errors) {
1928
+ if (e.errorCode !== void 0 && MISSING_BATCH_CODES.has(e.errorCode)) continue;
1929
+ const code = (e.errorCode === void 0 ? void 0 : AWS_ERROR_CODES[e.errorCode]) ?? chunk5AEPFQD7_cjs.ErrorCode.Unavailable;
1930
+ throw chunk5AEPFQD7_cjs.errorForCode(code, `secrets.getMany ${e.secretId ?? ""}: ${e.errorCode ?? "error"}`);
1931
+ }
1932
+ for (const v of result.secretValues) {
1933
+ const requested = byFull.get(v.name) ?? byFull.get(v.arn);
1934
+ if (requested !== void 0) found.set(requested, v.value);
1935
+ }
1936
+ }
1937
+ const ordered = /* @__PURE__ */ new Map();
1938
+ for (const n of unique) {
1939
+ const value = found.get(n);
1940
+ if (value !== void 0) ordered.set(n, value);
1941
+ }
1942
+ return ordered;
1943
+ }
1944
+ async putSecret(name, value, options) {
1945
+ if (options.cas !== void 0) {
1946
+ throw new chunk5AEPFQD7_cjs.ValidationError(
1947
+ `secrets.set ${name}: AWS Secrets Manager has no compare-and-set (cas)`
1948
+ );
1949
+ }
1950
+ const id = fullName(name, options.path);
1951
+ const encoded = encodeBytes(value);
1952
+ const input = "SecretString" in encoded ? encoded.SecretString : encoded.SecretBinary;
1953
+ const call = signalOnly2(options);
1954
+ const putExisting = async () => {
1955
+ const out = await this.#client.putSecretValue(id, input, call);
1956
+ if (options.tags !== void 0 && Object.keys(options.tags).length > 0) {
1957
+ await this.#client.tagResource(id, options.tags, call);
1958
+ }
1959
+ if (options.description !== void 0) {
1960
+ await this.#client.updateSecret(id, { ...call, description: options.description });
1961
+ }
1962
+ return out.versionId;
1963
+ };
1964
+ try {
1965
+ return await putExisting();
1966
+ } catch (err) {
1967
+ if (!chunk5AEPFQD7_cjs.isAwsSecretsManagerError(err, chunk5AEPFQD7_cjs.ErrorCode.NotFound)) throw err;
1968
+ }
1969
+ try {
1970
+ const created = await this.#client.createSecret(id, input, {
1971
+ ...call,
1972
+ ...options.description === void 0 ? {} : { description: options.description },
1973
+ ...options.tags === void 0 ? {} : { tags: options.tags }
1974
+ });
1975
+ return created.versionId ?? "";
1976
+ } catch (err) {
1977
+ if (chunk5AEPFQD7_cjs.isAwsSecretsManagerError(err, chunk5AEPFQD7_cjs.ErrorCode.Conflict) && err.message.includes("ResourceExistsException")) {
1978
+ return await putExisting();
1979
+ }
1980
+ throw err;
1981
+ }
1982
+ }
1983
+ async removeSecret(name, options) {
1984
+ if (options.versions !== void 0) {
1985
+ throw new chunk5AEPFQD7_cjs.ValidationError(
1986
+ `secrets.delete ${name}: AWS Secrets Manager cannot delete single versions; use updateSecretVersionStage`
1987
+ );
1988
+ }
1989
+ const id = fullName(name, options.path);
1990
+ const call = signalOnly2(options);
1991
+ const meta = await this.#describe(id, call);
1992
+ if (meta === null) throw new chunk5AEPFQD7_cjs.NotFoundError(`secrets.delete ${id}: not found`);
1993
+ await this.#client.deleteSecret(
1994
+ id,
1995
+ options.permanent === true ? { ...call, forceDeleteWithoutRecovery: true } : { ...call, recoveryWindowDays: this.#recoveryWindowDays }
1996
+ );
1997
+ }
1998
+ async fetchMetadata(name, options) {
1999
+ const d = await this.#describe(fullName(name, options.path), signalOnly2(options));
2000
+ return d === null ? null : toMetadata(d);
2001
+ }
2002
+ /** DescribeSecret; `null` when missing or scheduled for deletion. */
2003
+ async #describe(id, options) {
2004
+ try {
2005
+ const d = await this.#client.describeSecret(id, options);
2006
+ return d.deletedDate === void 0 ? d : null;
2007
+ } catch (err) {
2008
+ if (isMissing(err)) return null;
2009
+ throw err;
2010
+ }
2011
+ }
2012
+ /** Stops the watchers of this provider. Idempotent. */
2013
+ async close() {
2014
+ await super.close();
2015
+ this.#onClose?.();
2016
+ }
2017
+ };
2018
+
2019
+ // src/client.ts
2020
+ var EMULATOR_GAPS = /* @__PURE__ */ new Set(["validateResourcePolicy"]);
2021
+ var HEALTH_TIMEOUT_MS = 5e3;
2022
+ var AwsSecretsManagerClient = class _AwsSecretsManagerClient {
2023
+ /** The immutable configuration. */
2024
+ config;
2025
+ #sdk;
2026
+ #ownsSdk;
2027
+ #handler;
2028
+ #sdkConfig;
2029
+ #healthSdk;
2030
+ #providers = /* @__PURE__ */ new Set();
2031
+ #closed = false;
2032
+ /** Accepts a {@link AwsSecretsManagerConfig} or plain options. */
2033
+ constructor(config = {}, internals = {}) {
2034
+ const cfg = AwsSecretsManagerConfig.from(config);
2035
+ this.config = cfg;
2036
+ if (cfg.sdkClient !== void 0) {
2037
+ this.#sdk = cfg.sdkClient;
2038
+ this.#ownsSdk = false;
2039
+ return;
2040
+ }
2041
+ const handler = new GrowHttpHandler({
2042
+ config: cfg,
2043
+ ...internals.dispatcher === void 0 ? {} : { dispatcher: internals.dispatcher }
2044
+ });
2045
+ this.#handler = handler;
2046
+ const credentials = buildCredentials(cfg, handler);
2047
+ this.#sdkConfig = {
2048
+ maxAttempts: cfg.retry.maxRetries + 1,
2049
+ retryMode: "standard",
2050
+ requestHandler: handler,
2051
+ ...cfg.region === void 0 ? {} : { region: cfg.region },
2052
+ ...cfg.endpoint === void 0 ? {} : { endpoint: cfg.endpoint },
2053
+ ...cfg.profile === void 0 ? {} : { profile: cfg.profile },
2054
+ ...credentials === void 0 ? {} : { credentials }
2055
+ };
2056
+ this.#sdk = new clientSecretsManager.SecretsManagerClient(this.#sdkConfig);
2057
+ this.#ownsSdk = true;
2058
+ }
2059
+ /** Builds a client from `GROW_AWS_SECRETS_MANAGER_*` and the standard AWS environment variables. */
2060
+ static fromEnv(overrides = {}) {
2061
+ return new _AwsSecretsManagerClient(AwsSecretsManagerConfig.fromEnv(overrides));
2062
+ }
2063
+ /** Wraps an existing AWS SDK client; `close()` leaves it open. */
2064
+ static withSdkClient(sdkClient, options = {}) {
2065
+ return new _AwsSecretsManagerClient({ ...options, sdkClient });
2066
+ }
2067
+ /** The underlying AWS SDK client (escape hatch for operations not wrapped here). */
2068
+ get sdk() {
2069
+ return this.#sdk;
2070
+ }
2071
+ /** Whether {@link close} was called. */
2072
+ get closed() {
2073
+ return this.#closed;
2074
+ }
2075
+ // ---------------------------------------------------------------------------------------
2076
+ // core
2077
+ /**
2078
+ * Liveness: a signed `ListSecrets {MaxResults: 1}` with a short timeout and no retries.
2079
+ * `ok` when AWS answers (also when the credentials are rejected: `details.auth = "failed"`),
2080
+ * `degraded` when throttled, `unhealthy` on HTTP 5xx, `unreachable` on network errors.
2081
+ * Throws only `CancelledError` (also on a closed client) and `ConfigError`.
2082
+ */
2083
+ async health(options = {}) {
2084
+ try {
2085
+ await this.#send("health", new clientSecretsManager.ListSecretsCommand({ MaxResults: 1 }), {
2086
+ ...options,
2087
+ requestTimeout: Math.min(this.config.requestTimeoutMs, HEALTH_TIMEOUT_MS),
2088
+ sdk: this.#healthClient()
2089
+ });
2090
+ return healthStatus("ok", {}, true);
2091
+ } catch (err) {
2092
+ const e = err;
2093
+ switch (e.code) {
2094
+ case chunk5AEPFQD7_cjs.ErrorCode.Cancelled:
2095
+ case chunk5AEPFQD7_cjs.ErrorCode.Config:
2096
+ throw e;
2097
+ case chunk5AEPFQD7_cjs.ErrorCode.RateLimited:
2098
+ return healthStatus("degraded", { code: e.code }, true);
2099
+ case chunk5AEPFQD7_cjs.ErrorCode.Authentication:
2100
+ case chunk5AEPFQD7_cjs.ErrorCode.PermissionDenied:
2101
+ return healthStatus("ok", { auth: "failed", code: e.code }, true);
2102
+ default:
2103
+ if (e.httpStatus === void 0) {
2104
+ return healthStatus("unreachable", { error: e.code }, false);
2105
+ }
2106
+ if (e.httpStatus >= 500) {
2107
+ return healthStatus("unhealthy", { httpStatus: e.httpStatus, error: e.code }, false);
2108
+ }
2109
+ return healthStatus("ok", { httpStatus: e.httpStatus, code: e.code }, true);
2110
+ }
2111
+ }
2112
+ }
2113
+ /**
2114
+ * Authenticated round trip (`ListSecrets {MaxResults: 1}`); returns the latency in ms.
2115
+ * `AuthenticationError` for unknown keys or bad signatures, `PermissionDeniedError` when the
2116
+ * principal may not call `secretsmanager:ListSecrets`.
2117
+ */
2118
+ async ping(options = {}) {
2119
+ const start = performance.now();
2120
+ await this.#send("ping", new clientSecretsManager.ListSecretsCommand({ MaxResults: 1 }), options);
2121
+ return performance.now() - start;
2122
+ }
2123
+ /**
2124
+ * Always throws {@link UnsupportedError}: AWS Secrets Manager exposes no server version (the API
2125
+ * contract date is the constant `API_VERSION`).
2126
+ */
2127
+ // eslint-disable-next-line @typescript-eslint/require-await
2128
+ async serverVersion(options = {}) {
2129
+ chunk5AEPFQD7_cjs.throwIfAborted(options.signal, "serverVersion");
2130
+ throw new chunk5AEPFQD7_cjs.UnsupportedError(
2131
+ "serverVersion: AWS Secrets Manager does not expose a server version"
2132
+ );
2133
+ }
2134
+ /**
2135
+ * Stops every watcher of the providers created by {@link secrets} and destroys the SDK client
2136
+ * this instance built (never a caller-supplied one). Idempotent.
2137
+ */
2138
+ async close() {
2139
+ if (this.#closed) return;
2140
+ this.#closed = true;
2141
+ await Promise.all([...this.#providers].map((p) => p.close()));
2142
+ this.#providers.clear();
2143
+ if (this.#ownsSdk) {
2144
+ this.#sdk.destroy();
2145
+ this.#healthSdk?.destroy();
2146
+ }
2147
+ this.#handler?.destroy();
2148
+ }
2149
+ // ---------------------------------------------------------------------------------------
2150
+ // category interface
2151
+ /**
2152
+ * The {@link SecretsProvider} view (SPEC §3) of this client. `close()` of the client stops its
2153
+ * watchers.
2154
+ */
2155
+ secrets(options = {}) {
2156
+ const provider = new AwsSecretsManagerSecretsProvider(
2157
+ this,
2158
+ options,
2159
+ () => this.#providers.delete(provider)
2160
+ );
2161
+ this.#providers.add(provider);
2162
+ return provider;
2163
+ }
2164
+ /** A version-stage aware cache with the AWS caching-client semantics (TTL 1 h, 1 024 entries). */
2165
+ secretCache(options = {}) {
2166
+ return new AwsSecretCache(this, options);
2167
+ }
2168
+ // ---------------------------------------------------------------------------------------
2169
+ // read
2170
+ /**
2171
+ * Reads a secret value (`GetSecretValue`), by default the `AWSCURRENT` version. `secretId` is a
2172
+ * name or ARN. `NotFoundError` when the secret, version or stage does not exist; `ConflictError`
2173
+ * when the secret is scheduled for deletion.
2174
+ */
2175
+ async getSecretValue(secretId, options = {}) {
2176
+ requireId("getSecretValue", secretId);
2177
+ const out = await this.#send(
2178
+ `getSecretValue ${secretId}`,
2179
+ new clientSecretsManager.GetSecretValueCommand({
2180
+ SecretId: secretId,
2181
+ ...options.versionId === void 0 ? {} : { VersionId: options.versionId },
2182
+ ...options.versionStage === void 0 ? {} : { VersionStage: options.versionStage }
2183
+ }),
2184
+ options
2185
+ );
2186
+ return toSecretValue(out);
2187
+ }
2188
+ /**
2189
+ * Reads many secrets at once (`BatchGetSecretValue`). With a list of ids, lists longer than 20
2190
+ * are split and the values come back in request order; with `{ filters }` every page is read.
2191
+ * Per-secret failures are returned in `errors` (the call itself succeeds).
2192
+ */
2193
+ async batchGetSecretValue(selector, options = {}) {
2194
+ const secretValues2 = [];
2195
+ const errors = [];
2196
+ if (Array.isArray(selector)) {
2197
+ const ids = selector;
2198
+ for (let i = 0; i < ids.length; i += BATCH_GET_MAX_IDS) {
2199
+ const chunk = ids.slice(i, i + BATCH_GET_MAX_IDS);
2200
+ const pageValues = [];
2201
+ let token2;
2202
+ do {
2203
+ const out = await this.#send(
2204
+ "batchGetSecretValue",
2205
+ new clientSecretsManager.BatchGetSecretValueCommand({
2206
+ SecretIdList: [...chunk],
2207
+ ...token2 === void 0 ? {} : { NextToken: token2 }
2208
+ }),
2209
+ options
2210
+ );
2211
+ pageValues.push(...(out.SecretValues ?? []).map(toSecretValue));
2212
+ errors.push(...(out.Errors ?? []).map(toBatchError));
2213
+ token2 = hasMore(out.NextToken) ? out.NextToken : void 0;
2214
+ } while (token2 !== void 0);
2215
+ secretValues2.push(...orderByIds(pageValues, chunk));
2216
+ }
2217
+ return { secretValues: secretValues2, errors };
2218
+ }
2219
+ const filters = selector.filters;
2220
+ if (filters === void 0 || filters.length === 0) {
2221
+ throw new chunk5AEPFQD7_cjs.ValidationError("batchGetSecretValue: give secret ids or at least one filter");
2222
+ }
2223
+ let token;
2224
+ do {
2225
+ const input = {
2226
+ Filters: toAwsFilters(filters),
2227
+ ...options.maxResults === void 0 ? {} : { MaxResults: options.maxResults },
2228
+ ...token === void 0 ? {} : { NextToken: token }
2229
+ };
2230
+ const out = await this.#send(
2231
+ "batchGetSecretValue",
2232
+ new clientSecretsManager.BatchGetSecretValueCommand(input),
2233
+ options
2234
+ );
2235
+ secretValues2.push(...(out.SecretValues ?? []).map(toSecretValue));
2236
+ errors.push(...(out.Errors ?? []).map(toBatchError));
2237
+ token = hasMore(out.NextToken) ? out.NextToken : void 0;
2238
+ } while (token !== void 0);
2239
+ return { secretValues: secretValues2, errors };
2240
+ }
2241
+ /** Metadata of a secret (`DescribeSecret`), never the value. */
2242
+ async describeSecret(secretId, options = {}) {
2243
+ requireId("describeSecret", secretId);
2244
+ const out = await this.#send(
2245
+ `describeSecret ${secretId}`,
2246
+ new clientSecretsManager.DescribeSecretCommand({ SecretId: secretId }),
2247
+ options
2248
+ );
2249
+ return toDescription(out);
2250
+ }
2251
+ /**
2252
+ * Lists secrets (`ListSecrets`) lazily across all pages: `for await (const s of
2253
+ * client.listSecrets())` or `await client.listSecrets().toArray()`.
2254
+ */
2255
+ listSecrets(options = {}) {
2256
+ return new Paginator(async (token) => {
2257
+ const out = await this.#send(
2258
+ "listSecrets",
2259
+ new clientSecretsManager.ListSecretsCommand({
2260
+ ...options.filters === void 0 || options.filters.length === 0 ? {} : { Filters: toAwsFilters(options.filters) },
2261
+ ...options.includePlannedDeletion === void 0 ? {} : { IncludePlannedDeletion: options.includePlannedDeletion },
2262
+ ...options.sortOrder === void 0 ? {} : { SortOrder: options.sortOrder },
2263
+ ...options.maxResults === void 0 ? {} : { MaxResults: options.maxResults },
2264
+ ...token === void 0 ? {} : { NextToken: token }
2265
+ }),
2266
+ options
2267
+ );
2268
+ return {
2269
+ items: (out.SecretList ?? []).map(toDescription),
2270
+ nextToken: hasMore(out.NextToken) ? out.NextToken : void 0
2271
+ };
2272
+ });
2273
+ }
2274
+ /** Lists the versions of a secret (`ListSecretVersionIds`) lazily across all pages. */
2275
+ listSecretVersionIds(secretId, options = {}) {
2276
+ requireId("listSecretVersionIds", secretId);
2277
+ return new Paginator(async (token) => {
2278
+ const out = await this.#send(
2279
+ `listSecretVersionIds ${secretId}`,
2280
+ new clientSecretsManager.ListSecretVersionIdsCommand({
2281
+ SecretId: secretId,
2282
+ ...options.includeDeprecated === void 0 ? {} : { IncludeDeprecated: options.includeDeprecated },
2283
+ ...options.maxResults === void 0 ? {} : { MaxResults: options.maxResults },
2284
+ ...token === void 0 ? {} : { NextToken: token }
2285
+ }),
2286
+ options
2287
+ );
2288
+ return {
2289
+ items: (out.Versions ?? []).map(toVersion),
2290
+ nextToken: hasMore(out.NextToken) ? out.NextToken : void 0
2291
+ };
2292
+ });
2293
+ }
2294
+ // ---------------------------------------------------------------------------------------
2295
+ // write
2296
+ /**
2297
+ * Creates a secret (`CreateSecret`). `value`: string → `SecretString`, bytes → `SecretBinary`,
2298
+ * object → JSON `SecretString`, `undefined`/`null` → a secret without a version.
2299
+ * `ConflictError` when the name exists (or is scheduled for deletion).
2300
+ */
2301
+ async createSecret(name, value, options = {}) {
2302
+ requireId("createSecret", name);
2303
+ const input = {
2304
+ Name: name,
2305
+ ...value === void 0 || value === null ? {} : encodeValue(value),
2306
+ ...options.description === void 0 ? {} : { Description: options.description },
2307
+ ...options.kmsKeyId === void 0 ? {} : { KmsKeyId: options.kmsKeyId },
2308
+ ...options.tags === void 0 ? {} : { Tags: toAwsTags(options.tags) },
2309
+ ...options.clientRequestToken === void 0 ? {} : { ClientRequestToken: options.clientRequestToken },
2310
+ ...options.addReplicaRegions === void 0 ? {} : {
2311
+ AddReplicaRegions: options.addReplicaRegions.map((r) => ({
2312
+ Region: r.region,
2313
+ ...r.kmsKeyId === void 0 ? {} : { KmsKeyId: r.kmsKeyId }
2314
+ }))
2315
+ },
2316
+ ...options.forceOverwriteReplicaSecret === void 0 ? {} : { ForceOverwriteReplicaSecret: options.forceOverwriteReplicaSecret }
2317
+ };
2318
+ const out = await this.#send(`createSecret ${name}`, new clientSecretsManager.CreateSecretCommand(input), options);
2319
+ return writeResult(out);
2320
+ }
2321
+ /**
2322
+ * Stores a new version (`PutSecretValue`). By default it becomes `AWSCURRENT` (the old one
2323
+ * becomes `AWSPREVIOUS`); with custom `versionStages` only those labels are attached.
2324
+ */
2325
+ async putSecretValue(secretId, value, options = {}) {
2326
+ requireId("putSecretValue", secretId);
2327
+ const out = await this.#send(
2328
+ `putSecretValue ${secretId}`,
2329
+ new clientSecretsManager.PutSecretValueCommand({
2330
+ SecretId: secretId,
2331
+ ...encodeValue(value),
2332
+ ...options.versionStages === void 0 ? {} : { VersionStages: [...options.versionStages] },
2333
+ ...options.clientRequestToken === void 0 ? {} : { ClientRequestToken: options.clientRequestToken }
2334
+ }),
2335
+ options
2336
+ );
2337
+ return {
2338
+ arn: out.ARN ?? "",
2339
+ name: out.Name ?? "",
2340
+ versionId: out.VersionId ?? "",
2341
+ versionStages: [...out.VersionStages ?? []]
2342
+ };
2343
+ }
2344
+ /**
2345
+ * Updates description, KMS key and/or value (`UpdateSecret`). A new version is created only
2346
+ * when `value` is given.
2347
+ */
2348
+ async updateSecret(secretId, options = {}) {
2349
+ requireId("updateSecret", secretId);
2350
+ const input = {
2351
+ SecretId: secretId,
2352
+ ...options.value === void 0 ? {} : encodeValue(options.value),
2353
+ ...options.description === void 0 ? {} : { Description: options.description },
2354
+ ...options.kmsKeyId === void 0 ? {} : { KmsKeyId: options.kmsKeyId },
2355
+ ...options.clientRequestToken === void 0 ? {} : { ClientRequestToken: options.clientRequestToken }
2356
+ };
2357
+ const out = await this.#send(
2358
+ `updateSecret ${secretId}`,
2359
+ new clientSecretsManager.UpdateSecretCommand(input),
2360
+ options
2361
+ );
2362
+ return writeResult(out);
2363
+ }
2364
+ /**
2365
+ * Moves a stage label between versions (`UpdateSecretVersionStage`). Moving `AWSCURRENT` needs
2366
+ * `removeFromVersionId` = the current version; the old current version gets `AWSPREVIOUS`.
2367
+ */
2368
+ async updateSecretVersionStage(secretId, versionStage, options = {}) {
2369
+ requireId("updateSecretVersionStage", secretId);
2370
+ if (options.moveToVersionId === void 0 && options.removeFromVersionId === void 0) {
2371
+ throw new chunk5AEPFQD7_cjs.ValidationError(
2372
+ "updateSecretVersionStage: give moveToVersionId and/or removeFromVersionId"
2373
+ );
2374
+ }
2375
+ const out = await this.#send(
2376
+ `updateSecretVersionStage ${secretId}`,
2377
+ new clientSecretsManager.UpdateSecretVersionStageCommand({
2378
+ SecretId: secretId,
2379
+ VersionStage: versionStage,
2380
+ ...options.moveToVersionId === void 0 ? {} : { MoveToVersionId: options.moveToVersionId },
2381
+ ...options.removeFromVersionId === void 0 ? {} : { RemoveFromVersionId: options.removeFromVersionId }
2382
+ }),
2383
+ options
2384
+ );
2385
+ return { arn: out.ARN ?? "", name: out.Name ?? "" };
2386
+ }
2387
+ /**
2388
+ * Schedules deletion (`DeleteSecret`) after `recoveryWindowDays` (AWS default 30) or deletes
2389
+ * immediately with `forceDeleteWithoutRecovery`. Note: AWS answers success for a forced delete
2390
+ * of a secret that does not exist.
2391
+ */
2392
+ async deleteSecret(secretId, options = {}) {
2393
+ requireId("deleteSecret", secretId);
2394
+ const { recoveryWindowDays: days, forceDeleteWithoutRecovery: force } = options;
2395
+ if (days !== void 0 && force === true) {
2396
+ throw new chunk5AEPFQD7_cjs.ValidationError(
2397
+ "deleteSecret: recoveryWindowDays and forceDeleteWithoutRecovery are mutually exclusive"
2398
+ );
2399
+ }
2400
+ if (days !== void 0 && !(Number.isInteger(days) && days >= 7 && days <= 30)) {
2401
+ throw new chunk5AEPFQD7_cjs.ValidationError("deleteSecret: recoveryWindowDays must be an integer from 7 to 30");
2402
+ }
2403
+ const input = {
2404
+ SecretId: secretId,
2405
+ ...days === void 0 ? {} : { RecoveryWindowInDays: days },
2406
+ ...force === void 0 ? {} : { ForceDeleteWithoutRecovery: force }
2407
+ };
2408
+ const out = await this.#send(
2409
+ `deleteSecret ${secretId}`,
2410
+ new clientSecretsManager.DeleteSecretCommand(input),
2411
+ options
2412
+ );
2413
+ return {
2414
+ arn: out.ARN ?? "",
2415
+ name: out.Name ?? "",
2416
+ ...out.DeletionDate === void 0 ? {} : { deletionDate: out.DeletionDate }
2417
+ };
2418
+ }
2419
+ /** Cancels a scheduled deletion (`RestoreSecret`). A no-op for a live secret. */
2420
+ async restoreSecret(secretId, options = {}) {
2421
+ requireId("restoreSecret", secretId);
2422
+ const out = await this.#send(
2423
+ `restoreSecret ${secretId}`,
2424
+ new clientSecretsManager.RestoreSecretCommand({ SecretId: secretId }),
2425
+ options
2426
+ );
2427
+ return { arn: out.ARN ?? "", name: out.Name ?? "" };
2428
+ }
2429
+ // ---------------------------------------------------------------------------------------
2430
+ // tags and resource policy
2431
+ /** Adds or replaces tags (`TagResource`). */
2432
+ async tagResource(secretId, tags, options = {}) {
2433
+ requireId("tagResource", secretId);
2434
+ await this.#send(
2435
+ `tagResource ${secretId}`,
2436
+ new clientSecretsManager.TagResourceCommand({ SecretId: secretId, Tags: toAwsTags(tags) }),
2437
+ options
2438
+ );
2439
+ }
2440
+ /** Removes tags by key (`UntagResource`). */
2441
+ async untagResource(secretId, tagKeys, options = {}) {
2442
+ requireId("untagResource", secretId);
2443
+ await this.#send(
2444
+ `untagResource ${secretId}`,
2445
+ new clientSecretsManager.UntagResourceCommand({ SecretId: secretId, TagKeys: [...tagKeys] }),
2446
+ options
2447
+ );
2448
+ }
2449
+ /** Attaches a resource policy (`PutResourcePolicy`); objects are JSON-encoded. */
2450
+ async putResourcePolicy(secretId, policy, options = {}) {
2451
+ requireId("putResourcePolicy", secretId);
2452
+ const out = await this.#send(
2453
+ `putResourcePolicy ${secretId}`,
2454
+ new clientSecretsManager.PutResourcePolicyCommand({
2455
+ SecretId: secretId,
2456
+ ResourcePolicy: typeof policy === "string" ? policy : JSON.stringify(policy),
2457
+ ...options.blockPublicPolicy === void 0 ? {} : { BlockPublicPolicy: options.blockPublicPolicy }
2458
+ }),
2459
+ options
2460
+ );
2461
+ return { arn: out.ARN ?? "", name: out.Name ?? "" };
2462
+ }
2463
+ /** Reads the resource policy (`GetResourcePolicy`); `resourcePolicy` is absent when there is none. */
2464
+ async getResourcePolicy(secretId, options = {}) {
2465
+ requireId("getResourcePolicy", secretId);
2466
+ const out = await this.#send(
2467
+ `getResourcePolicy ${secretId}`,
2468
+ new clientSecretsManager.GetResourcePolicyCommand({ SecretId: secretId }),
2469
+ options
2470
+ );
2471
+ const text = out.ResourcePolicy ?? void 0;
2472
+ const policy = parsePolicy(text);
2473
+ return {
2474
+ arn: out.ARN ?? "",
2475
+ name: out.Name ?? "",
2476
+ ...text === void 0 ? {} : { resourcePolicy: text },
2477
+ ...policy === void 0 ? {} : { policy }
2478
+ };
2479
+ }
2480
+ /** Removes the resource policy (`DeleteResourcePolicy`). */
2481
+ async deleteResourcePolicy(secretId, options = {}) {
2482
+ requireId("deleteResourcePolicy", secretId);
2483
+ const out = await this.#send(
2484
+ `deleteResourcePolicy ${secretId}`,
2485
+ new clientSecretsManager.DeleteResourcePolicyCommand({ SecretId: secretId }),
2486
+ options
2487
+ );
2488
+ return { arn: out.ARN ?? "", name: out.Name ?? "" };
2489
+ }
2490
+ /**
2491
+ * Checks a policy with IAM Access Analyzer (`ValidateResourcePolicy`). Emulators that lack the
2492
+ * operation (Moto 5.2.4) raise `UnsupportedError`.
2493
+ */
2494
+ async validateResourcePolicy(policy, options = {}) {
2495
+ const out = await this.#send(
2496
+ "validateResourcePolicy",
2497
+ new clientSecretsManager.ValidateResourcePolicyCommand({
2498
+ ResourcePolicy: typeof policy === "string" ? policy : JSON.stringify(policy),
2499
+ ...options.secretId === void 0 ? {} : { SecretId: options.secretId }
2500
+ }),
2501
+ options
2502
+ );
2503
+ return {
2504
+ policyValidationPassed: out.PolicyValidationPassed === true,
2505
+ validationErrors: (out.ValidationErrors ?? []).map(toPolicyError)
2506
+ };
2507
+ }
2508
+ // ---------------------------------------------------------------------------------------
2509
+ // rotation
2510
+ /**
2511
+ * Configures and/or starts rotation (`RotateSecret`). Without `lambdaArn` the secret's managed
2512
+ * or existing rotation function is used.
2513
+ */
2514
+ async rotateSecret(secretId, options = {}) {
2515
+ requireId("rotateSecret", secretId);
2516
+ const rules = options.rules;
2517
+ const input = {
2518
+ SecretId: secretId,
2519
+ ...options.lambdaArn === void 0 ? {} : { RotationLambdaARN: options.lambdaArn },
2520
+ ...rules === void 0 ? {} : {
2521
+ RotationRules: {
2522
+ ...rules.automaticallyAfterDays === void 0 ? {} : { AutomaticallyAfterDays: rules.automaticallyAfterDays },
2523
+ ...rules.duration === void 0 ? {} : { Duration: rules.duration },
2524
+ ...rules.scheduleExpression === void 0 ? {} : { ScheduleExpression: rules.scheduleExpression }
2525
+ }
2526
+ },
2527
+ ...options.rotateImmediately === void 0 ? {} : { RotateImmediately: options.rotateImmediately },
2528
+ ...options.clientRequestToken === void 0 ? {} : { ClientRequestToken: options.clientRequestToken }
2529
+ };
2530
+ const out = await this.#send(
2531
+ `rotateSecret ${secretId}`,
2532
+ new clientSecretsManager.RotateSecretCommand(input),
2533
+ options
2534
+ );
2535
+ return writeResult(out);
2536
+ }
2537
+ /** Turns rotation off and cancels a rotation in progress (`CancelRotateSecret`). */
2538
+ async cancelRotateSecret(secretId, options = {}) {
2539
+ requireId("cancelRotateSecret", secretId);
2540
+ const out = await this.#send(
2541
+ `cancelRotateSecret ${secretId}`,
2542
+ new clientSecretsManager.CancelRotateSecretCommand({ SecretId: secretId }),
2543
+ options
2544
+ );
2545
+ return writeResult(out);
2546
+ }
2547
+ // ---------------------------------------------------------------------------------------
2548
+ // utilities
2549
+ /** Generates a random password (`GetRandomPassword`), returned as a redacting {@link Secret}. */
2550
+ async getRandomPassword(options = {}) {
2551
+ const input = {
2552
+ PasswordLength: options.length ?? 32,
2553
+ ...options.excludeCharacters === void 0 ? {} : { ExcludeCharacters: options.excludeCharacters },
2554
+ ...options.excludeNumbers === void 0 ? {} : { ExcludeNumbers: options.excludeNumbers },
2555
+ ...options.excludePunctuation === void 0 ? {} : { ExcludePunctuation: options.excludePunctuation },
2556
+ ...options.excludeUppercase === void 0 ? {} : { ExcludeUppercase: options.excludeUppercase },
2557
+ ...options.excludeLowercase === void 0 ? {} : { ExcludeLowercase: options.excludeLowercase },
2558
+ ...options.includeSpace === void 0 ? {} : { IncludeSpace: options.includeSpace },
2559
+ ...options.requireEachIncludedType === void 0 ? {} : { RequireEachIncludedType: options.requireEachIncludedType }
2560
+ };
2561
+ const out = await this.#send("getRandomPassword", new clientSecretsManager.GetRandomPasswordCommand(input), options);
2562
+ return new chunk5AEPFQD7_cjs.Secret(out.RandomPassword ?? "");
2563
+ }
2564
+ /**
2565
+ * Reads one field of a JSON secret: `GetSecretValue`, parse `SecretString` as a JSON object,
2566
+ * return `field` (an exact key first, otherwise a dot path such as `"db.host"`). `null` when
2567
+ * the field is absent; `ValidationError` when the value is binary or not a JSON object;
2568
+ * `NotFoundError` when the secret is missing.
2569
+ */
2570
+ async getJsonField(secretId, field, options = {}) {
2571
+ const secret = await this.getSecretValue(secretId, options);
2572
+ if (secret.binary) {
2573
+ throw new chunk5AEPFQD7_cjs.ValidationError(`getJsonField ${secretId}: the secret is binary, not JSON`);
2574
+ }
2575
+ let parsed;
2576
+ try {
2577
+ parsed = secret.value.json();
2578
+ } catch {
2579
+ throw new chunk5AEPFQD7_cjs.ValidationError(`getJsonField ${secretId}: the value is not valid JSON`);
2580
+ }
2581
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2582
+ throw new chunk5AEPFQD7_cjs.ValidationError(`getJsonField ${secretId}: the value is not a JSON object`);
2583
+ }
2584
+ return jsonField(parsed, field);
2585
+ }
2586
+ // ---------------------------------------------------------------------------------------
2587
+ // internals
2588
+ /** Known credential values for redaction. @internal */
2589
+ knownSecrets() {
2590
+ return this.config.knownSecrets();
2591
+ }
2592
+ #healthClient() {
2593
+ if (this.#sdkConfig === void 0) return this.#sdk;
2594
+ this.#healthSdk ??= new clientSecretsManager.SecretsManagerClient({ ...this.#sdkConfig, maxAttempts: 1 });
2595
+ return this.#healthSdk;
2596
+ }
2597
+ /** Sends a command with cancellation, the total timeout and error mapping. */
2598
+ async #send(operation, command, options = {}) {
2599
+ if (this.#closed) throw new chunk5AEPFQD7_cjs.CancelledError(`${operation}: client is closed`);
2600
+ const signal = options.signal;
2601
+ if (signal?.aborted === true) throw new chunk5AEPFQD7_cjs.CancelledError(`${operation}: cancelled`);
2602
+ const total = new AbortController();
2603
+ const timer = setTimeout(() => {
2604
+ total.abort();
2605
+ }, this.config.totalTimeoutMs);
2606
+ timer.unref();
2607
+ const abortSignal = signal === void 0 ? total.signal : AbortSignal.any([signal, total.signal]);
2608
+ const sdk = options.sdk ?? this.#sdk;
2609
+ try {
2610
+ const send = sdk.send.bind(sdk);
2611
+ return await send(command, {
2612
+ abortSignal,
2613
+ ...options.requestTimeout === void 0 ? {} : { requestTimeout: options.requestTimeout }
2614
+ });
2615
+ } catch (err) {
2616
+ let mapped;
2617
+ if (isAborted(signal)) {
2618
+ mapped = new chunk5AEPFQD7_cjs.CancelledError(`${operation}: cancelled`, { cause: err });
2619
+ } else if (total.signal.aborted) {
2620
+ mapped = new chunk5AEPFQD7_cjs.TimeoutError(
2621
+ `${operation}: total timeout of ${String(this.config.totalTimeoutMs)} ms exceeded`,
2622
+ { cause: err }
2623
+ );
2624
+ } else {
2625
+ mapped = mapAwsError(err, operation, {
2626
+ knownSecrets: this.knownSecrets(),
2627
+ unsupportedOnHtml500: EMULATOR_GAPS.has(operation.split(" ")[0] ?? "")
2628
+ });
2629
+ }
2630
+ if (mapped.httpStatus !== void 0) {
2631
+ safeCall(this.config.hooks?.onError, {
2632
+ method: "POST",
2633
+ url: this.config.url,
2634
+ error: mapped,
2635
+ attempt: attemptsOf(err),
2636
+ willRetry: false
2637
+ });
2638
+ }
2639
+ throw mapped;
2640
+ } finally {
2641
+ clearTimeout(timer);
2642
+ }
2643
+ }
2644
+ };
2645
+ function isAborted(signal) {
2646
+ return signal?.aborted === true;
2647
+ }
2648
+ function attemptsOf(err) {
2649
+ const attempts = err.$metadata?.attempts;
2650
+ return typeof attempts === "number" && attempts > 0 ? attempts : 1;
2651
+ }
2652
+ function requireId(operation, id) {
2653
+ if (typeof id !== "string" || id.trim() === "") {
2654
+ throw new chunk5AEPFQD7_cjs.ValidationError(`${operation}: secret id must not be empty`);
2655
+ }
2656
+ }
2657
+ function writeResult(out) {
2658
+ return {
2659
+ arn: out.ARN ?? "",
2660
+ name: out.Name ?? "",
2661
+ ...out.VersionId === void 0 ? {} : { versionId: out.VersionId }
2662
+ };
2663
+ }
2664
+ function orderByIds(values, ids) {
2665
+ const rank = (v) => {
2666
+ const i = ids.findIndex(
2667
+ (id) => id === v.name || id === v.arn || id.startsWith("arn:") && v.arn.startsWith(id)
2668
+ );
2669
+ return i === -1 ? ids.length : i;
2670
+ };
2671
+ return [...values].sort((a, b) => rank(a) - rank(b));
2672
+ }
2673
+ function jsonField(obj, field) {
2674
+ if (Object.hasOwn(obj, field)) return obj[field] ?? null;
2675
+ let current = obj;
2676
+ for (const part of field.split(".")) {
2677
+ if (typeof current !== "object" || current === null || Array.isArray(current)) return null;
2678
+ if (!Object.hasOwn(current, part)) return null;
2679
+ current = current[part];
2680
+ }
2681
+ return current ?? null;
2682
+ }
2683
+ function buildCredentials(cfg, handler) {
2684
+ let base;
2685
+ if (cfg.accessKeyId !== void 0 && cfg.secretAccessKey !== void 0) {
2686
+ base = {
2687
+ accessKeyId: cfg.accessKeyId,
2688
+ secretAccessKey: cfg.secretAccessKey.reveal(),
2689
+ ...cfg.sessionToken === void 0 ? {} : { sessionToken: cfg.sessionToken.reveal() }
2690
+ };
2691
+ } else if (cfg.credentials !== void 0) {
2692
+ base = cfg.credentials;
2693
+ } else if (cfg.profile !== void 0) {
2694
+ base = credentialProviders.fromIni({ profile: cfg.profile });
2695
+ }
2696
+ if (cfg.roleArn === void 0) return base;
2697
+ return credentialProviders.fromTemporaryCredentials({
2698
+ params: {
2699
+ RoleArn: cfg.roleArn,
2700
+ RoleSessionName: cfg.roleSessionName,
2701
+ ...cfg.externalId === void 0 ? {} : { ExternalId: cfg.externalId },
2702
+ ...cfg.roleDurationMs === void 0 ? {} : { DurationSeconds: Math.floor(cfg.roleDurationMs / 1e3) }
2703
+ },
2704
+ ...base === void 0 ? {} : { masterCredentials: base },
2705
+ clientConfig: {
2706
+ requestHandler: handler,
2707
+ ...cfg.region === void 0 ? {} : { region: cfg.region }
2708
+ }
2709
+ });
2710
+ }
2711
+
2712
+ Object.defineProperty(exports, "AuthenticationError", {
2713
+ enumerable: true,
2714
+ get: function () { return chunk5AEPFQD7_cjs.AuthenticationError; }
2715
+ });
2716
+ Object.defineProperty(exports, "AwsSecretsManagerError", {
2717
+ enumerable: true,
2718
+ get: function () { return chunk5AEPFQD7_cjs.AwsSecretsManagerError; }
2719
+ });
2720
+ Object.defineProperty(exports, "BaseSecretsProvider", {
2721
+ enumerable: true,
2722
+ get: function () { return chunk5AEPFQD7_cjs.BaseSecretsProvider; }
2723
+ });
2724
+ Object.defineProperty(exports, "CancelledError", {
2725
+ enumerable: true,
2726
+ get: function () { return chunk5AEPFQD7_cjs.CancelledError; }
2727
+ });
2728
+ Object.defineProperty(exports, "ConfigError", {
2729
+ enumerable: true,
2730
+ get: function () { return chunk5AEPFQD7_cjs.ConfigError; }
2731
+ });
2732
+ Object.defineProperty(exports, "ConflictError", {
2733
+ enumerable: true,
2734
+ get: function () { return chunk5AEPFQD7_cjs.ConflictError; }
2735
+ });
2736
+ Object.defineProperty(exports, "EnvReader", {
2737
+ enumerable: true,
2738
+ get: function () { return chunk5AEPFQD7_cjs.EnvReader; }
2739
+ });
2740
+ Object.defineProperty(exports, "ErrorCode", {
2741
+ enumerable: true,
2742
+ get: function () { return chunk5AEPFQD7_cjs.ErrorCode; }
2743
+ });
2744
+ Object.defineProperty(exports, "GET_MANY_CONCURRENCY", {
2745
+ enumerable: true,
2746
+ get: function () { return chunk5AEPFQD7_cjs.GET_MANY_CONCURRENCY; }
2747
+ });
2748
+ Object.defineProperty(exports, "MIN_SECRET_LENGTH", {
2749
+ enumerable: true,
2750
+ get: function () { return chunk5AEPFQD7_cjs.MIN_SECRET_LENGTH; }
2751
+ });
2752
+ Object.defineProperty(exports, "NotFoundError", {
2753
+ enumerable: true,
2754
+ get: function () { return chunk5AEPFQD7_cjs.NotFoundError; }
2755
+ });
2756
+ Object.defineProperty(exports, "PermissionDeniedError", {
2757
+ enumerable: true,
2758
+ get: function () { return chunk5AEPFQD7_cjs.PermissionDeniedError; }
2759
+ });
2760
+ Object.defineProperty(exports, "REDACTED", {
2761
+ enumerable: true,
2762
+ get: function () { return chunk5AEPFQD7_cjs.REDACTED; }
2763
+ });
2764
+ Object.defineProperty(exports, "RateLimitError", {
2765
+ enumerable: true,
2766
+ get: function () { return chunk5AEPFQD7_cjs.RateLimitError; }
2767
+ });
2768
+ Object.defineProperty(exports, "SENSITIVE_FIELD_PARTS", {
2769
+ enumerable: true,
2770
+ get: function () { return chunk5AEPFQD7_cjs.SENSITIVE_FIELD_PARTS; }
2771
+ });
2772
+ Object.defineProperty(exports, "Secret", {
2773
+ enumerable: true,
2774
+ get: function () { return chunk5AEPFQD7_cjs.Secret; }
2775
+ });
2776
+ Object.defineProperty(exports, "SecretValue", {
2777
+ enumerable: true,
2778
+ get: function () { return chunk5AEPFQD7_cjs.SecretValue; }
2779
+ });
2780
+ Object.defineProperty(exports, "TimeoutError", {
2781
+ enumerable: true,
2782
+ get: function () { return chunk5AEPFQD7_cjs.TimeoutError; }
2783
+ });
2784
+ Object.defineProperty(exports, "UnavailableError", {
2785
+ enumerable: true,
2786
+ get: function () { return chunk5AEPFQD7_cjs.UnavailableError; }
2787
+ });
2788
+ Object.defineProperty(exports, "UnsupportedError", {
2789
+ enumerable: true,
2790
+ get: function () { return chunk5AEPFQD7_cjs.UnsupportedError; }
2791
+ });
2792
+ Object.defineProperty(exports, "ValidationError", {
2793
+ enumerable: true,
2794
+ get: function () { return chunk5AEPFQD7_cjs.ValidationError; }
2795
+ });
2796
+ Object.defineProperty(exports, "applyEnv", {
2797
+ enumerable: true,
2798
+ get: function () { return chunk5AEPFQD7_cjs.applyEnv; }
2799
+ });
2800
+ Object.defineProperty(exports, "codeForStatus", {
2801
+ enumerable: true,
2802
+ get: function () { return chunk5AEPFQD7_cjs.codeForStatus; }
2803
+ });
2804
+ Object.defineProperty(exports, "encodeSecretInput", {
2805
+ enumerable: true,
2806
+ get: function () { return chunk5AEPFQD7_cjs.encodeSecretInput; }
2807
+ });
2808
+ Object.defineProperty(exports, "envNameFor", {
2809
+ enumerable: true,
2810
+ get: function () { return chunk5AEPFQD7_cjs.envNameFor; }
2811
+ });
2812
+ Object.defineProperty(exports, "errorForCode", {
2813
+ enumerable: true,
2814
+ get: function () { return chunk5AEPFQD7_cjs.errorForCode; }
2815
+ });
2816
+ Object.defineProperty(exports, "errorForStatus", {
2817
+ enumerable: true,
2818
+ get: function () { return chunk5AEPFQD7_cjs.errorForStatus; }
2819
+ });
2820
+ Object.defineProperty(exports, "isAwsSecretsManagerError", {
2821
+ enumerable: true,
2822
+ get: function () { return chunk5AEPFQD7_cjs.isAwsSecretsManagerError; }
2823
+ });
2824
+ Object.defineProperty(exports, "isSensitiveField", {
2825
+ enumerable: true,
2826
+ get: function () { return chunk5AEPFQD7_cjs.isSensitiveField; }
2827
+ });
2828
+ Object.defineProperty(exports, "isSensitiveHeader", {
2829
+ enumerable: true,
2830
+ get: function () { return chunk5AEPFQD7_cjs.isSensitiveHeader; }
2831
+ });
2832
+ Object.defineProperty(exports, "parseBool", {
2833
+ enumerable: true,
2834
+ get: function () { return chunk5AEPFQD7_cjs.parseBool; }
2835
+ });
2836
+ Object.defineProperty(exports, "parseDuration", {
2837
+ enumerable: true,
2838
+ get: function () { return chunk5AEPFQD7_cjs.parseDuration; }
2839
+ });
2840
+ Object.defineProperty(exports, "parseInteger", {
2841
+ enumerable: true,
2842
+ get: function () { return chunk5AEPFQD7_cjs.parseInteger; }
2843
+ });
2844
+ Object.defineProperty(exports, "pollUntil", {
2845
+ enumerable: true,
2846
+ get: function () { return chunk5AEPFQD7_cjs.pollUntil; }
2847
+ });
2848
+ Object.defineProperty(exports, "reasonForCode", {
2849
+ enumerable: true,
2850
+ get: function () { return chunk5AEPFQD7_cjs.reasonForCode; }
2851
+ });
2852
+ Object.defineProperty(exports, "redactError", {
2853
+ enumerable: true,
2854
+ get: function () { return chunk5AEPFQD7_cjs.redactError; }
2855
+ });
2856
+ Object.defineProperty(exports, "redactFields", {
2857
+ enumerable: true,
2858
+ get: function () { return chunk5AEPFQD7_cjs.redactFields; }
2859
+ });
2860
+ Object.defineProperty(exports, "redactHeaders", {
2861
+ enumerable: true,
2862
+ get: function () { return chunk5AEPFQD7_cjs.redactHeaders; }
2863
+ });
2864
+ Object.defineProperty(exports, "redactText", {
2865
+ enumerable: true,
2866
+ get: function () { return chunk5AEPFQD7_cjs.redactText; }
2867
+ });
2868
+ Object.defineProperty(exports, "redactUrl", {
2869
+ enumerable: true,
2870
+ get: function () { return chunk5AEPFQD7_cjs.redactUrl; }
2871
+ });
2872
+ Object.defineProperty(exports, "relativeName", {
2873
+ enumerable: true,
2874
+ get: function () { return chunk5AEPFQD7_cjs.relativeName; }
2875
+ });
2876
+ Object.defineProperty(exports, "secretFingerprint", {
2877
+ enumerable: true,
2878
+ get: function () { return chunk5AEPFQD7_cjs.secretFingerprint; }
2879
+ });
2880
+ Object.defineProperty(exports, "sleep", {
2881
+ enumerable: true,
2882
+ get: function () { return chunk5AEPFQD7_cjs.sleep; }
2883
+ });
2884
+ Object.defineProperty(exports, "throwIfAborted", {
2885
+ enumerable: true,
2886
+ get: function () { return chunk5AEPFQD7_cjs.throwIfAborted; }
2887
+ });
2888
+ Object.defineProperty(exports, "watchSecret", {
2889
+ enumerable: true,
2890
+ get: function () { return chunk5AEPFQD7_cjs.watchSecret; }
2891
+ });
2892
+ exports.API_VERSION = API_VERSION;
2893
+ exports.AWSCURRENT = AWSCURRENT;
2894
+ exports.AWSPENDING = AWSPENDING;
2895
+ exports.AWSPREVIOUS = AWSPREVIOUS;
2896
+ exports.AWS_ERROR_CODES = AWS_ERROR_CODES;
2897
+ exports.AWS_SECRET_CACHE_DEFAULTS = AWS_SECRET_CACHE_DEFAULTS;
2898
+ exports.AttemptTimeoutError = AttemptTimeoutError;
2899
+ exports.AwsSecretCache = AwsSecretCache;
2900
+ exports.AwsSecretsManagerClient = AwsSecretsManagerClient;
2901
+ exports.AwsSecretsManagerConfig = AwsSecretsManagerConfig;
2902
+ exports.AwsSecretsManagerSecretsProvider = AwsSecretsManagerSecretsProvider;
2903
+ exports.BATCH_GET_MAX_IDS = BATCH_GET_MAX_IDS;
2904
+ exports.DEFAULT_RECOVERY_WINDOW_DAYS = DEFAULT_RECOVERY_WINDOW_DAYS;
2905
+ exports.DEFAULT_REQUEST_ID_HEADERS = DEFAULT_REQUEST_ID_HEADERS;
2906
+ exports.DEFAULT_ROLE_SESSION_NAME = DEFAULT_ROLE_SESSION_NAME;
2907
+ exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS;
2908
+ exports.GROW_USER_AGENT = GROW_USER_AGENT;
2909
+ exports.GrowHttpHandler = GrowHttpHandler;
2910
+ exports.HttpTransport = HttpTransport;
2911
+ exports.LANGUAGE = LANGUAGE;
2912
+ exports.MAX_VENDOR_TEXT = MAX_VENDOR_TEXT;
2913
+ exports.PACKAGE_KEY = PACKAGE_KEY;
2914
+ exports.Paginator = Paginator;
2915
+ exports.RetryPolicy = RetryPolicy;
2916
+ exports.SDK_KIT_VERSION = SDK_KIT_VERSION;
2917
+ exports.SDK_VERSION = SDK_VERSION;
2918
+ exports.SecretCache = SecretCache;
2919
+ exports.VENDOR_ENV = VENDOR_ENV;
2920
+ exports.createDispatcher = createDispatcher;
2921
+ exports.definedOnly = definedOnly;
2922
+ exports.describeCommonConfig = describeCommonConfig;
2923
+ exports.encodeBytes = encodeBytes;
2924
+ exports.encodeValue = encodeValue;
2925
+ exports.errorCodeFromBody = errorCodeFromBody;
2926
+ exports.fromAwsTags = fromAwsTags;
2927
+ exports.fullName = fullName;
2928
+ exports.hasMore = hasMore;
2929
+ exports.healthStatus = healthStatus;
2930
+ exports.isHealthyWord = isHealthyWord;
2931
+ exports.isIdempotentMethod = isIdempotentMethod;
2932
+ exports.isRetryableStatus = isRetryableStatus;
2933
+ exports.jsonField = jsonField;
2934
+ exports.mapAwsError = mapAwsError;
2935
+ exports.mergeOptions = mergeOptions;
2936
+ exports.parsePolicy = parsePolicy;
2937
+ exports.parseRetryAfter = parseRetryAfter;
2938
+ exports.probeHealth = probeHealth;
2939
+ exports.readCommonEnv = readCommonEnv;
2940
+ exports.redactSecretsInText = redactSecretsInText;
2941
+ exports.resolveCommonConfig = resolveCommonConfig;
2942
+ exports.safeCall = safeCall;
2943
+ exports.safeLogger = safeLogger;
2944
+ exports.secretValues = secretValues;
2945
+ exports.silentLogger = silentLogger;
2946
+ exports.toAwsFilters = toAwsFilters;
2947
+ exports.toAwsTags = toAwsTags;
2948
+ exports.toBatchError = toBatchError;
2949
+ exports.toDescription = toDescription;
2950
+ exports.toMetadata = toMetadata;
2951
+ exports.toPolicyError = toPolicyError;
2952
+ exports.toSecretValue = toSecretValue;
2953
+ exports.toVersion = toVersion;
2954
+ exports.validateCommonConfig = validateCommonConfig;
2955
+ //# sourceMappingURL=index.cjs.map
2956
+ //# sourceMappingURL=index.cjs.map