@firebase-function-kits/firestore-bigquery-export 0.0.2-rc.9 → 0.1.1

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.
@@ -14,6 +14,7 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
+ import { logger } from "firebase-functions";
17
18
  import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
18
19
 
19
20
  const { publish, channel } = vi.hoisted(() => {
@@ -27,6 +28,7 @@ vi.mock("firebase-admin/eventarc", () => ({
27
28
  }));
28
29
 
29
30
  import {
31
+ configuredEventChannel,
30
32
  recordCompletionEvent,
31
33
  recordErrorEvent,
32
34
  recordStartEvent,
@@ -51,6 +53,28 @@ describe("no channel configured", () => {
51
53
  await recordCompletionEvent({ a: 1 });
52
54
  expect(publish).not.toHaveBeenCalled();
53
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
+ });
54
78
  });
55
79
 
56
80
  describe("channel configured", () => {
@@ -59,16 +83,30 @@ describe("channel configured", () => {
59
83
  setupEventChannel();
60
84
  });
61
85
 
62
- test("publishes the firestore-bigquery-export event type only", async () => {
63
- await recordStartEvent({ a: 1 });
64
- expect(publish).toHaveBeenCalledTimes(1);
65
- expect(publish).toHaveBeenCalledWith(
66
- expect.objectContaining({
67
- type: "firebase.extensions.firestore-bigquery-export.v1.onStart",
68
- })
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()
69
98
  );
70
99
  });
71
100
 
101
+ test("publishes both the legacy and the current event type", async () => {
102
+ await recordStartEvent({ a: 1 });
103
+ expect(publish).toHaveBeenCalledTimes(2);
104
+ expect(publish.mock.calls.map((c) => c[0].type)).toEqual([
105
+ "firebase.extensions.firestore-counter.v1.onStart",
106
+ "firebase.extensions.firestore-bigquery-export.v1.onStart",
107
+ ]);
108
+ });
109
+
72
110
  test("error / success / completion map to their event types", async () => {
73
111
  await recordErrorEvent(new Error("boom"));
74
112
  await recordSuccessEvent({ subject: "doc1", data: { a: 1 } });
@@ -76,9 +114,51 @@ describe("channel configured", () => {
76
114
 
77
115
  const types = publish.mock.calls.map((c) => c[0].type);
78
116
  expect(types).toEqual([
117
+ "firebase.extensions.firestore-counter.v1.onError",
79
118
  "firebase.extensions.firestore-bigquery-export.v1.onError",
119
+ "firebase.extensions.firestore-counter.v1.onSuccess",
80
120
  "firebase.extensions.firestore-bigquery-export.v1.onSuccess",
121
+ "firebase.extensions.firestore-counter.v1.onCompletion",
81
122
  "firebase.extensions.firestore-bigquery-export.v1.onCompletion",
82
123
  ]);
83
124
  });
125
+
126
+ test("the legacy copy carries the same payload as the current one", async () => {
127
+ await recordErrorEvent(new Error("boom"), "doc1");
128
+
129
+ const [legacy, current] = publish.mock.calls.map((c) => c[0]);
130
+ expect(legacy.data).toEqual({ message: "boom" });
131
+ expect(legacy.subject).toBe("doc1");
132
+ expect({ ...legacy, type: undefined }).toEqual({
133
+ ...current,
134
+ type: undefined,
135
+ });
136
+ });
137
+ });
138
+
139
+ describe("publish failures", () => {
140
+ afterEach(() => {
141
+ publish.mockReset();
142
+ publish.mockResolvedValue(undefined);
143
+ });
144
+
145
+ test("a rejected publish is logged and never reaches the caller", async () => {
146
+ const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
147
+ publish.mockRejectedValue(
148
+ Object.assign(new Error("Permission denied"), { code: 403 })
149
+ );
150
+ process.env.EVENTARC_CHANNEL = "projects/p/locations/l/channels/c";
151
+ setupEventChannel();
152
+
153
+ await expect(recordStartEvent({ a: 1 })).resolves.toBeUndefined();
154
+ await expect(recordErrorEvent(new Error("boom"))).resolves.toBeUndefined();
155
+ await expect(
156
+ recordSuccessEvent({ subject: "s", data: {} })
157
+ ).resolves.toBeUndefined();
158
+ await expect(recordCompletionEvent({ a: 1 })).resolves.toBeUndefined();
159
+
160
+ // Two event types per call: the old and the new.
161
+ expect(warn).toHaveBeenCalledTimes(8);
162
+ warn.mockRestore();
163
+ });
84
164
  });
@@ -332,18 +332,4 @@ describe("handleSyncBigQueryTask", () => {
332
332
  // belong to Cloud Tasks alone.
333
333
  expect(ctx.enqueue).not.toHaveBeenCalled();
334
334
  });
335
-
336
- test("does not rethrow when the success event fails after the row lands", async () => {
337
- // The row is already in BigQuery; a Cloud Tasks retry would land past the
338
- // insertId dedupe window and duplicate it.
339
- const ctx = makeCtx();
340
- (
341
- events.recordSuccessEvent as ReturnType<typeof vi.fn>
342
- ).mockRejectedValueOnce(new Error("channel down"));
343
-
344
- await expect(
345
- handleSyncBigQueryTask(taskRequest(serializedChange()), ctx)
346
- ).resolves.toBeUndefined();
347
- expect(ctx.tracker.record).toHaveBeenCalledTimes(1);
348
- });
349
335
  });
@@ -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
  });
