firebase-tools-with-isolate 13.26.0 → 13.29.1-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/lib/appdistribution/client.js +2 -1
  2. package/lib/appdistribution/options-parser-util.js +5 -5
  3. package/lib/apphosting/config.js +86 -1
  4. package/lib/apphosting/secrets/index.js +1 -39
  5. package/lib/apphosting/yaml.js +3 -0
  6. package/lib/auth.js +13 -3
  7. package/lib/bin/firebase.js +4 -3
  8. package/lib/commands/appdistribution-distribute.js +55 -31
  9. package/lib/commands/apphosting-config-export.js +3 -26
  10. package/lib/commands/firestore-indexes-list.js +4 -2
  11. package/lib/commands/index.js +4 -6
  12. package/lib/dataconnect/fileUtils.js +3 -0
  13. package/lib/dataconnect/schemaMigration.js +10 -16
  14. package/lib/dataconnect/types.js +1 -1
  15. package/lib/deploy/extensions/tasks.js +2 -2
  16. package/lib/deploy/functions/backend.js +1 -3
  17. package/lib/deploy/functions/build.js +3 -1
  18. package/lib/deploy/functions/prepare.js +23 -20
  19. package/lib/deploy/functions/prepareFunctionsUpload.js +19 -16
  20. package/lib/deploy/functions/release/fabricator.js +1 -1
  21. package/lib/deploy/functions/release/planner.js +4 -4
  22. package/lib/deploy/functions/runtimes/discovery/v1alpha1.js +4 -0
  23. package/lib/deploy/functions/runtimes/supported/types.js +1 -1
  24. package/lib/emulator/apphosting/developmentServer.js +32 -0
  25. package/lib/emulator/apphosting/index.js +5 -4
  26. package/lib/emulator/apphosting/serve.js +7 -7
  27. package/lib/emulator/auth/operations.js +8 -5
  28. package/lib/emulator/commandUtils.js +2 -1
  29. package/lib/emulator/controller.js +46 -18
  30. package/lib/emulator/dataconnect/pgliteServer.js +76 -19
  31. package/lib/emulator/dataconnectEmulator.js +43 -2
  32. package/lib/emulator/downloadableEmulators.js +21 -10
  33. package/lib/emulator/eventarcEmulator.js +1 -0
  34. package/lib/emulator/hub.js +16 -0
  35. package/lib/emulator/hubExport.js +23 -0
  36. package/lib/emulator/initEmulators.js +63 -0
  37. package/lib/emulator/types.js +2 -2
  38. package/lib/error.js +11 -1
  39. package/lib/experiments.js +0 -6
  40. package/lib/extensions/localHelper.js +2 -2
  41. package/lib/extensions/runtimes/node.js +16 -15
  42. package/lib/extensions/types.js +6 -9
  43. package/lib/functions/events/v2.js +7 -3
  44. package/lib/gcp/cloudfunctionsv2.js +7 -0
  45. package/lib/init/features/dataconnect/index.js +8 -5
  46. package/lib/init/features/emulators.js +11 -0
  47. package/lib/init/features/genkit/index.js +13 -5
  48. package/lib/init/spawn.js +37 -7
  49. package/lib/management/projects.js +23 -1
  50. package/lib/requireAuth.js +2 -1
  51. package/lib/utils.js +16 -1
  52. package/package.json +7 -3
  53. package/schema/firebase-config.json +6 -0
  54. package/templates/init/dataconnect/dataconnect.yaml +1 -0
  55. package/templates/init/functions/javascript/package.lint.json +1 -1
  56. package/templates/init/functions/javascript/package.nolint.json +1 -1
  57. package/templates/init/functions/typescript/package.lint.json +1 -1
  58. package/templates/init/functions/typescript/package.nolint.json +1 -1
  59. package/templates/init/functions/typescript/tsconfig.json +3 -1
  60. package/lib/emulator/apphosting/utils.js +0 -18
  61. package/templates/init/dataconnect/dataconnect-fdccompatiblemode.yaml +0 -12
@@ -7,7 +7,7 @@ const extensionsApi = require("../../extensions/extensionsApi");
7
7
  const extensionsHelper_1 = require("../../extensions/extensionsHelper");
8
8
  const refs = require("../../extensions/refs");
9
9
  const utils = require("../../utils");
10
- const types_1 = require("../../extensions/types");
10
+ const error_2 = require("../../error");
11
11
  const isRetryable = (err) => err.status === 429 || err.status === 409;
