@hot-updater/firebase 1.2.0-rc.6 → 1.2.0-rc.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,6 +3,8 @@ let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
3
3
  let firebase_admin_app = require("firebase-admin/app");
4
4
  let firebase_admin_firestore = require("firebase-admin/firestore");
5
5
  let node_crypto = require("node:crypto");
6
+ let node_stream = require("node:stream");
7
+ let node_stream_promises = require("node:stream/promises");
6
8
  let firebase_admin_storage = require("firebase-admin/storage");
7
9
  //#region src/firebaseInfrastructureNames.ts
8
10
  /**
@@ -167,14 +169,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
167
169
  };
168
170
  };
169
171
  //#endregion
172
+ //#region src/googleCredential.ts
173
+ const CLOUD_PLATFORM_SCOPE$1 = "https://www.googleapis.com/auth/cloud-platform";
174
+ /**
175
+ * Resolves application default credentials as Firestore will, from
176
+ * GOOGLE_APPLICATION_CREDENTIALS's file or the environment, for the app's
177
+ * `projectId`, so it neither exchanges a token nor discovers a project
178
+ * Firestore itself wouldn't. Only `applicationDefault()`'s credential: a
179
+ * service account's or refresh token's was read from its file already.
180
+ */
181
+ const resolveApplicationDefault = async (credential, projectId) => {
182
+ if (credential.constructor.name !== "ApplicationDefaultCredential") return;
183
+ const { GoogleAuth } = await import("google-auth-library");
184
+ await new GoogleAuth({
185
+ scopes: [CLOUD_PLATFORM_SCOPE$1],
186
+ ...projectId === void 0 ? {} : { projectId }
187
+ }).getClient();
188
+ };
189
+ //#endregion
170
190
  //#region src/firebaseDatabase.ts
