@hot-updater/firebase 1.2.0-rc.3 → 1.2.0-rc.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -201,11 +201,14 @@ const firebaseDatabase = (config) => ({
201
201
  //#region src/firebaseStorage.ts
202
202
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
203
203
  const MAX_CACHED_SIGNED_URLS = 1e4;
204
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
205
+ const DELETE_CONCURRENCY = 16;
204
206
  const firebaseStorage = (config) => {
205
207
  const app = getApps().length ? getApp() : initializeApp(config);
206
208
  let opened;
207
209
  const bucket = () => opened ??= getStorage(app).bucket(config.storageBucket);
208
210
  const getStorageKey = createStorageKeyBuilder(config.basePath);
211
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
209
212
  /**
210
213
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
211
214
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -294,6 +297,39 @@ const firebaseStorage = (config) => {
294
297
  const { key } = parseAndValidate(storageUri);
295
298
  await bucket().file(key).delete({ ignoreNotFound: true });
296
299
  return { deleted: true };
300
+ },
301
+ async listObjects(prefix) {
302
+ const folder = getStorageKey(prefix ?? "");
303
+ const [files] = await bucket().getFiles({
304
+ autoPaginate: true,
305
+ prefix: folder ? `${folder}/` : ""
306
+ });
307
+ const objects = [];
308
+ for (const file of files) {
309
+ if (!file.name.startsWith(basePrefix)) continue;
310
+ let storageUri;
311
+ try {
312
+ storageUri = createStorageUri({
313
+ bucket: config.storageBucket,
314
+ key: file.name,
315
+ protocol: "gs"
316
+ });
317
+ } catch {
318
+ continue;
319
+ }
320
+ const { size, updated } = file.metadata;
321
+ objects.push({
322
+ key: file.name.slice(basePrefix.length),
323
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
324
+ size: Number(size ?? 0),
325
+ storageUri
326
+ });
327
+ }
328
+ return objects;
329
+ },
330
+ async deleteObjects(relativeKeys) {
331
+ const keys = relativeKeys.map((key) => getStorageKey(key));
332
+ 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 })));
297
333
  }
298
334
  });
299
335
  };
@@ -355,22 +391,61 @@ const crc32c = (bytes) => {
355
391
  /** The version IDs the secret's annotation lists. */
356
392
  const trackedVersions = (secret) => (secret.annotations?.[VERSIONS_ANNOTATION] ?? "").split(",").map((entry) => entry.trim()).filter((entry) => VERSION_ID_PATTERN.test(entry));
357
393
  const versionOf = (name) => typeof name === "string" ? name.slice(name.lastIndexOf("/") + 1) : "";
358
- const hint = (response, permission) => {
394
+ /** An error of one line each, for a terminal. */
395
+ const failure = (lines, cause) => new Error(lines.join("\n"), cause === void 0 ? void 0 : { cause });
396
+ /**
397
+ * The one step that can fix the credentials in use, by the order they're
398
+ * tried: signing in with gcloud changes nothing while a variable comes first.
399
+ */
400
+ const signInHint = (credentials) => {
401
+ if (credentials) return [`Check the credentials passed to ${ADAPTER_NAME}().`];
402
+ const variable = ACCESS_TOKEN_ENV_NAMES.find((name) => process.env[name]?.trim()) ?? (process.env["GOOGLE_APPLICATION_CREDENTIALS"]?.trim() ? "GOOGLE_APPLICATION_CREDENTIALS" : void 0);
403
+ if (variable) return [`Fix or unset ${variable}.`];
404
+ return process.env["CI"] ? ["Use google-github-actions/auth."] : ["Sign in:", "gcloud auth application-default login"];
405
+ };
406
+ const hint = (response, permission, signIn, projectId) => {
359
407
  const { status, error } = response;
360
- 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>.";
361
- 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.";
362
- if (status === 403) return ` The Google identity needs ${permission}.`;
363
- if (status === 429) return " Secret Manager's quota is exhausted: try again later.";
364
- return "";
408
+ 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}`];
409
+ if (status === 401) return ["Google rejected the access token.", ...signIn];
410
+ if (status === 403) return [`The identity needs ${permission}.`];
411
+ if (status === 429) return ["Secret Manager's quota is exhausted: try again later."];
412
+ return [];
365
413
  };
366
414
  /**
367
- * An error for a failed request: the HTTP status, Google's status and
368
- * message, which name resources but never a value, and what to fix.
415
+ * An error for a failed request on `resource`, a line each: the HTTP status,
416
+ * the resource, `notes`, and what to fix, or Google's own status and message,
417
+ * which name resources but never a value, when nothing here says what to fix.
369
418
  */
370
- const requestError = (action, response, permission) => {
419
+ const requestErrorOf = (signIn, projectId, action, resource, response, permission, notes = []) => {
371
420
  const { status, message } = response.error;
372
- const detail = [status, message?.slice(0, 300)].filter(Boolean).join(": ");
373
- return /* @__PURE__ */ new Error(`${ADAPTER_NAME} could not ${action} (${response.status}${detail ? ` ${detail}` : ""}).${hint(response, permission)}`);
421
+ const fix = hint(response, permission, signIn, projectId);
422
+ if (response.status === 401 && notes.length === 0) return failure(fix);
423
+ return failure([
424
+ `${ADAPTER_NAME} couldn't ${action} (${response.status}).`,
425
+ resourceLine(resource),
426
+ ...notes,
427
+ ...fix.length > 0 ? fix : [[status, message?.slice(0, 300)].filter(Boolean).join(": ")]
428
+ ]);
429
+ };
430
+ /** The line that names a secret: its resource name is a line's worth. */
431
+ const resourceLine = (secret) => `Secret: ${secret}`;
432
+ let metadataWarningFiltered = false;
433
+ /**
434
+ * Drops the one warning `gcp-metadata` emits when its probe for a Google
435
+ * runtime fails oddly: credentials are about to be reported as missing, and
436
+ * the warning has nothing to act on. It stays filtered for the process, as
437
+ * the library caches the probe; every other warning passes through.
438
+ * `METADATA_SERVER_DETECTION=none` would also silence it, but skips the probe,
439
+ * and with it the credentials of a Google runtime.
440
+ */
441
+ const filterMetadataWarning = () => {
442
+ if (metadataWarningFiltered) return;
443
+ metadataWarningFiltered = true;
444
+ const emitWarning = process.emitWarning;
445
+ process.emitWarning = ((warning, ...rest) => {
446
+ if (rest[0] === "MetadataLookupWarning") return;
447
+ Reflect.apply(emitWarning, process, [warning, ...rest]);
448
+ });
374
449
  };
375
450
  /** Masks a value in the CLI's output, which loads `@hot-updater/cli-tools`. */
376
451
  const mask = async (value) => {
@@ -407,10 +482,11 @@ const createAccessToken = (credentials, projectId) => {
407
482
  throw error;
408
483
  });
409
484
  const client = await auth;
485
+ filterMetadataWarning();
410
486
  try {
411
487
  return await client.getAccessToken() ?? void 0;
412
488
  } catch (error) {
413
- 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 });
489
+ throw failure([`${ADAPTER_NAME} found no Google credentials.`, ...signInHint(void 0)], error);
414
490
  }
