@hot-updater/firebase 1.2.0-rc.5 → 1.2.0-rc.51
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/firebase/functions/index.cjs +2331 -394
- package/dist/index.cjs +198 -37
- package/dist/index.d.cts +4 -5
- package/dist/index.d.mts +4 -5
- package/dist/index.mjs +198 -37
- package/dist/init/index.cjs +86 -10
- package/dist/init/index.d.cts +2 -2
- package/dist/init/index.d.mts +2 -2
- package/dist/init/index.mjs +87 -11
- package/package.json +7 -7
package/dist/index.mjs
CHANGED
|
@@ -166,14 +166,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
|
|
|
166
166
|
};
|
|
167
167
|
};
|
|
168
168
|
//#endregion
|
|
169
|
+
//#region src/googleCredential.ts
|
|
170
|
+
const CLOUD_PLATFORM_SCOPE$1 = "https://www.googleapis.com/auth/cloud-platform";
|
|
171
|
+
/**
|
|
172
|
+
* Resolves application default credentials as Firestore will, from
|
|
173
|
+
* GOOGLE_APPLICATION_CREDENTIALS's file or the environment, for the app's
|
|
174
|
+
* `projectId`, so it neither exchanges a token nor discovers a project
|
|
175
|
+
* Firestore itself wouldn't. Only `applicationDefault()`'s credential: a
|
|
176
|
+
* service account's or refresh token's was read from its file already.
|
|
177
|
+
*/
|
|
178
|
+
const resolveApplicationDefault = async (credential, projectId) => {
|
|
179
|
+
if (credential.constructor.name !== "ApplicationDefaultCredential") return;
|
|
180
|
+
const { GoogleAuth } = await import("google-auth-library");
|
|
181
|
+
await new GoogleAuth({
|
|
182
|
+
scopes: [CLOUD_PLATFORM_SCOPE$1],
|
|
183
|
+
...projectId === void 0 ? {} : { projectId }
|
|
184
|
+
}).getClient();
|
|
185
|
+
};
|
|
186
|
+
//#endregion
|
|
169
187
|
//#region src/firebaseDatabase.ts
|
|
188
|
+
/**
|
|
189
|
+
* `store` that loads `credential` before its first call: one that cannot
|
|
190
|
+
* load, such as GOOGLE_APPLICATION_CREDENTIALS naming a missing file, fails
|
|
191
|
+
* that call with what is wrong. Firestore's own client would also reject a
|
|
192
|
+
* promise nobody awaits, which ends a CLI process with a stack trace.
|
|
193
|
+
*/
|
|
194
|
+
const withLoadedCredential = (store, credential, projectId) => {
|
|
195
|
+
let loaded;
|
|
196
|
+
const load = () => loaded ??= resolveApplicationDefault(credential, projectId).then(() => void 0, (error) => {
|
|
197
|
+
loaded = void 0;
|
|
198
|
+
throw new Error(`Could not load the Google credentials for Firestore: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
199
|
+
});
|
|
200
|
+
const { deleteConsumed } = store;
|
|
201
|
+
return {
|
|
202
|
+
...store,
|
|
203
|
+
get: async (keys) => {
|
|
204
|
+
await load();
|
|
205
|
+
return store.get(keys);
|
|
206
|
+
},
|
|
207
|
+
query: async (range) => {
|
|
208
|
+
await load();
|
|
209
|
+
return store.query(range);
|
|
210
|
+
},
|
|
211
|
+
write: async (ops) => {
|
|
212
|
+
await load();
|
|
213
|
+
return store.write(ops);
|
|
214
|
+
},
|
|
215
|
+
...deleteConsumed && { deleteConsumed: async (keys) => {
|
|
216
|
+
await load();
|
|
217
|
+
return deleteConsumed.call(store, keys);
|
|
218
|
+
} }
|
|
219
|
+
};
|
|
220
|
+
};
|
|
170
221
|
const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
|
|
171
222
|
const app = getApps().length ? getApp() : initializeApp(appOptions);
|
|
172
223
|
const firestore = databaseId ? getFirestore(app, databaseId) : getFirestore(app);
|
|
173
|
-
|
|
224
|
+
const store = createFirestoreStore({
|
|
174
225
|
firestore,
|
|
175
226
|
collection
|
|
176
|
-
})
|
|
227
|
+
});
|
|
228
|
+
const credential = app.options.credential;
|
|
229
|
+
return createKvAdapter({ store: appOptions.credential === void 0 || credential === void 0 || process.env["FIRESTORE_EMULATOR_HOST"] ? store : withLoadedCredential(store, credential, app.options.projectId) });
|
|
177
230
|
};
|
|
178
231
|
/**
|
|
179
232
|
* Writes the schema settings of core and `plugins`, the plugins the server
|
|
@@ -201,11 +254,14 @@ const firebaseDatabase = (config) => ({
|
|
|
201
254
|
//#region src/firebaseStorage.ts
|
|
202
255
|
/** Signed URLs kept per adapter, enough for a few Bundles' assets. */
|
|
203
256
|
const MAX_CACHED_SIGNED_URLS = 1e4;
|
|
257
|
+
/** Objects deleted at once: Cloud Storage deletes one object a request. */
|
|
258
|
+
const DELETE_CONCURRENCY = 16;
|
|
204
259
|
const firebaseStorage = (config) => {
|
|
205
260
|
const app = getApps().length ? getApp() : initializeApp(config);
|
|
206
261
|
let opened;
|
|
207
262
|
const bucket = () => opened ??= getStorage(app).bucket(config.storageBucket);
|
|
208
263
|
const getStorageKey = createStorageKeyBuilder(config.basePath);
|
|
264
|
+
const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
|
|
209
265
|
/**
|
|
210
266
|
* Signed URLs by object. Without a private key, as in Cloud Functions, each
|
|
211
267
|
* signature is an IAM signBlob request, and an update check returns a URL
|
|
@@ -294,6 +350,39 @@ const firebaseStorage = (config) => {
|
|
|
294
350
|
const { key } = parseAndValidate(storageUri);
|
|
295
351
|
await bucket().file(key).delete({ ignoreNotFound: true });
|
|
296
352
|
return { deleted: true };
|
|
353
|
+
},
|
|
354
|
+
async listObjects(prefix) {
|
|
355
|
+
const folder = getStorageKey(prefix ?? "");
|
|
356
|
+
const [files] = await bucket().getFiles({
|
|
357
|
+
autoPaginate: true,
|
|
358
|
+
prefix: folder ? `${folder}/` : ""
|
|
359
|
+
});
|
|
360
|
+
const objects = [];
|
|
361
|
+
for (const file of files) {
|
|
362
|
+
if (!file.name.startsWith(basePrefix)) continue;
|
|
363
|
+
let storageUri;
|
|
364
|
+
try {
|
|
365
|
+
storageUri = createStorageUri({
|
|
366
|
+
bucket: config.storageBucket,
|
|
367
|
+
key: file.name,
|
|
368
|
+
protocol: "gs"
|
|
369
|
+
});
|
|
370
|
+
} catch {
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
const { size, updated } = file.metadata;
|
|
374
|
+
objects.push({
|
|
375
|
+
key: file.name.slice(basePrefix.length),
|
|
376
|
+
...updated ? { lastModifiedAt: new Date(updated) } : {},
|
|
377
|
+
size: Number(size ?? 0),
|
|
378
|
+
storageUri
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
return objects;
|
|
382
|
+
},
|
|
383
|
+
async deleteObjects(relativeKeys) {
|
|
384
|
+
const keys = relativeKeys.map((key) => getStorageKey(key));
|
|
385
|
+
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
386
|
}
|
|
298
387
|
});
|
|
299
388
|
};
|
|
@@ -355,22 +444,61 @@ const crc32c = (bytes) => {
|
|
|
355
444
|
/** The version IDs the secret's annotation lists. */
|
|
356
445
|
const trackedVersions = (secret) => (secret.annotations?.[VERSIONS_ANNOTATION] ?? "").split(",").map((entry) => entry.trim()).filter((entry) => VERSION_ID_PATTERN.test(entry));
|
|
357
446
|
const versionOf = (name) => typeof name === "string" ? name.slice(name.lastIndexOf("/") + 1) : "";
|
|
358
|
-
|
|
447
|
+
/** An error of one line each, for a terminal. */
|
|
448
|
+
const failure = (lines, cause) => new Error(lines.join("\n"), cause === void 0 ? void 0 : { cause });
|
|
449
|
+
/**
|
|
450
|
+
* The one step that can fix the credentials in use, by the order they're
|
|
451
|
+
* tried: signing in with gcloud changes nothing while a variable comes first.
|
|
452
|
+
*/
|
|
453
|
+
const signInHint = (credentials) => {
|
|
454
|
+
if (credentials) return [`Check the credentials passed to ${ADAPTER_NAME}().`];
|
|
455
|
+
const variable = ACCESS_TOKEN_ENV_NAMES.find((name) => process.env[name]?.trim()) ?? (process.env["GOOGLE_APPLICATION_CREDENTIALS"]?.trim() ? "GOOGLE_APPLICATION_CREDENTIALS" : void 0);
|
|
456
|
+
if (variable) return [`Fix or unset ${variable}.`];
|
|
457
|
+
return process.env["CI"] ? ["Use google-github-actions/auth."] : ["Sign in:", "gcloud auth application-default login"];
|
|
458
|
+
};
|
|
459
|
+
const hint = (response, permission, signIn, projectId) => {
|
|
359
460
|
const { status, error } = response;
|
|
360
|
-
if (error.details?.some((detail) => detail.reason === "SERVICE_DISABLED")) return "
|
|
361
|
-
if (status === 401) return "
|
|
362
|
-
if (status === 403) return `
|
|
363
|
-
if (status === 429) return "
|
|
364
|
-
return
|
|
461
|
+
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}`];
|
|
462
|
+
if (status === 401) return ["Google rejected the access token.", ...signIn];
|
|
463
|
+
if (status === 403) return [`The identity needs ${permission}.`];
|
|
464
|
+
if (status === 429) return ["Secret Manager's quota is exhausted: try again later."];
|
|
465
|
+
return [];
|
|
365
466
|
};
|
|
366
467
|
/**
|
|
367
|
-
* An error for a failed request: the HTTP status,
|
|
368
|
-
*
|
|
468
|
+
* An error for a failed request on `resource`, a line each: the HTTP status,
|
|
469
|
+
* the resource, `notes`, and what to fix, or Google's own status and message,
|
|
470
|
+
* which name resources but never a value, when nothing here says what to fix.
|
|
369
471
|
*/
|
|
370
|
-
const
|
|
472
|
+
const requestErrorOf = (signIn, projectId, action, resource, response, permission, notes = []) => {
|
|
371
473
|
const { status, message } = response.error;
|
|
372
|
-
const
|
|
373
|
-
|
|
474
|
+
const fix = hint(response, permission, signIn, projectId);
|
|
475
|
+
if (response.status === 401 && notes.length === 0) return failure(fix);
|
|
476
|
+
return failure([
|
|
477
|
+
`${ADAPTER_NAME} couldn't ${action} (${response.status}).`,
|
|
478
|
+
resourceLine(resource),
|
|
479
|
+
...notes,
|
|
480
|
+
...fix.length > 0 ? fix : [[status, message?.slice(0, 300)].filter(Boolean).join(": ")]
|
|
481
|
+
]);
|
|
482
|
+
};
|
|
483
|
+
/** The line that names a secret: its resource name is a line's worth. */
|
|
484
|
+
const resourceLine = (secret) => `Secret: ${secret}`;
|
|
485
|
+
let metadataWarningFiltered = false;
|
|
486
|
+
/**
|
|
487
|
+
* Drops the one warning `gcp-metadata` emits when its probe for a Google
|
|
488
|
+
* runtime fails oddly: credentials are about to be reported as missing, and
|
|
489
|
+
* the warning has nothing to act on. It stays filtered for the process, as
|
|
490
|
+
* the library caches the probe; every other warning passes through.
|
|
491
|
+
* `METADATA_SERVER_DETECTION=none` would also silence it, but skips the probe,
|
|
492
|
+
* and with it the credentials of a Google runtime.
|
|
493
|
+
*/
|
|
494
|
+
const filterMetadataWarning = () => {
|
|
495
|
+
if (metadataWarningFiltered) return;
|
|
496
|
+
metadataWarningFiltered = true;
|
|
497
|
+
const emitWarning = process.emitWarning;
|
|
498
|
+
process.emitWarning = ((warning, ...rest) => {
|
|
499
|
+
if (rest[0] === "MetadataLookupWarning") return;
|
|
500
|
+
Reflect.apply(emitWarning, process, [warning, ...rest]);
|
|
501
|
+
});
|
|
374
502
|
};
|
|
375
503
|
/** Masks a value in the CLI's output, which loads `@hot-updater/cli-tools`. */
|
|
376
504
|
const mask = async (value) => {
|
|
@@ -407,10 +535,11 @@ const createAccessToken = (credentials, projectId) => {
|
|
|
407
535
|
throw error;
|
|
408
536
|
});
|
|
409
537
|
const client = await auth;
|
|
538
|
+
filterMetadataWarning();
|
|
410
539
|
try {
|
|
411
540
|
return await client.getAccessToken() ?? void 0;
|
|
412
541
|
} catch (error) {
|
|
413
|
-
throw
|
|
542
|
+
throw failure([`${ADAPTER_NAME} found no Google credentials.`, ...signInHint(void 0)], error);
|
|
414
543
|
}
|
|
415
544
|
};
|
|
416
545
|
return async () => {
|
|
@@ -432,14 +561,19 @@ const createAccessToken = (credentials, projectId) => {
|
|
|
432
561
|
*/
|
|
433
562
|
const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
434
563
|
const accessToken = createAccessToken(credentials, projectId);
|
|
564
|
+
const requestError = (action, resource, response, permission, notes) => requestErrorOf(signInHint(credentials), projectId, action, resource, response, permission, notes);
|
|
435
565
|
const projectPath = () => {
|
|
436
|
-
if (typeof projectId !== "string" || !PROJECT_PATTERN.test(projectId)) throw
|
|
437
|
-
if (!PREFIX_PATTERN.test(prefix)) throw
|
|
566
|
+
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."]);
|
|
567
|
+
if (!PREFIX_PATTERN.test(prefix)) throw failure([`${ADAPTER_NAME} can't use the prefix ${JSON.stringify(prefix)}.`, "It takes letters, digits, \"-\", and \"_\"."]);
|
|
438
568
|
return `projects/${projectId}`;
|
|
439
569
|
};
|
|
440
570
|
const secretId = (name) => {
|
|
441
571
|
const id = `${prefix}${name}`;
|
|
442
|
-
if (!SECRET_ID_PATTERN.test(id)) throw
|
|
572
|
+
if (!SECRET_ID_PATTERN.test(id)) throw failure([
|
|
573
|
+
`${ADAPTER_NAME} can't name a secret ${JSON.stringify(name)}.`,
|
|
574
|
+
`Secret: ${id}`,
|
|
575
|
+
"Secret Manager's IDs take up to 255 letters, digits, \"-\", and \"_\"."
|
|
576
|
+
]);
|
|
443
577
|
return id;
|
|
444
578
|
};
|
|
445
579
|
const request = async (token, method, path, body) => {
|
|
@@ -474,14 +608,18 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
|
474
608
|
const accessLatest = async (token, secret) => {
|
|
475
609
|
const response = await request(token, "GET", `${secret}/versions/latest:access`);
|
|
476
610
|
if (response.status === 404) return void 0;
|
|
477
|
-
if (!response.ok) throw requestError(
|
|
611
|
+
if (!response.ok) throw requestError("read", secret, response, "roles/secretmanager.secretAccessor on the secret");
|
|
478
612
|
const body = isRecord(response.body) ? response.body : void 0;
|
|
479
613
|
const payload = body?.payload;
|
|
480
614
|
const data = isRecord(payload) ? payload.data : void 0;
|
|
481
|
-
if (typeof data !== "string") throw
|
|
615
|
+
if (typeof data !== "string") throw failure([`${ADAPTER_NAME} read no payload.`, resourceLine(secret)]);
|
|
482
616
|
const bytes = Buffer.from(data, "base64");
|
|
483
617
|
const checksum = isRecord(payload) ? payload.dataCrc32c : void 0;
|
|
484
|
-
if (checksum !== void 0 && Number(checksum) !== crc32c(bytes)) throw
|
|
618
|
+
if (checksum !== void 0 && Number(checksum) !== crc32c(bytes)) throw failure([
|
|
619
|
+
`${ADAPTER_NAME} can't trust what it read.`,
|
|
620
|
+
resourceLine(secret),
|
|
621
|
+
"Its checksum doesn't match its payload."
|
|
622
|
+
]);
|
|
485
623
|
const value = bytes.toString("utf8");
|
|
486
624
|
await mask(value);
|
|
487
625
|
return {
|
|
@@ -514,7 +652,7 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
|
514
652
|
const readSecret = async (token, secret) => {
|
|
515
653
|
const response = await request(token, "GET", secret);
|
|
516
654
|
if (response.status === 404) return void 0;
|
|
517
|
-
if (!response.ok) throw requestError(
|
|
655
|
+
if (!response.ok) throw requestError("read", secret, response, "secretmanager.secrets.get on the secret");
|
|
518
656
|
return response.body;
|
|
519
657
|
};
|
|
520
658
|
const getOrCreateSecret = async (token, parent, id) => {
|
|
@@ -527,14 +665,19 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
|
527
665
|
const raced = await readSecret(token, secret);
|
|
528
666
|
if (raced) return raced;
|
|
529
667
|
}
|
|
530
|
-
throw requestError(
|
|
668
|
+
throw requestError("create", secret, created, `secretmanager.secrets.create on ${parent}`);
|
|
531
669
|
};
|
|
532
670
|
const assertCanSet = async (token, secret) => {
|
|
533
671
|
const response = await request(token, "POST", `${secret}:testIamPermissions`, { permissions: SET_PERMISSIONS });
|
|
534
|
-
if (!response.ok) throw requestError(
|
|
672
|
+
if (!response.ok) throw requestError("check its permissions", secret, response, SET_PERMISSIONS.join(", "));
|
|
535
673
|
const held = isRecord(response.body) && Array.isArray(response.body.permissions) ? response.body.permissions : [];
|
|
536
674
|
const missing = SET_PERMISSIONS.filter((name) => !held.includes(name));
|
|
537
|
-
if (missing.length > 0) throw
|
|
675
|
+
if (missing.length > 0) throw failure([
|
|
676
|
+
`${ADAPTER_NAME} can't store a value.`,
|
|
677
|
+
resourceLine(secret),
|
|
678
|
+
`The identity lacks ${missing.join(", ")} on it.`,
|
|
679
|
+
"Grant roles/secretmanager.admin."
|
|
680
|
+
]);
|
|
538
681
|
};
|
|
539
682
|
/**
|
|
540
683
|
* Destroys `version` of `secret`: true once it is destroyed, or already
|
|
@@ -567,10 +710,11 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
|
567
710
|
/**
|
|
568
711
|
* Adds `value` as the secret's newest version, creating the secret when
|
|
569
712
|
* it is missing, and waits until the `latest` alias resolves to it. Then
|
|
570
|
-
* it destroys the
|
|
571
|
-
* `hot-updater-versions` annotation lists
|
|
572
|
-
*
|
|
573
|
-
*
|
|
713
|
+
* it destroys the versions this adapter added before the previous one,
|
|
714
|
+
* which the secret's `hot-updater-versions` annotation lists, keeping
|
|
715
|
+
* the previous value: versions added any other way are never touched.
|
|
716
|
+
* The permissions this needs are checked on the secret, once it exists,
|
|
717
|
+
* before any version is added. A version that could not be destroyed stays
|
|
574
718
|
* listed for the next `set`. The annotation is updated against the
|
|
575
719
|
* secret's etag, so a concurrent `set` loses no listed version. When
|
|
576
720
|
* `latest` does not resolve to the new version in time, or the
|
|
@@ -581,7 +725,7 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
|
581
725
|
const parent = projectPath();
|
|
582
726
|
const id = secretId(name);
|
|
583
727
|
const secret = `${parent}/secrets/${id}`;
|
|
584
|
-
if (typeof value !== "string" || value === "") throw
|
|
728
|
+
if (typeof value !== "string" || value === "") throw failure([`${ADAPTER_NAME} can't store an empty value.`, resourceLine(secret)]);
|
|
585
729
|
await mask(value);
|
|
586
730
|
const token = await accessToken();
|
|
587
731
|
const current = await getOrCreateSecret(token, parent, id);
|
|
@@ -592,17 +736,20 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
|
592
736
|
dataCrc32c: String(crc32c(data))
|
|
593
737
|
} });
|
|
594
738
|
const version = versionOf(isRecord(added.body) ? added.body.name : void 0);
|
|
595
|
-
if (!added.ok || !VERSION_ID_PATTERN.test(version)) throw requestError(
|
|
739
|
+
if (!added.ok || !VERSION_ID_PATTERN.test(version)) throw requestError("add a version", secret, added, "secretmanager.versions.add on the secret");
|
|
740
|
+
const own = trackedVersions(current).filter((entry) => Number(entry) < Number(version));
|
|
741
|
+
const previous = own.reduce((newest, entry) => newest === void 0 || Number(entry) > Number(newest) ? entry : newest, void 0);
|
|
596
742
|
const visible = await waitForLatest(token, secret, version);
|
|
597
743
|
const destroyed = /* @__PURE__ */ new Set();
|
|
598
744
|
if (visible) {
|
|
599
|
-
const older =
|
|
745
|
+
const older = own.filter((entry) => entry !== previous);
|
|
600
746
|
const results = await Promise.all(older.map((entry) => destroy(token, secret, entry)));
|
|
601
747
|
older.forEach((entry, index) => {
|
|
602
748
|
if (results[index]) destroyed.add(entry);
|
|
603
749
|
});
|
|
604
750
|
}
|
|
605
|
-
const notListed = `
|
|
751
|
+
const notListed = `record version ${version}, which it stored`;
|
|
752
|
+
const notDestroyed = `The next set won't destroy it: ${VERSIONS_ANNOTATION} misses it.`;
|
|
606
753
|
let base = current;
|
|
607
754
|
let updated;
|
|
608
755
|
try {
|
|
@@ -611,7 +758,11 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
|
611
758
|
await delay(LATEST_RETRY_DELAYS_MS[attempt - 1] ?? 0);
|
|
612
759
|
base = await readSecret(token, secret) ?? {};
|
|
613
760
|
}
|
|
614
|
-
const listed = [.../* @__PURE__ */ new Set([
|
|
761
|
+
const listed = [.../* @__PURE__ */ new Set([
|
|
762
|
+
version,
|
|
763
|
+
...previous === void 0 ? [] : [previous],
|
|
764
|
+
...trackedVersions(base)
|
|
765
|
+
])].filter((entry) => !destroyed.has(entry));
|
|
615
766
|
updated = await request(token, "PATCH", `${secret}?updateMask=annotations`, {
|
|
616
767
|
...base.etag === void 0 ? {} : { etag: base.etag },
|
|
617
768
|
annotations: {
|
|
@@ -622,14 +773,24 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
|
|
|
622
773
|
if (updated.error.status !== "FAILED_PRECONDITION") break;
|
|
623
774
|
}
|
|
624
775
|
} catch (error) {
|
|
625
|
-
throw
|
|
776
|
+
throw failure([
|
|
777
|
+
`${ADAPTER_NAME} couldn't ${notListed}.`,
|
|
778
|
+
resourceLine(secret),
|
|
779
|
+
error instanceof Error ? error.message : String(error),
|
|
780
|
+
notDestroyed
|
|
781
|
+
], error);
|
|
626
782
|
}
|
|
627
|
-
if (!updated?.ok) throw requestError(notListed, updated, "secretmanager.secrets.update on the secret");
|
|
628
|
-
if (!visible) throw
|
|
783
|
+
if (!updated?.ok) throw requestError(notListed, secret, updated, "secretmanager.secrets.update on the secret", [notDestroyed]);
|
|
784
|
+
if (!visible) throw failure([
|
|
785
|
+
`${ADAPTER_NAME} stored version ${version}.`,
|
|
786
|
+
resourceLine(secret),
|
|
787
|
+
"Its latest alias doesn't resolve to that version yet.",
|
|
788
|
+
"It kept the versions it added before: the next set destroys them."
|
|
789
|
+
]);
|
|
629
790
|
},
|
|
630
791
|
describe: (name) => {
|
|
631
792
|
const id = `${prefix}${name}`;
|
|
632
|
-
return `
|
|
793
|
+
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
794
|
}
|
|
634
795
|
};
|
|
635
796
|
};
|
package/dist/init/index.cjs
CHANGED
|
@@ -6863,14 +6863,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
|
|
|
6863
6863
|
};
|
|
6864
6864
|
};
|
|
6865
6865
|
//#endregion
|
|
6866
|
+
//#region src/googleCredential.ts
|
|
6867
|
+
const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
|
|
6868
|
+
/**
|
|
6869
|
+
* Resolves application default credentials as Firestore will, from
|
|
6870
|
+
* GOOGLE_APPLICATION_CREDENTIALS's file or the environment, for the app's
|
|
6871
|
+
* `projectId`, so it neither exchanges a token nor discovers a project
|
|
6872
|
+
* Firestore itself wouldn't. Only `applicationDefault()`'s credential: a
|
|
6873
|
+
* service account's or refresh token's was read from its file already.
|
|
6874
|
+
*/
|
|
6875
|
+
const resolveApplicationDefault = async (credential, projectId) => {
|
|
6876
|
+
if (credential.constructor.name !== "ApplicationDefaultCredential") return;
|
|
6877
|
+
const { GoogleAuth } = await import("google-auth-library");
|
|
6878
|
+
await new GoogleAuth({
|
|
6879
|
+
scopes: [CLOUD_PLATFORM_SCOPE],
|
|
6880
|
+
...projectId === void 0 ? {} : { projectId }
|
|
6881
|
+
}).getClient();
|
|
6882
|
+
};
|
|
6883
|
+
//#endregion
|
|
6866
6884
|
//#region src/firebaseDatabase.ts
|
|
6885
|
+
/**
|
|
6886
|
+
* `store` that loads `credential` before its first call: one that cannot
|
|
6887
|
+
* load, such as GOOGLE_APPLICATION_CREDENTIALS naming a missing file, fails
|
|
6888
|
+
* that call with what is wrong. Firestore's own client would also reject a
|
|
6889
|
+
* promise nobody awaits, which ends a CLI process with a stack trace.
|
|
6890
|
+
*/
|
|
6891
|
+
const withLoadedCredential = (store, credential, projectId) => {
|
|
6892
|
+
let loaded;
|
|
6893
|
+
const load = () => loaded ??= resolveApplicationDefault(credential, projectId).then(() => void 0, (error) => {
|
|
6894
|
+
loaded = void 0;
|
|
6895
|
+
throw new Error(`Could not load the Google credentials for Firestore: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
6896
|
+
});
|
|
6897
|
+
const { deleteConsumed } = store;
|
|
6898
|
+
return {
|
|
6899
|
+
...store,
|
|
6900
|
+
get: async (keys) => {
|
|
6901
|
+
await load();
|
|
6902
|
+
return store.get(keys);
|
|
6903
|
+
},
|
|
6904
|
+
query: async (range) => {
|
|
6905
|
+
await load();
|
|
6906
|
+
return store.query(range);
|
|
6907
|
+
},
|
|
6908
|
+
write: async (ops) => {
|
|
6909
|
+
await load();
|
|
6910
|
+
return store.write(ops);
|
|
6911
|
+
},
|
|
6912
|
+
...deleteConsumed && { deleteConsumed: async (keys) => {
|
|
6913
|
+
await load();
|
|
6914
|
+
return deleteConsumed.call(store, keys);
|
|
6915
|
+
} }
|
|
6916
|
+
};
|
|
6917
|
+
};
|
|
6867
6918
|
const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
|
|
6868
6919
|
const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(appOptions);
|
|
6869
6920
|
const firestore = databaseId ? (0, firebase_admin_firestore.getFirestore)(app, databaseId) : (0, firebase_admin_firestore.getFirestore)(app);
|
|
6870
|
-
|
|
6921
|
+
const store = createFirestoreStore({
|
|
6871
6922
|
firestore,
|
|
6872
6923
|
collection
|
|
6873
|
-
})
|
|
6924
|
+
});
|
|
6925
|
+
const credential = app.options.credential;
|
|
6926
|
+
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) });
|
|
6874
6927
|
};
|
|
6875
6928
|
/**
|
|
6876
6929
|
* Writes the schema settings of core and `plugins`, the plugins the server
|
|
@@ -6976,8 +7029,32 @@ const firebaseEngineSettingDocumentId = () => firestoreDocumentId({
|
|
|
6976
7029
|
pk: _hot_updater_plugin_core.SETTINGS_TABLE.name,
|
|
6977
7030
|
sk: (0, _hot_updater_plugin_core.encodeKvKey)([ENGINE_SETTING])
|
|
6978
7031
|
});
|
|
7032
|
+
/**
|
|
7033
|
+
* The Google credential init reads Firestore with, once it loads: the
|
|
7034
|
+
* service account key file `applicationCredentials` names, or the
|
|
7035
|
+
* application default credentials. Before any change, an InitError says
|
|
7036
|
+
* what is wrong with one that does not load, where Firestore's client would
|
|
7037
|
+
* end init with a stack trace.
|
|
7038
|
+
*/
|
|
7039
|
+
const loadGoogleCredential = async (applicationCredentials, projectId) => {
|
|
7040
|
+
const next = "Set GOOGLE_APPLICATION_CREDENTIALS to a service account key file, then rerun init.";
|
|
7041
|
+
let credential;
|
|
7042
|
+
try {
|
|
7043
|
+
credential = applicationCredentials ? (0, firebase_admin_app.cert)(JSON.parse(await fs_promises.default.readFile(applicationCredentials, "utf8"))) : (0, firebase_admin_app.applicationDefault)();
|
|
7044
|
+
} catch {
|
|
7045
|
+
throw new _hot_updater_cli_tools.InitError(`GOOGLE_APPLICATION_CREDENTIALS names ${applicationCredentials}, which is not a readable service account key file. ${next}`);
|
|
7046
|
+
}
|
|
7047
|
+
if (process.env["FIRESTORE_EMULATOR_HOST"]) return credential;
|
|
7048
|
+
try {
|
|
7049
|
+
await resolveApplicationDefault(credential, projectId);
|
|
7050
|
+
} catch (error) {
|
|
7051
|
+
const reason = (error instanceof Error ? error.message : String(error)).split(/(?<=\.)\s/u)[0].replace(/\.$/u, "");
|
|
7052
|
+
throw new _hot_updater_cli_tools.InitError(`Could not load Google credentials: ${reason}. ${next}`);
|
|
7053
|
+
}
|
|
7054
|
+
return credential;
|
|
7055
|
+
};
|
|
6979
7056
|
const assertFirebaseInfrastructureCanInitialize = async ({ applicationCredentials, databaseId, projectId }) => {
|
|
6980
|
-
const credential =
|
|
7057
|
+
const credential = await loadGoogleCredential(applicationCredentials, projectId);
|
|
6981
7058
|
const app = (0, firebase_admin_app.initializeApp)({
|
|
6982
7059
|
credential,
|
|
6983
7060
|
projectId
|
|
@@ -7823,7 +7900,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
7823
7900
|
});
|
|
7824
7901
|
await (0, _hot_updater_cli_tools.makeEnv)(persistedInputs);
|
|
7825
7902
|
await removeTmpDir();
|
|
7826
|
-
return;
|
|
7903
|
+
return null;
|
|
7827
7904
|
}
|
|
7828
7905
|
const functionsCode = (0, _hot_updater_cli_tools.transformEnv)(functionsIndexPath, {
|
|
7829
7906
|
REGION: currentRegion,
|
|
@@ -7853,8 +7930,8 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
7853
7930
|
}
|
|
7854
7931
|
}]);
|
|
7855
7932
|
await deployFirestore(tmpDir, initializeVariable.databaseId, nonInteractive, cliEnv);
|
|
7856
|
-
const credential =
|
|
7857
|
-
|
|
7933
|
+
const credential = await loadGoogleCredential(applicationCredentials, initializeVariable.projectId);
|
|
7934
|
+
await Promise.all((0, firebase_admin_app.getApps)().map((app) => (0, firebase_admin_app.deleteApp)(app)));
|
|
7858
7935
|
const databaseConfig = {
|
|
7859
7936
|
credential,
|
|
7860
7937
|
databaseId: initializeVariable.databaseId,
|
|
@@ -7872,6 +7949,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
7872
7949
|
let clientCredential;
|
|
7873
7950
|
try {
|
|
7874
7951
|
await migrateFirebaseDatabase(databaseConfig, server.plugins);
|
|
7952
|
+
await (0, _hot_updater_cli_tools.fillReleaseLabels)(server);
|
|
7875
7953
|
clientCredential = await (0, _hot_updater_cli_tools.provisionClientCredential)(server, {
|
|
7876
7954
|
env: initInputEnv,
|
|
7877
7955
|
name: "Firebase init"
|
|
@@ -7879,7 +7957,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
7879
7957
|
if (clientCredential !== void 0) await (0, _hot_updater_cli_tools.makeEnv)({ [clientCredential.env]: clientCredential.value });
|
|
7880
7958
|
} finally {
|
|
7881
7959
|
await database.dispose?.();
|
|
7882
|
-
await Promise.all((0, firebase_admin_app.getApps)().
|
|
7960
|
+
await Promise.all((0, firebase_admin_app.getApps)().map((app) => (0, firebase_admin_app.deleteApp)(app)));
|
|
7883
7961
|
}
|
|
7884
7962
|
await deployFunctions(tmpDir, nonInteractive, cliEnv);
|
|
7885
7963
|
await _hot_updater_cli_tools.p.tasks([{
|
|
@@ -7926,9 +8004,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
7926
8004
|
}
|
|
7927
8005
|
await printTemplate(clientCredential, initializeVariable.projectId, currentRegion, server.clientPlugins, cliEnv);
|
|
7928
8006
|
await removeTmpDir();
|
|
7929
|
-
|
|
7930
|
-
if (!applicationCredentials) _hot_updater_cli_tools.p.log.message("Next step: Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater");
|
|
7931
|
-
_hot_updater_cli_tools.p.log.success("Done! 🎉");
|
|
8007
|
+
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"]] };
|
|
7932
8008
|
};
|
|
7933
8009
|
//#endregion
|
|
7934
8010
|
exports.initProvider = initProvider;
|
package/dist/init/index.d.cts
CHANGED
|
@@ -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, secretsEnv }: RunInitOptions) => Promise<
|
|
89
|
+
declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
|
|
90
90
|
//#endregion
|
|
91
91
|
export { initProvider, mergeIndexes, runInit, setFirestoreDatabase };
|
package/dist/init/index.d.mts
CHANGED
|
@@ -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, secretsEnv }: RunInitOptions) => Promise<
|
|
89
|
+
declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
|
|
90
90
|
//#endregion
|
|
91
91
|
export { initProvider, mergeIndexes, runInit, setFirestoreDatabase };
|