@firebase-function-kits/firestore-bigquery-export 0.0.2-rc.13 → 0.0.2-rc.15

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firebase-function-kits/firestore-bigquery-export",
3
- "version": "0.0.2-rc.13",
3
+ "version": "0.0.2-rc.15",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/firebase/extensions.git",
@@ -42,10 +42,5 @@
42
42
  "@firebaseextensions/firestore-bigquery-change-tracker": {
43
43
  "firebase-functions": "$firebase-functions"
44
44
  }
45
- },
46
- "devDependencies": {
47
- "@types/lodash": "^4.17.0",
48
- "typescript": "^5.9.3",
49
- "vitest": "^3.2.4"
50
45
  }
51
46
  }
package/src/config.ts CHANGED
@@ -120,13 +120,16 @@ const params = {
120
120
  "Override the default project for BigQuery instance. This can allow updates to be directed to to a BigQuery instance on another GCP project.",
121
121
 
122
122
  default: projectID,
123
+ // `required: true` in the extension, which refuses an empty answer.
124
+ input: { text: { nonEmpty: true } },
123
125
  }),
124
126
  database: defineString("DATABASE", {
125
127
  label: "Firestore Instance ID",
126
128
  description:
127
129
  'The Firestore database to use. Use "(default)" for the default database. You can view your available Firestore databases at https://console.cloud.google.com/firestore/databases.',
128
130
  default: "(default)",
129
- input: { text: { example: "(default)" } },
131
+ // `required: true` in the extension, which refuses an empty answer.
132
+ input: { text: { example: "(default)", nonEmpty: true } },
130
133
  }),
131
134
  // Declared so the CLI prompts for the value and persists it to `.env`; the
132
135
  // location to Cloud Run region lookup needs a nested ternary the CLI's CEL