@@ -41,4 +41,22 @@ describe("firestoreLocationToFunctionRegion", () => {
41
41
  test("returns undefined for an empty location", () => {
42
42
  expect(firestoreLocationToFunctionRegion("")).toBeUndefined();
43
43
  });
44
+
45
+ test("returns undefined for a whitespace-only location", () => {
46
+ expect(firestoreLocationToFunctionRegion(" ")).toBeUndefined();
47
+ });
48
+
49
+ test.each([
50
+ ["NAM5", "us-central1"],
51
+ ["Eur3", "europe-west1"],
52
+ [" nam7 ", "us-central1"],
53
+ ])("normalizes %s before the multi-region lookup", (location, region) => {
54
+ expect(firestoreLocationToFunctionRegion(location)).toBe(region);
55
+ });
56
+
57
+ test("lowercases and trims a regional location", () => {
58
+ expect(firestoreLocationToFunctionRegion(" Europe-West2 ")).toBe(
59
+ "europe-west2"
60
+ );
61
+ });
44
62
  });
@@ -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,10 +48,99 @@ test.each([
46
48
  "bigquery.googleapis.com",
47
49
  "Mirrors data from your Cloud Firestore collection in BigQuery.",
48
50
  ],
49
- ])("declares %s", (api, reason) => {
50
- 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();
51
65
  });
52
66
 
53
- test("declares exactly the two APIs", () => {
54
- expect(requiresAPI).toHaveBeenCalledTimes(2);
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
+ });
55
146
  });
@@ -0,0 +1,138 @@
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 { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
18
+ import { declaredParams } from "firebase-functions/params";
19
+
20
+ const REQUIRED = [
21
+ "DATASET_LOCATION",
22
+ "BIGQUERY_PROJECT_ID",
23
+ "DATABASE",
24
+ "COLLECTION_PATH",
25
+ "DATASET_ID",
26
+ "TABLE_ID",
27
+ "VIEW_TYPE",
28
+ "USE_NEW_SNAPSHOT_QUERY_SYNTAX",
29
+ "LOG_LEVEL",
30
+ ];
31
+
32
+ const OPTIONAL = [
33
+ "DATABASE_REGION",
34
+ "BACKUP_COLLECTION",
35
+ "MAX_DISPATCHES_PER_SECOND",
36
+ "MAX_ENQUEUE_ATTEMPTS",
37
+ ];
38
+
39
+ let assertRequiredParams: (names?: ReadonlyArray<string>) => void;
40
+
41
+ beforeAll(async () => {
42
+ // Some kits resolve the instance id at import; the CLI injects it for real
43
+ // instances, so supply one before loading the module under test.
44
+ process.env.FIREBASE_KIT_INSTANCE_ID ??= "test-instance";
45
+ ({ assertRequiredParams } = await import("../src/config"));
46
+ });
47
+
48
+ afterEach(() => {
49
+ vi.unstubAllEnvs();
50
+ });
51
+
52
+ describe("assertRequiredParams", () => {
53
+ test("passes when no params have been supplied yet", () => {
54
+ expect(() => assertRequiredParams()).not.toThrow();
55
+ });
56
+
57
+ test("passes when every required param holds a value", () => {
58
+ for (const name of REQUIRED) {
59
+ vi.stubEnv(name, "set");
60
+ }
61
+
62
+ expect(() => assertRequiredParams()).not.toThrow();
63
+ });
64
+
65
+ test("rejects required params blanked in .env, naming each one", () => {
66
+ for (const name of REQUIRED) {
67
+ vi.stubEnv(name, "");
68
+ }
69
+
70
+ expect(() => assertRequiredParams()).toThrow(REQUIRED.join(", "));
71
+ });
72
+
73
+ test("rejects a whitespace-only value, which the CLI prompt accepts", () => {
74
+ vi.stubEnv(REQUIRED[0], " ");
75
+
76
+ expect(() => assertRequiredParams()).toThrow(REQUIRED[0]);
77
+ });
78
+
79
+ test("ignores optional params left blank", () => {
80
+ for (const name of OPTIONAL) {
81
+ vi.stubEnv(name, "");
82
+ }
83
+
84
+ expect(() => assertRequiredParams()).not.toThrow();
85
+ });
86
+ });
87
+
88
+ type Declaration = {
89
+ name: string;
90
+ options?: {
91
+ default?: unknown;
92
+ input?: {
93
+ text?: { nonEmpty?: boolean; validationRegex?: string | RegExp };
94
+ multiSelect?: { nonEmpty?: boolean };
95
+ };
96
+ };
97
+ };
98
+
99
+ // The CLI writes whatever a prompt resolves to into .env, an empty answer
100
+ // included, so a required param the prompt accepts empty reaches
101
+ // assertRequiredParams as a blank entry the user never typed.
102
+ function promptAcceptsEmpty({ options }: Declaration): boolean {
103
+ const fallback = options?.default;
104
+ if (fallback !== undefined && String(fallback).trim() !== "") {
105
+ return false;
106
+ }
107
+
108
+ const input = options?.input;
109
+ if (!input) {
110
+ return true;
111
+ }
112
+ if (input.multiSelect) {
113
+ return input.multiSelect.nonEmpty !== true;
114
+ }
115
+ if (!input.text) {
116
+ return false;
117
+ }
118
+ if (input.text.nonEmpty) {
119
+ return false;
120
+ }
121
+ if (input.text.validationRegex) {
122
+ return new RegExp(input.text.validationRegex).test("");
123
+ }
124
+ return true;
125
+ }
126
+
127
+ describe("required param declarations", () => {
128
+ test("the CLI prompt cannot resolve any of them to an empty value", () => {
129
+ const declarations = declaredParams as unknown as Declaration[];
130
+
131
+ for (const name of REQUIRED) {
132
+ const declaration = declarations.find((param) => param.name === name);
133
+
134
+ expect(declaration, name).toBeDefined();
135
+ expect(promptAcceptsEmpty(declaration as Declaration), name).toBe(false);
136
+ }
137
+ });
138
+ });