@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.
@@ -0,0 +1,655 @@
1
+ import { pollUntil, TimeoutError, BaseSecretsProvider, SecretValue, ConflictError, NotFoundError } from '../chunk-SDDDS6RG.js';
2
+ import { isDeepStrictEqual, inspect } from 'util';
3
+ import { readdirSync, readFileSync } from 'fs';
4
+ import { join } from 'path';
5
+
6
+ // src/testing/core-ops.ts
7
+ var coreOps = {
8
+ ops: {
9
+ health: (client) => client.health(),
10
+ ping: (client) => client.ping(),
11
+ serverVersion: (client) => client.serverVersion(),
12
+ close: (client) => client.close()
13
+ },
14
+ dispose: (client) => client.close()
15
+ };
16
+ function toPlain(value) {
17
+ if (value instanceof Map) {
18
+ return Object.fromEntries([...value.entries()].map(([k, v]) => [String(k), toPlain(v)]));
19
+ }
20
+ if (value instanceof Set) return [...value].map(toPlain);
21
+ if (Array.isArray(value)) return value.map(toPlain);
22
+ return value;
23
+ }
24
+ function subsetEquals(actual, expected) {
25
+ const a = toPlain(actual);
26
+ if (Array.isArray(expected)) {
27
+ return Array.isArray(a) && a.length === expected.length && expected.every((e, i) => subsetEquals(a[i], e));
28
+ }
29
+ if (expected !== null && typeof expected === "object") {
30
+ if (a === null || typeof a !== "object" || Array.isArray(a)) return false;
31
+ const obj = a;
32
+ return Object.entries(expected).every(([k, v]) => subsetEquals(obj[k], v));
33
+ }
34
+ return isDeepStrictEqual(a, expected);
35
+ }
36
+ function sizeOf(value) {
37
+ if (Array.isArray(value)) return value.length;
38
+ if (value instanceof Map || value instanceof Set) return value.size;
39
+ if (typeof value === "string") return value.length;
40
+ if (value !== null && typeof value === "object") {
41
+ const obj = value;
42
+ if (Array.isArray(obj.spans)) return obj.spans.length;
43
+ if (Array.isArray(obj.records)) return obj.records.length;
44
+ return Object.keys(obj).length;
45
+ }
46
+ throw new Error(`cannot count a ${value === null ? "null" : typeof value}`);
47
+ }
48
+ function stringForms(value) {
49
+ const forms = [];
50
+ try {
51
+ forms.push(String(value));
52
+ } catch {
53
+ }
54
+ try {
55
+ const json = JSON.stringify(toPlain(value));
56
+ if (typeof json === "string") forms.push(json);
57
+ } catch {
58
+ }
59
+ forms.push(inspect(value, { depth: 20, maxArrayLength: null, maxStringLength: null }));
60
+ return forms;
61
+ }
62
+ function sortKey(item) {
63
+ if (typeof item === "string") return item;
64
+ if (item !== null && typeof item === "object") {
65
+ const obj = item;
66
+ if (typeof obj.name === "string") return obj.name;
67
+ if (typeof obj.id === "string") return obj.id;
68
+ }
69
+ return String(item);
70
+ }
71
+ function containsValue(actual, needle) {
72
+ if (typeof actual === "string") return typeof needle === "string" && actual.includes(needle);
73
+ const list = actual instanceof Map ? [...actual.keys()] : actual instanceof Set ? [...actual] : actual;
74
+ if (Array.isArray(list))
75
+ return list.some(
76
+ (item) => isDeepStrictEqual(item, needle) || needle !== null && typeof needle === "object" && subsetEquals(item, needle)
77
+ );
78
+ if (actual !== null && typeof actual === "object" && typeof needle === "string")
79
+ return needle in actual;
80
+ return false;
81
+ }
82
+ function typeName(value) {
83
+ if (Array.isArray(value)) return "array";
84
+ if (value === null) return "null";
85
+ return typeof value;
86
+ }
87
+ function checkTree(value, tree) {
88
+ const spans = value?.spans;
89
+ if (!Array.isArray(spans)) throw new Error("tree: result has no spans");
90
+ const list = spans;
91
+ for (const [parentName, children] of Object.entries(tree)) {
92
+ const parents = list.filter((s) => s.name === parentName);
93
+ if (parents.length === 0) throw new Error(`tree: no span named "${parentName}"`);
94
+ const ids = new Set(parents.map((p) => p.spanId));
95
+ const actual = list.filter((s) => s.parentSpanId !== void 0 && ids.has(s.parentSpanId)).map((s) => s.name);
96
+ const absent = children.filter((c) => !actual.includes(c));
97
+ if (absent.length > 0) {
98
+ throw new Error(
99
+ `tree: "${parentName}" lacks children ${JSON.stringify(absent)} (has ${JSON.stringify(actual)})`
100
+ );
101
+ }
102
+ }
103
+ }
104
+ function describe(value) {
105
+ return inspect(value, { depth: 4, breakLength: Infinity });
106
+ }
107
+ function checkExpectations(value, expect) {
108
+ if (expect.reveal !== void 0) {
109
+ const v = value;
110
+ if (typeof v?.reveal !== "function") throw new Error("reveal: result is not a SecretValue");
111
+ if (v.reveal() !== expect.reveal)
112
+ throw new Error("reveal: value differs from the expected text");
113
+ }
114
+ if ("equals" in expect && !subsetEquals(value, expect.equals)) {
115
+ throw new Error(`equals: expected ${describe(expect.equals)}, got ${describe(value)}`);
116
+ }
117
+ if (expect.null === true && value !== null && value !== void 0)
118
+ throw new Error(`null: got ${describe(value)}`);
119
+ if (expect.notNull === true && (value === null || value === void 0))
120
+ throw new Error("notNull: got null");
121
+ if (expect.true === true && value !== true) throw new Error(`true: got ${describe(value)}`);
122
+ if (expect.false === true && value !== false) throw new Error(`false: got ${describe(value)}`);
123
+ if ("contains" in expect && !containsValue(value, expect.contains)) {
124
+ throw new Error(`contains: ${describe(expect.contains)} not found in ${describe(value)}`);
125
+ }
126
+ if ("notContains" in expect && containsValue(value, expect.notContains)) {
127
+ throw new Error(`notContains: ${describe(expect.notContains)} found`);
128
+ }
129
+ if (expect.count !== void 0 && sizeOf(value) !== expect.count) {
130
+ throw new Error(`count: expected ${expect.count}, got ${sizeOf(value)}`);
131
+ }
132
+ if (expect.minCount !== void 0 && sizeOf(value) < expect.minCount) {
133
+ throw new Error(`minCount: expected >= ${expect.minCount}, got ${sizeOf(value)}`);
134
+ }
135
+ if (expect.sorted === true) {
136
+ if (!Array.isArray(value)) throw new Error("sorted: result is not an array");
137
+ const keys = value.map(sortKey);
138
+ for (let i = 1; i < keys.length; i++) {
139
+ if (keys[i - 1] > keys[i])
140
+ throw new Error(`sorted: "${keys[i - 1]}" before "${keys[i]}"`);
141
+ }
142
+ }
143
+ if (expect.type !== void 0 && typeName(value) !== expect.type) {
144
+ throw new Error(`type: expected ${expect.type}, got ${typeName(value)}`);
145
+ }
146
+ if (expect.stringForm !== void 0) {
147
+ const forms = stringForms(value);
148
+ const { contains, notContains } = expect.stringForm;
149
+ if (notContains !== void 0 && forms.some((f) => f.includes(notContains))) {
150
+ throw new Error("stringForm: the string form contains a forbidden value");
151
+ }
152
+ if (contains !== void 0 && !forms.some((f) => f.includes(contains))) {
153
+ throw new Error(`stringForm: no string form contains ${JSON.stringify(contains)}`);
154
+ }
155
+ }
156
+ if (expect.tree !== void 0) checkTree(value, expect.tree);
157
+ }
158
+ async function pollForExpectation(fn, args, context, options = {}) {
159
+ const expect = context.step.expect;
160
+ if (expect === void 0 || expect.error !== void 0) return fn();
161
+ const expectation = context.substitute(expect);
162
+ let last;
163
+ try {
164
+ return await pollUntil(
165
+ async () => {
166
+ last = { value: await fn() };
167
+ return last.value;
168
+ },
169
+ (value) => {
170
+ try {
171
+ checkExpectations(value, expectation);
172
+ return true;
173
+ } catch {
174
+ return false;
175
+ }
176
+ },
177
+ {
178
+ timeoutMs: typeof args.timeoutMs === "number" ? args.timeoutMs : options.defaultTimeoutMs ?? 6e4,
179
+ intervalMs: typeof args.intervalMs === "number" ? args.intervalMs : 1e3,
180
+ operation: options.operation ?? "poll"
181
+ }
182
+ );
183
+ } catch (error) {
184
+ if (error instanceof TimeoutError && last !== void 0) return last.value;
185
+ throw error;
186
+ }
187
+ }
188
+
189
+ // src/testing/secrets-ops.ts
190
+ function str(args, key) {
191
+ const v = args[key];
192
+ if (typeof v !== "string") throw new Error(`argument "${key}" must be a string`);
193
+ return v;
194
+ }
195
+ function optStr(args, key) {
196
+ const v = args[key];
197
+ return typeof v === "string" ? v : void 0;
198
+ }
199
+ function getOptions(args) {
200
+ const out = {};
201
+ const version = optStr(args, "version");
202
+ const path = optStr(args, "path");
203
+ if (version !== void 0) out.version = version;
204
+ if (path !== void 0) out.path = path;
205
+ return out;
206
+ }
207
+ function setOptions(args) {
208
+ const out = {};
209
+ const path = optStr(args, "path");
210
+ if (path !== void 0) out.path = path;
211
+ if (typeof args.cas === "number") out.cas = args.cas;
212
+ if (args.tags !== null && typeof args.tags === "object")
213
+ out.tags = args.tags;
214
+ const description = optStr(args, "description");
215
+ if (description !== void 0) out.description = description;
216
+ return out;
217
+ }
218
+ function deleteOptions(args) {
219
+ const out = {};
220
+ const path = optStr(args, "path");
221
+ if (path !== void 0) out.path = path;
222
+ if (Array.isArray(args.versions)) out.versions = args.versions.map(String);
223
+ if (typeof args.permanent === "boolean") out.permanent = args.permanent;
224
+ return out;
225
+ }
226
+ var secretsOps = {
227
+ ops: {
228
+ set: (p, a) => p.set(str(a, "name"), a.value, setOptions(a)),
229
+ get: (p, a) => p.get(str(a, "name"), getOptions(a)),
230
+ getString: (p, a) => p.getString(str(a, "name"), getOptions(a)),
231
+ getJson: (p, a) => p.getJson(str(a, "name"), getOptions(a)),
232
+ getNumber: (p, a) => p.getNumber(str(a, "name"), getOptions(a)),
233
+ getBool: (p, a) => p.getBool(str(a, "name"), getOptions(a)),
234
+ require: (p, a) => p.require(str(a, "name"), getOptions(a)),
235
+ exists: (p, a) => p.exists(str(a, "name"), getOptions(a)),
236
+ getMany: (p, a) => {
237
+ if (!Array.isArray(a.names)) throw new Error('argument "names" must be an array');
238
+ return p.getMany(a.names.map(String), getOptions(a));
239
+ },
240
+ getAll: (p, a) => p.getAll(optStr(a, "path")),
241
+ list: (p, a) => p.list(optStr(a, "prefix") ?? optStr(a, "path")),
242
+ delete: (p, a) => p.delete(str(a, "name"), deleteOptions(a)),
243
+ metadata: (p, a) => p.metadata(str(a, "name"), getOptions(a)),
244
+ loadEnv: async (p, a, ctx) => {
245
+ const source = optStr(a, "path") ?? a.mapping;
246
+ if (source === void 0) throw new Error('loadEnv needs "path" or "mapping"');
247
+ const set = await p.loadEnv(source, {
248
+ prefix: optStr(a, "prefix") ?? "",
249
+ override: a.override === true
250
+ });
251
+ ctx.onCleanup(() => {
252
+ for (const name of Object.keys(set)) Reflect.deleteProperty(process.env, name);
253
+ });
254
+ return set;
255
+ }
256
+ }
257
+ };
258
+
259
+ // src/testing/ops.ts
260
+ var builtinOps = Object.freeze({
261
+ core: coreOps,
262
+ secrets: secretsOps
263
+ });
264
+ var registry = /* @__PURE__ */ new Map();
265
+ function registerOps(category, ops) {
266
+ const normalized = isCategoryOps(ops) ? ops : { ops };
267
+ const prev = registry.get(category);
268
+ registry.set(category, prev === void 0 ? normalized : mergeOps(prev, normalized));
269
+ }
270
+ function resetRegisteredOps() {
271
+ registry.clear();
272
+ }
273
+ function isCategoryOps(value) {
274
+ return typeof value.ops === "object" && typeof value.ops !== "function";
275
+ }
276
+ function mergeOps(base, over) {
277
+ const merged = { ops: { ...base.ops, ...over.ops } };
278
+ const dispose = over.dispose ?? base.dispose;
279
+ const variables = over.variables ?? base.variables;
280
+ if (dispose !== void 0) merged.dispose = dispose;
281
+ if (variables !== void 0) merged.variables = variables;
282
+ return merged;
283
+ }
284
+ function resolveOps(category, extra) {
285
+ let ops = builtinOps[category];
286
+ const registered = registry.get(category);
287
+ if (registered !== void 0) ops = ops === void 0 ? registered : mergeOps(ops, registered);
288
+ const more = extra?.[category];
289
+ if (more !== void 0) {
290
+ const normalized = isCategoryOps(more) ? more : { ops: more };
291
+ ops = ops === void 0 ? normalized : mergeOps(ops, normalized);
292
+ }
293
+ return ops;
294
+ }
295
+ function randomRunId() {
296
+ const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
297
+ let out = "";
298
+ for (let i = 0; i < 8; i++)
299
+ out += alphabet[Math.floor(Math.random() * alphabet.length)];
300
+ return out;
301
+ }
302
+ function loadScenarios(scenariosDir) {
303
+ const files = readdirSync(scenariosDir).filter((f) => f.endsWith(".json"));
304
+ const scenarios = files.map((f) => {
305
+ const parsed = JSON.parse(readFileSync(join(scenariosDir, f), "utf8"));
306
+ if (typeof parsed.id !== "string" || typeof parsed.category !== "string" || !Array.isArray(parsed.steps)) {
307
+ throw new Error(`invalid scenario file ${f}`);
308
+ }
309
+ return parsed;
310
+ });
311
+ return scenarios.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
312
+ }
313
+ var VAR = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
314
+ var WHOLE_VAR = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
315
+ function substitute(value, vars) {
316
+ const lookup = (name) => {
317
+ if (!(name in vars)) throw new Error(`unknown variable \${${name}}`);
318
+ return vars[name];
319
+ };
320
+ const walk = (v) => {
321
+ if (typeof v === "string") {
322
+ const whole = WHOLE_VAR.exec(v);
323
+ if (whole !== null) return lookup(whole[1]);
324
+ return v.replace(VAR, (_m, name) => String(lookup(name)));
325
+ }
326
+ if (Array.isArray(v)) return v.map(walk);
327
+ if (v !== null && typeof v === "object") {
328
+ return Object.fromEntries(
329
+ Object.entries(v).map(([k, x]) => [
330
+ k.replace(VAR, (_m, name) => String(lookup(name))),
331
+ walk(x)
332
+ ])
333
+ );
334
+ }
335
+ return v;
336
+ };
337
+ return walk(value);
338
+ }
339
+ function capabilitySet(options, category) {
340
+ const caps = options.capabilities;
341
+ if (caps === void 0) return /* @__PURE__ */ new Set();
342
+ if (Array.isArray(caps)) return new Set(caps);
343
+ return new Set(caps[category] ?? []);
344
+ }
345
+ function missing(requires, caps) {
346
+ return (requires ?? []).filter((r) => !caps.has(r));
347
+ }
348
+ function message(err) {
349
+ if (err instanceof Error) {
350
+ const code = err.code;
351
+ return typeof code === "string" ? `${code}: ${err.message}` : err.message;
352
+ }
353
+ return String(err);
354
+ }
355
+ function planScenarios(options) {
356
+ const categories = new Set(options.categories ?? Object.keys(options.factories));
357
+ for (const c of categories) {
358
+ if (options.factories[c] === void 0) {
359
+ throw new Error(`conformance: no factory for category "${c}"`);
360
+ }
361
+ }
362
+ return loadScenarios(options.scenariosDir).filter((s) => categories.has(s.category)).filter((s) => options.only === void 0 || options.only.includes(s.id)).map((scenario) => {
363
+ const lacking = missing(scenario.requires, capabilitySet(options, scenario.category));
364
+ return lacking.length > 0 ? { scenario, skipReason: `missing capabilities: ${lacking.join(", ")}` } : { scenario };
365
+ });
366
+ }
367
+ async function runScenario(scenario, options) {
368
+ const started = performance.now();
369
+ const caps = capabilitySet(options, scenario.category);
370
+ const result = {
371
+ id: scenario.id,
372
+ category: scenario.category,
373
+ status: "passed",
374
+ steps: [],
375
+ durationMs: 0
376
+ };
377
+ const lacking = missing(scenario.requires, caps);
378
+ if (lacking.length > 0) {
379
+ result.status = "skipped";
380
+ result.skipReason = `missing capabilities: ${lacking.join(", ")}`;
381
+ return result;
382
+ }
383
+ const category = resolveOps(scenario.category, options.ops);
384
+ const factory = options.factories[scenario.category];
385
+ if (category === void 0 || factory === void 0) {
386
+ result.status = "failed";
387
+ result.error = category === void 0 ? `no op handlers for category "${scenario.category}"` : `no factory for category "${scenario.category}"`;
388
+ return result;
389
+ }
390
+ const run = (options.runId ?? randomRunId)();
391
+ const vars = { ...options.variables, run };
392
+ const prefix = substitute(options.prefix ?? "grow-conformance/${run}/", vars);
393
+ vars.prefix = prefix;
394
+ const cleanups = [];
395
+ let currentStep = scenario.steps[0] ?? { op: "" };
396
+ const context = {
397
+ scenario,
398
+ get step() {
399
+ return currentStep;
400
+ },
401
+ run,
402
+ prefix,
403
+ vars,
404
+ capabilities: caps,
405
+ substitute: (v) => substitute(v, vars),
406
+ onCleanup: (fn) => {
407
+ cleanups.push(fn);
408
+ }
409
+ };
410
+ let target;
411
+ try {
412
+ target = await factory({
413
+ scenario,
414
+ run,
415
+ prefix,
416
+ ...scenario.batchOptions === void 0 ? {} : { batchOptions: scenario.batchOptions }
417
+ });
418
+ Object.assign(vars, category.variables?.(target) ?? {}, { ...options.variables, run, prefix });
419
+ for (const [index, step] of scenario.steps.entries()) {
420
+ currentStep = step;
421
+ const stepStart = performance.now();
422
+ const stepResult = { index, op: step.op, status: "passed", durationMs: 0 };
423
+ result.steps.push(stepResult);
424
+ const stepLacking = missing(step.requires, caps);
425
+ if (stepLacking.length > 0) {
426
+ stepResult.status = "skipped";
427
+ stepResult.skipReason = `missing capabilities: ${stepLacking.join(", ")}`;
428
+ continue;
429
+ }
430
+ try {
431
+ const handler = category.ops[step.op];
432
+ if (handler === void 0)
433
+ throw new Error(`unknown op "${step.op}" for category ${scenario.category}`);
434
+ const args = substitute(step.args ?? {}, vars);
435
+ const expectation = step.expect === void 0 ? void 0 : substitute(step.expect, vars);
436
+ let value;
437
+ let thrown;
438
+ let failed = false;
439
+ try {
440
+ value = await handler(target, args, context);
441
+ } catch (err) {
442
+ failed = true;
443
+ thrown = err;
444
+ }
445
+ if (expectation?.error !== void 0) {
446
+ if (!failed) throw new Error(`expected error ${expectation.error} but the op succeeded`);
447
+ const code = thrown.code;
448
+ if (code !== expectation.error) {
449
+ throw new Error(`expected error ${expectation.error}, got ${message(thrown)}`);
450
+ }
451
+ } else {
452
+ if (failed) throw thrown;
453
+ if (expectation !== void 0) checkExpectations(value, expectation);
454
+ if (step.save !== void 0) vars[step.save] = value;
455
+ }
456
+ } catch (err) {
457
+ stepResult.status = "failed";
458
+ stepResult.error = message(err);
459
+ result.status = "failed";
460
+ result.error = `step ${index} (${step.op}): ${stepResult.error}`;
461
+ break;
462
+ } finally {
463
+ stepResult.durationMs = performance.now() - stepStart;
464
+ }
465
+ }
466
+ } catch (err) {
467
+ result.status = "failed";
468
+ result.error = `setup: ${message(err)}`;
469
+ } finally {
470
+ if (target !== void 0 && category.dispose !== void 0) {
471
+ try {
472
+ await category.dispose(target, context);
473
+ } catch (err) {
474
+ if (result.status !== "failed") {
475
+ result.status = "failed";
476
+ result.error = `dispose: ${message(err)}`;
477
+ }
478
+ }
479
+ }
480
+ for (const fn of cleanups.reverse()) {
481
+ try {
482
+ await fn();
483
+ } catch {
484
+ }
485
+ }
486
+ result.durationMs = performance.now() - started;
487
+ }
488
+ return result;
489
+ }
490
+ async function runConformance(options) {
491
+ const results = [];
492
+ for (const { scenario } of planScenarios(options)) {
493
+ results.push(await runScenario(scenario, options));
494
+ }
495
+ const count = (s) => results.filter((r) => r.status === s).length;
496
+ const failed = count("failed");
497
+ return { ok: failed === 0, passed: count("passed"), failed, skipped: count("skipped"), results };
498
+ }
499
+ function formatReport(report) {
500
+ const lines = report.results.map((r) => {
501
+ const extra = r.status === "failed" ? ` \u2014 ${r.error ?? ""}` : r.status === "skipped" ? ` \u2014 ${r.skipReason ?? ""}` : "";
502
+ const skippedSteps = r.steps.filter((s) => s.status === "skipped").map((s) => `${s.op}#${s.index}`);
503
+ const stepNote = skippedSteps.length > 0 ? ` (skipped steps: ${skippedSteps.join(", ")})` : "";
504
+ return `${r.status.toUpperCase().padEnd(7)} ${r.id}${extra}${stepNote}`;
505
+ });
506
+ lines.push(`passed ${report.passed}, failed ${report.failed}, skipped ${report.skipped}`);
507
+ return lines.join("\n");
508
+ }
509
+ function assertConformance(report) {
510
+ if (!report.ok) throw new Error(`conformance failed:
511
+ ${formatReport(report)}`);
512
+ }
513
+ function conformanceCases(options) {
514
+ return planScenarios(options).map(({ scenario, skipReason }) => ({
515
+ id: scenario.id,
516
+ category: scenario.category,
517
+ ...skipReason === void 0 ? {} : { skip: skipReason },
518
+ run: async () => {
519
+ const result = await runScenario(scenario, options);
520
+ if (result.status === "failed")
521
+ throw new Error(`${scenario.id}: ${result.error ?? "failed"}`);
522
+ return result;
523
+ }
524
+ }));
525
+ }
526
+
527
+ // src/testing/secrets-memory.ts
528
+ var InMemorySecretsProvider = class _InMemorySecretsProvider extends BaseSecretsProvider {
529
+ /** Capabilities to declare to the conformance runner. */
530
+ static capabilities = ["write", "versions", "delete"];
531
+ #store = /* @__PURE__ */ new Map();
532
+ #now;
533
+ /** Number of primitive calls by name (`fetchSecret`, `putSecret`, …), for tests. */
534
+ calls = {};
535
+ constructor(options = {}) {
536
+ super();
537
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
538
+ for (const [name, value] of Object.entries(options.initial ?? {})) {
539
+ const at = this.#now();
540
+ this.#store.set(name, {
541
+ versions: [{ bytes: new TextEncoder().encode(value), createdAt: at, deleted: false }],
542
+ tags: {},
543
+ createdAt: at,
544
+ updatedAt: at
545
+ });
546
+ }
547
+ }
548
+ #count(primitive) {
549
+ this.calls[primitive] = (this.calls[primitive] ?? 0) + 1;
550
+ }
551
+ /** Full name for a name and optional path. */
552
+ static fullName(name, path) {
553
+ if (path === void 0 || path === "") return name;
554
+ return `${path.replace(/\/+$/, "")}/${name}`;
555
+ }
556
+ #current(secret) {
557
+ for (let i = secret.versions.length - 1; i >= 0; i--) {
558
+ if (!secret.versions[i].deleted) return i + 1;
559
+ }
560
+ return 0;
561
+ }
562
+ fetchSecret(name, options) {
563
+ this.#count("fetchSecret");
564
+ const secret = this.#store.get(_InMemorySecretsProvider.fullName(name, options.path));
565
+ if (secret === void 0) return Promise.resolve(null);
566
+ const index = options.version !== void 0 ? Number(options.version) : this.#current(secret);
567
+ const version = secret.versions[index - 1];
568
+ if (version === void 0 || version.deleted) return Promise.resolve(null);
569
+ return Promise.resolve(new SecretValue(version.bytes, String(index)));
570
+ }
571
+ listSecrets(prefixOrPath, _options) {
572
+ this.#count("listSecrets");
573
+ const prefix = prefixOrPath ?? "";
574
+ const out = [];
575
+ for (const [name, secret] of this.#store) {
576
+ if (!name.startsWith(prefix)) continue;
577
+ const rest = name.slice(prefix.length).replace(/^\//, "");
578
+ if (rest === "" || rest.includes("/")) continue;
579
+ if (this.#current(secret) === 0) continue;
580
+ out.push(this.#meta(name, secret));
581
+ }
582
+ return Promise.resolve(out);
583
+ }
584
+ putSecret(name, value, options) {
585
+ this.#count("putSecret");
586
+ const full = _InMemorySecretsProvider.fullName(name, options.path);
587
+ const now = this.#now();
588
+ let secret = this.#store.get(full);
589
+ const current = secret === void 0 ? 0 : this.#current(secret);
590
+ if (options.cas !== void 0 && options.cas !== current) {
591
+ return Promise.reject(
592
+ new ConflictError(`secrets.set ${full}: version mismatch (cas ${options.cas})`)
593
+ );
594
+ }
595
+ if (secret === void 0) {
596
+ secret = { versions: [], tags: {}, createdAt: now, updatedAt: now };
597
+ this.#store.set(full, secret);
598
+ }
599
+ secret.versions.push({ bytes: Uint8Array.from(value), createdAt: now, deleted: false });
600
+ secret.updatedAt = now;
601
+ if (options.tags !== void 0) secret.tags = { ...options.tags };
602
+ if (options.description !== void 0) secret.description = options.description;
603
+ return Promise.resolve(String(secret.versions.length));
604
+ }
605
+ removeSecret(name, options) {
606
+ this.#count("removeSecret");
607
+ const full = _InMemorySecretsProvider.fullName(name, options.path);
608
+ const secret = this.#store.get(full);
609
+ if (secret === void 0 || this.#current(secret) === 0) {
610
+ return Promise.reject(new NotFoundError(`secrets.delete ${full}: not found`));
611
+ }
612
+ const selected = options.versions ?? [];
613
+ if (selected.length > 0) {
614
+ for (const v of selected) {
615
+ const stored = secret.versions[Number(v) - 1];
616
+ if (stored !== void 0) stored.deleted = true;
617
+ }
618
+ if (this.#current(secret) === 0) this.#store.delete(full);
619
+ } else if (options.permanent === true) {
620
+ this.#store.delete(full);
621
+ } else {
622
+ for (const v of secret.versions) v.deleted = true;
623
+ }
624
+ return Promise.resolve();
625
+ }
626
+ fetchMetadata(name, options) {
627
+ this.#count("fetchMetadata");
628
+ const full = _InMemorySecretsProvider.fullName(name, options.path);
629
+ const secret = this.#store.get(full);
630
+ if (secret === void 0 || this.#current(secret) === 0) return Promise.resolve(null);
631
+ return Promise.resolve(this.#meta(full, secret));
632
+ }
633
+ #meta(name, secret) {
634
+ const slash = name.lastIndexOf("/");
635
+ const meta = {
636
+ name,
637
+ version: String(this.#current(secret)),
638
+ createdAt: secret.createdAt,
639
+ updatedAt: secret.updatedAt,
640
+ tags: { ...secret.tags },
641
+ versions: secret.versions.length,
642
+ extra: secret.description === void 0 ? {} : { description: secret.description }
643
+ };
644
+ if (slash > 0) meta.path = name.slice(0, slash);
645
+ return meta;
646
+ }
647
+ /** Number of stored secrets (tests). */
648
+ get size() {
649
+ return this.#store.size;
650
+ }
651
+ };
652
+
653
+ export { InMemorySecretsProvider, assertConformance, builtinOps, checkExpectations, conformanceCases, coreOps, formatReport, loadScenarios, planScenarios, pollForExpectation, randomRunId, registerOps, resetRegisteredOps, resolveOps, runConformance, runScenario, secretsOps, sizeOf, stringForms, subsetEquals, substitute, toPlain };
654
+ //# sourceMappingURL=index.js.map
655
+ //# sourceMappingURL=index.js.map