415
491
  };
416
492
  return async () => {
@@ -432,14 +508,19 @@ const createAccessToken = (credentials, projectId) => {
432
508
  */
433
509
  const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
434
510
  const accessToken = createAccessToken(credentials, projectId);
511
+ const requestError = (action, resource, response, permission, notes) => requestErrorOf(signInHint(credentials), projectId, action, resource, response, permission, notes);
435
512
  const projectPath = () => {
436
- 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.`);
437
- if (!PREFIX_PATTERN.test(prefix)) throw new Error(`${ADAPTER_NAME}'s prefix takes letters, digits, "-", and "_", and ${JSON.stringify(prefix)} has others.`);
513
+ 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."]);
514
+ if (!PREFIX_PATTERN.test(prefix)) throw failure([`${ADAPTER_NAME} can't use the prefix ${JSON.stringify(prefix)}.`, "It takes letters, digits, \"-\", and \"_\"."]);
438
515
  return `projects/${projectId}`;
439
516
  };
440
517
  const secretId = (name) => {
441
518
  const id = `${prefix}${name}`;
442
- 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.`);
519
+ if (!SECRET_ID_PATTERN.test(id)) throw failure([
520
+ `${ADAPTER_NAME} can't name a secret ${JSON.stringify(name)}.`,
521
+ `Secret: ${id}`,
522
+ "Secret Manager's IDs take up to 255 letters, digits, \"-\", and \"_\"."
523
+ ]);
443
524
  return id;
444
525
  };
