@dz9systems/vibeinfra 0.0.0-stage → 0.0.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.
@@ -0,0 +1,794 @@
1
+ import {
2
+ ADC_LOGIN_COMMAND,
3
+ VibeInfraError,
4
+ assertOperationName,
5
+ assertParent,
6
+ assertProjectId,
7
+ assertServiceId,
8
+ assertWebAppId
9
+ } from "./chunk-ZDFLQZGF.js";
10
+
11
+ // packages/firebase-provider/src/auth.ts
12
+ import { readFile } from "node:fs/promises";
13
+ import { GoogleAuth } from "google-auth-library";
14
+ var ADC_SCOPES = ["https://www.googleapis.com/auth/cloud-platform"];
15
+ async function connectApplicationDefaultCredentials(auth = new GoogleAuth({ scopes: [...ADC_SCOPES] })) {
16
+ let googleClient;
17
+ try {
18
+ googleClient = await auth.getClient();
19
+ const token = await googleClient.getAccessToken();
20
+ if (!token.token) {
21
+ throw new Error("Application Default Credentials did not return an access token.");
22
+ }
23
+ } catch (error) {
24
+ if (error instanceof VibeInfraError) {
25
+ throw error;
26
+ }
27
+ throw new VibeInfraError({
28
+ code: "missing_credentials",
29
+ message: "Application Default Credentials are not available.",
30
+ remediation: `Run \`${ADC_LOGIN_COMMAND}\` and retry. VibeInfra uses ADC for Google API calls. It does not read Firebase CLI credential files and it does not ask you to create a service account key. Firebase CLI login is a separate credential used only by firebase-tools when it is already present.`,
31
+ category: "provider",
32
+ cause: error
33
+ });
34
+ }
35
+ const credentials = await auth.getCredentials();
36
+ const serviceAccount = clientEmail(credentials);
37
+ let account = serviceAccount;
38
+ let credentialKind = serviceAccount ? "service-account" : "unknown";
39
+ if (!serviceAccount) {
40
+ const email = await lookupEmail(googleClient);
41
+ if (email) {
42
+ account = email;
43
+ credentialKind = "authorized-user";
44
+ }
45
+ }
46
+ const credentialFile = process.env.GOOGLE_APPLICATION_CREDENTIALS;
47
+ if (credentialFile) {
48
+ const type = await readCredentialType(credentialFile);
49
+ if (type === "service_account") {
50
+ credentialKind = "service-account";
51
+ } else if (type === "authorized_user") {
52
+ credentialKind = "authorized-user";
53
+ }
54
+ }
55
+ return {
56
+ identity: {
57
+ source: credentialFile ? "google-application-credentials" : "application-default-credentials",
58
+ account,
59
+ credentialKind
60
+ },
61
+ client: {
62
+ async request(input) {
63
+ const response = await googleClient.request({
64
+ url: input.url,
65
+ method: input.method,
66
+ ...input.body !== void 0 ? { data: input.body } : {},
67
+ responseType: "json",
68
+ validateStatus: () => true
69
+ });
70
+ return { status: response.status, data: response.data };
71
+ }
72
+ }
73
+ };
74
+ }
75
+ async function lookupEmail(client) {
76
+ try {
77
+ const response = await client.request({
78
+ url: "https://www.googleapis.com/oauth2/v3/userinfo",
79
+ validateStatus: () => true
80
+ });
81
+ if (response.status !== 200) {
82
+ return null;
83
+ }
84
+ return response.data.email ?? null;
85
+ } catch {
86
+ return null;
87
+ }
88
+ }
89
+ async function readCredentialType(file) {
90
+ try {
91
+ const parsed = JSON.parse(await readFile(file, "utf8"));
92
+ return typeof parsed.type === "string" ? parsed.type : null;
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
97
+ function clientEmail(credentials) {
98
+ if (typeof credentials === "object" && credentials !== null && "client_email" in credentials && typeof credentials.client_email === "string") {
99
+ return credentials.client_email;
100
+ }
101
+ return null;
102
+ }
103
+
104
+ // packages/firebase-provider/src/hosting.ts
105
+ async function loadFirebaseTools() {
106
+ const imported = await import("firebase-tools");
107
+ const client = imported.default && typeof imported.default.deploy === "function" ? imported.default : imported;
108
+ if (typeof client.deploy !== "function") {
109
+ throw new VibeInfraError({
110
+ code: "firebase_tools_unavailable",
111
+ message: "The installed firebase-tools package does not expose deploy().",
112
+ remediation: "Reinstall dependencies from the VibeInfra repository. Hosting deploy uses the Firebase CLI module and does not reimplement the upload protocol.",
113
+ category: "provider"
114
+ });
115
+ }
116
+ return client;
117
+ }
118
+ async function deployHostingWithFirebaseTools(input, load = loadFirebaseTools) {
119
+ const tools = await load();
120
+ try {
121
+ const result = await tools.deploy({
122
+ only: "hosting",
123
+ project: input.projectId,
124
+ cwd: input.projectPath,
125
+ nonInteractive: true
126
+ });
127
+ const versionName = extractVersion(result);
128
+ return versionName ? { versionName } : {};
129
+ } catch (error) {
130
+ if (error instanceof VibeInfraError) {
131
+ throw error;
132
+ }
133
+ const message = error instanceof Error ? error.message : "Firebase CLI hosting deploy failed.";
134
+ throw new VibeInfraError({
135
+ code: "hosting_deploy_failed",
136
+ message,
137
+ remediation: "Firebase CLI chooses credentials in this order: FIREBASE_TOKEN, an existing `firebase login` session, GOOGLE_APPLICATION_CREDENTIALS, then Application Default Credentials. Management API calls always use ADC. Use the same Google account for both, or log out of the Firebase CLI if ADC should be used for the deploy. Confirm firebase.json has a static hosting.public directory and that the Hosting API is enabled.",
138
+ category: "provider",
139
+ cause: error
140
+ });
141
+ }
142
+ }
143
+ function extractVersion(result) {
144
+ if (typeof result !== "object" || result === null || !("hosting" in result)) {
145
+ return void 0;
146
+ }
147
+ const hosting = result.hosting;
148
+ if (typeof hosting === "string") {
149
+ return hosting;
150
+ }
151
+ if (Array.isArray(hosting) && typeof hosting[0] === "string") {
152
+ return hosting[0];
153
+ }
154
+ return void 0;
155
+ }
156
+
157
+ // packages/firebase-provider/src/google-error.ts
158
+ function mapHttpError(status, data, method, url) {
159
+ const body = isRecord(data) ? data : void 0;
160
+ const message = body?.error?.message ?? `${method} ${pathOf(url)} failed with HTTP ${status}.`;
161
+ const reason = body?.error?.status ?? body?.error?.errors?.[0]?.reason ?? "";
162
+ const quota = status === 429 || /RESOURCE_EXHAUSTED|RATE_LIMIT|QUOTA/i.test(`${reason} ${message}`);
163
+ if (quota) {
164
+ return new VibeInfraError({
165
+ code: "quota_exceeded",
166
+ message,
167
+ remediation: "Wait and retry. VibeInfra retries quota responses with backoff, then stops. No resources are deleted.",
168
+ retryable: true,
169
+ category: "provider",
170
+ httpStatus: status
171
+ });
172
+ }
173
+ if (status === 409 || reason === "ALREADY_EXISTS") {
174
+ return new VibeInfraError({
175
+ code: "project_id_collision",
176
+ message,
177
+ remediation: "Choose another project id, or rerun against the existing project so VibeInfra can reuse it. Nothing is deleted.",
178
+ category: "provider",
179
+ httpStatus: status
180
+ });
181
+ }
182
+ if (status === 401) {
183
+ return new VibeInfraError({
184
+ code: "unauthenticated",
185
+ message,
186
+ remediation: "Run `gcloud auth application-default login` and retry. VibeInfra does not read the Firebase CLI credential cache.",
187
+ category: "provider",
188
+ httpStatus: status
189
+ });
190
+ }
191
+ if (status === 403) {
192
+ return new VibeInfraError({
193
+ code: "permission_denied",
194
+ message,
195
+ remediation: "Grant the permissions listed in the plan on this project. A missing project can also be hidden as permission denied. VibeInfra did not attach billing or delete resources.",
196
+ category: "provider",
197
+ httpStatus: status
198
+ });
199
+ }
200
+ if (status === 400) {
201
+ return new VibeInfraError({
202
+ code: "invalid_request",
203
+ message,
204
+ remediation: "Check the project id, parent, and service names. The Google API rejected the request before resources were changed by this call.",
205
+ category: "provider",
206
+ httpStatus: status
207
+ });
208
+ }
209
+ return new VibeInfraError({
210
+ code: "google_api_error",
211
+ message,
212
+ remediation: "Read the Google API message, fix the condition, and retry. Completed resources will be reconciled on the next run.",
213
+ retryable: status >= 500,
214
+ category: "provider",
215
+ httpStatus: status
216
+ });
217
+ }
218
+ function assertOk(status, data, method, url) {
219
+ if (status < 200 || status >= 300) {
220
+ throw mapHttpError(status, data, method, url);
221
+ }
222
+ }
223
+ function pathOf(url) {
224
+ try {
225
+ return new URL(url).pathname;
226
+ } catch {
227
+ return url;
228
+ }
229
+ }
230
+ function isRecord(value) {
231
+ return typeof value === "object" && value !== null;
232
+ }
233
+
234
+ // packages/firebase-provider/src/urls.ts
235
+ var FIREBASE_API = "https://firebase.googleapis.com/v1beta1";
236
+ var RESOURCE_MANAGER_API = "https://cloudresourcemanager.googleapis.com/v3";
237
+ var SERVICE_USAGE_API = "https://serviceusage.googleapis.com/v1";
238
+ var ALLOWED_HOSTS = /* @__PURE__ */ new Set([
239
+ "firebase.googleapis.com",
240
+ "cloudresourcemanager.googleapis.com",
241
+ "serviceusage.googleapis.com"
242
+ ]);
243
+ function assertAllowedApiUrl(url) {
244
+ const host = new URL(url).host;
245
+ if (!ALLOWED_HOSTS.has(host)) {
246
+ throw new VibeInfraError({
247
+ code: "blocked_api_host",
248
+ message: `Refusing to call ${host}.`,
249
+ remediation: "Phase 1 only calls Firebase Management, Cloud Resource Manager, and Service Usage. It does not call Cloud Billing.",
250
+ category: "provider"
251
+ });
252
+ }
253
+ }
254
+ function firebaseProjectUrl(projectId) {
255
+ assertProjectId(projectId);
256
+ return `${FIREBASE_API}/projects/${projectId}`;
257
+ }
258
+ function addFirebaseUrl(projectId) {
259
+ return `${firebaseProjectUrl(projectId)}:addFirebase`;
260
+ }
261
+ function webAppsUrl(projectId) {
262
+ return `${firebaseProjectUrl(projectId)}/webApps`;
263
+ }
264
+ function webAppUrl(projectId, appId) {
265
+ assertWebAppId(appId);
266
+ return `${webAppsUrl(projectId)}/${appId}`;
267
+ }
268
+ function webAppConfigUrl(projectId, appId) {
269
+ return `${webAppUrl(projectId, appId)}/config`;
270
+ }
271
+ function cloudProjectUrl(projectId) {
272
+ assertProjectId(projectId);
273
+ return `${RESOURCE_MANAGER_API}/projects/${projectId}`;
274
+ }
275
+ function serviceUrl(projectId, serviceId) {
276
+ assertProjectId(projectId);
277
+ assertServiceId(serviceId);
278
+ return `${SERVICE_USAGE_API}/projects/${projectId}/services/${serviceId}`;
279
+ }
280
+ function batchEnableUrl(projectId) {
281
+ assertProjectId(projectId);
282
+ return `${SERVICE_USAGE_API}/projects/${projectId}/services:batchEnable`;
283
+ }
284
+
285
+ // packages/firebase-provider/src/http.ts
286
+ var sleepDefault = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
287
+ async function send(client, input) {
288
+ assertAllowedApiUrl(input.url);
289
+ const attempts = input.retry === false ? 1 : 4;
290
+ const sleep = input.sleep ?? sleepDefault;
291
+ let delay = 500;
292
+ let latest = null;
293
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
294
+ latest = await client.request({ url: input.url, method: input.method, ...input.body !== void 0 ? { body: input.body } : {} });
295
+ if ((latest.status === 429 || latest.status === 503) && attempt < attempts) {
296
+ await sleep(delay);
297
+ delay = Math.min(8e3, delay * 2);
298
+ continue;
299
+ }
300
+ return latest;
301
+ }
302
+ if (!latest) {
303
+ throw new VibeInfraError({
304
+ code: "google_api_error",
305
+ message: "The Google API request did not return a response.",
306
+ remediation: "Retry the command.",
307
+ category: "provider",
308
+ retryable: true
309
+ });
310
+ }
311
+ return latest;
312
+ }
313
+ async function listPages(readPage) {
314
+ const items = [];
315
+ let pageToken;
316
+ for (let page = 0; page < 50; page += 1) {
317
+ const result = await readPage(pageToken);
318
+ items.push(...result.items);
319
+ if (!result.nextPageToken) {
320
+ return items;
321
+ }
322
+ pageToken = result.nextPageToken;
323
+ }
324
+ throw new VibeInfraError({
325
+ code: "pagination_limit",
326
+ message: "Google returned more than 50 pages of results.",
327
+ remediation: "Pass --project with the exact project id instead of relying on a full listing.",
328
+ category: "provider"
329
+ });
330
+ }
331
+
332
+ // packages/firebase-provider/src/map.ts
333
+ function mapFirebaseProject(data) {
334
+ if (!data?.projectId) {
335
+ return null;
336
+ }
337
+ return {
338
+ projectId: data.projectId,
339
+ projectNumber: data.projectNumber ?? null,
340
+ displayName: data.displayName ?? null,
341
+ resourceName: data.name ?? `projects/${data.projectId}`,
342
+ firebaseEnabled: true,
343
+ hostingSite: data.resources?.hostingSite ?? null,
344
+ state: data.state ?? "ACTIVE"
345
+ };
346
+ }
347
+ function mapCloudProject(data) {
348
+ if (!data?.projectId) {
349
+ return null;
350
+ }
351
+ return {
352
+ projectId: data.projectId,
353
+ projectNumber: data.projectNumber ?? projectNumberFromName(data.name),
354
+ displayName: data.displayName ?? null,
355
+ resourceName: data.name ?? `projects/${data.projectId}`,
356
+ firebaseEnabled: false,
357
+ hostingSite: null,
358
+ state: data.state ?? data.lifecycleState ?? null
359
+ };
360
+ }
361
+ function mapWebApp(data) {
362
+ if (!data?.appId || !data.projectId) {
363
+ return null;
364
+ }
365
+ return {
366
+ appId: data.appId,
367
+ displayName: data.displayName ?? null,
368
+ projectId: data.projectId,
369
+ name: data.name ?? `projects/${data.projectId}/webApps/${data.appId}`
370
+ };
371
+ }
372
+ function mapWebAppConfig(data) {
373
+ if (!data?.projectId || !data.appId || !data.apiKey) {
374
+ throw new VibeInfraError({
375
+ code: "web_app_config_incomplete",
376
+ message: "Firebase returned a web app config without a project id, app id, or API key.",
377
+ remediation: "Retry the command. If the app was just created, wait for it to become readable and resume.",
378
+ category: "provider",
379
+ retryable: true
380
+ });
381
+ }
382
+ return {
383
+ projectId: data.projectId,
384
+ appId: data.appId,
385
+ apiKey: data.apiKey,
386
+ ...data.authDomain ? { authDomain: data.authDomain } : {},
387
+ ...data.databaseURL ? { databaseURL: data.databaseURL } : {},
388
+ ...data.storageBucket ? { storageBucket: data.storageBucket } : {},
389
+ ...data.messagingSenderId ? { messagingSenderId: data.messagingSenderId } : {},
390
+ ...data.measurementId ? { measurementId: data.measurementId } : {},
391
+ ...data.projectNumber ? { projectNumber: data.projectNumber } : {}
392
+ };
393
+ }
394
+ function projectIdFromResource(resource) {
395
+ if (!resource) {
396
+ return null;
397
+ }
398
+ const match = /^projects\/([a-z][a-z0-9-]{4,28}[a-z0-9])$/.exec(resource);
399
+ return match?.[1] ?? null;
400
+ }
401
+ function projectNumberFromName(name) {
402
+ const match = /^projects\/([0-9]+)$/.exec(name ?? "");
403
+ return match?.[1] ?? null;
404
+ }
405
+
406
+ // packages/firebase-provider/src/operations.ts
407
+ async function waitForOperation(input) {
408
+ if (input.operation.done) {
409
+ assertOperationSucceeded(input.operation);
410
+ return input.operation;
411
+ }
412
+ const rawName = input.operation.name;
413
+ if (!rawName) {
414
+ throw new VibeInfraError({
415
+ code: "invalid_operation",
416
+ message: "Google did not return an operation name.",
417
+ remediation: "Retry the command. If a resource was created, the next run reconciles it instead of duplicating it.",
418
+ category: "provider",
419
+ retryable: true
420
+ });
421
+ }
422
+ const name = rawName.startsWith(`${input.apiRoot}/`) ? rawName.slice(input.apiRoot.length + 1) : rawName;
423
+ assertOperationName(name);
424
+ const sleep = input.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
425
+ const now = input.now ?? Date.now;
426
+ const timeoutMs = input.timeoutMs ?? 18e4;
427
+ const deadline = now() + timeoutMs;
428
+ let delay = 1e3;
429
+ for (; ; ) {
430
+ const response = await send(input.client, {
431
+ url: `${input.apiRoot}/${name}`,
432
+ method: "GET",
433
+ sleep
434
+ });
435
+ if (response.status === 404) {
436
+ throw new VibeInfraError({
437
+ code: "operation_not_found",
438
+ message: `Operation ${name} is no longer available.`,
439
+ remediation: "Retry the command. VibeInfra reads the project again and reuses resources that were created.",
440
+ category: "provider",
441
+ retryable: true
442
+ });
443
+ }
444
+ assertOk(response.status, response.data, "GET", `${input.apiRoot}/${name}`);
445
+ if (response.data.done) {
446
+ assertOperationSucceeded(response.data);
447
+ return response.data;
448
+ }
449
+ if (now() >= deadline) {
450
+ throw new VibeInfraError({
451
+ code: "operation_timeout",
452
+ message: `Operation ${name} did not finish within ${timeoutMs}ms.`,
453
+ remediation: "Wait and retry. The operation may still complete. The next run reconciles existing resources and does not delete them.",
454
+ category: "provider",
455
+ retryable: true
456
+ });
457
+ }
458
+ await sleep(delay);
459
+ delay = Math.min(1e4, Math.floor(delay * 1.5));
460
+ }
461
+ }
462
+ function assertOperationSucceeded(operation) {
463
+ if (!operation.error) {
464
+ return;
465
+ }
466
+ throw new VibeInfraError({
467
+ code: "operation_failed",
468
+ message: operation.error.message ?? "A Google Cloud operation failed.",
469
+ remediation: "Fix the error and retry. VibeInfra will not delete resources created before the failure.",
470
+ category: "provider",
471
+ retryable: operation.error.code === 429 || operation.error.status === "RESOURCE_EXHAUSTED",
472
+ ...operation.error.code !== void 0 ? { httpStatus: operation.error.code } : {}
473
+ });
474
+ }
475
+
476
+ // packages/firebase-provider/src/projects.ts
477
+ async function listFirebaseProjects(client, options = {}) {
478
+ return listPages(async (pageToken) => {
479
+ const url = new URL(`${FIREBASE_API}/projects`);
480
+ url.searchParams.set("pageSize", "100");
481
+ if (pageToken) {
482
+ url.searchParams.set("pageToken", pageToken);
483
+ }
484
+ const response = await send(client, {
485
+ url: url.toString(),
486
+ method: "GET",
487
+ ...options
488
+ });
489
+ assertOk(response.status, response.data, "GET", url.toString());
490
+ return {
491
+ items: (response.data.results ?? []).flatMap((project) => {
492
+ const mapped = mapFirebaseProject(project);
493
+ return mapped ? [mapped] : [];
494
+ }),
495
+ ...response.data.nextPageToken ? { nextPageToken: response.data.nextPageToken } : {}
496
+ };
497
+ });
498
+ }
499
+ async function listAvailableCloudProjects(client, options = {}) {
500
+ return listPages(async (pageToken) => {
501
+ const url = new URL(`${FIREBASE_API}/availableProjects`);
502
+ if (pageToken) {
503
+ url.searchParams.set("pageToken", pageToken);
504
+ }
505
+ const response = await send(client, {
506
+ url: url.toString(),
507
+ method: "GET",
508
+ ...options
509
+ });
510
+ assertOk(response.status, response.data, "GET", url.toString());
511
+ return {
512
+ items: (response.data.projectInfo ?? []).flatMap((project) => {
513
+ const projectId = projectIdFromResource(project.project);
514
+ if (!projectId) {
515
+ return [];
516
+ }
517
+ return [{
518
+ projectId,
519
+ projectNumber: null,
520
+ displayName: project.displayName ?? null,
521
+ resourceName: project.project ?? `projects/${projectId}`,
522
+ firebaseEnabled: false,
523
+ hostingSite: null,
524
+ state: null
525
+ }];
526
+ }),
527
+ ...response.data.nextPageToken ? { nextPageToken: response.data.nextPageToken } : {}
528
+ };
529
+ });
530
+ }
531
+ async function getFirebaseProject(client, projectId, options = {}) {
532
+ const url = firebaseProjectUrl(projectId);
533
+ const response = await send(client, { url, method: "GET", ...options });
534
+ if (response.status === 404) {
535
+ return null;
536
+ }
537
+ assertOk(response.status, response.data, "GET", url);
538
+ return mapFirebaseProject(response.data);
539
+ }
540
+ async function getCloudProject(client, projectId, options = {}) {
541
+ const url = cloudProjectUrl(projectId);
542
+ const response = await send(client, { url, method: "GET", ...options });
543
+ if (response.status === 404) {
544
+ return null;
545
+ }
546
+ assertOk(response.status, response.data, "GET", url);
547
+ return mapCloudProject(response.data);
548
+ }
549
+ async function createCloudProject(client, input, options = {}) {
550
+ assertProjectId(input.projectId);
551
+ if (input.parent) {
552
+ assertParent(input.parent);
553
+ }
554
+ const url = `${RESOURCE_MANAGER_API}/projects`;
555
+ const response = await send(client, {
556
+ url,
557
+ method: "POST",
558
+ body: {
559
+ projectId: input.projectId,
560
+ displayName: input.displayName,
561
+ ...input.parent ? { parent: input.parent } : {}
562
+ },
563
+ ...options,
564
+ retry: false
565
+ });
566
+ assertOk(response.status, response.data, "POST", url);
567
+ const operation = await waitForOperation({ operation: response.data, apiRoot: RESOURCE_MANAGER_API, client, ...options });
568
+ const created = await getCloudProject(client, input.projectId, options);
569
+ if (created) {
570
+ return created;
571
+ }
572
+ const mapped = mapCloudProject(operation.response);
573
+ if (mapped) {
574
+ return mapped;
575
+ }
576
+ throw unconfirmed(input.projectId);
577
+ }
578
+ async function addFirebase(client, projectId, options = {}) {
579
+ const url = addFirebaseUrl(projectId);
580
+ const response = await send(client, { url, method: "POST", ...options, retry: false });
581
+ if (response.status === 409) {
582
+ const existing = await getFirebaseProject(client, projectId, options);
583
+ if (existing) {
584
+ return existing;
585
+ }
586
+ }
587
+ assertOk(response.status, response.data, "POST", url);
588
+ const operation = await waitForOperation({ operation: response.data, apiRoot: FIREBASE_API, client, ...options });
589
+ const refreshed = await getFirebaseProject(client, projectId, options);
590
+ if (refreshed) {
591
+ return refreshed;
592
+ }
593
+ const mapped = mapFirebaseProject(operation.response);
594
+ if (mapped) {
595
+ return mapped;
596
+ }
597
+ throw unconfirmed(projectId);
598
+ }
599
+ function unconfirmed(projectId) {
600
+ return new VibeInfraError({
601
+ code: "project_unconfirmed",
602
+ message: `Project ${projectId} was requested, but Google did not return it on the following read.`,
603
+ remediation: "Wait and retry. If the project exists, the next run reuses it instead of creating another.",
604
+ category: "provider",
605
+ retryable: true
606
+ });
607
+ }
608
+
609
+ // packages/firebase-provider/src/services.ts
610
+ async function enableServices(client, projectId, serviceIds, options = {}) {
611
+ assertProjectId(projectId);
612
+ const alreadyEnabled = [];
613
+ const pending = [];
614
+ for (const serviceId of serviceIds) {
615
+ assertServiceId(serviceId);
616
+ const current = await readServiceState(client, projectId, serviceId, options);
617
+ if (current === "ENABLED") {
618
+ alreadyEnabled.push(serviceId);
619
+ } else {
620
+ pending.push(serviceId);
621
+ }
622
+ }
623
+ if (pending.length === 0) {
624
+ return { enabled: [], alreadyEnabled, changed: false };
625
+ }
626
+ const url = batchEnableUrl(projectId);
627
+ const response = await send(client, {
628
+ url,
629
+ method: "POST",
630
+ body: { serviceIds: pending },
631
+ ...options
632
+ });
633
+ assertOk(response.status, response.data, "POST", url);
634
+ await waitForOperation({ operation: response.data, apiRoot: SERVICE_USAGE_API, client, ...options });
635
+ return { enabled: pending, alreadyEnabled, changed: true };
636
+ }
637
+ async function readServiceState(client, projectId, serviceId, options) {
638
+ const url = serviceUrl(projectId, serviceId);
639
+ const response = await send(client, { url, method: "GET", ...options });
640
+ if (response.status === 404) {
641
+ return null;
642
+ }
643
+ assertOk(response.status, response.data, "GET", url);
644
+ return response.data.state ?? null;
645
+ }
646
+
647
+ // packages/firebase-provider/src/web-apps.ts
648
+ async function listWebApps(client, projectId, options = {}) {
649
+ return listPages(async (pageToken) => {
650
+ const url = new URL(webAppsUrl(projectId));
651
+ url.searchParams.set("pageSize", "100");
652
+ if (pageToken) {
653
+ url.searchParams.set("pageToken", pageToken);
654
+ }
655
+ const response = await send(client, {
656
+ url: url.toString(),
657
+ method: "GET",
658
+ ...options
659
+ });
660
+ assertOk(response.status, response.data, "GET", url.toString());
661
+ return {
662
+ items: (response.data.apps ?? []).flatMap((app) => {
663
+ const mapped = mapWebApp(app);
664
+ return mapped ? [mapped] : [];
665
+ }),
666
+ ...response.data.nextPageToken ? { nextPageToken: response.data.nextPageToken } : {}
667
+ };
668
+ });
669
+ }
670
+ async function getWebApp(client, projectId, appId, options = {}) {
671
+ const url = webAppUrl(projectId, appId);
672
+ const response = await send(client, { url, method: "GET", ...options });
673
+ if (response.status === 404) {
674
+ return null;
675
+ }
676
+ assertOk(response.status, response.data, "GET", url);
677
+ return mapWebApp(response.data);
678
+ }
679
+ async function createWebApp(client, projectId, displayName, options = {}) {
680
+ const url = webAppsUrl(projectId);
681
+ const response = await send(client, {
682
+ url,
683
+ method: "POST",
684
+ body: { displayName },
685
+ ...options,
686
+ retry: false
687
+ });
688
+ if (response.status === 409) {
689
+ const apps2 = await listWebApps(client, projectId, options);
690
+ const existing = apps2.find((app) => app.displayName === displayName);
691
+ if (existing) {
692
+ return existing;
693
+ }
694
+ }
695
+ assertOk(response.status, response.data, "POST", url);
696
+ const operation = await waitForOperation({ operation: response.data, apiRoot: FIREBASE_API, client, ...options });
697
+ const created = mapWebApp(operation.response);
698
+ if (created) {
699
+ return created;
700
+ }
701
+ const apps = await listWebApps(client, projectId, options);
702
+ const matched = apps.find((app) => app.displayName === displayName);
703
+ if (matched) {
704
+ return matched;
705
+ }
706
+ throw new VibeInfraError({
707
+ code: "web_app_unconfirmed",
708
+ message: "The web app operation finished without a readable app id.",
709
+ remediation: "Retry the command. If the app exists, pass --app with its id so VibeInfra reuses it.",
710
+ category: "provider",
711
+ retryable: true
712
+ });
713
+ }
714
+ async function getWebAppConfig(client, projectId, appId, options = {}) {
715
+ const url = webAppConfigUrl(projectId, appId);
716
+ const response = await send(client, { url, method: "GET", ...options });
717
+ assertOk(response.status, response.data, "GET", url);
718
+ return mapWebAppConfig(response.data);
719
+ }
720
+
721
+ // packages/firebase-provider/src/provider.ts
722
+ function createFirebaseProvider(dependencies = {}) {
723
+ let connection = null;
724
+ const connect = dependencies.connect ?? connectApplicationDefaultCredentials;
725
+ const runtime = {
726
+ ...dependencies.sleep ? { sleep: dependencies.sleep } : {},
727
+ ...dependencies.now ? { now: dependencies.now } : {},
728
+ ...dependencies.timeoutMs !== void 0 ? { timeoutMs: dependencies.timeoutMs } : {}
729
+ };
730
+ const client = async () => {
731
+ connection ??= connect();
732
+ return (await connection).client;
733
+ };
734
+ return {
735
+ async authenticate() {
736
+ connection ??= connect();
737
+ return (await connection).identity;
738
+ },
739
+ async listFirebaseProjects() {
740
+ return listFirebaseProjects(await client(), runtime);
741
+ },
742
+ async listAvailableCloudProjects() {
743
+ return listAvailableCloudProjects(await client(), runtime);
744
+ },
745
+ async getFirebaseProject(projectId) {
746
+ return getFirebaseProject(await client(), projectId, runtime);
747
+ },
748
+ async getCloudProject(projectId) {
749
+ return getCloudProject(await client(), projectId, runtime);
750
+ },
751
+ async createCloudProject(input) {
752
+ return createCloudProject(await client(), input, runtime);
753
+ },
754
+ async addFirebase(projectId) {
755
+ return addFirebase(await client(), projectId, runtime);
756
+ },
757
+ async enableServices(projectId, serviceIds) {
758
+ return enableServices(await client(), projectId, serviceIds, runtime);
759
+ },
760
+ async listWebApps(projectId) {
761
+ return listWebApps(await client(), projectId, runtime);
762
+ },
763
+ async getWebApp(projectId, appId) {
764
+ return getWebApp(await client(), projectId, appId, runtime);
765
+ },
766
+ async createWebApp(projectId, displayName) {
767
+ return createWebApp(await client(), projectId, displayName, runtime);
768
+ },
769
+ async getWebAppConfig(projectId, appId) {
770
+ return getWebAppConfig(await client(), projectId, appId, runtime);
771
+ },
772
+ async deployHosting(input) {
773
+ return deployHostingWithFirebaseTools(input, dependencies.loadFirebaseTools ?? loadFirebaseTools);
774
+ }
775
+ };
776
+ }
777
+ export {
778
+ ADC_SCOPES,
779
+ FIREBASE_API,
780
+ RESOURCE_MANAGER_API,
781
+ SERVICE_USAGE_API,
782
+ addFirebaseUrl,
783
+ batchEnableUrl,
784
+ cloudProjectUrl,
785
+ connectApplicationDefaultCredentials,
786
+ createFirebaseProvider,
787
+ deployHostingWithFirebaseTools,
788
+ firebaseProjectUrl,
789
+ loadFirebaseTools,
790
+ serviceUrl,
791
+ webAppConfigUrl,
792
+ webAppUrl,
793
+ webAppsUrl
794
+ };