12
12
  function extensionsDeploymentHandler(errorHandler) {
13
13
  return async (task) => {
@@ -53,7 +53,7 @@ function createExtensionInstanceTask(projectId, instanceSpec, validateOnly = fal
53
53
  await extensionsApi.createInstance(createArgs);
54
54
  }
55
55
  catch (err) {
56
- if ((0, types_1.isObject)(err) && err.status === 409) {
56
+ if ((0, error_2.isObject)(err) && err.status === 409) {
57
57
  throw new error_1.FirebaseError(`Failed to create extension instance. Extension instance ${clc.bold(instanceSpec.instanceId)} already exists.`);
58
58
  }
59
59
  throw err;
@@ -25,9 +25,7 @@ function endpointTriggerType(endpoint) {
25
25
  else if (isBlockingTriggered(endpoint)) {
26
26
  return endpoint.blockingTrigger.eventType;
27
27
  }
28
- else {
29
- throw new Error("Unexpected trigger type for endpoint " + JSON.stringify(endpoint));
30
- }
28
+ (0, functional_1.assertExhaustive)(endpoint);
31
29
  }
32
30
  exports.endpointTriggerType = endpointTriggerType;
33
31
  exports.AllVpcEgressSettings = ["PRIVATE_RANGES_ONLY", "ALL_TRAFFIC"];
@@ -267,7 +267,9 @@ function discoverTrigger(endpoint, region, r) {
267
267
  return { httpsTrigger };
268
268
  }
269
269
  else if (isCallableTriggered(endpoint)) {
270
- return { callableTrigger: {} };
270
+ const trigger = { callableTrigger: {} };
271
+ proto.copyIfPresent(trigger.callableTrigger, endpoint.callableTrigger, "genkitAction");
272
+ return trigger;
271
273
  }
272
274
  else if (isBlockingTriggered(endpoint)) {
273
275
  return { blockingTrigger: endpoint.blockingTrigger };
@@ -2,32 +2,32 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.loadCodebases = exports.resolveCpuAndConcurrency = exports.inferBlockingDetails = exports.updateEndpointTargetedStatus = exports.inferDetailsFromExisting = exports.prepare = exports.EVENTARC_SOURCE_ENV = void 0;
4
4
  const clc = require("colorette");
5
- const backend = require("./backend");
6
- const build = require("./build");
5
+ const api_1 = require("../../api");
7
6
  const ensureApiEnabled = require("../../ensureApiEnabled");
8
- const functionsConfig = require("../../functionsConfig");
7
+ const error_1 = require("../../error");
8
+ const functional_1 = require("../../functional");
9
9
  const functionsEnv = require("../../functions/env");
10
- const runtimes = require("./runtimes");
11
- const supported = require("./runtimes/supported");
12
- const validate = require("./validate");
10
+ const v1_1 = require("../../functions/events/v1");
11
+ const projectConfig_1 = require("../../functions/projectConfig");
12
+ const functionsConfig = require("../../functionsConfig");
13
+ const serviceusage_1 = require("../../gcp/serviceusage");
14
+ const logger_1 = require("../../logger");
15
+ const projectUtils_1 = require("../../projectUtils");
16
+ const utils_1 = require("../../utils");
17
+ const prepare_1 = require("../extensions/prepare");
18
+ const backend = require("./backend");
19
+ const backend_1 = require("./backend");
20
+ const build = require("./build");
21
+ const applyHash_1 = require("./cache/applyHash");
22
+ const checkIam_1 = require("./checkIam");
13
23
  const ensure = require("./ensure");
14
- const api_1 = require("../../api");
15
24
  const functionsDeployHelper_1 = require("./functionsDeployHelper");
16
- const utils_1 = require("../../utils");
17
25
  const prepareFunctionsUpload_1 = require("./prepareFunctionsUpload");
18
26
  const prompts_1 = require("./prompts");
19
- const projectUtils_1 = require("../../projectUtils");
20
- const logger_1 = require("../../logger");
27
+ const runtimes = require("./runtimes");
28
+ const supported = require("./runtimes/supported");
21
29
  const triggerRegionHelper_1 = require("./triggerRegionHelper");
22
- const checkIam_1 = require("./checkIam");
23
- const error_1 = require("../../error");
24
- const projectConfig_1 = require("../../functions/projectConfig");
25
- const v1_1 = require("../../functions/events/v1");
26
- const serviceusage_1 = require("../../gcp/serviceusage");
27
- const applyHash_1 = require("./cache/applyHash");
28
- const backend_1 = require("./backend");
29
- const functional_1 = require("../../functional");
30
- const prepare_1 = require("../extensions/prepare");
30
+ const validate = require("./validate");
31
31
  exports.EVENTARC_SOURCE_ENV = "EVENTARC_CLOUD_EVENT_SOURCE";
32
32
  async function prepare(context, options, payload) {
33
33
  const projectId = (0, projectUtils_1.needProjectId)(options);
@@ -137,11 +137,14 @@ async function prepare(context, options, payload) {
137
137
  for (const [codebase, wantBackend] of Object.entries(wantBackends)) {
138
138
  const config = (0, projectConfig_1.configForCodebase)(context.config, codebase);
139
139
  const sourceDirName = config.source;
140
- const sourceDir = options.config.path(sourceDirName);
140
+ let sourceDir = options.config.path(sourceDirName);
141
141
  const source = {};
142
142
  if (backend.someEndpoint(wantBackend, () => true)) {
143
143
  (0, utils_1.logLabeledBullet)("functions", `preparing ${clc.bold(sourceDirName)} directory for uploading...`);
144
144
  }
145
+ if (config.isolate === true) {
146
+ sourceDir = await (0, prepareFunctionsUpload_1.runIsolate)(sourceDirName);
147
+ }
145
148
  if (backend.someEndpoint(wantBackend, (e) => e.platform === "gcfv2")) {
146
149
  const packagedSource = await (0, prepareFunctionsUpload_1.prepareFunctionsUpload)(sourceDir, config);
147
150
  source.functionsSourceV2 = packagedSource?.pathToSource;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.convertToSortedKeyValueArray = exports.prepareFunctionsUpload = exports.getFunctionsConfig = void 0;
3
+ exports.convertToSortedKeyValueArray = exports.runIsolate = exports.prepareFunctionsUpload = exports.getFunctionsConfig = void 0;
4
4
  const archiver = require("archiver");
5
5
  const clc = require("colorette");
6
6
  const filesize = require("filesize");
@@ -92,24 +92,27 @@ async function packageSource(sourceDir, config, runtimeConfig) {
92
92
  return { pathToSource: tmpFile, hash };
93
93
  }
94
94
  async function prepareFunctionsUpload(sourceDir, config, runtimeConfig) {
95
- if (config.isolate === true) {
96
- utils.logLabeledBullet("functions", `Start isolating the source folder...`);
97
- try {
98
- const { isolate } = (await (0, dynamicImport_1.dynamicImport)("isolate-package"));
99
- const isolateDir = await isolate();
100
- utils.logLabeledBullet("functions", `Finished isolation at ${clc.bold(isolateDir)}`);
101
- return packageSource(isolateDir, config, runtimeConfig);
102
- }
103
- catch (err) {
104
- utils.logLabeledBullet("functions", `+++ Failed to isolate: ${err.message}`);
105
- throw err;
106
- }
95
+ return packageSource(sourceDir, config, runtimeConfig);
96
+ }
97
+ exports.prepareFunctionsUpload = prepareFunctionsUpload;
98
+ async function runIsolate(sourceDirName) {
99
+ try {
100
+ utils.logLabeledBullet("isolate", `Isolating the source`);
101
+ const { isolate } = (await (0, dynamicImport_1.dynamicImport)("isolate-package"));
102
+ const isolateDir = await isolate(sourceDirName !== "."
103
+ ? {
104
+ config: { targetPackagePath: path.join("./", sourceDirName) },
105
+ }
106
+ : undefined);
107
+ utils.logLabeledBullet("isolate", `Finished isolation at ${clc.bold(isolateDir)}`);
108
+ return isolateDir;
107
109
  }
108
- else {
109
- return packageSource(sourceDir, config, runtimeConfig);
110
+ catch (err) {
111
+ utils.logLabeledBullet("isolate", `Isolation failed: ${err.message}`, "error");
112
+ throw err;
110
113
  }
111
114
  }
112
- exports.prepareFunctionsUpload = prepareFunctionsUpload;
115
+ exports.runIsolate = runIsolate;
113
116
  function convertToSortedKeyValueArray(config) {
114
117
  if (typeof config !== "object" || config === null)
115
118
  return config;
@@ -307,7 +307,7 @@ class Fabricator {
307
307
  }
308
308
  });
309
309
  }
310
- endpoint.uri = resultFunction.serviceConfig?.uri;
310
+ endpoint.uri = resultFunction.url;
311
311
  const serviceName = resultFunction.serviceConfig?.service;
312
312
  endpoint.runServiceId = utils.last(serviceName?.split("/"));
313
313
  if (!serviceName) {
@@ -7,7 +7,6 @@ const error_1 = require("../../../error");
7
7
  const utils = require("../../../utils");
8
8
  const backend = require("../backend");
9
9
  const v2events = require("../../../functions/events/v2");
10
- const v2_1 = require("../../../functions/events/v2");
11
10
  function calculateChangesets(want, have, keyFn, deleteAll) {
12
11
  const toCreate = utils.groupBy(Object.keys(want)
13
12
  .filter((id) => !have[id])
@@ -166,9 +165,9 @@ function upgradedScheduleFromV1ToV2(want, have) {
166
165
  exports.upgradedScheduleFromV1ToV2 = upgradedScheduleFromV1ToV2;
167
166
  function checkForUnsafeUpdate(want, have) {
168
167
  return (backend.isEventTriggered(want) &&
169
- v2_1.FIRESTORE_EVENT_WITH_AUTH_CONTEXT_REGEX.test(want.eventTrigger.eventType) &&
170
168
  backend.isEventTriggered(have) &&
171
- v2_1.FIRESTORE_EVENT_REGEX.test(have.eventTrigger.eventType));
169
+ want.eventTrigger.eventType ===
170
+ v2events.CONVERTABLE_EVENTS[have.eventTrigger.eventType]);
172
171
  }
173
172
  exports.checkForUnsafeUpdate = checkForUnsafeUpdate;
174
173
  function checkForIllegalUpdate(want, have) {
@@ -195,7 +194,8 @@ function checkForIllegalUpdate(want, have) {
195
194
  };
196
195
  const wantType = triggerType(want);
197
196
  const haveType = triggerType(have);
198
- if (wantType !== haveType) {
197
+ const upgradingHttpsFunction = backend.isHttpsTriggered(have) && backend.isCallableTriggered(want);
198
+ if (wantType !== haveType && !upgradingHttpsFunction) {
199
199
  throw new error_1.FirebaseError(`[${(0, functionsDeployHelper_1.getFunctionLabel)(want)}] Changing from ${haveType} function to ${wantType} function is not allowed. Please delete your function and create a new one instead.`);
200
200
  }
201
201
  if (want.platform === "gcfv1" && have.platform === "gcfv2") {
@@ -134,6 +134,9 @@ function assertBuildEndpoint(ep, id) {
134
134
  });
135
135
  }
136
136
  else if (build.isCallableTriggered(ep)) {
137
+ (0, parsing_1.assertKeyTypes)(prefix + ".callableTrigger", ep.callableTrigger, {
138
+ genkitAction: "string?",
139
+ });
137
140
  }
138
141
  else if (build.isScheduleTriggered(ep)) {
139
142
  (0, parsing_1.assertKeyTypes)(prefix + ".scheduleTrigger", ep.scheduleTrigger, {
@@ -215,6 +218,7 @@ function parseEndpointForBuild(id, ep, project, defaultRegion, runtime) {
215
218
  }
216
219
  else if (build.isCallableTriggered(ep)) {
217
220
  triggered = { callableTrigger: {} };
221
+ (0, proto_1.copyIfPresent)(triggered.callableTrigger, ep.callableTrigger, "genkitAction");
218
222
  }
219
223
  else if (build.isScheduleTriggered(ep)) {
220
224
  const st = {
@@ -55,7 +55,7 @@ exports.RUNTIMES = runtimes({
55
55
  },
56
56
  nodejs22: {
57
57
  friendly: "Node.js 22",
58
- status: "beta",
58
+ status: "GA",
59
59
  deprecationDate: "2027-04-30",
60
60
  decommissionDate: "2027-10-31",
61
61
  },
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.detectStartCommand = exports.detectPackageManager = exports.logger = void 0;
4
+ const fs_extra_1 = require("fs-extra");
5
+ const path_1 = require("path");
6
+ const emulatorLogger_1 = require("../emulatorLogger");
7
+ const types_1 = require("../types");
8
+ const error_1 = require("../../error");
9
+ exports.logger = emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.APPHOSTING);
10
+ async function detectPackageManager(rootdir) {
11
+ if (await (0, fs_extra_1.pathExists)((0, path_1.join)(rootdir, "pnpm-lock.yaml"))) {
12
+ return "pnpm";
13
+ }
14
+ if (await (0, fs_extra_1.pathExists)((0, path_1.join)(rootdir, "yarn.lock"))) {
15
+ return "yarn";
16
+ }
17
+ if (await (0, fs_extra_1.pathExists)((0, path_1.join)(rootdir, "package-lock.json"))) {
18
+ return "npm";
19
+ }
20
+ throw new error_1.FirebaseError("Unsupported package manager");
21
+ }
22
+ exports.detectPackageManager = detectPackageManager;
23
+ async function detectStartCommand(rootDir) {
24
+ try {
25
+ const packageManager = await detectPackageManager(rootDir);
26
+ return `${packageManager} run dev`;
27
+ }
28
+ catch (e) {
29
+ throw new error_1.FirebaseError("Failed to auto-detect your project's start command. Consider manually setting the start command by setting `firebase.json#emulators.apphosting.startCommand`");
30
+ }
31
+ }
32
+ exports.detectStartCommand = detectStartCommand;
@@ -3,25 +3,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AppHostingEmulator = void 0;
4
4
  const types_1 = require("../types");
5
5
  const serve_1 = require("./serve");
6
- const utils_1 = require("./utils");
6
+ const developmentServer_1 = require("./developmentServer");
7
7
  class AppHostingEmulator {
8
8
  constructor(args) {
9
9
  this.args = args;
10
10
  }
11
11
  async start() {
12
12
  const { hostname, port } = await (0, serve_1.start)({
13
- startCommand: this.args.startCommandOverride,
13
+ port: this.args.port,
14
+ startCommand: this.args.startCommand,
14
15
  rootDirectory: this.args.rootDirectory,
15
16
  });
16
17
  this.args.options.host = hostname;
17
18
  this.args.options.port = port;
18
19
  }
19
20
  connect() {
20
- utils_1.logger.logLabeled("INFO", types_1.Emulators.APPHOSTING, "connecting apphosting emulator");
21
+ developmentServer_1.logger.logLabeled("INFO", types_1.Emulators.APPHOSTING, "connecting apphosting emulator");
21
22
  return Promise.resolve();
22
23
  }
23
24
  stop() {
24
- utils_1.logger.logLabeled("INFO", types_1.Emulators.APPHOSTING, "stopping apphosting emulator");
25
+ developmentServer_1.logger.logLabeled("INFO", types_1.Emulators.APPHOSTING, "stopping apphosting emulator");
25
26
  return Promise.resolve();
26
27
  }
27
28
  getInfo() {
@@ -3,16 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.start = void 0;
4
4
  const net_1 = require("net");
5
5
  const portUtils_1 = require("../portUtils");
6
- const utils_1 = require("./utils");
6
+ const developmentServer_1 = require("./developmentServer");
7
7
  const constants_1 = require("../constants");
8
8
  const spawn_1 = require("../../init/spawn");
9
- const utils_2 = require("./utils");
9
+ const developmentServer_2 = require("./developmentServer");
10
10
  const types_1 = require("../types");
11
11
  const config_1 = require("./config");
12
12
  const projectPath_1 = require("../../projectPath");
13
13
  async function start(options) {
14
14
  const hostname = constants_1.DEFAULT_HOST;
15
- let port = constants_1.DEFAULT_PORTS.apphosting;
15
+ let port = options?.port ?? constants_1.DEFAULT_PORTS.apphosting;
16
16
  while (!(await availablePort(hostname, port))) {
17
17
  port += 1;
18
18
  }
@@ -33,13 +33,13 @@ async function serve(port, startCommand, backendRelativeDir) {
33
33
  PORT: port.toString(),
34
34
  };
35
35
  if (startCommand) {
36
- utils_2.logger.logLabeled("BULLET", types_1.Emulators.APPHOSTING, `running custom start command: '${startCommand}'`);
36
+ developmentServer_2.logger.logLabeled("BULLET", types_1.Emulators.APPHOSTING, `running custom start command: '${startCommand}'`);
37
37
  await (0, spawn_1.spawnWithCommandString)(startCommand, backendRoot, environmentVariablesToInject);
38
38
  return;
39
39
  }
40
- const packageManager = await (0, utils_1.discoverPackageManager)(backendRoot);
41
- utils_2.logger.logLabeled("BULLET", types_1.Emulators.APPHOSTING, `starting app with: '${packageManager} run dev'`);
42
- await (0, spawn_1.wrapSpawn)(packageManager, ["run", "dev"], backendRoot, environmentVariablesToInject);
40
+ const detectedStartCommand = await (0, developmentServer_1.detectStartCommand)(backendRoot);
41
+ developmentServer_2.logger.logLabeled("BULLET", types_1.Emulators.APPHOSTING, `starting app with: '${detectedStartCommand}'`);
42
+ await (0, spawn_1.spawnWithCommandString)(detectedStartCommand, backendRoot, environmentVariablesToInject);
43
43
  }
44
44
  function availablePort(host, port) {
45
45
  return (0, portUtils_1.checkListenable)({
@@ -737,11 +737,7 @@ function setAccountInfo(state, reqBody, ctx) {
737
737
  });
738
738
  }
739
739
  function setAccountInfoImpl(state, reqBody, { privileged = false, emulatorUrl = undefined } = {}) {
740
- const unimplementedFields = [
741
- "provider",
742
- "upgradeToFederatedLogin",
743
- "linkProviderUserInfo",
744
- ];
740
+ const unimplementedFields = ["provider", "upgradeToFederatedLogin"];
745
741
  for (const field of unimplementedFields) {
746
742
  if (field in reqBody) {
747
743
  throw new errors_1.NotImplementedError(`${field} is not implemented yet.`);
@@ -907,8 +903,15 @@ function setAccountInfoImpl(state, reqBody, { privileged = false, emulatorUrl =
907
903
  updates.phoneNumber = undefined;
908
904
  }
909
905
  }
906
+ if (reqBody.linkProviderUserInfo) {
907
+ (0, errors_1.assert)(reqBody.linkProviderUserInfo.providerId, "MISSING_PROVIDER_ID");
908
+ (0, errors_1.assert)(reqBody.linkProviderUserInfo.rawId, "MISSING_RAW_ID");
909
+ }
910
910
  user = state.updateUserByLocalId(user.localId, updates, {
911
911
  deleteProviders: reqBody.deleteProvider,
912
+ upsertProviders: reqBody.linkProviderUserInfo
913
+ ? [reqBody.linkProviderUserInfo]
914
+ : undefined,
912
915
  });
913
916
  if (signInProvider !== state_1.PROVIDER_ANONYMOUS && user.initialEmail && isEmailUpdate) {
914
917
  if (!emulatorUrl) {
@@ -301,8 +301,9 @@ async function emulatorExec(script, options) {
301
301
  exitCode = await runScript(script, extraEnv);
302
302
  await controller.onExit(options);
303
303
  }
304
- catch {
304
+ catch (err) {
305
305
  await (0, webhook_1.sendVSCodeMessage)({ message: webhook_1.VSCODE_MESSAGE.EMULATORS_START_ERRORED });
306
+ throw err;
306
307
  }
307
308
  finally {
308
309
  await controller.cleanShutdown();
@@ -58,7 +58,7 @@ async function exportOnExit(options) {
58
58
  await exportEmulatorData(exportOnExitDir, options, "exit");
59
59
  }
60
60
  catch (e) {
61
- utils.logWarning(e);
61
+ utils.logWarning(`${e}`);
62
62
  utils.logWarning(`Automatic export to "${exportOnExitDir}" failed, going to exit now...`);
63
63
  }
64
64
  }
@@ -566,19 +566,45 @@ async function startAll(options, showUI = true, runningTestScript = false) {
566
566
  else if (config.length > 1) {
567
567
  logger_1.logger.warn(`TODO: Add support for multiple services in the Data Connect emulator. Currently emulating first service ${config[0].source}`);
568
568
  }
569
- const configDir = config[0].source;
570
- const dataConnectEmulator = new dataconnectEmulator_1.DataConnectEmulator({
569
+ const args = {
571
570
  listen: listenForEmulator.dataconnect,
572
571
  projectId,
573
572
  auto_download: true,
574
- configDir,
573
+ configDir: config[0].source,
575
574
  rc: options.rc,
576
575
  config: options.config,
577
576
  autoconnectToPostgres: true,
578
577
  postgresListen: listenForEmulator["dataconnect.postgres"],
579
578
  enable_output_generated_sdk: true,
580
579
  enable_output_schema_extensions: true,
581
- });
580
+ debug: options.debug,
581
+ };
582
+ if (exportMetadata.dataconnect) {
583
+ utils.assertIsString(options.import);
584
+ const importDirAbsPath = path.resolve(options.import);
585
+ const exportMetadataFilePath = path.resolve(importDirAbsPath, exportMetadata.dataconnect.path);
586
+ const dataDirectory = options.config.get("emulators.dataconnect.dataDir");
587
+ if (exportMetadataFilePath && dataDirectory) {
588
+ emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.DATACONNECT).logLabeled("WARN", "dataconnect", "'firebase.json#emulators.dataconnect.dataDir' is set and `--import` flag was passed. " +
589
+ "This will overwrite any data saved from previous runs.");
590
+ if (!options.nonInteractive &&
591
+ !(await (0, prompt_1.promptOnce)({
592
+ type: "confirm",
593
+ message: `Do you wish to continue and overwrite data in ${dataDirectory}?`,
594
+ default: false,
595
+ }))) {
596
+ await cleanShutdown();
597
+ return { deprecationNotices: [] };
598
+ }
599
+ }
600
+ emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.DATACONNECT).logLabeled("BULLET", "dataconnect", `Importing data from ${exportMetadataFilePath}`);
601
+ args.importPath = exportMetadataFilePath;
602
+ void (0, track_1.trackEmulator)("emulator_import", {
603
+ initiated_by: "start",
604
+ emulator_name: types_1.Emulators.DATACONNECT,
605
+ });
606
+ }
607
+ const dataConnectEmulator = new dataconnectEmulator_1.DataConnectEmulator(args);
582
608
  await startEmulator(dataConnectEmulator);
583
609
  }
584
610
  if (listenForEmulator.storage) {
@@ -606,19 +632,21 @@ async function startAll(options, showUI = true, runningTestScript = false) {
606
632
  });
607
633
  await startEmulator(hostingEmulator);
608
634
  }
609
- if (experiments.isEnabled("emulatorapphosting")) {
610
- const apphostingConfig = options.config.src.emulators?.[types_1.Emulators.APPHOSTING];
611
- if (listenForEmulator.apphosting) {
612
- const apphostingAddr = legacyGetFirstAddr(types_1.Emulators.APPHOSTING);
613
- const apphostingEmulator = new apphosting_1.AppHostingEmulator({
614
- host: apphostingAddr.host,
615
- port: apphostingAddr.port,
616
- startCommandOverride: apphostingConfig?.startCommandOverride,
617
- rootDirectory: apphostingConfig?.rootDirectory,
618
- options,
619
- });
620
- await startEmulator(apphostingEmulator);
621
- }
635
+ const apphostingConfig = options.config.src.emulators?.[types_1.Emulators.APPHOSTING];
636
+ if (listenForEmulator.apphosting) {
637
+ const apphostingAddr = legacyGetFirstAddr(types_1.Emulators.APPHOSTING);
638
+ if (apphostingConfig?.startCommandOverride) {
639
+ const apphostingLogger = emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.APPHOSTING);
640
+ apphostingLogger.logLabeled("WARN", types_1.Emulators.APPHOSTING, "The `firebase.json#emulators.apphosting.startCommandOverride` config is deprecated, please use `firebase.json#emulators.apphosting.startCommand` to set a custom start command instead");
641
+ }
642
+ const apphostingEmulator = new apphosting_1.AppHostingEmulator({
643
+ host: apphostingAddr.host,
644
+ port: apphostingAddr.port,
645
+ startCommand: apphostingConfig?.startCommand || apphostingConfig?.startCommandOverride,
646
+ rootDirectory: apphostingConfig?.rootDirectory,
647
+ options,
648
+ });
649
+ await startEmulator(apphostingEmulator);
622
650
  }
623
651
  if (listenForEmulator.logging) {
624
652
  const loggingAddr = legacyGetFirstAddr(types_1.Emulators.LOGGING);
@@ -1,16 +1,29 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PGliteExtendedQueryPatch = exports.PostgresServer = void 0;
3
+ exports.PGliteExtendedQueryPatch = exports.PostgresServer = exports.TRUNCATE_TABLES_SQL = void 0;
4
4
  const pglite_1 = require("@electric-sql/pglite");
5
5
  const { dynamicImport } = require(true && "../../dynamicImport");
6
6
  const net = require("node:net");
7
+ const fs = require("fs");
7
8
  const index_1 = require("./pg-gateway/index");
8
9
  const node_1 = require("./pg-gateway/platforms/node");
9
10
  const logger_1 = require("../../logger");
11
+ const error_1 = require("../../error");
12
+ exports.TRUNCATE_TABLES_SQL = `
13
+ DO $do$
14
+ DECLARE _clear text;
15
+ BEGIN
16
+ SELECT 'TRUNCATE TABLE ' || string_agg(oid::regclass::text, ', ') || ' CASCADE'
17
+ FROM pg_class
18
+ WHERE relkind = 'r'
19
+ AND relnamespace = 'public'::regnamespace
20
+ INTO _clear;
21
+ EXECUTE COALESCE(_clear, 'select now()');
22
+ END
23
+ $do$;`;
10
24
  class PostgresServer {
11
25
  async createPGServer(host = "127.0.0.1", port) {
12
- const db = await this.getDb();
13
- await db.waitReady;
26
+ const getDb = this.getDb.bind(this);
14
27
  const server = net.createServer(async (socket) => {
15
28
  const connection = await (0, node_1.fromNodeSocket)(socket, {
16
29
  serverVersion: "16.3 (PGlite 0.2.0)",
@@ -19,6 +32,7 @@ class PostgresServer {
19
32
  if (!isAuthenticated) {
20
33
  return;
21
34
  }
35
+ const db = await getDb();
22
36
  const result = await db.execProtocolRaw(data);
23
37
  return extendedQueryPatch.filterResponse(data, result);
24
38
  },
@@ -31,34 +45,77 @@ class PostgresServer {
31
45
  server.emit("error", err);
32
46
  });
33
47
  });
48
+ this.server = server;
34
49
  const listeningPromise = new Promise((resolve) => {
35
50
  server.listen(port, host, () => {
36
51
  resolve();
37
52
  });
38
53
  });
39
- await db.waitReady;
40
54
  await listeningPromise;
41
55
  return server;
42
56
  }
43
57
  async getDb() {
58
+ if (!this.db) {
59
+ const vector = (await dynamicImport("@electric-sql/pglite/vector")).vector;
60
+ const uuidOssp = (await dynamicImport("@electric-sql/pglite/contrib/uuid_ossp")).uuid_ossp;
61
+ const pgliteArgs = {
62
+ debug: this.debug,
63
+ extensions: {
64
+ vector,
65
+ uuidOssp,
66
+ },
67
+ dataDir: this.dataDirectory,
68
+ };
69
+ if (this.importPath) {
70
+ logger_1.logger.debug(`Importing from ${this.importPath}`);
71
+ const rf = fs.readFileSync(this.importPath);
72
+ const file = new File([rf], this.importPath);
73
+ pgliteArgs.loadDataDir = file;
74
+ }
75
+ this.db = await this.forceCreateDB(pgliteArgs);
76
+ await this.db.waitReady;
77
+ }
78
+ return this.db;
79
+ }
80
+ async clearDb() {
81
+ const db = await this.getDb();
82
+ await db.query(exports.TRUNCATE_TABLES_SQL);
83
+ }
84
+ async exportData(exportPath) {
85
+ const db = await this.getDb();
86
+ const dump = await db.dumpDataDir();
87
+ const arrayBuff = await dump.arrayBuffer();
88
+ fs.writeFileSync(exportPath, new Uint8Array(arrayBuff));
89
+ }
90
+ async forceCreateDB(pgliteArgs) {
91
+ try {
92
+ const db = await pglite_1.PGlite.create(pgliteArgs);
93
+ return db;
94
+ }
95
+ catch (err) {
96
+ if (pgliteArgs.dataDir && (0, error_1.hasMessage)(err) && /Database already exists/.test(err.message)) {
97
+ fs.rmSync(pgliteArgs.dataDir, { force: true, recursive: true });
98
+ const db = await pglite_1.PGlite.create(pgliteArgs);
99
+ return db;
100
+ }
101
+ throw err;
102
+ }
103
+ }
104
+ async stop() {
44
105
  if (this.db) {
45
- return this.db;
106
+ await this.db.close();
46
107
  }
47
- const vector = (await dynamicImport("@electric-sql/pglite/vector")).vector;
48
- const uuidOssp = (await dynamicImport("@electric-sql/pglite/contrib/uuid_ossp")).uuid_ossp;
49
- return pglite_1.PGlite.create({
50
- username: this.username,
51
- database: this.database,
52
- debug: 0,
53
- extensions: {
54
- vector,
55
- uuidOssp,
56
- },
57
- });
108
+ if (this.server) {
109
+ this.server.close();
110
+ }
111
+ return;
58
112
  }
59
- constructor(database, username) {
60
- this.username = username;
61
- this.database = database;
113
+ constructor(args) {
114
+ this.db = undefined;
115
+ this.server = undefined;
116
+ this.dataDirectory = args.dataDirectory;
117
+ this.importPath = args.importPath;
118
+ this.debug = args.debug ? 5 : 0;
62
119
  }
63
120
  }
64
121
  exports.PostgresServer = PostgresServer;