package/src/events.ts CHANGED
@@ -34,6 +34,13 @@ const getEventTypes = (eventName: string) => [
34
34
 
35
35
  let eventChannel: eventArc.Channel | undefined;
36
36
 
37
+ /**
38
+ * The Eventarc channel named by `EVENTARC_CHANNEL`, or `undefined` when the
39
+ * variable is unset or blank, which disables event publishing.
40
+ */
41
+ export const configuredEventChannel = (): string | undefined =>
42
+ process.env.EVENTARC_CHANNEL?.trim() || undefined;
43
+
37
44
  /**
38
45
  * Sets up the Eventarc channel.
39
46
  *
@@ -44,8 +51,9 @@ let eventChannel: eventArc.Channel | undefined;
44
51
  * @function setupEventChannel
45
52
  */
46
53
  export const setupEventChannel = () => {
47
- eventChannel = process.env.EVENTARC_CHANNEL
48
- ? getEventarc().channel(process.env.EVENTARC_CHANNEL, {
54
+ const channel = configuredEventChannel();
55
+ eventChannel = channel
56
+ ? getEventarc().channel(channel, {
49
57
  allowedEventTypes: process.env.EXT_SELECTED_EVENTS,
50
58
  })
51
59
  : undefined;
package/src/index.ts CHANGED
@@ -82,11 +82,6 @@ const REQUIRED_ROLES: ReadonlyArray<Role> = [
82
82
  // Gen2 Firestore triggers need Eventarc receive and run.invoker on the function SA.
83
83
  "roles/eventarc.eventReceiver",
84
84
  "roles/run.invoker",
85
- // The Extensions platform granted publish rights on the extension's Eventarc
86
- // channel implicitly from `events:` in extension.yaml. Kits get no implicit
87
- // grant, so without this the `channel.publish()` calls in ./events fail with
88
- // PERMISSION_DENIED and no custom event is ever delivered.
89
- "roles/eventarc.publisher",
90
85
  // The trigger enqueues failed writes onto its own syncBigQuery task queue.
91
86
  "roles/cloudtasks.enqueuer",
92
87
  ];
@@ -99,10 +94,6 @@ const REQUIRED_APIS = [
99
94
  api: "bigquery.googleapis.com",
100
95
  reason: "Mirrors data from your Cloud Firestore collection in BigQuery.",
101
96
  },
102
- {
103
- api: "eventarcpublishing.googleapis.com",
104
- reason: "Publishes the extension's custom events to its Eventarc channel.",
105
- },
106
97
  ] as const;
107
98
 
108
99
  for (const role of REQUIRED_ROLES) {
@@ -113,6 +104,15 @@ for (const { api, reason } of REQUIRED_APIS) {
113
104
  requiresAPI(api, reason);
114
105
  }
115
106
 
107
+ // Declining a `requiresAPI` prompt aborts the deploy, and nothing publishes without a channel.
108
+ if (events.configuredEventChannel()) {
109
+ requiresRole("roles/eventarc.publisher");
110
+ requiresAPI(
111
+ "eventarcpublishing.googleapis.com",
112
+ "Publishes the extension's custom events to its Eventarc channel."
113
+ );
114
+ }
115
+
116
116
  afterFirstDeploy({
117
117
  task: { function: INIT_BIGQUERY_SYNC_FUNCTION, body: { data: {} } },
118
118
  });
@@ -167,6 +167,33 @@ const functionRegion = firestoreLocationToFunctionRegion(
167
167
  process.env.DATABASE_REGION
168
168
  );
169
169
 
170
+ /** Region placement shared by every function; empty when `DATABASE_REGION` is unset. */
171
+ const REGION_OPTION = functionRegion
172
+ ? ({ region: functionRegion } as const)
173
+ : {};
174
+
175
+ /** Options of the Firestore trigger, matching the extension's deployed trigger. */
176
+ const EVENT_FUNCTION_OPTIONS = {
177
+ ...REGION_OPTION,
178
+ concurrency: 1,
179
+ cpu: "gcf_gen1",
180
+ ingressSettings: "ALLOW_INTERNAL_ONLY",
181
+ } as const;
182
+
183
+ /** Options shared by the task-queue functions, matching the extension's 1st gen task functions. */
184
+ const TASK_FUNCTION_OPTIONS = {
185
+ ...REGION_OPTION,
186
+ concurrency: 1,
187
+ cpu: "gcf_gen1",
188
+ timeoutSeconds: 540,
189
+ } as const;
190
+
191
+ /** Options of the two lifecycle tasks, which share one retry config. */
192
+ const LIFECYCLE_TASK_OPTIONS = {
193
+ ...TASK_FUNCTION_OPTIONS,
194
+ retryConfig: LIFECYCLE_RETRY_CONFIG,
195
+ } as const;
196
+
170
197
  /**
171
198
  * Firestore trigger: streams document writes on the watched collection into the
172
199
  * BigQuery changelog table. A failed inline write buffers through the
@@ -176,7 +203,7 @@ const functionRegion = firestoreLocationToFunctionRegion(
176
203
  */
177
204
  export const fsexportbigquery = onDocumentWritten(
178
205
  {
179
- ...(functionRegion ? { region: functionRegion } : {}),
206
+ ...EVENT_FUNCTION_OPTIONS,
180
207
  document: expr`${CONFIG_EXPRESSIONS.collectionPath}/{documentId}`,
181
208
  database: CONFIG_EXPRESSIONS.database,
182
209
  },
@@ -188,12 +215,15 @@ export const fsexportbigquery = onDocumentWritten(
188
215
  * Tasks' schedule (5 attempts, 60s minimum backoff, dispatch-throttled by
189
216
  * `MAX_DISPATCHES_PER_SECOND`). After the last attempt the task is dropped;
190
217
  * by then the tracker has written the row to `BACKUP_COLLECTION` on every
191
- * terminal insert failure, when that collection is configured.
218
+ * terminal insert failure, when that collection is configured. A task refused
219
+ * with 429s at the instance ceiling never runs the handler, so no backup row
220
+ * is written for it.
192
221
  */
193
222
  export const syncBigQuery = onTaskDispatched<SerializedDocumentChange>(
194
223
  {
195
- ...(functionRegion ? { region: functionRegion } : {}),
224
+ ...TASK_FUNCTION_OPTIONS,
196
225
  retryConfig: SYNC_RETRY_CONFIG,
226
+ maxInstances: SYNC_MAX_CONCURRENT_DISPATCHES,
197
227
  rateLimits: {
198
228
  maxConcurrentDispatches: SYNC_MAX_CONCURRENT_DISPATCHES, // A blank .env value reaches this deploy-time expression as 0, which
199
229
  // Cloud Tasks would not accept; runtime falls back to the same default.
@@ -227,10 +257,7 @@ async function handleBigQuerySyncInitialization(): Promise<void> {
227
257
  * authenticated HTTP POST, without queue retries.
228
258
  */
229
259
  export const initBigQuerySync = onTaskDispatched(
230
- {
231
- ...(functionRegion ? { region: functionRegion } : {}),
232
- retryConfig: LIFECYCLE_RETRY_CONFIG,
233
- },
260
+ LIFECYCLE_TASK_OPTIONS,
234
261
  handleBigQuerySyncInitialization
235
262
  );
236
263
 
@@ -239,9 +266,6 @@ export const initBigQuerySync = onTaskDispatched(
239
266
  * so BigQuery resources are reconciled after parameter changes.
240
267
  */
241
268
  export const setupBigQuerySync = onTaskDispatched(
242
- {
243
- ...(functionRegion ? { region: functionRegion } : {}),
244
- retryConfig: LIFECYCLE_RETRY_CONFIG,
245
- },
269
+ LIFECYCLE_TASK_OPTIONS,
246
270
  handleBigQuerySyncInitialization
247
271
  );
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { declaredParams } from "firebase-functions/params";
18
+ import { describe, expect, test } from "vitest";
19
+ import "../src/config";
20
+
21
+ // config.test.ts fakes firebase-functions/params and drops the declaration
22
+ // options, so these cases read the real declarations instead.
23
+ function text(name: string): Record<string, unknown> {
24
+ const param = declaredParams.find((candidate) => candidate.name === name) as
25
+ | { options?: { input?: { text?: Record<string, unknown> } } }
26
+ | undefined;
27
+
28
+ return param?.options?.input?.text ?? {};
29
+ }
30
+
31
+ /**
32
+ * Compatibility requirement: extension.yaml marks both params `required: true`,
33
+ * so the extension's installer refuses an empty answer and re-prompts. The CLI
34
+ * enforces that for a kit only when the declaration says `nonEmpty`.
35
+ */
36
+ describe("params the extension marks required", () => {
37
+ test.each(["BIGQUERY_PROJECT_ID", "DATABASE"])(
38
+ "%s refuses an empty value at the prompt",
39
+ (name) => {
40
+ expect(text(name).nonEmpty).toBe(true);
41
+ }
42
+ );
43
+ });
@@ -28,6 +28,7 @@ vi.mock("firebase-admin/eventarc", () => ({
28
28
  }));
29
29
 
30
30
  import {
31
+ configuredEventChannel,
31
32
  recordCompletionEvent,
32
33
  recordErrorEvent,
33
34
  recordStartEvent,
@@ -52,6 +53,28 @@ describe("no channel configured", () => {
52
53
  await recordCompletionEvent({ a: 1 });
53
54
  expect(publish).not.toHaveBeenCalled();
54
55
  });
56
+
57
+ test.each([
58
+ ["empty", ""],
59
+ ["whitespace-only", " "],
60
+ ])("a %s EVENTARC_CHANNEL opens no channel", async (_label, value) => {
61
+ process.env.EVENTARC_CHANNEL = value;
62
+ setupEventChannel();
63
+
64
+ await recordStartEvent({ a: 1 });
65
+ expect(channel).not.toHaveBeenCalled();
66
+ expect(publish).not.toHaveBeenCalled();
67
+ });
68
+
69
+ test.each([
70
+ ["unset", undefined],
71
+ ["empty", ""],
72
+ ["whitespace-only", " "],
73
+ ])("configuredEventChannel is undefined when %s", (_label, value) => {
74
+ if (value === undefined) delete process.env.EVENTARC_CHANNEL;
75
+ else process.env.EVENTARC_CHANNEL = value;
76
+ expect(configuredEventChannel()).toBeUndefined();
77
+ });
55
78
  });
56
79
 
57
80
  describe("channel configured", () => {
@@ -60,6 +83,21 @@ describe("channel configured", () => {
60
83
  setupEventChannel();
61
84
  });
62
85
 
86
+ test("configuredEventChannel returns the trimmed channel name", () => {
87
+ process.env.EVENTARC_CHANNEL = " projects/p/locations/l/channels/c ";
88
+ expect(configuredEventChannel()).toBe("projects/p/locations/l/channels/c");
89
+ });
90
+
91
+ test("opens the channel on the trimmed name", () => {
92
+ process.env.EVENTARC_CHANNEL = " projects/p/locations/l/channels/c ";
93
+ setupEventChannel();
94
+ expect(channel).toHaveBeenCalledTimes(2);
95
+ expect(channel).toHaveBeenLastCalledWith(
96
+ "projects/p/locations/l/channels/c",
97
+ expect.anything()
98
+ );
99
+ });
100
+
63
101
  test("publishes both the legacy and the current event type", async () => {
64
102
  await recordStartEvent({ a: 1 });
65
103
  expect(publish).toHaveBeenCalledTimes(2);
@@ -17,10 +17,10 @@
17
17
  import { afterEach, describe, expect, test, vi } from "vitest";
18
18
 
19
19
  vi.mock("firebase-functions/firestore", () => ({
20
- onDocumentWritten: vi.fn(() => ({})),
20
+ onDocumentWritten: vi.fn((options: unknown) => ({ deployOptions: options })),
21
21
  }));
22
22
  vi.mock("firebase-functions/tasks", () => ({
23
- onTaskDispatched: vi.fn(() => ({})),
23
+ onTaskDispatched: vi.fn((options: unknown) => ({ deployOptions: options })),
24
24
  }));
25
25
  vi.mock("firebase-functions/v2", () => ({
26
26
  requiresAPI: vi.fn(),
@@ -39,6 +39,31 @@ interface ExportedOptions {
39
39
  tasks: FunctionOptions[];
40
40
  }
41
41
 
42
+ type Ingress = "ALLOW_INTERNAL_ONLY" | undefined;
43
+
44
+ /**
45
+ * Expected per-function runtime options; `undefined` means the declaration
46
+ * sets none, so the codebase's global options apply.
47
+ */
48
+ const RUNTIME_OPTIONS_BY_FUNCTION: ReadonlyArray<
49
+ [
50
+ name: string,
51
+ ingress: Ingress,
52
+ maxInstances: number | undefined,
53
+ timeoutSeconds: number | undefined
54
+ ]
55
+ > = [
56
+ ["fsexportbigquery", "ALLOW_INTERNAL_ONLY", undefined, undefined],
57
+ ["syncBigQuery", undefined, 500, 540],
58
+ ["initBigQuerySync", undefined, undefined, 540],
59
+ ["setupBigQuerySync", undefined, undefined, 540],
60
+ ];
61
+
62
+ /** Task-queue functions in the table's order: syncBigQuery first, then the two lifecycle tasks. */
63
+ const TASK_FUNCTIONS = RUNTIME_OPTIONS_BY_FUNCTION.map(([name]) => name).filter(
64
+ (name) => name !== "fsexportbigquery"
65
+ );
66
+
42
67
  const originalDatabaseRegion = process.env.DATABASE_REGION;
43
68
 
44
69
  afterEach(() => {
@@ -49,9 +74,18 @@ afterEach(() => {
49
74
  }
50
75
  });
51
76
 
52
- async function loadExportedOptions(
77
+ function isDeployed(
78
+ value: unknown
79
+ ): value is { deployOptions: FunctionOptions } {
80
+ return (
81
+ typeof value === "object" && value !== null && "deployOptions" in value
82
+ );
83
+ }
84
+
85
+ /** The entry's exported functions by name, each with the options it was declared with. */
86
+ async function loadDeployedOptions(
53
87
  databaseRegion?: string
54
- ): Promise<ExportedOptions> {
88
+ ): Promise<Record<string, FunctionOptions>> {
55
89
  vi.resetModules();
56
90
  if (databaseRegion === undefined) {
57
91
  delete process.env.DATABASE_REGION;
@@ -59,25 +93,44 @@ async function loadExportedOptions(
59
93
  process.env.DATABASE_REGION = databaseRegion;
60
94
  }
61
95
 
62
- await import("../src/index");
63
- const { onDocumentWritten } = await import("firebase-functions/firestore");
64
- const { onTaskDispatched } = await import("firebase-functions/tasks");
65
-
66
- const triggerCalls = vi.mocked(onDocumentWritten).mock.calls;
67
- const taskCalls = vi.mocked(onTaskDispatched).mock.calls;
68
- const trigger = triggerCalls[triggerCalls.length - 1][0] as FunctionOptions;
69
- const tasks = taskCalls
70
- .slice(-3)
71
- .map((call) => call[0] as unknown as FunctionOptions);
96
+ const index: Record<string, unknown> = await import("../src/index");
97
+ const deployed: Record<string, FunctionOptions> = {};
98
+ for (const [name, value] of Object.entries(index)) {
99
+ if (isDeployed(value)) {
100
+ deployed[name] = value.deployOptions;
101
+ }
102
+ }
103
+ return deployed;
104
+ }
72
105
 
73
- expect(tasks).toHaveLength(3);
74
- return { trigger, tasks };
106
+ async function loadExportedOptions(
107
+ databaseRegion?: string
108
+ ): Promise<ExportedOptions> {
109
+ const deployed = await loadDeployedOptions(databaseRegion);
110
+ const tasks = TASK_FUNCTIONS.map((name) => {
111
+ expect(deployed[name], name).toBeDefined();
112
+ return deployed[name];
113
+ });
114
+ return { trigger: deployed.fsexportbigquery, tasks };
75
115
  }
76
116
 
77
117
  function allOptions({ trigger, tasks }: ExportedOptions): FunctionOptions[] {
78
118
  return [trigger, ...tasks];
79
119
  }
80
120
 
121
+ /** Asserts `key` holds `expected`, or is absent from the declaration when `expected` is undefined. */
122
+ function expectOptional(
123
+ opts: FunctionOptions,
124
+ key: string,
125
+ expected: unknown
126
+ ): void {
127
+ if (expected === undefined) {
128
+ expect(opts).not.toHaveProperty(key);
129
+ } else {
130
+ expect(opts[key]).toBe(expected);
131
+ }
132
+ }
133
+
81
134
  describe("exported function options", () => {
82
135
  test.each([
83
136
  ["nam5", "us-central1"],
@@ -140,9 +193,8 @@ describe("exported function options", () => {
140
193
  });
141
194
 
142
195
  const rateLimits = syncTask.rateLimits as Record<string, unknown>;
143
- expect(rateLimits.maxConcurrentDispatches).toBe(500); // Concurrency comes from the gen2 defaults (80 per instance), so no
144
- // instance cap is declared.
145
- expect(syncTask.maxInstances).toBeUndefined();
196
+ expect(rateLimits.maxConcurrentDispatches).toBe(500);
197
+ expect(syncTask.maxInstances).toBe(500);
146
198
  // A blank .env value is 0 at deploy; the ternary restores the default.
147
199
  expect(String(rateLimits.maxDispatchesPerSecond)).toBe(
148
200
  "params.MAX_DISPATCHES_PER_SECOND < 1 ? 100 : params.MAX_DISPATCHES_PER_SECOND"
@@ -159,4 +211,24 @@ describe("exported function options", () => {
159
211
  expect(opts).not.toHaveProperty("rateLimits");
160
212
  }
161
213
  });
214
+
215
+ test.each(RUNTIME_OPTIONS_BY_FUNCTION)(
216
+ "%s runs one request per 0.1666 vCPU instance with ingress %s, maxInstances %s, timeout %s",
217
+ async (name, ingress, maxInstances, timeoutSeconds) => {
218
+ const deployed = await loadDeployedOptions();
219
+ const opts = deployed[name];
220
+ expect(opts.concurrency).toBe(1);
221
+ expect(opts.cpu).toBe("gcf_gen1");
222
+ expectOptional(opts, "ingressSettings", ingress);
223
+ expectOptional(opts, "maxInstances", maxInstances);
224
+ expectOptional(opts, "timeoutSeconds", timeoutSeconds);
225
+ }
226
+ );
227
+
228
+ test("the runtime options table names every exported function", async () => {
229
+ const deployed = await loadDeployedOptions();
230
+ expect(Object.keys(deployed).sort()).toEqual(
231
+ RUNTIME_OPTIONS_BY_FUNCTION.map(([name]) => name).sort()
232
+ );
233
+ });
162
234
  });
@@ -14,9 +14,12 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
- import { beforeAll, expect, test, vi } from "vitest";
17
+ import { afterEach, describe, expect, test, vi } from "vitest";
18
18
 
19
- const { requiresAPI } = vi.hoisted(() => ({ requiresAPI: vi.fn() }));
19
+ const { requiresAPI, requiresRole } = vi.hoisted(() => ({
20
+ requiresAPI: vi.fn(),
21
+ requiresRole: vi.fn(),
22
+ }));
20
23
 
21
24
  vi.mock("firebase-functions/firestore", () => ({
22
25
  onDocumentWritten: vi.fn(() => ({})),
@@ -26,18 +29,17 @@ vi.mock("firebase-functions/tasks", () => ({
26
29
  }));
27
30
  vi.mock("firebase-functions/v2", () => ({
28
31
  requiresAPI,
29
- requiresRole: vi.fn(),
32
+ requiresRole,
30
33
  }));
31
34
  vi.mock("firebase-functions/v2/lifecycle", () => ({
32
35
  afterFirstDeploy: vi.fn(),
33
36
  afterRedeploy: vi.fn(),
34
37
  }));
35
38
 
36
- beforeAll(async () => {
37
- await import("../src/index");
38
- });
39
+ const EVENTARC_API = "eventarcpublishing.googleapis.com";
40
+ const EVENTARC_PUBLISHER = "roles/eventarc.publisher";
39
41
 
40
- test.each([
42
+ const UNCONDITIONAL_APIS: ReadonlyArray<[api: string, reason: string]> = [
41
43
  [
42
44
  "firestore.googleapis.com",
43
45
  "Receives document change events from Cloud Firestore.",
@@ -46,14 +48,99 @@ test.each([
46
48
  "bigquery.googleapis.com",
47
49
  "Mirrors data from your Cloud Firestore collection in BigQuery.",
48
50
  ],
49
- [
50
- "eventarcpublishing.googleapis.com",
51
- "Publishes the extension's custom events to its Eventarc channel.",
52
- ],
53
- ])("declares %s", (api, reason) => {
54
- expect(requiresAPI).toHaveBeenCalledWith(api, reason);
51
+ ];
52
+
53
+ const UNCONDITIONAL_ROLES = [
54
+ "roles/bigquery.dataEditor",
55
+ "roles/datastore.user",
56
+ "roles/bigquery.user",
57
+ "roles/eventarc.eventReceiver",
58
+ "roles/run.invoker",
59
+ "roles/cloudtasks.enqueuer",
60
+ ];
61
+
62
+ afterEach(() => {
63
+ vi.unstubAllEnvs();
64
+ vi.clearAllMocks();
55
65
  });
56
66
 
57
- test("declares exactly the 3 APIs the kit needs", () => {
58
- expect(requiresAPI).toHaveBeenCalledTimes(3);
67
+ /** Loads the entry afresh with `EVENTARC_CHANNEL` set to `channel`, or unset when omitted. */
68
+ async function loadWithChannel(channel?: string): Promise<void> {
69
+ vi.resetModules();
70
+ if (channel === undefined) {
71
+ vi.stubEnv("EVENTARC_CHANNEL", undefined);
72
+ } else {
73
+ vi.stubEnv("EVENTARC_CHANNEL", channel);
74
+ }
75
+ await import("../src/index");
76
+ }
77
+
78
+ function declaredApis(): string[] {
79
+ return requiresAPI.mock.calls.map(([api]) => api);
80
+ }
81
+
82
+ function declaredRoles(): string[] {
83
+ return requiresRole.mock.calls.map(([role]) => role);
84
+ }
85
+
86
+ describe("without an Eventarc channel", () => {
87
+ test.each(UNCONDITIONAL_APIS)("declares %s", async (api, reason) => {
88
+ await loadWithChannel();
89
+ expect(requiresAPI).toHaveBeenCalledWith(api, reason);
90
+ });
91
+
92
+ test("declares exactly the 2 APIs the export path needs", async () => {
93
+ await loadWithChannel();
94
+ expect(declaredApis()).toEqual(UNCONDITIONAL_APIS.map(([api]) => api));
95
+ });
96
+
97
+ test("declares the roles the export path needs and no publisher role", async () => {
98
+ await loadWithChannel();
99
+ expect(declaredRoles()).toEqual(UNCONDITIONAL_ROLES);
100
+ });
101
+
102
+ // The extension declared one API and gained Eventarc publishing only when the
103
+ // user opted into events, so a default install must not gate the deploy on it.
104
+ test.each([
105
+ ["unset", undefined],
106
+ ["empty", ""],
107
+ ["whitespace-only", " "],
108
+ ])(
109
+ "leaves the Eventarc publishing API and role undeclared when EVENTARC_CHANNEL is %s",
110
+ async (_label, channel) => {
111
+ await loadWithChannel(channel);
112
+ expect(declaredApis()).not.toContain(EVENTARC_API);
113
+ expect(declaredRoles()).not.toContain(EVENTARC_PUBLISHER);
114
+ }
115
+ );
116
+ });
117
+
118
+ describe("with an Eventarc channel", () => {
119
+ const CHANNEL = "projects/p/locations/l/channels/firebase";
120
+
121
+ test("declares the Eventarc publishing API", async () => {
122
+ await loadWithChannel(CHANNEL);
123
+ expect(requiresAPI).toHaveBeenCalledWith(
124
+ EVENTARC_API,
125
+ "Publishes the extension's custom events to its Eventarc channel."
126
+ );
127
+ expect(declaredApis()).toEqual([
128
+ ...UNCONDITIONAL_APIS.map(([api]) => api),
129
+ EVENTARC_API,
130
+ ]);
131
+ });
132
+
133
+ test("declares the publisher role alongside the unconditional roles", async () => {
134
+ await loadWithChannel(CHANNEL);
135
+ expect(declaredRoles()).toEqual([
136
+ ...UNCONDITIONAL_ROLES,
137
+ EVENTARC_PUBLISHER,
138
+ ]);
139
+ });
140
+
141
+ test("a padded channel name still counts as configured", async () => {
142
+ await loadWithChannel(` ${CHANNEL} `);
143
+ expect(declaredApis()).toContain(EVENTARC_API);
144
+ expect(declaredRoles()).toContain(EVENTARC_PUBLISHER);
145
+ });
59
146
  });