191
+ /**
192
+ * `store` that loads `credential` before its first call: one that cannot
193
+ * load, such as GOOGLE_APPLICATION_CREDENTIALS naming a missing file, fails
194
+ * that call with what is wrong. Firestore's own client would also reject a
195
+ * promise nobody awaits, which ends a CLI process with a stack trace.
196
+ */
197
+ const withLoadedCredential = (store, credential, projectId) => {
198
+ let loaded;
199
+ const load = () => loaded ??= resolveApplicationDefault(credential, projectId).then(() => void 0, (error) => {
200
+ loaded = void 0;
201
+ throw new Error(`Could not load the Google credentials for Firestore: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
202
+ });
203
+ const { deleteConsumed } = store;
204
+ return {
205
+ ...store,
206
+ get: async (keys) => {
207
+ await load();
208
+ return store.get(keys);
209
+ },
210
+ query: async (range) => {
211
+ await load();
212
+ return store.query(range);
213
+ },
214
+ write: async (ops) => {
215
+ await load();
216
+ return store.write(ops);
217
+ },
218
+ ...deleteConsumed && { deleteConsumed: async (keys) => {
219
+ await load();
220
+ return deleteConsumed.call(store, keys);
221
+ } }
222
+ };
223
+ };
171
224
  const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
172
225
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(appOptions);
173
226
  const firestore = databaseId ? (0, firebase_admin_firestore.getFirestore)(app, databaseId) : (0, firebase_admin_firestore.getFirestore)(app);
174
- return (0, _hot_updater_plugin_core.createKvAdapter)({ store: createFirestoreStore({
227
+ const store = createFirestoreStore({
175
228
  firestore,
176
229
  collection
177
- }) });
230
+ });
231
+ const credential = app.options.credential;
232
+ return (0, _hot_updater_plugin_core.createKvAdapter)({ store: appOptions.credential === void 0 || credential === void 0 || process.env["FIRESTORE_EMULATOR_HOST"] ? store : withLoadedCredential(store, credential, app.options.projectId) });
178
233
  };
179
234
  /**
180
235
  * Writes the schema settings of core and `plugins`, the plugins the server
@@ -202,11 +257,14 @@ const firebaseDatabase = (config) => ({
202
257
  //#region src/firebaseStorage.ts
203
258
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
204
259
  const MAX_CACHED_SIGNED_URLS = 1e4;
260
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
261
+ const DELETE_CONCURRENCY = 16;
205
262
  const firebaseStorage = (config) => {
206
263
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(config);
207
264
  let opened;
208
265
  const bucket = () => opened ??= (0, firebase_admin_storage.getStorage)(app).bucket(config.storageBucket);
209
266
  const getStorageKey = (0, _hot_updater_plugin_core.createStorageKeyBuilder)(config.basePath);
267
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
210
268
  /**
211
269
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
212
270
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -249,11 +307,21 @@ const firebaseStorage = (config) => {
249
307
  protocol: "gs",
250
308
  async put({ key, body, contentType }) {
251
309
  const storageKey = getStorageKey(key);
252
- const [{ Readable }, { pipeline }] = await Promise.all([import("node:stream"), import("node:stream/promises")]);
253
- await pipeline(Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({ metadata: {
254
- contentType,
255
- cacheControl: "public, max-age=31536000, immutable"
256
- } }));
310
+ try {
311
+ await (0, node_stream_promises.pipeline)(node_stream.Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({
312
+ resumable: false,
313
+ metadata: {
314
+ contentType,
315
+ cacheControl: "public, max-age=31536000, immutable"
316
+ }
317
+ }));
318
+ } catch (error) {
319
+ const status = Reflect.get(Object(error), "code");
320
+ if (typeof status !== "number") throw error;
321
+ const message = error.message;
322
+ const detail = /<html|<!doctype/i.test(message) ? "" : `: ${message}`;
323
+ throw new Error(`Firebase Storage answered HTTP ${status} while uploading ${storageKey}${detail}`, { cause: error });
324
+ }
257
325
  return { storageUri: (0, _hot_updater_plugin_core.createStorageUri)({
258
326
  bucket: config.storageBucket,
259
327
  key: storageKey,
@@ -295,6 +363,39 @@ const firebaseStorage = (config) => {
295
363
  const { key } = parseAndValidate(storageUri);
296
364
  await bucket().file(key).delete({ ignoreNotFound: true });
297
365
  return { deleted: true };
366
+ },
367
+ async listObjects(prefix) {
368
+ const folder = getStorageKey(prefix ?? "");
369
+ const [files] = await bucket().getFiles({
370
+ autoPaginate: true,
371
+ prefix: folder ? `${folder}/` : ""
372
+ });
373
+ const objects = [];
374
+ for (const file of files) {
375
+ if (!file.name.startsWith(basePrefix)) continue;
376
+ let storageUri;
377
+ try {
378
+ storageUri = (0, _hot_updater_plugin_core.createStorageUri)({
379
+ bucket: config.storageBucket,
380
+ key: file.name,
381
+ protocol: "gs"
382
+ });
383
+ } catch {
384
+ continue;
385
+ }
386
+ const { size, updated } = file.metadata;
387
+ objects.push({
388
+ key: file.name.slice(basePrefix.length),
389
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
390
+ size: Number(size ?? 0),
391
+ storageUri
392
+ });
393
+ }
394
+ return objects;
395
+ },
396
+ async deleteObjects(relativeKeys) {
397
+ const keys = relativeKeys.map((key) => getStorageKey(key));
398
+ for (let offset = 0; offset < keys.length; offset += DELETE_CONCURRENCY) await Promise.all(keys.slice(offset, offset + DELETE_CONCURRENCY).map((key) => bucket().file(key).delete({ ignoreNotFound: true })));
298
399
  }
299
400
  });
300
401
  };
@@ -356,22 +457,61 @@ const crc32c = (bytes) => {
356
457
  /** The version IDs the secret's annotation lists. */
357
458
  const trackedVersions = (secret) => (secret.annotations?.[VERSIONS_ANNOTATION] ?? "").split(",").map((entry) => entry.trim()).filter((entry) => VERSION_ID_PATTERN.test(entry));
358
459
  const versionOf = (name) => typeof name === "string" ? name.slice(name.lastIndexOf("/") + 1) : "";
359
- const hint = (response, permission) => {
460
+ /** An error of one line each, for a terminal. */
461
+ const failure = (lines, cause) => new Error(lines.join("\n"), cause === void 0 ? void 0 : { cause });
462
+ /**
463
+ * The one step that can fix the credentials in use, by the order they're
464
+ * tried: signing in with gcloud changes nothing while a variable comes first.
465
+ */
466
+ const signInHint = (credentials) => {
467
+ if (credentials) return [`Check the credentials passed to ${ADAPTER_NAME}().`];
468
+ const variable = ACCESS_TOKEN_ENV_NAMES.find((name) => process.env[name]?.trim()) ?? (process.env["GOOGLE_APPLICATION_CREDENTIALS"]?.trim() ? "GOOGLE_APPLICATION_CREDENTIALS" : void 0);
469
+ if (variable) return [`Fix or unset ${variable}.`];
470
+ return process.env["CI"] ? ["Use google-github-actions/auth."] : ["Sign in:", "gcloud auth application-default login"];
471
+ };
472
+ const hint = (response, permission, signIn, projectId) => {
360
473
  const { status, error } = response;
361
- if (error.details?.some((detail) => detail.reason === "SERVICE_DISABLED")) return " Enable the Secret Manager API (secretmanager.googleapis.com) in the project: gcloud services enable secretmanager.googleapis.com --project <project>.";
362
- if (status === 401) return " Google rejected the access token: sign in again with `gcloud auth application-default login`, or check the job's Workload Identity Federation.";
363
- if (status === 403) return ` The Google identity needs ${permission}.`;
364
- if (status === 429) return " Secret Manager's quota is exhausted: try again later.";
365
- return "";
474
+ if (error.details?.some((detail) => detail.reason === "SERVICE_DISABLED")) return ["Enable the Secret Manager API in the project:", `gcloud services enable secretmanager.googleapis.com --project ${projectId}`];
475
+ if (status === 401) return ["Google rejected the access token.", ...signIn];
476
+ if (status === 403) return [`The identity needs ${permission}.`];
477
+ if (status === 429) return ["Secret Manager's quota is exhausted: try again later."];
478
+ return [];
366
479
  };
367
480
  /**
368
- * An error for a failed request: the HTTP status, Google's status and
369
- * message, which name resources but never a value, and what to fix.
481
+ * An error for a failed request on `resource`, a line each: the HTTP status,
482
+ * the resource, `notes`, and what to fix, or Google's own status and message,
483
+ * which name resources but never a value, when nothing here says what to fix.
370
484
  */
371
- const requestError = (action, response, permission) => {
485
+ const requestErrorOf = (signIn, projectId, action, resource, response, permission, notes = []) => {
372
486
  const { status, message } = response.error;
373
- const detail = [status, message?.slice(0, 300)].filter(Boolean).join(": ");
374
- return /* @__PURE__ */ new Error(`${ADAPTER_NAME} could not ${action} (${response.status}${detail ? ` ${detail}` : ""}).${hint(response, permission)}`);
487
+ const fix = hint(response, permission, signIn, projectId);
488
+ if (response.status === 401 && notes.length === 0) return failure(fix);
489
+ return failure([
490
+ `${ADAPTER_NAME} couldn't ${action} (${response.status}).`,
491
+ resourceLine(resource),
492
+ ...notes,
493
+ ...fix.length > 0 ? fix : [[status, message?.slice(0, 300)].filter(Boolean).join(": ")]
494
+ ]);
495
+ };
496
+ /** The line that names a secret: its resource name is a line's worth. */
497
+ const resourceLine = (secret) => `Secret: ${secret}`;
498
+ let metadataWarningFiltered = false;
499
+ /**
500
+ * Drops the one warning `gcp-metadata` emits when its probe for a Google
501
+ * runtime fails oddly: credentials are about to be reported as missing, and
502
+ * the warning has nothing to act on. It stays filtered for the process, as
503
+ * the library caches the probe; every other warning passes through.
504
+ * `METADATA_SERVER_DETECTION=none` would also silence it, but skips the probe,
505
+ * and with it the credentials of a Google runtime.
506
+ */
507
+ const filterMetadataWarning = () => {
508
+ if (metadataWarningFiltered) return;
509
+ metadataWarningFiltered = true;
510
+ const emitWarning = process.emitWarning;
511
+ process.emitWarning = ((warning, ...rest) => {
512
+ if (rest[0] === "MetadataLookupWarning") return;
513
+ Reflect.apply(emitWarning, process, [warning, ...rest]);
514
+ });
375
515
  };
376
516
  /** Masks a value in the CLI's output, which loads `@hot-updater/cli-tools`. */
377
517
  const mask = async (value) => {
@@ -408,10 +548,11 @@ const createAccessToken = (credentials, projectId) => {
408
548
  throw error;
409
549
  });
410
550
  const client = await auth;
551
+ filterMetadataWarning();
411
552
  try {
412
553
  return await client.getAccessToken() ?? void 0;
413
554
  } catch (error) {
414
- throw new Error(`${ADAPTER_NAME} found no Google credentials (${error instanceof Error ? error.message.split("\n")[0] : String(error)}). Sign in with \`gcloud auth application-default login\`, use google-github-actions/auth in CI, set GOOGLE_APPLICATION_CREDENTIALS, or set ${ACCESS_TOKEN_ENV_NAMES.join(" or ")} to an access token.`, { cause: error });
555
+ throw failure([`${ADAPTER_NAME} found no Google credentials.`, ...signInHint(void 0)], error);
415
556
  }
416
557
  };