445
526
  const request = async (token, method, path, body) => {
@@ -474,14 +555,18 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
474
555
  const accessLatest = async (token, secret) => {
475
556
  const response = await request(token, "GET", `${secret}/versions/latest:access`);
476
557
  if (response.status === 404) return void 0;
477
- if (!response.ok) throw requestError(`read ${secret}`, response, "roles/secretmanager.secretAccessor on the secret");
558
+ if (!response.ok) throw requestError("read", secret, response, "roles/secretmanager.secretAccessor on the secret");
478
559
  const body = isRecord(response.body) ? response.body : void 0;
479
560
  const payload = body?.payload;
480
561
  const data = isRecord(payload) ? payload.data : void 0;
481
- if (typeof data !== "string") throw new Error(`${ADAPTER_NAME} read no payload for ${secret}.`);
562
+ if (typeof data !== "string") throw failure([`${ADAPTER_NAME} read no payload.`, resourceLine(secret)]);
482
563
  const bytes = Buffer.from(data, "base64");
483
564
  const checksum = isRecord(payload) ? payload.dataCrc32c : void 0;
484
- if (checksum !== void 0 && Number(checksum) !== crc32c(bytes)) throw new Error(`${ADAPTER_NAME} read ${secret} with a checksum that does not match its payload.`);
565
+ if (checksum !== void 0 && Number(checksum) !== crc32c(bytes)) throw failure([
566
+ `${ADAPTER_NAME} can't trust what it read.`,
567
+ resourceLine(secret),
568
+ "Its checksum doesn't match its payload."
569
+ ]);
485
570
  const value = bytes.toString("utf8");
486
571
  await mask(value);
487
572
  return {
@@ -514,7 +599,7 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
514
599
  const readSecret = async (token, secret) => {
515
600
  const response = await request(token, "GET", secret);
516
601
  if (response.status === 404) return void 0;
517
- if (!response.ok) throw requestError(`read ${secret}`, response, "secretmanager.secrets.get on the secret");
602
+ if (!response.ok) throw requestError("read", secret, response, "secretmanager.secrets.get on the secret");
518
603
  return response.body;
519
604
  };
520
605
  const getOrCreateSecret = async (token, parent, id) => {
@@ -527,14 +612,19 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
527
612
  const raced = await readSecret(token, secret);
528
613
  if (raced) return raced;
529
614
  }
530
- throw requestError(`create ${secret}`, created, `secretmanager.secrets.create on ${parent}`);
615
+ throw requestError("create", secret, created, `secretmanager.secrets.create on ${parent}`);
531
616
  };
532
617
  const assertCanSet = async (token, secret) => {
533
618
  const response = await request(token, "POST", `${secret}:testIamPermissions`, { permissions: SET_PERMISSIONS });
534
- if (!response.ok) throw requestError(`check its permissions on ${secret}`, response, SET_PERMISSIONS.join(", "));
619
+ if (!response.ok) throw requestError("check its permissions", secret, response, SET_PERMISSIONS.join(", "));
535
620
  const held = isRecord(response.body) && Array.isArray(response.body.permissions) ? response.body.permissions : [];
536
621
  const missing = SET_PERMISSIONS.filter((name) => !held.includes(name));
537
- 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.`);
622
+ if (missing.length > 0) throw failure([
623
+ `${ADAPTER_NAME} can't store a value.`,
624
+ resourceLine(secret),
625
+ `The identity lacks ${missing.join(", ")} on it.`,
626
+ "Grant roles/secretmanager.admin."
627
+ ]);
538
628
  };
