firebase-tools-with-isolate 15.30.1 → 15.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,6 +24,7 @@ exports.validateAndResolveDirectoryKit = validateAndResolveDirectoryKit;
24
24
  exports.buildAndInstallDirectoryKit = buildAndInstallDirectoryKit;
25
25
  exports.findKitConfig = findKitConfig;
26
26
  exports.addInstanceToKitConfig = addInstanceToKitConfig;
27
+ exports.revertFunctionsConfig = revertFunctionsConfig;
27
28
  exports.scaffoldKit = scaffoldKit;
28
29
  exports.addInstanceToKit = addInstanceToKit;
29
30
  exports.discoverKitBuild = discoverKitBuild;
@@ -56,9 +57,10 @@ const iam = require("../../gcp/iam");
56
57
  const functionsEnv = require("../env");
57
58
  const functionsConfig = require("../../functionsConfig");
58
59
  const prepare_1 = require("../../deploy/functions/prepare");
59
- const utils_2 = require("../../utils");
60
+ const functional_1 = require("../../functional");
60
61
  const env_1 = require("../env");
61
62
  const env_2 = require("./env");
63
+ const fsutils_1 = require("../../fsutils");
62
64
  exports.TEMPLATES = {
63
65
  installation: "init/functions/typescript/index-kit.ts",
64
66
  migration: "init/functions/typescript/index-kit-migration.ts",
@@ -540,6 +542,22 @@ function addInstanceToKitConfig(config, kitId, instanceId, configDirPath) {
540
542
  target.instances[instanceId] = configDirPath;
541
543
  config.writeProjectFile("firebase.json", config.src);
542
544
  }
545
+ function revertFunctionsConfig(options) {
546
+ try {
547
+ if (!(0, utils_1.deepEqual)(options.config.src.functions, options.originalFunctions)) {
548
+ if (options.originalFunctions === undefined) {
549
+ delete options.config.src.functions;
550
+ }
551
+ else {
552
+ options.config.src.functions = options.originalFunctions;
553
+ }
554
+ options.config.writeProjectFile("firebase.json", options.config.src);
555
+ }
556
+ }
557
+ catch (err) {
558
+ logger_1.logger.debug(`Failed to revert firebase.json: ${(0, error_1.getErrMsg)(err)}`);
559
+ }
560
+ }
543
561
  async function scaffoldKit(options) {
544
562
  const paths = await scaffoldKitFiles(options.config, options.kitId, options.instanceId, options.packageName, options.templateType);
545
563
  if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
@@ -611,6 +629,12 @@ async function promptAndWriteKitParams(options) {
611
629
  };
612
630
  const rawUserEnvs = functionsEnv.loadUserEnvs(userEnvOpt);
613
631
  const { userEnvs, secretRefs } = (0, prepare_1.partitionUserEnvs)(rawUserEnvs);
632
+ const parsedSecretRefs = (0, functional_1.mapObject)(secretRefs, (unparsed) => build.parseSecretRef(unparsed));
633
+ const secretPrefixForInstance = (0, projectConfig_1.addKitPrefix)(options.instanceId);
634
+ for (const secretParam of options.params.filter((p) => params.isSecretParam(p))) {
635
+ secretParam.resourceId = `${secretPrefixForInstance}-${secretParam.name}`;
636
+ }
637
+ build.applyEnvSecretBindingsToParams(options.params, parsedSecretRefs);
614
638
  let firebaseConfig = { projectId: options.projectId };
615
639
  try {
616
640
  firebaseConfig = await functionsConfig.getFirebaseConfig({ projectId: options.projectId });
@@ -625,10 +649,10 @@ async function promptAndWriteKitParams(options) {
625
649
  userEnvs: typedUserEnvs,
626
650
  codebase: options.instanceId,
627
651
  nonInteractive: options.nonInteractive,
628
- force: options.force,
629
652
  });
630
653
  functionsEnv.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);
631
- if (experiments.isEnabled("secretEnvParams")) {
654
+ if (experiments.isEnabled("secretEnvParams") &&
655
+ experiments.isEnabled("writeDefaultSecretBindings")) {
632
656
  functionsEnv.writeResolvedSecretRefs(resolvedSecretRefs, secretRefs, userEnvOpt);
633
657
  }
634
658
  }
@@ -637,9 +661,9 @@ async function printKitFirstDeployReport(options) {
637
661
  const prefix = (0, projectConfig_1.addKitPrefix)(options.instanceId);
638
662
  try {
639
663
  discoveredBuild = options.preDiscoveredBuild
640
- ? (0, utils_2.cloneDeep)(options.preDiscoveredBuild)
664
+ ? (0, utils_1.cloneDeep)(options.preDiscoveredBuild)
641
665
  : await discoverKitBuild(options, options.absSourcePath);
642
- build.applyPrefix(discoveredBuild, prefix);
666
+ build.applyEndpointPrefix(discoveredBuild, prefix);
643
667
  }
644
668
  catch (err) {
645
669
  logger_1.logger.debug(`Could not discover kit build for reporting: ${(0, error_1.getErrMsg)(err)}`);
@@ -687,7 +711,8 @@ async function printKitFirstDeployReport(options) {
687
711
  (0, utils_1.logLabeledWarning)("functions", `${clc.bold("Please review the changes above. If you do not want them applied to your project, uninstall this kit before running firebase deploy.")}`);
688
712
  }
689
713
  }
690
- async function addKitInstanceOrConfigureProject(options, existingKit, existingFunctionsInfo) {
714
+ async function addKitInstanceOrConfigureProject(options) {
715
+ const { existingKit, existingFunctionsInfo, createdPaths = [] } = options;
691
716
  const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
692
717
  const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
693
718
  ? options.project
@@ -735,6 +760,9 @@ async function addKitInstanceOrConfigureProject(options, existingKit, existingFu
735
760
  if (action === "addInstance") {
736
761
  resultAction = "addedInstance";
737
762
  instanceId = await promptKitInstanceId(options.defaultInstanceId ?? existingKit.kit, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
763
+ const expectedConfigDirPath = path.join(exports.FUNCTION_KITS_DIR, existingKit.kit, `config-${instanceId}`);
764
+ absConfigDirPath = options.config.path(expectedConfigDirPath);
765
+ createdPaths.push(absConfigDirPath);
738
766
  const result = await addInstanceToKit({
739
767
  config: options.config,
740
768
  kitId: existingKit.kit,
@@ -756,6 +784,12 @@ async function addKitInstanceOrConfigureProject(options, existingKit, existingFu
756
784
  throw new error_1.FirebaseError(`Configuration directory for instance '${instanceId}' not found in kit '${existingKit.kit}'.`);
757
785
  }
758
786
  absConfigDirPath = options.config.path(configDirPath);
787
+ if (projectId) {
788
+ const envPath = path.join(absConfigDirPath, `.env.${projectId}`);
789
+ if (!(await fs.pathExists(envPath))) {
790
+ createdPaths.push(envPath);
791
+ }
792
+ }
759
793
  if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
760
794
  await fs.ensureDir(absConfigDirPath);
761
795
  (0, env_2.seedKitInstanceEnv)({
@@ -793,7 +827,6 @@ async function addKitInstanceOrConfigureProject(options, existingKit, existingFu
793
827
  absSourcePath,
794
828
  instanceId,
795
829
  nonInteractive: options.nonInteractive,
796
- force: options.force,
797
830
  params: discoveredBuild.params,
798
831
  });
799
832
  }
@@ -897,80 +930,112 @@ async function installKitOrInstance(options) {
897
930
  if (options.directory && options.template) {
898
931
  throw new error_1.FirebaseError("Cannot specify --template with --directory.");
899
932
  }
900
- const existingFunctionsInfo = extractExistingFunctionsInfo(options.config.src.functions);
901
- const existingKit = findExistingKit(existingFunctionsInfo.existingFunctions, options);
902
- if (existingKit) {
903
- return addKitInstanceOrConfigureProject(options, existingKit, existingFunctionsInfo);
904
- }
905
- const source = options.directory
906
- ? await resolveDirectorySource(options)
907
- : await resolvePackageSource(options);
908
- const kitId = await promptKitId(source.defaultKitName, existingFunctionsInfo.existingKitIds, options.nonInteractive, options.kitId);
909
- const instanceId = await promptKitInstanceId(options.defaultInstanceId ?? kitId, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
910
- const { sourcePath, configDirPath, absSourcePath, absConfigDirPath } = await source.setup(kitId, instanceId);
911
- if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
912
- (0, env_2.seedKitInstanceEnv)({
913
- configDir: absConfigDirPath,
914
- functionsSource: absSourcePath,
915
- projectDir: options.config.projectDir,
916
- projectId: options.seedEnv.projectId,
917
- projectAlias: options.seedEnv.projectAlias,
918
- envs: options.seedEnv.envs,
919
- });
920
- }
921
- await source.buildAndInstall(absSourcePath);
922
- const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
923
- const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
924
- ? options.project
925
- : undefined;
926
- if (projectId) {
927
- fs.ensureFileSync(path.join(absConfigDirPath, `.env.${projectId}`));
928
- }
929
- let discoveredBuild;
930
- const shouldConfigure = options.configure !== false;
931
- if (shouldConfigure) {
932
- try {
933
- discoveredBuild = await discoverKitBuild({ ...options, instanceId }, absSourcePath);
933
+ const originalFunctions = (0, utils_1.cloneDeep)(options.config.src.functions);
934
+ const createdPaths = [];
935
+ let kitId;
936
+ try {
937
+ const existingFunctionsInfo = extractExistingFunctionsInfo(options.config.src.functions);
938
+ const existingKit = findExistingKit(existingFunctionsInfo.existingFunctions, options);
939
+ if (existingKit) {
940
+ kitId = existingKit.kit;
941
+ return await addKitInstanceOrConfigureProject({
942
+ ...options,
943
+ existingKit,
944
+ existingFunctionsInfo,
945
+ createdPaths,
946
+ });
934
947
  }
935
- catch (err) {
936
- logger_1.logger.debug(`Could not discover kit build for params prompting: ${(0, error_1.getErrMsg)(err)}`);
948
+ const source = options.directory
949
+ ? await resolveDirectorySource(options)
950
+ : await resolvePackageSource(options);
951
+ kitId = await promptKitId(source.defaultKitName, existingFunctionsInfo.existingKitIds, options.nonInteractive, options.kitId);
952
+ const instanceId = await promptKitInstanceId(options.defaultInstanceId ?? kitId, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
953
+ const isPackageKit = !options.directory;
954
+ const absKitDir = options.config.path(path.join(exports.FUNCTION_KITS_DIR, kitId));
955
+ const expectedConfigDirPath = path.join(exports.FUNCTION_KITS_DIR, kitId, `config-${instanceId}`);
956
+ const absConfigDirPath = options.config.path(expectedConfigDirPath);
957
+ if (isPackageKit) {
958
+ createdPaths.push(absKitDir);
937
959
  }
938
- if (discoveredBuild?.params && discoveredBuild.params.length > 0) {
939
- await promptAndWriteKitParams({
940
- config: options.config,
941
- projectId,
942
- projectAlias,
943
- absConfigDirPath,
944
- absSourcePath,
945
- instanceId,
946
- nonInteractive: options.nonInteractive,
947
- force: options.force,
948
- params: discoveredBuild.params,
960
+ else {
961
+ createdPaths.push(absConfigDirPath);
962
+ }
963
+ const setupResult = await source.setup(kitId, instanceId);
964
+ const { sourcePath, configDirPath, absSourcePath } = setupResult;
965
+ if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
966
+ (0, env_2.seedKitInstanceEnv)({
967
+ configDir: setupResult.absConfigDirPath,
968
+ functionsSource: absSourcePath,
969
+ projectDir: options.config.projectDir,
970
+ projectId: options.seedEnv.projectId,
971
+ projectAlias: options.seedEnv.projectAlias,
972
+ envs: options.seedEnv.envs,
949
973
  });
950
974
  }
975
+ await source.buildAndInstall(absSourcePath);
976
+ const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
977
+ const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
978
+ ? options.project
979
+ : undefined;
980
+ if (projectId) {
981
+ fs.ensureFileSync(path.join(setupResult.absConfigDirPath, `.env.${projectId}`));
982
+ }
983
+ let discoveredBuild;
984
+ const shouldConfigure = options.configure !== false;
985
+ if (shouldConfigure) {
986
+ try {
987
+ discoveredBuild = await discoverKitBuild({ ...options, instanceId }, absSourcePath);
988
+ }
989
+ catch (err) {
990
+ logger_1.logger.debug(`Could not discover kit build for params prompting: ${(0, error_1.getErrMsg)(err)}`);
991
+ }
992
+ if (discoveredBuild?.params && discoveredBuild.params.length > 0) {
993
+ await promptAndWriteKitParams({
994
+ config: options.config,
995
+ projectId,
996
+ projectAlias,
997
+ absConfigDirPath: setupResult.absConfigDirPath,
998
+ absSourcePath,
999
+ instanceId,
1000
+ nonInteractive: options.nonInteractive,
1001
+ params: discoveredBuild.params,
1002
+ });
1003
+ }
1004
+ }
1005
+ addKitToConfig(options.config, {
1006
+ kitId,
1007
+ instanceId,
1008
+ packageName: source.sourcePackageName,
1009
+ sourcePath,
1010
+ configDirPath,
1011
+ hasBuildScript: source.hasBuildScript,
1012
+ });
1013
+ (0, utils_1.logLabeledSuccess)("functions", `Function kit ${clc.bold(kitId)} successfully installed.`);
1014
+ await printKitFirstDeployReport({
1015
+ config: options.config,
1016
+ project: options.project,
1017
+ projectId: options.projectId,
1018
+ instanceId,
1019
+ absSourcePath,
1020
+ preDiscoveredBuild: discoveredBuild,
1021
+ });
1022
+ return {
1023
+ action: "installedKit",
1024
+ kitId,
1025
+ instanceId,
1026
+ sourcePath,
1027
+ configDirPath,
1028
+ };
1029
+ }
1030
+ catch (err) {
1031
+ await Promise.all(createdPaths.map((targetPath) => fs.remove(targetPath).catch((cleanupErr) => {
1032
+ logger_1.logger.debug(`Failed to clean up path '${targetPath}': ${(0, error_1.getErrMsg)(cleanupErr)}`);
1033
+ })));
1034
+ if (kitId) {
1035
+ await (0, fsutils_1.removeDirectoryIfEmpty)(options.config.path(path.join(exports.FUNCTION_KITS_DIR, kitId)));
1036
+ }
1037
+ await (0, fsutils_1.removeDirectoryIfEmpty)(options.config.path(exports.FUNCTION_KITS_DIR));
1038
+ revertFunctionsConfig({ config: options.config, originalFunctions });
1039
+ throw err;
951
1040
  }
952
- addKitToConfig(options.config, {
953
- kitId,
954
- instanceId,
955
- packageName: source.sourcePackageName,
956
- sourcePath,
957
- configDirPath,
958
- hasBuildScript: source.hasBuildScript,
959
- });
960
- (0, utils_1.logLabeledSuccess)("functions", `Function kit ${clc.bold(kitId)} successfully installed.`);
961
- await printKitFirstDeployReport({
962
- config: options.config,
963
- project: options.project,
964
- projectId: options.projectId,
965
- instanceId,
966
- absSourcePath,
967
- preDiscoveredBuild: discoveredBuild,
968
- });
969
- return {
970
- action: "installedKit",
971
- kitId,
972
- instanceId,
973
- sourcePath,
974
- configDirPath,
975
- };
976
1041
  }
@@ -3,10 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DEFAULT_VENV_DIR = void 0;
4
4
  exports.virtualEnvCmd = virtualEnvCmd;
5
5
  exports.runWithVirtualEnv = runWithVirtualEnv;
6
+ exports.killProcessTree = killProcessTree;
7
+ exports.trackVirtualEnvChild = trackVirtualEnvChild;
8
+ exports.untrackVirtualEnvChild = untrackVirtualEnvChild;
9
+ const os = require("os");
6
10
  const path = require("path");
7
11
  const cross_spawn_1 = require("cross-spawn");
12
+ const cp = require("child_process");
8
13
  const logger_1 = require("../logger");
9
14
  const utils_1 = require("../utils");
15
+ const error_1 = require("../error");
10
16
  exports.DEFAULT_VENV_DIR = "venv";
11
17
  function virtualEnvCmd(cwd, venvDir) {
12
18
  const activateScriptPath = utils_1.IS_WINDOWS ? ["Scripts", "activate.bat"] : ["bin", "activate"];
@@ -28,3 +34,79 @@ function runWithVirtualEnv(commandAndArgs, cwd, envs, spawnOpts = {}, venvDir =
28
34
  env: { ...process.env, ...envs },
29
35
  });
30
36
  }
37
+ function killProcessTree(pid) {
38
+ if (!pid || pid <= 0) {
39
+ return;
40
+ }
41
+ if (utils_1.IS_WINDOWS) {
42
+ const result = cp.spawnSync("taskkill", ["/pid", pid.toString(), "/T", "/F"]);
43
+ if (result.error || result.status !== 0) {
44
+ logger_1.logger.debug(`taskkill on pid ${pid} exited with ${String(result.status)}: ` +
45
+ `${result.error?.message ?? result.stderr?.toString().trim() ?? ""}`);
46
+ }
47
+ return;
48
+ }
49
+ try {
50
+ process.kill(-pid, "SIGKILL");
51
+ }
52
+ catch (e) {
53
+ logger_1.logger.debug(`Failed to kill process group ${pid}: ${(0, error_1.getErrMsg)(e)}`);
54
+ }
55
+ }
56
+ const CLEANUP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"];
57
+ const trackedChildren = new Set();
58
+ const signalHandlers = new Map();
59
+ function reRaise(signal) {
60
+ try {
61
+ process.kill(process.pid, signal);
62
+ }
63
+ catch (e) {
64
+ logger_1.logger.debug(`Could not re-raise ${signal}, exiting instead: ${(0, error_1.getErrMsg)(e)}`);
65
+ process.exit(128 + (os.constants.signals[signal] ?? 0));
66
+ }
67
+ }
68
+ function killAllTrackedChildren() {
69
+ for (const child of trackedChildren) {
70
+ if (child.pid && child.exitCode === null && child.signalCode === null) {
71
+ killProcessTree(child.pid);
72
+ }
73
+ }
74
+ trackedChildren.clear();
75
+ }
76
+ function removeCleanupHandlers() {
77
+ if (!signalHandlers.size) {
78
+ return;
79
+ }
80
+ process.removeListener("exit", killAllTrackedChildren);
81
+ for (const [signal, handler] of signalHandlers) {
82
+ process.removeListener(signal, handler);
83
+ }
84
+ signalHandlers.clear();
85
+ }
86
+ function addCleanupHandlers() {
87
+ if (signalHandlers.size) {
88
+ return;
89
+ }
90
+ process.on("exit", killAllTrackedChildren);
91
+ for (const signal of CLEANUP_SIGNALS) {
92
+ const handler = () => {
93
+ killAllTrackedChildren();
94
+ removeCleanupHandlers();
95
+ if (process.listenerCount(signal) === 0) {
96
+ reRaise(signal);
97
+ }
98
+ };
99
+ signalHandlers.set(signal, handler);
100
+ process.on(signal, handler);
101
+ }
102
+ }
103
+ function trackVirtualEnvChild(child) {
104
+ trackedChildren.add(child);
105
+ addCleanupHandlers();
106
+ }
107
+ function untrackVirtualEnvChild(child) {
108
+ trackedChildren.delete(child);
109
+ if (!trackedChildren.size) {
110
+ removeCleanupHandlers();
111
+ }
112
+ }
@@ -257,6 +257,17 @@ async function createCloudProject(projectId, options) {
257
257
  }
258
258
  }
259
259
  }
260
+ function isTosNotAcceptedError(err) {
261
+ if (!(err instanceof error_1.FirebaseError) || !err.context) {
262
+ return false;
263
+ }
264
+ const context = err.context;
265
+ const details = context.body?.error?.details;
266
+ if (!Array.isArray(details)) {
267
+ return false;
268
+ }
269
+ return details.some((d) => typeof d?.detail === "string" && d.detail.includes("Firebase Tos Not Accepted"));
270
+ }
260
271
  async function addFirebaseToCloudProject(projectId) {
261
272
  try {
262
273
  const response = await firebaseAPIClient.request({
@@ -274,6 +285,9 @@ async function addFirebaseToCloudProject(projectId) {
274
285
  }
275
286
  catch (err) {
276
287
  logger_1.logger.debug(err.message);
288
+ if (isTosNotAcceptedError(err)) {
289
+ throw new error_1.FirebaseError(`Failed to add Firebase to Google Cloud Platform project ${clc.bold(projectId)} because your account has not accepted the Firebase Terms of Service. Please accept the Terms of Service in the Firebase console at ${api.consoleOrigin()} and try again.`, { exit: 2, original: err });
290
+ }
277
291
  throw new error_1.FirebaseError("Failed to add Firebase to Google Cloud Platform project. See firebase-debug.log for more info.", { exit: 2, original: err });
278
292
  }
279
293
  }
package/lib/prompt.js CHANGED
@@ -82,8 +82,12 @@ async function select(opts) {
82
82
  if (shouldReturn) {
83
83
  return value;
84
84
  }
85
+ const instructions = typeof opts.instructions === "string"
86
+ ? { navigation: opts.instructions, pager: opts.instructions }
87
+ : opts.instructions;
85
88
  return inquirer.select({
86
89
  ...opts,
90
+ instructions,
87
91
  loop: false,
88
92
  });
89
93
  }