417
558
  return async () => {
@@ -433,14 +574,19 @@ const createAccessToken = (credentials, projectId) => {
433
574
  */
434
575
  const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
435
576
  const accessToken = createAccessToken(credentials, projectId);
577
+ const requestError = (action, resource, response, permission, notes) => requestErrorOf(signInHint(credentials), projectId, action, resource, response, permission, notes);
436
578
  const projectPath = () => {
437
- if (typeof projectId !== "string" || !PROJECT_PATTERN.test(projectId)) throw new Error(`${ADAPTER_NAME} needs the Google Cloud project ID or number as projectId, and ${JSON.stringify(projectId)} is not one.`);
438
- if (!PREFIX_PATTERN.test(prefix)) throw new Error(`${ADAPTER_NAME}'s prefix takes letters, digits, "-", and "_", and ${JSON.stringify(prefix)} has others.`);
579
+ if (typeof projectId !== "string" || !PROJECT_PATTERN.test(projectId)) throw failure([`${ADAPTER_NAME} can't use the projectId ${JSON.stringify(projectId)}.`, "Set the Google Cloud project's ID or number."]);
580
+ if (!PREFIX_PATTERN.test(prefix)) throw failure([`${ADAPTER_NAME} can't use the prefix ${JSON.stringify(prefix)}.`, "It takes letters, digits, \"-\", and \"_\"."]);
439
581
  return `projects/${projectId}`;
440
582
  };
441
583
  const secretId = (name) => {
442
584
  const id = `${prefix}${name}`;
443
- if (!SECRET_ID_PATTERN.test(id)) throw new Error(`${ADAPTER_NAME} keeps ${JSON.stringify(name)} as the secret ID ${JSON.stringify(id)}, and Secret Manager's IDs take only letters, digits, "-", and "_", up to 255 characters.`);
585
+ if (!SECRET_ID_PATTERN.test(id)) throw failure([
586
+ `${ADAPTER_NAME} can't name a secret ${JSON.stringify(name)}.`,
587
+ `Secret: ${id}`,
588
+ "Secret Manager's IDs take up to 255 letters, digits, \"-\", and \"_\"."
589
+ ]);
444
590
  return id;
445
591
  };
446
592
  const request = async (token, method, path, body) => {
@@ -475,14 +621,18 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
475
621
  const accessLatest = async (token, secret) => {
476
622
  const response = await request(token, "GET", `${secret}/versions/latest:access`);
477
623
  if (response.status === 404) return void 0;
478
- if (!response.ok) throw requestError(`read ${secret}`, response, "roles/secretmanager.secretAccessor on the secret");
624
+ if (!response.ok) throw requestError("read", secret, response, "roles/secretmanager.secretAccessor on the secret");
479
625
  const body = isRecord(response.body) ? response.body : void 0;
480
626
  const payload = body?.payload;
481
627
  const data = isRecord(payload) ? payload.data : void 0;
482
- if (typeof data !== "string") throw new Error(`${ADAPTER_NAME} read no payload for ${secret}.`);
628
+ if (typeof data !== "string") throw failure([`${ADAPTER_NAME} read no payload.`, resourceLine(secret)]);
483
629
  const bytes = Buffer.from(data, "base64");
484
630
  const checksum = isRecord(payload) ? payload.dataCrc32c : void 0;
485
- if (checksum !== void 0 && Number(checksum) !== crc32c(bytes)) throw new Error(`${ADAPTER_NAME} read ${secret} with a checksum that does not match its payload.`);
631
+ if (checksum !== void 0 && Number(checksum) !== crc32c(bytes)) throw failure([
632
+ `${ADAPTER_NAME} can't trust what it read.`,
633
+ resourceLine(secret),
634
+ "Its checksum doesn't match its payload."
635
+ ]);
486
636
  const value = bytes.toString("utf8");
487
637
  await mask(value);
488
638
  return {
@@ -515,7 +665,7 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
515
665
  const readSecret = async (token, secret) => {
516
666
  const response = await request(token, "GET", secret);
517
667
  if (response.status === 404) return void 0;
518
- if (!response.ok) throw requestError(`read ${secret}`, response, "secretmanager.secrets.get on the secret");
668
+ if (!response.ok) throw requestError("read", secret, response, "secretmanager.secrets.get on the secret");
519
669
  return response.body;
520
670
  };
521
671
  const getOrCreateSecret = async (token, parent, id) => {
@@ -528,14 +678,19 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
528
678
  const raced = await readSecret(token, secret);
529
679
  if (raced) return raced;
530
680
  }
531
- throw requestError(`create ${secret}`, created, `secretmanager.secrets.create on ${parent}`);
681
+ throw requestError("create", secret, created, `secretmanager.secrets.create on ${parent}`);
532
682
  };
533
683
  const assertCanSet = async (token, secret) => {
534
684
  const response = await request(token, "POST", `${secret}:testIamPermissions`, { permissions: SET_PERMISSIONS });
535
- if (!response.ok) throw requestError(`check its permissions on ${secret}`, response, SET_PERMISSIONS.join(", "));
685
+ if (!response.ok) throw requestError("check its permissions", secret, response, SET_PERMISSIONS.join(", "));
536
686
  const held = isRecord(response.body) && Array.isArray(response.body.permissions) ? response.body.permissions : [];
537
687
  const missing = SET_PERMISSIONS.filter((name) => !held.includes(name));
538
- if (missing.length > 0) throw new Error(`${ADAPTER_NAME} stores a value as a new version of ${secret} and destroys the versions it added before, and the Google identity lacks ${missing.join(", ")} on it: grant a custom role with secretmanager.secrets.get, secretmanager.secrets.update, secretmanager.versions.add, secretmanager.versions.destroy, and secretmanager.versions.access on it, or roles/secretmanager.admin.`);
688
+ if (missing.length > 0) throw failure([
689
+ `${ADAPTER_NAME} can't store a value.`,
690
+ resourceLine(secret),
691
+ `The identity lacks ${missing.join(", ")} on it.`,
692
+ "Grant roles/secretmanager.admin."
693
+ ]);
539
694
  };
540
695
  /**
541
696
  * Destroys `version` of `secret`: true once it is destroyed, or already
@@ -568,10 +723,11 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
568
723
  /**
569
724
  * Adds `value` as the secret's newest version, creating the secret when
570
725
  * it is missing, and waits until the `latest` alias resolves to it. Then
571
- * it destroys the older versions this adapter added, which the secret's
572
- * `hot-updater-versions` annotation lists: versions added any other way
573
- * are never touched. The permissions this needs are checked before
574
- * anything is written. A version that could not be destroyed stays
726
+ * it destroys the versions this adapter added before the previous one,
727
+ * which the secret's `hot-updater-versions` annotation lists, keeping
728
+ * the previous value: versions added any other way are never touched.
729
+ * The permissions this needs are checked on the secret, once it exists,
730
+ * before any version is added. A version that could not be destroyed stays
575
731
  * listed for the next `set`. The annotation is updated against the
576
732
  * secret's etag, so a concurrent `set` loses no listed version. When
577
733
  * `latest` does not resolve to the new version in time, or the
@@ -582,7 +738,7 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
582
738
  const parent = projectPath();
583
739
  const id = secretId(name);
584
740
  const secret = `${parent}/secrets/${id}`;
585
- if (typeof value !== "string" || value === "") throw new Error(`${ADAPTER_NAME} cannot store an empty ${secret}.`);
741
+ if (typeof value !== "string" || value === "") throw failure([`${ADAPTER_NAME} can't store an empty value.`, resourceLine(secret)]);
586
742
  await mask(value);
587
743
  const token = await accessToken();
588
744
  const current = await getOrCreateSecret(token, parent, id);
@@ -593,17 +749,20 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
593
749
  dataCrc32c: String(crc32c(data))
594
750
  } });
595
751
  const version = versionOf(isRecord(added.body) ? added.body.name : void 0);
596
- if (!added.ok || !VERSION_ID_PATTERN.test(version)) throw requestError(`add a version to ${secret}`, added, "secretmanager.versions.add on the secret");
752
+ if (!added.ok || !VERSION_ID_PATTERN.test(version)) throw requestError("add a version", secret, added, "secretmanager.versions.add on the secret");
753
+ const own = trackedVersions(current).filter((entry) => Number(entry) < Number(version));
754
+ const previous = own.reduce((newest, entry) => newest === void 0 || Number(entry) > Number(newest) ? entry : newest, void 0);
597
755
  const visible = await waitForLatest(token, secret, version);
598
756
  const destroyed = /* @__PURE__ */ new Set();
599
757
  if (visible) {
600
- const older = trackedVersions(current).filter((entry) => Number(entry) < Number(version));
758
+ const older = own.filter((entry) => entry !== previous);
601
759
  const results = await Promise.all(older.map((entry) => destroy(token, secret, entry)));
602
760
  older.forEach((entry, index) => {
603
761
  if (results[index]) destroyed.add(entry);
604
762
  });
605
763
  }
606
- const notListed = `list version ${version}, which it stored, in ${secret}'s ${VERSIONS_ANNOTATION} annotation, so the next set will not destroy it`;
764
+ const notListed = `record version ${version}, which it stored`;
765
+ const notDestroyed = `The next set won't destroy it: ${VERSIONS_ANNOTATION} misses it.`;
607
766
  let base = current;
608
767
  let updated;
609
768
  try {
@@ -612,7 +771,11 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
612
771
  await delay(LATEST_RETRY_DELAYS_MS[attempt - 1] ?? 0);
613
772
  base = await readSecret(token, secret) ?? {};
614
773
  }
615
- const listed = [.../* @__PURE__ */ new Set([version, ...trackedVersions(base)])].filter((entry) => !destroyed.has(entry));
774
+ const listed = [.../* @__PURE__ */ new Set([
775
+ version,
776
+ ...previous === void 0 ? [] : [previous],
777
+ ...trackedVersions(base)
778
+ ])].filter((entry) => !destroyed.has(entry));
616
779
  updated = await request(token, "PATCH", `${secret}?updateMask=annotations`, {
617
780
  ...base.etag === void 0 ? {} : { etag: base.etag },
618
781
  annotations: {
@@ -623,14 +786,24 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
623
786
  if (updated.error.status !== "FAILED_PRECONDITION") break;
624
787
  }
625
788
  } catch (error) {
626
- throw new Error(`${ADAPTER_NAME} could not ${notListed} (${error instanceof Error ? error.message : String(error)}).`, { cause: error });
789
+ throw failure([
790
+ `${ADAPTER_NAME} couldn't ${notListed}.`,
791
+ resourceLine(secret),
792
+ error instanceof Error ? error.message : String(error),
793
+ notDestroyed
794
+ ], error);
627
795
  }
628
- if (!updated?.ok) throw requestError(notListed, updated, "secretmanager.secrets.update on the secret");
629
- if (!visible) throw new Error(`${ADAPTER_NAME} stored ${secret} as version ${version}, and its latest alias does not resolve to that version yet, so it kept the versions it added before; the next set destroys them.`);
796
+ if (!updated?.ok) throw requestError(notListed, secret, updated, "secretmanager.secrets.update on the secret", [notDestroyed]);
797
+ if (!visible) throw failure([
798
+ `${ADAPTER_NAME} stored version ${version}.`,
799
+ resourceLine(secret),
800
+ "Its latest alias doesn't resolve to that version yet.",
801
+ "It kept the versions it added before: the next set destroys them."
802
+ ]);
630
803
  },
631
804
  describe: (name) => {
632
805
  const id = `${prefix}${name}`;
633
- return `projects/${projectId}/secrets/${id} (https://console.cloud.google.com/security/secret-manager/secret/${encodeURIComponent(id)}/versions?project=${encodeURIComponent(projectId)})`;
806
+ return `the secret ${JSON.stringify(id)} in Google Secret Manager (https://console.cloud.google.com/security/secret-manager/secret/${encodeURIComponent(id)}/versions?project=${encodeURIComponent(projectId)})`;
634
807
  }
635
808
  };
636
809
  };
package/dist/index.d.cts CHANGED
@@ -11,9 +11,8 @@ type FirebaseDatabaseConfig = AppOptions & {
11
11
  readonly collection?: string;
12
12
  /**
13
13
  * Firestore bills each document write, so Insights' aggregates are
14
- * batched: through log rows a compaction merges (the default), or
15
- * `{ mode: "memory" }` on a long-lived server. `false` commits them with
16
- * each event.
14
+ * batched: through log rows a compaction merges (the default). `false` commits
15
+ * them with each event.
17
16
  */
18
17
  readonly aggregateBatching?: EngineDatabase["aggregateBatching"] | false;
19
18
  };
@@ -37,7 +36,7 @@ interface FirebaseStorageConfig extends AppOptions {
37
36
  /** Firebase signed URL lifetime in seconds. @default 3600 */
38
37
  signedUrlExpiresIn?: number;
39
38
  }
40
- declare const firebaseStorage: (config: FirebaseStorageConfig) => StorageAdapterWith<"put" | "get" | "getDownloadUrl" | "exists" | "delete">;
39
+ declare const firebaseStorage: (config: FirebaseStorageConfig) => StorageAdapterWith<"put" | "get" | "getDownloadUrl" | "exists" | "delete" | "listObjects" | "deleteObjects">;
41
40
  //#endregion
42
41
  //#region src/secretManager.d.ts
43
42
  /**
@@ -56,7 +55,7 @@ interface SecretManagerOptions {
56
55
  /** The Google Cloud project ID or number that holds the secrets. */
57
56
  readonly projectId: string;
58
57
  /**
59
- * Put before each name to make its secret ID, so `secret:asc-api-key`
58
+ * Put before each name to make its secret ID, so `secret("asc-api-key")`
60
59
  * reads `hot-updater-asc-api-key`. Letters, digits, `-`, and `_`.
61
60
  *
62
61
  * @default "hot-updater-"
package/dist/index.d.mts CHANGED
@@ -11,9 +11,8 @@ type FirebaseDatabaseConfig = AppOptions & {
11
11
  readonly collection?: string;
12
12
  /**
13
13
  * Firestore bills each document write, so Insights' aggregates are
14
- * batched: through log rows a compaction merges (the default), or
15
- * `{ mode: "memory" }` on a long-lived server. `false` commits them with
16
- * each event.
14
+ * batched: through log rows a compaction merges (the default). `false` commits
15
+ * them with each event.
17
16
  */
18
17
  readonly aggregateBatching?: EngineDatabase["aggregateBatching"] | false;
19
18
  };
@@ -37,7 +36,7 @@ interface FirebaseStorageConfig extends AppOptions {
37
36
  /** Firebase signed URL lifetime in seconds. @default 3600 */
38
37
  signedUrlExpiresIn?: number;
39
38
  }
40
- declare const firebaseStorage: (config: FirebaseStorageConfig) => StorageAdapterWith<"put" | "get" | "getDownloadUrl" | "exists" | "delete">;
39
+ declare const firebaseStorage: (config: FirebaseStorageConfig) => StorageAdapterWith<"put" | "get" | "getDownloadUrl" | "exists" | "delete" | "listObjects" | "deleteObjects">;
41
40
  //#endregion
42
41
  //#region src/secretManager.d.ts
43
42
  /**
@@ -56,7 +55,7 @@ interface SecretManagerOptions {
56
55
  /** The Google Cloud project ID or number that holds the secrets. */
57
56
  readonly projectId: string;
58
57
  /**
59
- * Put before each name to make its secret ID, so `secret:asc-api-key`
58
+ * Put before each name to make its secret ID, so `secret("asc-api-key")`
60
59
  * reads `hot-updater-asc-api-key`. Letters, digits, `-`, and `_`.
61
60
  *
62
61
  * @default "hot-updater-"