539
629
  /**
540
630
  * Destroys `version` of `secret`: true once it is destroyed, or already
@@ -567,10 +657,11 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
567
657
  /**
568
658
  * Adds `value` as the secret's newest version, creating the secret when
569
659
  * it is missing, and waits until the `latest` alias resolves to it. Then
570
- * it destroys the older versions this adapter added, which the secret's
571
- * `hot-updater-versions` annotation lists: versions added any other way
572
- * are never touched. The permissions this needs are checked before
573
- * anything is written. A version that could not be destroyed stays
660
+ * it destroys the versions this adapter added before the previous one,
661
+ * which the secret's `hot-updater-versions` annotation lists, keeping
662
+ * the previous value: versions added any other way are never touched.
663
+ * The permissions this needs are checked on the secret, once it exists,
664
+ * before any version is added. A version that could not be destroyed stays
574
665
  * listed for the next `set`. The annotation is updated against the
575
666
  * secret's etag, so a concurrent `set` loses no listed version. When
576
667
  * `latest` does not resolve to the new version in time, or the
@@ -581,7 +672,7 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
581
672
  const parent = projectPath();
582
673
  const id = secretId(name);
583
674
  const secret = `${parent}/secrets/${id}`;
584
- if (typeof value !== "string" || value === "") throw new Error(`${ADAPTER_NAME} cannot store an empty ${secret}.`);
675
+ if (typeof value !== "string" || value === "") throw failure([`${ADAPTER_NAME} can't store an empty value.`, resourceLine(secret)]);
585
676
  await mask(value);
586
677
  const token = await accessToken();
587
678
  const current = await getOrCreateSecret(token, parent, id);
@@ -592,17 +683,20 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
592
683
  dataCrc32c: String(crc32c(data))
593
684
  } });
594
685
  const version = versionOf(isRecord(added.body) ? added.body.name : void 0);
595
- if (!added.ok || !VERSION_ID_PATTERN.test(version)) throw requestError(`add a version to ${secret}`, added, "secretmanager.versions.add on the secret");
686
+ if (!added.ok || !VERSION_ID_PATTERN.test(version)) throw requestError("add a version", secret, added, "secretmanager.versions.add on the secret");
687
+ const own = trackedVersions(current).filter((entry) => Number(entry) < Number(version));
688
+ const previous = own.reduce((newest, entry) => newest === void 0 || Number(entry) > Number(newest) ? entry : newest, void 0);
596
689
  const visible = await waitForLatest(token, secret, version);
597
690
  const destroyed = /* @__PURE__ */ new Set();
598
691
  if (visible) {
599
- const older = trackedVersions(current).filter((entry) => Number(entry) < Number(version));
692
+ const older = own.filter((entry) => entry !== previous);
600
693
  const results = await Promise.all(older.map((entry) => destroy(token, secret, entry)));
601
694
  older.forEach((entry, index) => {
602
695
  if (results[index]) destroyed.add(entry);
603
696
  });
604
697
  }
605
- const notListed = `list version ${version}, which it stored, in ${secret}'s ${VERSIONS_ANNOTATION} annotation, so the next set will not destroy it`;
698
+ const notListed = `record version ${version}, which it stored`;
699
+ const notDestroyed = `The next set won't destroy it: ${VERSIONS_ANNOTATION} misses it.`;
606
700
  let base = current;
607
701
  let updated;
608
702
  try {
@@ -611,7 +705,11 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
611
705
  await delay(LATEST_RETRY_DELAYS_MS[attempt - 1] ?? 0);
612
706
  base = await readSecret(token, secret) ?? {};
613
707
  }
614
- const listed = [.../* @__PURE__ */ new Set([version, ...trackedVersions(base)])].filter((entry) => !destroyed.has(entry));
708
+ const listed = [.../* @__PURE__ */ new Set([
709
+ version,
710
+ ...previous === void 0 ? [] : [previous],
711
+ ...trackedVersions(base)
712
+ ])].filter((entry) => !destroyed.has(entry));
615
713
  updated = await request(token, "PATCH", `${secret}?updateMask=annotations`, {
616
714
  ...base.etag === void 0 ? {} : { etag: base.etag },
617
715
  annotations: {
@@ -622,14 +720,24 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
622
720
  if (updated.error.status !== "FAILED_PRECONDITION") break;
623
721
  }
624
722
  } catch (error) {
625
- throw new Error(`${ADAPTER_NAME} could not ${notListed} (${error instanceof Error ? error.message : String(error)}).`, { cause: error });
723
+ throw failure([
724
+ `${ADAPTER_NAME} couldn't ${notListed}.`,
725
+ resourceLine(secret),
726
+ error instanceof Error ? error.message : String(error),
727
+ notDestroyed
728
+ ], error);
626
729
  }
627
- if (!updated?.ok) throw requestError(notListed, updated, "secretmanager.secrets.update on the secret");
628
- 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.`);
730
+ if (!updated?.ok) throw requestError(notListed, secret, updated, "secretmanager.secrets.update on the secret", [notDestroyed]);
731
+ if (!visible) throw failure([
732
+ `${ADAPTER_NAME} stored version ${version}.`,
733
+ resourceLine(secret),
734
+ "Its latest alias doesn't resolve to that version yet.",
735
+ "It kept the versions it added before: the next set destroys them."
736
+ ]);
629
737
  },
630
738
  describe: (name) => {
631
739
  const id = `${prefix}${name}`;
632
- return `projects/${projectId}/secrets/${id} (https://console.cloud.google.com/security/secret-manager/secret/${encodeURIComponent(id)}/versions?project=${encodeURIComponent(projectId)})`;
740
+ 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)})`;
633
741
  }
634
742
  };
635
743
  };
@@ -7202,15 +7202,22 @@ const prepareFirebaseTemplate = async (firebaseRootDir) => {
7202
7202
  };
7203
7203
  //#endregion
7204
7204
  //#region iac/configTemplate.ts
7205
- const getConfigScaffold = (build) => {
7205
+ /**
7206
+ * The config init writes. With the `resources` init set up, it names them;
7207
+ * without them, as the agent scaffold writes it, it reads them from the
7208
+ * environment. Either way it signs in with each person's own Google
7209
+ * credentials (ADC), so it reads no secret.
7210
+ */
7211
+ const getConfigScaffold = (build, resources) => {
7212
+ const projectId = resources === void 0 ? "process.env.HOT_UPDATER_FIREBASE_PROJECT_ID!" : JSON.stringify(resources.projectId);
7206
7213
  const storageConfig = {
7207
7214
  imports: [{
7208
7215
  pkg: "@hot-updater/firebase",
7209
7216
  named: ["firebaseStorage"]
7210
7217
  }],
7211
7218
  configString: `firebaseStorage({
7212
- projectId: process.env.HOT_UPDATER_FIREBASE_PROJECT_ID!,
7213
- storageBucket: process.env.HOT_UPDATER_FIREBASE_STORAGE_BUCKET!,
7219
+ projectId: ${projectId},
7220
+ storageBucket: ${resources === void 0 ? "process.env.HOT_UPDATER_FIREBASE_STORAGE_BUCKET!" : JSON.stringify(resources.storageBucket)},
7214
7221
  credential,
7215
7222
  })`
7216
7223
  };
@@ -7220,8 +7227,8 @@ const getConfigScaffold = (build) => {
7220
7227
  named: ["firebaseDatabase"]
7221
7228
  }],
7222
7229
  configString: `firebaseDatabase({
7223
- projectId: process.env.HOT_UPDATER_FIREBASE_PROJECT_ID!,
7224
- databaseId: process.env.HOT_UPDATER_FIREBASE_DATABASE_ID,
7230
+ projectId: ${projectId},
7231
+ databaseId: ${resources === void 0 ? "process.env.HOT_UPDATER_FIREBASE_DATABASE_ID" : JSON.stringify(resources.databaseId)},
7225
7232
  credential,
7226
7233
  })`
7227
7234
  };
@@ -7315,7 +7322,11 @@ const setEnv = async ({ applicationCredentials, databaseId, projectId, storageBu
7315
7322
  HOT_UPDATER_FIREBASE_STORAGE_BUCKET: storageBucket
7316
7323
  }, ".env.hotupdater", { preserveKeys: applicationCredentials ? [] : [initProvider.inputs.applicationCredentials.envKey] });
7317
7324
  _hot_updater_cli_tools.p.log.success("Firebase credentials have been successfully configured.");
7318
- await (0, _hot_updater_cli_tools.writeHotUpdaterFiles)(getConfigScaffold(build), {
7325
+ await (0, _hot_updater_cli_tools.writeHotUpdaterFiles)(getConfigScaffold(build, {
7326
+ projectId,
7327
+ storageBucket,
7328
+ databaseId
7329
+ }), {
7319
7330
  cwd: process.cwd(),
7320
7331
  settings: "Firebase"
7321
7332
  });
@@ -7744,9 +7755,9 @@ const checkIfGcloudCliInstalled = async () => {
7744
7755
  return false;
7745
7756
  }
7746
7757
  };
7747
- const runInit = async ({ build, envFile }) => {
7758
+ const runInit = async ({ build, envFile, secretsEnv }) => {
7748
7759
  const nonInteractive = envFile !== void 0;
7749
- const initEnvSources = await (0, _hot_updater_cli_tools.readHotUpdaterInitEnv)(process.cwd(), envFile);
7760
+ const initEnvSources = await (0, _hot_updater_cli_tools.readHotUpdaterInitEnv)(process.cwd(), envFile, secretsEnv);
7750
7761
  const { managedEnv } = initEnvSources;
7751
7762
  const initInputEnv = (0, _hot_updater_cli_tools.getHotUpdaterInitInputEnv)(initEnvSources, nonInteractive);
7752
7763
  const savedInputs = resolveFirebaseInitInputs(initInputEnv);
@@ -7812,7 +7823,7 @@ const runInit = async ({ build, envFile }) => {
7812
7823
  });
7813
7824
  await (0, _hot_updater_cli_tools.makeEnv)(persistedInputs);
7814
7825
  await removeTmpDir();
7815
- return;
7826
+ return null;
7816
7827
  }
7817
7828
  const functionsCode = (0, _hot_updater_cli_tools.transformEnv)(functionsIndexPath, {
7818
7829
  REGION: currentRegion,
@@ -7843,7 +7854,7 @@ const runInit = async ({ build, envFile }) => {
7843
7854
  }]);
7844
7855
  await deployFirestore(tmpDir, initializeVariable.databaseId, nonInteractive, cliEnv);
7845
7856
  const credential = applicationCredentials ? (0, firebase_admin_app.cert)(JSON.parse(await fs.default.promises.readFile(applicationCredentials, "utf-8"))) : (0, firebase_admin_app.applicationDefault)();
7846
- const existingApps = new Set((0, firebase_admin_app.getApps)());
7857
+ await Promise.all((0, firebase_admin_app.getApps)().map((app) => (0, firebase_admin_app.deleteApp)(app)));
7847
7858
  const databaseConfig = {
7848
7859
  credential,
7849
7860
  databaseId: initializeVariable.databaseId,
@@ -7868,7 +7879,7 @@ const runInit = async ({ build, envFile }) => {
7868
7879
  if (clientCredential !== void 0) await (0, _hot_updater_cli_tools.makeEnv)({ [clientCredential.env]: clientCredential.value });
7869
7880
  } finally {
7870
7881
  await database.dispose?.();
7871
- await Promise.all((0, firebase_admin_app.getApps)().filter((app) => !existingApps.has(app)).map((app) => (0, firebase_admin_app.deleteApp)(app)));
7882
+ await Promise.all((0, firebase_admin_app.getApps)().map((app) => (0, firebase_admin_app.deleteApp)(app)));
7872
7883
  }
7873
7884
  await deployFunctions(tmpDir, nonInteractive, cliEnv);
7874
7885
  await _hot_updater_cli_tools.p.tasks([{
@@ -7915,9 +7926,7 @@ const runInit = async ({ build, envFile }) => {
7915
7926
  }
7916
7927
  await printTemplate(clientCredential, initializeVariable.projectId, currentRegion, server.clientPlugins, cliEnv);
7917
7928
  await removeTmpDir();
7918
- _hot_updater_cli_tools.p.log.message(`Next step: ${(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/firebase#step-3-add-hotupdater-to-your-project")}`);
7919
- if (!applicationCredentials) _hot_updater_cli_tools.p.log.message("Next step: Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater");
7920
- _hot_updater_cli_tools.p.log.success("Done! 🎉");
7929
+ return { nextSteps: [(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/firebase#step-3-add-hotupdater-to-your-project"), ...applicationCredentials ? [] : ["Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater"]] };
7921
7930
  };
7922
7931
  //#endregion
7923
7932
  exports.initProvider = initProvider;
@@ -1,4 +1,4 @@
1
- import { RunInitOptions } from "@hot-updater/cli-tools";
1
+ import { RunInitOptions, RunInitResult } from "@hot-updater/cli-tools";
2
2
  //#region iac/init/index.d.ts
3
3
  declare const initProvider: {
4
4
  readonly label: "Firebase";
@@ -86,6 +86,6 @@ declare const mergeIndexes: (originalIndexes: {
86
86
  };
87
87
  /** Points the template's `firebase.json` at the database init sets up. */
88
88
  declare const setFirestoreDatabase: (cwd: string, databaseId: string) => Promise<void>;
89
- declare const runInit: ({ build, envFile }: RunInitOptions) => Promise<void>;
89
+ declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
90
90
  //#endregion
91
91
  export { initProvider, mergeIndexes, runInit, setFirestoreDatabase };
@@ -1,4 +1,4 @@
1
- import { RunInitOptions } from "@hot-updater/cli-tools";
1
+ import { RunInitOptions, RunInitResult } from "@hot-updater/cli-tools";
2
2
  //#region iac/init/index.d.ts
3
3
  declare const initProvider: {
4
4
  readonly label: "Firebase";
@@ -86,6 +86,6 @@ declare const mergeIndexes: (originalIndexes: {
86
86
  };
87
87
  /** Points the template's `firebase.json` at the database init sets up. */
88
88
  declare const setFirestoreDatabase: (cwd: string, databaseId: string) => Promise<void>;
89
- declare const runInit: ({ build, envFile }: RunInitOptions) => Promise<void>;
89
+ declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
90
90
  //#endregion
91
91
  export { initProvider, mergeIndexes, runInit, setFirestoreDatabase };
@@ -7195,15 +7195,22 @@ const prepareFirebaseTemplate = async (firebaseRootDir) => {
7195
7195
  };
7196
7196
  //#endregion
7197
7197
  //#region iac/configTemplate.ts
7198
- const getConfigScaffold = (build) => {
7198
+ /**
7199
+ * The config init writes. With the `resources` init set up, it names them;
7200
+ * without them, as the agent scaffold writes it, it reads them from the
7201
+ * environment. Either way it signs in with each person's own Google
7202
+ * credentials (ADC), so it reads no secret.
7203
+ */
7204
+ const getConfigScaffold = (build, resources) => {
7205
+ const projectId = resources === void 0 ? "process.env.HOT_UPDATER_FIREBASE_PROJECT_ID!" : JSON.stringify(resources.projectId);
7199
7206
  const storageConfig = {
7200
7207
  imports: [{
7201
7208
  pkg: "@hot-updater/firebase",
7202
7209
  named: ["firebaseStorage"]
7203
7210
  }],
7204
7211
  configString: `firebaseStorage({
7205
- projectId: process.env.HOT_UPDATER_FIREBASE_PROJECT_ID!,
7206
- storageBucket: process.env.HOT_UPDATER_FIREBASE_STORAGE_BUCKET!,
7212
+ projectId: ${projectId},
7213
+ storageBucket: ${resources === void 0 ? "process.env.HOT_UPDATER_FIREBASE_STORAGE_BUCKET!" : JSON.stringify(resources.storageBucket)},
7207
7214
  credential,
7208
7215
  })`
7209
7216
  };
@@ -7213,8 +7220,8 @@ const getConfigScaffold = (build) => {
7213
7220
  named: ["firebaseDatabase"]
7214
7221
  }],
7215
7222
  configString: `firebaseDatabase({
7216
- projectId: process.env.HOT_UPDATER_FIREBASE_PROJECT_ID!,
7217
- databaseId: process.env.HOT_UPDATER_FIREBASE_DATABASE_ID,
7223
+ projectId: ${projectId},
7224
+ databaseId: ${resources === void 0 ? "process.env.HOT_UPDATER_FIREBASE_DATABASE_ID" : JSON.stringify(resources.databaseId)},
7218
7225
  credential,
7219
7226
  })`
7220
7227
  };
@@ -7308,7 +7315,11 @@ const setEnv = async ({ applicationCredentials, databaseId, projectId, storageBu
7308
7315
  HOT_UPDATER_FIREBASE_STORAGE_BUCKET: storageBucket
7309
7316
  }, ".env.hotupdater", { preserveKeys: applicationCredentials ? [] : [initProvider.inputs.applicationCredentials.envKey] });
7310
7317
  p.log.success("Firebase credentials have been successfully configured.");
7311
- await writeHotUpdaterFiles(getConfigScaffold(build), {
7318
+ await writeHotUpdaterFiles(getConfigScaffold(build, {
7319
+ projectId,
7320
+ storageBucket,
7321
+ databaseId
7322
+ }), {
7312
7323
  cwd: process.cwd(),
7313
7324
  settings: "Firebase"
7314
7325
  });
@@ -7737,9 +7748,9 @@ const checkIfGcloudCliInstalled = async () => {
7737
7748
  return false;
7738
7749
  }
7739
7750
  };
7740
- const runInit = async ({ build, envFile }) => {
7751
+ const runInit = async ({ build, envFile, secretsEnv }) => {
7741
7752
  const nonInteractive = envFile !== void 0;
7742
- const initEnvSources = await readHotUpdaterInitEnv(process.cwd(), envFile);
7753
+ const initEnvSources = await readHotUpdaterInitEnv(process.cwd(), envFile, secretsEnv);
7743
7754
  const { managedEnv } = initEnvSources;
7744
7755
  const initInputEnv = getHotUpdaterInitInputEnv(initEnvSources, nonInteractive);
7745
7756
  const savedInputs = resolveFirebaseInitInputs(initInputEnv);
@@ -7805,7 +7816,7 @@ const runInit = async ({ build, envFile }) => {
7805
7816
  });
7806
7817
  await makeEnv(persistedInputs);
7807
7818
  await removeTmpDir();
7808
- return;
7819
+ return null;
7809
7820
  }
7810
7821
  const functionsCode = transformEnv(functionsIndexPath, {
7811
7822
  REGION: currentRegion,
@@ -7836,7 +7847,7 @@ const runInit = async ({ build, envFile }) => {
7836
7847
  }]);
7837
7848
  await deployFirestore(tmpDir, initializeVariable.databaseId, nonInteractive, cliEnv);
7838
7849
  const credential = applicationCredentials ? cert(JSON.parse(await fs.promises.readFile(applicationCredentials, "utf-8"))) : applicationDefault();
7839
- const existingApps = new Set(getApps());
7850
+ await Promise.all(getApps().map((app) => deleteApp(app)));
7840
7851
  const databaseConfig = {
7841
7852
  credential,
7842
7853
  databaseId: initializeVariable.databaseId,
@@ -7861,7 +7872,7 @@ const runInit = async ({ build, envFile }) => {
7861
7872
  if (clientCredential !== void 0) await makeEnv({ [clientCredential.env]: clientCredential.value });
7862
7873
  } finally {
7863
7874
  await database.dispose?.();
7864
- await Promise.all(getApps().filter((app) => !existingApps.has(app)).map((app) => deleteApp(app)));
7875
+ await Promise.all(getApps().map((app) => deleteApp(app)));
7865
7876
  }
7866
7877
  await deployFunctions(tmpDir, nonInteractive, cliEnv);
7867
7878
  await p.tasks([{
@@ -7908,9 +7919,7 @@ const runInit = async ({ build, envFile }) => {
7908
7919
  }
7909
7920
  await printTemplate(clientCredential, initializeVariable.projectId, currentRegion, server.clientPlugins, cliEnv);
7910
7921
  await removeTmpDir();
7911
- p.log.message(`Next step: ${link("https://hot-updater.dev/docs/managed/firebase#step-3-add-hotupdater-to-your-project")}`);
7912
- if (!applicationCredentials) p.log.message("Next step: Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater");
7913
- p.log.success("Done! 🎉");
7922
+ return { nextSteps: [link("https://hot-updater.dev/docs/managed/firebase#step-3-add-hotupdater-to-your-project"), ...applicationCredentials ? [] : ["Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater"]] };
7914
7923
  };
7915
7924
  //#endregion
7916
7925
  export { initProvider, mergeIndexes, runInit, setFirestoreDatabase };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/firebase",
3
3
  "type": "module",
4
- "version": "1.2.0-rc.3",
4
+ "version": "1.2.0-rc.30",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "main": "dist/index.cjs",
7
7
  "types": "dist/index.d.cts",
@@ -38,10 +38,10 @@
38
38
  "dependencies": {
39
39
  "hono": "4.12.34",
40
40
  "google-auth-library": "10.7.0",
41
- "@hot-updater/cli-tools": "1.2.0-rc.3",
42
- "@hot-updater/protocol": "1.2.0-rc.3",
43
- "@hot-updater/plugin-core": "1.2.0-rc.3",
44
- "@hot-updater/server": "1.2.0-rc.3"
41
+ "@hot-updater/cli-tools": "1.2.0-rc.30",
42
+ "@hot-updater/protocol": "1.2.0-rc.30",
43
+ "@hot-updater/plugin-core": "1.2.0-rc.30",
44
+ "@hot-updater/server": "1.2.0-rc.30"
45
45
  },
46
46
  "publishConfig": {
47
47
  "access": "public"
@@ -56,8 +56,8 @@
56
56
  "firebase-tools": "15.29.0",
57
57
  "fkill": "^9.0.0",
58
58
  "mime": "^4.0.4",
59
- "@hot-updater/mock": "1.2.0-rc.3",
60
- "@hot-updater/test-utils": "1.2.0-rc.3"
59
+ "@hot-updater/mock": "1.2.0-rc.30",
60
+ "@hot-updater/test-utils": "1.2.0-rc.30"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "firebase-admin": ">=11.10.0",