diff --git a/package.json b/package.json index f508370b2..4ae862929 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,8 @@ "generate": "tspc -p tsconfig.build.json && node -e \"require('./tools/build.js').zoneWrapExports().catch(err => { console.error(err); process.exit(1); })\"", "buildd": "tsc -p tsconfig.build.json && node --trace-warnings ./tools/build.js && npm pack ./dist/packages-dist", "build:jasmine": "npx tsc -p tsconfig.jasmine.json --module es2015 && cp ./dist/out-tsc/jasmine/tools/jasmine.js ./dist/out-tsc/jasmine/tools/jasmine.mjs && npx tsc -p tsconfig.jasmine.json && cp ./dist/packages-dist/schematics/versions.json ./dist/out-tsc/jasmine/src/schematics", - "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 1" + "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 1", + "update-regions": "node ./tools/update-app-hosting-regions.mts" }, "husky": { "hooks": { diff --git a/src/schematics/add/schema.json b/src/schematics/add/schema.json index 5b1ce2c4f..6de401271 100644 --- a/src/schematics/add/schema.json +++ b/src/schematics/add/schema.json @@ -10,6 +10,11 @@ "$default": { "$source": "projectName" } + }, + "deploy": { + "type": "string", + "enum": ["apphosting", "hosting", "none"], + "description": "Where ng deploy should deploy the app: Firebase App Hosting (apphosting), Firebase Hosting (hosting), or no deploy setup (none). Asked interactively when omitted." } }, "required": [] diff --git a/src/schematics/buildOptions.jasmine.ts b/src/schematics/buildOptions.jasmine.ts new file mode 100644 index 000000000..03078e30f --- /dev/null +++ b/src/schematics/buildOptions.jasmine.ts @@ -0,0 +1,145 @@ +import { + BuildTargetDefinition, + browserOutputDirectory, + clientSidePage, + productionBuildOptions, + rendersOnServer, +} from './buildOptions.js'; +import 'jasmine'; + +const applicationBuilder = '@angular/build:application'; + +describe('productionBuildOptions', () => { + + it('overlays the production configuration on the build options', () => { + const buildTarget: BuildTargetDefinition = { + builder: applicationBuilder, + options: { outputPath: 'dist/app', index: 'src/index.html' }, + configurations: { production: { outputPath: 'dist/production' } }, + }; + expect(productionBuildOptions(buildTarget)).toEqual({ + outputPath: 'dist/production', + index: 'src/index.html', + }); + }); + + it('is empty for a project with no build entry', () => { + expect(productionBuildOptions(undefined)).toEqual({}); + }); + +}); + +describe('rendersOnServer', () => { + + it('is true for the server output mode', () => { + expect(rendersOnServer({ outputMode: 'server', server: 'src/main.server.ts' })).toBeTrue(); + }); + + it('is false for the static output mode, which prerenders every route', () => { + const options = { outputMode: 'static', server: 'src/main.server.ts', ssr: { entry: 'src/server.ts' } }; + expect(rendersOnServer(options)).toBeFalse(); + }); + + it('is true without an output mode when the build has ssr and a server entry', () => { + expect(rendersOnServer({ server: 'src/main.server.ts', ssr: { entry: 'src/server.ts' } })).toBeTrue(); + }); + + it('is false without an output mode for a build that only prerenders', () => { + expect(rendersOnServer({ server: 'src/main.server.ts', prerender: true })).toBeFalse(); + }); + + it('is false for a client-rendered build', () => { + expect(rendersOnServer({ browser: 'src/main.ts' })).toBeFalse(); + }); + +}); + +describe('clientSidePage', () => { + + it('is index.html for a client-rendered build', () => { + expect(clientSidePage({ browser: 'src/main.ts' })).toBe('index.html'); + }); + + it('is index.csr.html for the server output mode', () => { + expect(clientSidePage({ outputMode: 'server', server: 'src/main.server.ts' })).toBe('index.csr.html'); + }); + + it('is index.csr.html for the static output mode', () => { + expect(clientSidePage({ outputMode: 'static', server: 'src/main.server.ts' })).toBe('index.csr.html'); + }); + + it('is index.csr.html without an output mode when the build has ssr', () => { + expect(clientSidePage({ server: 'src/main.server.ts', ssr: true })).toBe('index.csr.html'); + }); + + it('is index.csr.html without an output mode when the build prerenders', () => { + expect(clientSidePage({ server: 'src/main.server.ts', prerender: true })).toBe('index.csr.html'); + }); + + it('keeps the file name of a custom index source file, on a server-rendered build too', () => { + const options = { outputMode: 'server', server: 'src/main.server.ts', index: 'src/main.html' }; + expect(clientSidePage(options)).toBe('main.html'); + }); + + it('uses the output name of an index option written as an object', () => { + const options = { index: { input: 'src/index.html', output: 'home.html' } }; + expect(clientSidePage(options)).toBe('home.html'); + }); + +}); + +describe('browserOutputDirectory', () => { + + it('is dist//browser for the application builder with no output path', () => { + expect(browserOutputDirectory('my-app', { builder: applicationBuilder })).toBe('dist/my-app/browser'); + }); + + it('treats the application builder of @angular-devkit/build-angular the same way', () => { + const buildTarget: BuildTargetDefinition = { builder: '@angular-devkit/build-angular:application' }; + expect(browserOutputDirectory('my-app', buildTarget)).toBe('dist/my-app/browser'); + }); + + it('adds the browser folder to an output path written as text', () => { + const buildTarget: BuildTargetDefinition = { builder: applicationBuilder, options: { outputPath: 'build/' } }; + expect(browserOutputDirectory('my-app', buildTarget)).toBe('build/browser'); + }); + + it('joins the base and browser folders of an output path written as an object', () => { + const buildTarget: BuildTargetDefinition = { + builder: applicationBuilder, + options: { outputPath: { base: 'build', browser: 'public' } }, + }; + expect(browserOutputDirectory('my-app', buildTarget)).toBe('build/public'); + }); + + it('adds the browser folder to an output path object that has only a base folder', () => { + const buildTarget: BuildTargetDefinition = { builder: applicationBuilder, options: { outputPath: { base: 'build' } } }; + expect(browserOutputDirectory('my-app', buildTarget)).toBe('build/browser'); + }); + + it('is the base folder when the browser folder is set to an empty name', () => { + const buildTarget: BuildTargetDefinition = { + builder: applicationBuilder, + options: { outputPath: { base: 'build', browser: '' } }, + }; + expect(browserOutputDirectory('my-app', buildTarget)).toBe('build'); + }); + + it('uses the output path of the production configuration', () => { + const buildTarget: BuildTargetDefinition = { + builder: applicationBuilder, + options: { outputPath: 'build' }, + configurations: { production: { outputPath: 'release' } }, + }; + expect(browserOutputDirectory('my-app', buildTarget)).toBe('release/browser'); + }); + + it('is the output path itself for the older browser builder', () => { + const buildTarget: BuildTargetDefinition = { + builder: '@angular-devkit/build-angular:browser', + options: { outputPath: 'www' }, + }; + expect(browserOutputDirectory('my-app', buildTarget)).toBe('www'); + }); + +}); diff --git a/src/schematics/buildOptions.ts b/src/schematics/buildOptions.ts new file mode 100644 index 000000000..6e2bd9962 --- /dev/null +++ b/src/schematics/buildOptions.ts @@ -0,0 +1,88 @@ +/** + * @fileoverview What `ng add` and `ng deploy` need to know about how an Angular project builds, + * read from the project's `build` entry in angular.json: whether the build needs a server, where + * its browser files go, and which file is the client-side page. The rules mirror + * `@angular/build`'s application builder. + */ + +import { basename } from 'path'; +import { WorkspaceProject } from './interfaces'; + +/** The options of a `build` entry in angular.json, whose values this file checks before using. */ +export type BuildOptions = Record; + +/** One entry under a project's `architect` key in angular.json, such as its `build` entry. */ +export type BuildTargetDefinition = NonNullable[string]; + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null; + +/** The options `ng deploy` builds with: the `build` target's options overlaid by its `production` configuration. */ +export const productionBuildOptions = (buildTarget: BuildTargetDefinition | undefined): BuildOptions => ({ + ...buildTarget?.options, + ...buildTarget?.configurations?.production, +}); + +/** + * What `ng add` and `ng deploy` tell the user about Firebase Hosting when the build has the + * `localize` option. Such a build writes one folder per locale and no index page above them. + */ +export const localizedBuildHostingWarning = + 'This app is built once per locale (the "localize" build option), which puts each locale in ' + + 'its own folder with no index.html above them. The Hosting entry in firebase.json serves a ' + + 'single index.html, so pages will not load until that entry is changed by hand to serve the ' + + 'locale folders.'; + +/** Whether the build produces a server that renders pages per request, which static hosting cannot run. */ +export const rendersOnServer = (options: BuildOptions): boolean => { + if (options.outputMode === 'server') { return true; } + if (options.outputMode === 'static') { return false; } + return !!options.ssr && !!options.server; +}; + +/** + * The name the build gives its index page, from the `index` build option. That option is either + * the path of the source file, whose own file name is then used, or an object whose `output` is + * the name. Without either, the name is `index.html`. + */ +const indexFileName = (options: BuildOptions): string => { + const { index } = options; + if (typeof index === 'string') { return basename(index); } + if (isRecord(index) && typeof index.output === 'string' && index.output) { return basename(index.output); } + return 'index.html'; +}; + +/** + * The file a static host should serve for a route that has no file of its own, which is the + * build's index page. When the build also prerenders or renders on a server, the application + * builder writes an index page called `index.html` as `index.csr.html` instead. A page with + * another name keeps its name. + */ +export const clientSidePage = (options: BuildOptions): string => { + const fileName = indexFileName(options); + const prerendersOrRendersOnServer = options.outputMode + ? !!options.server + : !!options.ssr || !!options.prerender; + return prerendersOrRendersOnServer && fileName === 'index.html' ? 'index.csr.html' : fileName; +}; + +/** The directory the browser files are built into, relative to the workspace root, with forward slashes. */ +export const browserOutputDirectory = ( + projectName: string, + buildTarget: BuildTargetDefinition | undefined, +): string => { + const { outputPath } = productionBuildOptions(buildTarget); + const withoutTrailingSlash = (path: string) => path.replace(/\\/g, '/').replace(/\/+$/, ''); + + /* Only the application builder nests browser files in a subdirectory. The older builders write + * them straight into `outputPath`. */ + if (!buildTarget?.builder.endsWith(':application')) { + return withoutTrailingSlash(typeof outputPath === 'string' ? outputPath : `dist/${projectName}`); + } + + const base = typeof outputPath === 'string' ? outputPath + : isRecord(outputPath) && typeof outputPath.base === 'string' ? outputPath.base + : `dist/${projectName}`; + const browser = isRecord(outputPath) && typeof outputPath.browser === 'string' ? outputPath.browser : 'browser'; + return withoutTrailingSlash(browser ? `${withoutTrailingSlash(base)}/${browser}` : base); +}; diff --git a/src/schematics/deploy/actions.jasmine.ts b/src/schematics/deploy/actions.jasmine.ts index c8503c3f1..94e742b18 100644 --- a/src/schematics/deploy/actions.jasmine.ts +++ b/src/schematics/deploy/actions.jasmine.ts @@ -1,10 +1,14 @@ /* eslint-disable @typescript-eslint/no-empty-function */ +import { mkdtempSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; import { join } from 'path'; import { Script } from 'vm'; import { BuilderContext, BuilderRun, ScheduleOptions, Target } from '@angular-devkit/architect'; import { JsonObject, logging } from '@angular-devkit/core'; +import fsExtra from 'fs-extra'; +import inquirer from 'inquirer'; import { BuildTarget, DeployBuilderSchema, FSHost, FirebaseDeployConfig, FirebaseTools } from '../interfaces'; -import deploy, { CLOUD_FUNCTIONS_DEPRECATION, assertSafeDependencyName, assertSafeFunctionName, assertSafeNodeVersion, assertSafeOutputPath, assertSupportedPackageManager, buildCloudRunBuildsSubmitArgs, buildCloudRunDeployArgs, deployToCloudRun, deployToFunction, findPackageVersion, processHost } from './actions.js' +import deploy, { CLOUD_FUNCTIONS_DEPRECATION, HOSTING_SERVER_BUILD_WARNING, assertSafeDependencyName, assertSafeFunctionName, assertSafeNodeVersion, assertSafeOutputPath, assertSupportedPackageManager, buildCloudRunBuildsSubmitArgs, buildCloudRunDeployArgs, deployToAppHosting, deployToCloudRun, deployToFunction, findPackageVersion, processHost } from './actions.js' import 'jasmine'; let context: BuilderContext; @@ -108,7 +112,8 @@ const initMocks = () => { reportRunning: () => { }, scheduleBuilder: (_: string, __?: JsonObject, ___?: ScheduleOptions) => Promise.resolve({} as BuilderRun), - scheduleTarget: (_: Target, __?: JsonObject, ___?: ScheduleOptions) => Promise.resolve({} as BuilderRun) + scheduleTarget: (_: Target, __?: JsonObject, ___?: ScheduleOptions) => + Promise.resolve({ result: Promise.resolve({ success: true }) }) } as any); }; @@ -213,6 +218,29 @@ describe('Deploy Angular apps', () => { expect(e.message).toMatch(/Cannot execute the build target/); } }); + + it('stops before deploying when the build fails', async () => { + Object.assign(context, { + scheduleTarget: () => Promise.resolve({ result: Promise.resolve({ success: false }) }), + }); + const deploySpy = spyOn(firebaseMock, 'deploy'); + await expectAsync( + deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, undefined, FIREBASE_PROJECT, { preview: false }, FIREBASE_TOKEN) + ).toBeRejectedWithError(/failed, so nothing was deployed/); + expect(deploySpy).not.toHaveBeenCalled(); + }); + + it('stops before deploying when the prerender build fails', async () => { + Object.assign(context, { + scheduleTarget: () => Promise.resolve({ result: Promise.resolve({ success: false }) }), + }); + const prerenderBuildTarget: BuildTarget = { name: `${PROJECT}:prerender:production` }; + const deploySpy = spyOn(firebaseMock, 'deploy'); + await expectAsync( + deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, prerenderBuildTarget, FIREBASE_PROJECT, { preview: false }, FIREBASE_TOKEN) + ).toBeRejectedWithError(/failed, so nothing was deployed/); + expect(deploySpy).not.toHaveBeenCalled(); + }); }); }); @@ -720,3 +748,282 @@ describe('generated artifact validation is wired into the builders', () => { expect(writeSpy).not.toHaveBeenCalled(); }); }); + +describe('App Hosting deployment', () => { + const BACKEND = 'my-backend'; + + /** A real folder, because the deploy code reads firebase.json from disk. */ + let appHostingRoot: string; + + /** Each lookup of a backend that firebase-tools received: the backend id, and a copy of the options as given. */ + let backendLookups: { backendId: string, options: Record }[]; + + const writeFirebaseJson = (content: string) => writeFileSync(join(appHostingRoot, 'firebase.json'), content); + + beforeEach(() => { + initMocks(); + appHostingRoot = mkdtempSync(join(tmpdir(), 'angularfire-test-')); + writeFirebaseJson(JSON.stringify({ apphosting: { backendId: BACKEND, rootDir: '.' } })); + Object.assign(context, { workspaceRoot: appHostingRoot }); + + backendLookups = []; + firebaseMock.cli = { version: () => '15.28.1' }; + firebaseMock.apphosting = { + backends: { + list: () => Promise.resolve([]), + create: () => Promise.resolve(), + get: (backendId: string, options: Record) => { + backendLookups.push({ backendId, options: { ...options } }); + + // firebase-tools adds its loaded config to the options object it is given. + options.config = 'added by firebase-tools'; + return Promise.resolve({ name: `projects/${FIREBASE_PROJECT}/locations/us-central1/backends/${BACKEND}` }); + }, + }, + }; + }); + + afterEach(() => { + fsExtra.removeSync(appHostingRoot); + }); + + const deployBackend = () => + deployToAppHosting(firebaseMock, context, appHostingRoot, FIREBASE_PROJECT, BACKEND, FIREBASE_TOKEN); + + describe('deployToAppHosting', () => { + + it('deploys only the backend, from the workspace root, without questions from firebase-tools', async () => { + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await deployBackend(); + expect(deploySpy).toHaveBeenCalledOnceWith({ + only: `apphosting:${BACKEND}`, + project: FIREBASE_PROJECT, + cwd: appHostingRoot, + projectRoot: appHostingRoot, + token: FIREBASE_TOKEN, + nonInteractive: true, + }); + }); + + it('looks that backend up first, in the same project and with the same sign-in, without questions', async () => { + await deployBackend(); + expect(backendLookups).toEqual([{ + backendId: BACKEND, + options: { + project: FIREBASE_PROJECT, + cwd: appHostingRoot, + projectRoot: appHostingRoot, + token: FIREBASE_TOKEN, + nonInteractive: true, + }, + }]); + }); + + it('gives the deploy call an options object that the lookup call has not changed', async () => { + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await deployBackend(); + expect(Object.keys(deploySpy.calls.mostRecent().args[0])).not.toContain('config'); + }); + + it('finds the entry of the backend in a list of entries', async () => { + writeFirebaseJson(JSON.stringify({ apphosting: [{ backendId: 'other-backend' }, { backendId: BACKEND }] })); + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await deployBackend(); + expect(deploySpy).toHaveBeenCalledTimes(1); + }); + + it('reads a firebase.json that has comments, as the Firebase CLI does', async () => { + writeFirebaseJson(`{\n // deployed with ng deploy\n "apphosting": { "backendId": "${BACKEND}" }\n}`); + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await deployBackend(); + expect(deploySpy).toHaveBeenCalledTimes(1); + }); + + it('accepts firebase-tools 15.9.0, the oldest version that reports a failed rollout', async () => { + firebaseMock.cli = { version: () => '15.9.0' }; + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await deployBackend(); + expect(deploySpy).toHaveBeenCalledTimes(1); + }); + + it('stops before any firebase-tools call when firebase-tools is older than 15.9.0', async () => { + firebaseMock.cli = { version: () => '15.8.0' }; + const deploySpy = spyOn(firebaseMock, 'deploy'); + await expectAsync(deployBackend()) + .toBeRejectedWithError(/needs firebase-tools 15\.9\.0 or newer.*and this is 15\.8\.0/); + expect(backendLookups.length).toBe(0); + expect(deploySpy).not.toHaveBeenCalled(); + }); + + it('stops when firebase-tools has no App Hosting commands', async () => { + firebaseMock.apphosting = undefined; + await expectAsync(deployBackend()).toBeRejectedWithError(/needs firebase-tools 15\.9\.0 or newer/); + }); + + it('stops when firebase.json has no entry for the backend', async () => { + writeFirebaseJson(JSON.stringify({ apphosting: { backendId: 'other-backend' } })); + const deploySpy = spyOn(firebaseMock, 'deploy'); + await expectAsync(deployBackend()).toBeRejectedWithError( + new RegExp(`backend "${BACKEND}", but firebase\\.json has no apphosting entry with that backendId`) + ); + expect(deploySpy).not.toHaveBeenCalled(); + }); + + it('stops when there is no firebase.json', async () => { + fsExtra.removeSync(join(appHostingRoot, 'firebase.json')); + await expectAsync(deployBackend()) + .toBeRejectedWithError(/firebase\.json has no apphosting entry with that backendId/); + }); + + it('stops when firebase.json tells firebase-tools to skip the backend', async () => { + writeFirebaseJson(JSON.stringify({ apphosting: { backendId: BACKEND, alwaysDeployFromSource: false } })); + const deploySpy = spyOn(firebaseMock, 'deploy'); + await expectAsync(deployBackend()).toBeRejectedWithError(/sets alwaysDeployFromSource to false/); + expect(deploySpy).not.toHaveBeenCalled(); + }); + + it('deploys when only the entry of another backend tells firebase-tools to skip it', async () => { + writeFirebaseJson(JSON.stringify({ + apphosting: [{ backendId: 'other-backend', alwaysDeployFromSource: false }, { backendId: BACKEND }], + })); + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await deployBackend(); + expect(deploySpy).toHaveBeenCalledTimes(1); + }); + + it('deploys to a backend whose entry has alwaysDeployFromSource set to true', async () => { + writeFirebaseJson(JSON.stringify({ apphosting: { backendId: BACKEND, alwaysDeployFromSource: true } })); + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await deployBackend(); + expect(deploySpy).toHaveBeenCalledTimes(1); + }); + + it('stops when the backend does not exist in the Firebase project', async () => { + firebaseMock.apphosting = { + backends: { + list: () => Promise.resolve([]), + create: () => Promise.resolve(), + get: () => Promise.resolve(undefined), + }, + }; + const deploySpy = spyOn(firebaseMock, 'deploy'); + await expectAsync(deployBackend()) + .toBeRejectedWithError(new RegExp(`"${BACKEND}" does not exist in the Firebase project ${FIREBASE_PROJECT}`)); + expect(deploySpy).not.toHaveBeenCalled(); + }); + + }); + + describe('through ng deploy', () => { + + const appHostingOptions = { version: 2, appHostingBackend: BACKEND }; + + const runDeploy = (options: DeployBuilderSchema, firebaseToken: string | undefined = FIREBASE_TOKEN) => + deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, undefined, FIREBASE_PROJECT, options, firebaseToken); + + it('uploads to the backend without building the app locally', async () => { + const buildSpy = spyOn(context, 'scheduleTarget').and.callThrough(); + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await runDeploy(appHostingOptions); + expect(buildSpy).not.toHaveBeenCalled(); + expect(deploySpy).toHaveBeenCalledOnceWith(jasmine.objectContaining({ + only: `apphosting:${BACKEND}`, + project: FIREBASE_PROJECT, + token: FIREBASE_TOKEN, + })); + }); + + it('fails when the rollout fails', async () => { + spyOn(firebaseMock, 'deploy').and.rejectWith(new Error('Rollout failed')); + await expectAsync(runDeploy(appHostingOptions)).toBeRejectedWithError('Rollout failed'); + }); + + it('refuses the preview option and deploys nothing', async () => { + const deploySpy = spyOn(firebaseMock, 'deploy'); + await expectAsync(runDeploy({ ...appHostingOptions, preview: true })) + .toBeRejectedWithError(/preview option is not available for Firebase App Hosting/); + expect(deploySpy).not.toHaveBeenCalled(); + }); + + it('does not refuse the preview option for a Hosting deploy', async () => { + const serveSpy = spyOn(firebaseMock, 'serve').and.callThrough(); + spyOn(inquirer, 'prompt').and.resolveTo({ deployProject: false }); + const deploySpy = spyOn(firebaseMock, 'deploy'); + await runDeploy({ version: 2, preview: true }); + expect(serveSpy).toHaveBeenCalledTimes(1); + expect(deploySpy).not.toHaveBeenCalled(); + }); + + it('says which deploy options it ignores', async () => { + const warnSpy = spyOn(context.logger, 'warn'); + const buildTarget = `${PROJECT}:build:staging`; + await runDeploy({ ...appHostingOptions, ssr: true, prerender: true, buildTarget, browserTarget: buildTarget }); + expect(warnSpy).toHaveBeenCalledWith( + 'Deploying to App Hosting ignores these deploy options: prerender, ssr, buildTarget, browserTarget.' + ); + }); + + it('says so for a single ignored option too', async () => { + const warnSpy = spyOn(context.logger, 'warn'); + await runDeploy({ ...appHostingOptions, ssr: true }); + expect(warnSpy).toHaveBeenCalledWith('Deploying to App Hosting ignores these deploy options: ssr.'); + }); + + it('prints no warning about ignored options when there are none', async () => { + const warnSpy = spyOn(context.logger, 'warn'); + await runDeploy(appHostingOptions); + expect(warnSpy).not.toHaveBeenCalled(); + }); + + it('does not warn that Hosting cannot run a server, since App Hosting can', async () => { + Object.assign(context, { getTargetOptions: () => ({ outputMode: 'server', server: 'src/main.server.ts' }) }); + const warnSpy = spyOn(context.logger, 'warn'); + await runDeploy(appHostingOptions); + expect(warnSpy).not.toHaveBeenCalledWith(HOSTING_SERVER_BUILD_WARNING); + }); + + }); + +}); + +describe('Hosting warning for a server-rendered build', () => { + beforeEach(() => initMocks()); + + const runHostingDeploy = () => + deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, undefined, FIREBASE_PROJECT, { version: 2 }, FIREBASE_TOKEN); + + it('warns before the build when the build renders pages on a server', async () => { + Object.assign(context, { getTargetOptions: () => ({ outputMode: 'server', server: 'src/main.server.ts' }) }); + const events: string[] = []; + spyOn(context.logger, 'warn').and.callFake(message => { events.push(message); }); + spyOn(context, 'scheduleTarget').and.callFake(() => { + events.push('build'); + return Promise.resolve({ result: Promise.resolve({ success: true }) } as BuilderRun); + }); + await runHostingDeploy(); + expect(events).toEqual([HOSTING_SERVER_BUILD_WARNING, 'build']); + }); + + it('warns for a deploy entry from before version 2 as well', async () => { + Object.assign(context, { getTargetOptions: () => ({ outputMode: 'server', server: 'src/main.server.ts' }) }); + const warnSpy = spyOn(context.logger, 'warn'); + await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, undefined, FIREBASE_PROJECT, { preview: false }, FIREBASE_TOKEN); + expect(warnSpy).toHaveBeenCalledWith(HOSTING_SERVER_BUILD_WARNING); + }); + + it('does not warn for a client-rendered build', async () => { + const warnSpy = spyOn(context.logger, 'warn'); + await runHostingDeploy(); + expect(warnSpy).not.toHaveBeenCalled(); + }); + + it('deploys without the warning when the build options cannot be read', async () => { + Object.assign(context, { getTargetOptions: () => Promise.reject(new Error('no such target')) }); + const warnSpy = spyOn(context.logger, 'warn'); + const deploySpy = spyOn(firebaseMock, 'deploy').and.callThrough(); + await runHostingDeploy(); + expect(warnSpy).not.toHaveBeenCalled(); + expect(deploySpy).toHaveBeenCalledTimes(1); + }); + +}); diff --git a/src/schematics/deploy/actions.ts b/src/schematics/deploy/actions.ts index 74c1c3385..dd5d7c738 100644 --- a/src/schematics/deploy/actions.ts +++ b/src/schematics/deploy/actions.ts @@ -5,14 +5,18 @@ import { fileURLToPath } from 'url'; import { BuilderContext, targetFromTargetString } from '@angular-devkit/architect'; import crossSpawn from 'cross-spawn'; import fsExtra from 'fs-extra'; -import * as inquirer from 'inquirer'; +import inquirer from 'inquirer'; import open from 'open'; import { satisfies } from 'semver'; import tripleBeam from 'triple-beam'; import * as winston from 'winston'; -import { getActiveAccount } from '../firebaseTools.js'; -import { BuildTarget, CloudRunOptions, DeployBuilderSchema, FSHost, FirebaseTools } from '../interfaces'; -import { assertSafeDependencyName } from '../workspace.js'; +import { rendersOnServer } from '../buildOptions.js'; +import { appHostingMinVersion, getActiveAccount, supportsAppHosting } from '../firebaseTools.js'; +import { + BuildTarget, CloudRunOptions, DeployBuilderSchema, FSHost, FirebaseAppHostingConfig, FirebaseJSON, FirebaseTools, + FirebaseToolsCommandOptions, +} from '../interfaces'; +import { assertSafeDependencyName, readJson } from '../workspace.js'; import { DEFAULT_FUNCTION_NAME, defaultFunction, defaultPackage, dockerfile, functionGen2 } from './functions-templates.js'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment @@ -136,6 +140,9 @@ const deployToHosting = async ( if (options.preview) { + context.logger.info('Previewing locally. Press Ctrl+C to stop the preview and choose whether to deploy.'); + + // Resolves once the user stops the local server with Ctrl+C. await firebaseTools.serve({ port: DEFAULT_EMULATOR_PORT, host: DEFAULT_EMULATOR_HOST, @@ -276,6 +283,18 @@ export const CLOUD_FUNCTIONS_DEPRECATION = `⚠️ Deploying server-side renderi Deploy server-rendered apps with Firebase App Hosting instead: https://firebase.google.com/docs/app-hosting AngularFire's guide: https://github.com/angular/angularfire/blob/main/docs/app-hosting.md`; +export const HOSTING_SERVER_BUILD_WARNING = `⚠️ This app uses server-side rendering, which Firebase Hosting cannot run: every route that is not prerendered loads as a client-rendered page. +Run ng add @angular/fire and choose Firebase App Hosting to keep server-side rendering.`; + +/** Whether the build target `ng deploy` is about to build produces a server. Unknown counts as no. */ +const buildRendersOnServer = async (context: BuilderContext, buildTarget: BuildTarget) => { + try { + return rendersOnServer(await context.getTargetOptions(targetFromTargetString(buildTarget.name))); + } catch { + return false; + } +}; + export const deployToFunction = async ( firebaseTools: FirebaseTools, context: BuilderContext, @@ -546,6 +565,95 @@ export const deployToCloudRun = async ( }); }; +/** + * The App Hosting backends that firebase.json lists under its `apphosting` key. Each entry is for + * one backend (`backendId`) and holds the settings for deploying to it, and firebase-tools deploys + * only to backends listed there. firebase.json holds either a single entry or a list of them, + * and this always returns a list, empty when the file is missing, unreadable or has none. + */ +const appHostingEntries = (workspaceRoot: string): FirebaseAppHostingConfig[] => { + // The Firebase CLI accepts comments in firebase.json, so this reader has to accept them too. + const firebaseJson = readJson(join(workspaceRoot, 'firebase.json')) ?? {}; + + const { apphosting } = firebaseJson; + if (apphosting === undefined) { return []; } + return Array.isArray(apphosting) ? apphosting : [apphosting]; +}; + +/** + * Deploys to Firebase App Hosting by uploading the workspace's source to the backend `backendId`. + * App Hosting builds the app from that source in Google Cloud and runs the app's Node.js server + * there, on Cloud Run. So nothing is built locally, unlike a deploy to Firebase Hosting. + */ +export const deployToAppHosting = async ( + firebaseTools: FirebaseTools, + context: BuilderContext, + workspaceRoot: string, + firebaseProject: string, + backendId: string, + firebaseToken?: string, +) => { + if (!firebaseTools.apphosting || !supportsAppHosting(firebaseTools)) { + throw new Error( + `Deploying to App Hosting needs firebase-tools ${appHostingMinVersion} or newer with its ` + + `App Hosting commands enabled, and this is ${firebaseTools.cli.version()}. Upgrade firebase-tools, then run ng deploy again.` + ); + } + + // The backend id lives in angular.json and in firebase.json, and firebase-tools reads only the latter. + const entry = appHostingEntries(workspaceRoot).find(candidate => candidate.backendId === backendId); + if (!entry) { + throw new Error( + `angular.json deploys to the App Hosting backend "${backendId}", but firebase.json has no apphosting ` + + 'entry with that backendId. Run ng add @angular/fire again, or add ' + + `{ "apphosting": { "backendId": "${backendId}", "rootDir": "." } } to firebase.json.` + ); + } + if (entry.alwaysDeployFromSource === false) { + throw new Error( + `firebase.json sets alwaysDeployFromSource to false for the App Hosting backend "${backendId}", ` + + 'which makes firebase-tools skip it. Remove that setting to deploy local files with ng deploy.' + ); + } + + // A function instead of one shared object. Each Firebase CLI call needs a new options object. + const newCallOptions = (): FirebaseToolsCommandOptions & { cwd: string } => ({ + project: firebaseProject, + cwd: workspaceRoot, + projectRoot: workspaceRoot, + token: firebaseToken, + nonInteractive: true, + }); + + /* When the backend does not exist, firebase-tools responds by asking whether to create it. + * Questions are turned off for this deploy (`nonInteractive`), so that would surface as an + * error about an unanswerable question. Checking first gives an error that says what is wrong. */ + const backend = await firebaseTools.apphosting.backends.get(backendId, newCallOptions()); + if (!backend) { + throw new Error( + `The App Hosting backend "${backendId}" does not exist in the Firebase project ${firebaseProject}. ` + + 'Run ng add @angular/fire again, or create it with firebase apphosting:backends:create.' + ); + } + + context.logger.info(`📦 Uploading the workspace to the App Hosting backend "${backendId}", which builds it`); + + // The Firebase CLI prints the address of the deployed backend itself. + await firebaseTools.deploy({ ...newCallOptions(), only: `apphosting:${backendId}` }); +}; + +/** + * Runs one of the Angular project's build targets and waits for it to finish. Throws when the + * build fails, which stops the deploy before anything is uploaded. + */ +const runBuildTarget = async (context: BuilderContext, buildTarget: BuildTarget): Promise => { + const run = await context.scheduleTarget(targetFromTargetString(buildTarget.name), buildTarget.options); + const result = await run.result; + if (!result.success) { + throw new Error(`The build "${buildTarget.name}" failed, so nothing was deployed.`); + } +}; + /** Whether the Firebase CLI has at least one signed-in account. */ const isSignedIn = async (firebaseTools: FirebaseTools) => { const accounts = await firebaseTools.login.list(); @@ -562,9 +670,19 @@ export default async function deploy( options: DeployBuilderOptions, firebaseToken?: string, ) { + const { appHostingBackend } = options; const legacyNgDeploy = !options.version || options.version < 2; - const deploysToCloudRun = legacyNgDeploy && !!serverBuildTarget && options.ssr === 'cloud-run'; - const deploysToCloudFunctions = legacyNgDeploy && !!serverBuildTarget && !deploysToCloudRun; + const deploysToCloudRun = !appHostingBackend && legacyNgDeploy && !!serverBuildTarget && options.ssr === 'cloud-run'; + const deploysToCloudFunctions = !appHostingBackend && legacyNgDeploy && !!serverBuildTarget && !deploysToCloudRun; + const deploysToHosting = !appHostingBackend && !deploysToCloudRun && !deploysToCloudFunctions; + + // App Hosting has nothing to preview locally, and ignoring the option would deploy when the user asked not to. + if (appHostingBackend && options.preview) { + throw new Error( + 'The preview option is not available for Firebase App Hosting, which builds the app in Google Cloud, ' + + 'so there is no local build to preview. Nothing was deployed. Run ng deploy without --preview to deploy.' + ); + } if (!firebaseToken && !process.env.GOOGLE_APPLICATION_CREDENTIALS) { if (!await isSignedIn(firebaseTools)) { @@ -580,7 +698,11 @@ export default async function deploy( } if (!firebaseToken && process.env.GOOGLE_APPLICATION_CREDENTIALS) { - await spawnAsync('gcloud', ['auth', 'activate-service-account', '--key-file', process.env.GOOGLE_APPLICATION_CREDENTIALS]); + /* An App Hosting deploy runs no gcloud command, so it skips this gcloud sign-in and works on a + * machine without gcloud. The Firebase CLI reads the key file by itself. */ + if (!appHostingBackend) { + await spawnAsync('gcloud', ['auth', 'activate-service-account', '--key-file', process.env.GOOGLE_APPLICATION_CREDENTIALS]); + } console.log(`Using Google Application Credentials.`); } @@ -589,12 +711,17 @@ export default async function deploy( context.logger.warn(CLOUD_FUNCTIONS_DEPRECATION); } - if (prerenderBuildTarget) { - const run = await context.scheduleTarget( - targetFromTargetString(prerenderBuildTarget.name), - prerenderBuildTarget.options - ); - await run.result; + if (deploysToHosting && await buildRendersOnServer(context, staticBuildTarget)) { + context.logger.warn(HOSTING_SERVER_BUILD_WARNING); + } + + if (appHostingBackend) { + const ignored = ['prerender', 'ssr', 'buildTarget', 'browserTarget'].filter(name => options[name]); + if (ignored.length) { + context.logger.warn(`Deploying to App Hosting ignores these deploy options: ${ignored.join(', ')}.`); + } + } else if (prerenderBuildTarget) { + await runBuildTarget(context, prerenderBuildTarget); } else { @@ -604,21 +731,13 @@ export default async function deploy( context.logger.info(`📦 Building "${context.target.project}"`); - const builders = [ - context.scheduleTarget( - targetFromTargetString(staticBuildTarget.name), - staticBuildTarget.options - ).then(run => run.result) - ]; + const builds = [runBuildTarget(context, staticBuildTarget)]; if (serverBuildTarget) { - builders.push(context.scheduleTarget( - targetFromTargetString(serverBuildTarget.name), - serverBuildTarget.options - ).then(run => run.result)); + builds.push(runBuildTarget(context, serverBuildTarget)); } - await Promise.all(builders); + await Promise.all(builds); } @@ -653,7 +772,16 @@ export default async function deploy( firebaseTools.logger.logger.add(logger); - if (deploysToCloudRun) { + if (appHostingBackend) { + await deployToAppHosting( + firebaseTools, + context, + context.workspaceRoot, + firebaseProject, + appHostingBackend, + firebaseToken, + ); + } else if (deploysToCloudRun) { await deployToCloudRun( firebaseTools, context, diff --git a/src/schematics/deploy/builder.ts b/src/schematics/deploy/builder.ts index 9375dcd28..267ed11ab 100644 --- a/src/schematics/deploy/builder.ts +++ b/src/schematics/deploy/builder.ts @@ -1,8 +1,9 @@ import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import { getFirebaseTools } from '../firebaseTools'; -import { getFirebaseProjectNameFromFs } from '../firebaserc'; +import { hostingSiteFromRc, readFirebaseRc } from '../firebaserc'; import { BuildTarget } from '../interfaces'; import deploy, { DeployBuilderOptions } from './actions'; +import { chooseFirebaseProject } from './firebaseProject'; // Call the createBuilder() function to create a builder. This mirrors // createJobHandler() but add typings specific to Architect Builders. @@ -12,25 +13,24 @@ export default createBuilder( throw new Error('Cannot deploy the application without a target'); } - const [defaultFirebaseProject, defaultFirebaseHostingSite] = getFirebaseProjectNameFromFs( - context.workspaceRoot, - context.target.project - ); + const angularProjectName = context.target.project; + const firebaseRc = readFirebaseRc(context.workspaceRoot); - const firebaseProject = options.firebaseProject || defaultFirebaseProject; - if (!firebaseProject) { - throw new Error('Cannot determine the Firebase Project from your angular.json or .firebaserc'); - } - if (firebaseProject !== defaultFirebaseProject) { - throw new Error('The Firebase Project specified by your angular.json or .firebaserc is in conflict'); - } + const firebaseProject = await chooseFirebaseProject(context, firebaseRc, angularProjectName, options); + // Undefined means no project could be chosen, and the reason has been printed. + if (!firebaseProject) { return { success: false }; } - const firebaseHostingSite = options.firebaseHostingSite || defaultFirebaseHostingSite; - if (!firebaseHostingSite) { - throw new Error(`Cannot determine the Firebase Hosting Site from your angular.json or .firebaserc`); - } - if (firebaseHostingSite !== defaultFirebaseHostingSite) { - throw new Error('The Firebase Hosting Site specified by your angular.json or .firebaserc is in conflict'); + /* A Hosting site is needed only when deploying to Firebase Hosting. A deploy to Firebase + * App Hosting goes to the App Hosting backend that the `appHostingBackend` option specifies. */ + if (!options.appHostingBackend) { + const defaultFirebaseHostingSite = hostingSiteFromRc(firebaseRc, firebaseProject, angularProjectName); + const firebaseHostingSite = options.firebaseHostingSite || defaultFirebaseHostingSite; + if (!firebaseHostingSite) { + throw new Error(`Cannot determine the Firebase Hosting Site from your angular.json or .firebaserc`); + } + if (firebaseHostingSite !== defaultFirebaseHostingSite) { + throw new Error('The Firebase Hosting Site specified by your angular.json or .firebaserc is in conflict'); + } } const staticBuildTarget = { name: options.browserTarget || options.buildTarget || `${context.target.project}:build:production` }; diff --git a/src/schematics/deploy/firebaseProject.jasmine.ts b/src/schematics/deploy/firebaseProject.jasmine.ts new file mode 100644 index 000000000..ab2957dd3 --- /dev/null +++ b/src/schematics/deploy/firebaseProject.jasmine.ts @@ -0,0 +1,170 @@ +import { BuilderContext } from '@angular-devkit/architect'; +import { logging } from '@angular-devkit/core'; +import inquirer from 'inquirer'; +import { FirebaseRc } from '../interfaces'; +import { chooseFirebaseProject } from './firebaseProject.js'; +import 'jasmine'; + +const conflict = /is in conflict/; + +/** The target name `my-app` under one Firebase project, which is not the default project. */ +const targetUnderOneProject: FirebaseRc = { + projects: { default: 'default-project' }, + targets: { 'production-project': { hosting: { 'my-app': ['production-site'] } } }, +}; + +/** + * The target name `my-app` under three Firebase projects. `staging-project` is neither the first + * one listed nor the default project, so a spec that uses it can tell those three apart. + */ +const targetUnderSeveralProjects: FirebaseRc = { + projects: { default: 'production-project' }, + targets: { + 'dev-project': { hosting: { 'my-app': ['dev-site'] } }, + 'staging-project': { hosting: { 'my-app': ['staging-site'] } }, + 'production-project': { hosting: { 'my-app': ['production-site'] } }, + }, +}; + +describe('chooseFirebaseProject', () => { + let context: BuilderContext; + let terminalAtStart: boolean; + let prompt: jasmine.Spy; + + /** Makes the code under test see a terminal, or none, whatever the specs themselves run in. */ + const setTerminal = (present: boolean) => { process.stdin.isTTY = present; }; + + beforeEach(() => { + context = { logger: new logging.Logger('test') } as unknown as BuilderContext; + terminalAtStart = process.stdin.isTTY; + + // Every spec starts with no terminal and a question that answers `staging-project` if asked. + setTerminal(false); + prompt = spyOn(inquirer, 'prompt').and.resolveTo({ projectId: 'staging-project' }); + }); + + afterEach(() => { + process.stdin.isTTY = terminalAtStart; + }); + + describe('with the target name under one Firebase project or none', () => { + + it('is the default project when .firebaserc has no Hosting targets', async () => { + const firebaseRc: FirebaseRc = { projects: { default: 'default-project' } }; + expect(await chooseFirebaseProject(context, firebaseRc, 'my-app', {})).toBe('default-project'); + }); + + it('is the project that has the target name, not the default project', async () => { + expect(await chooseFirebaseProject(context, targetUnderOneProject, 'my-app', {})).toBe('production-project'); + }); + + it('asks nothing at a terminal', async () => { + setTerminal(true); + await chooseFirebaseProject(context, targetUnderOneProject, 'my-app', {}); + expect(prompt).not.toHaveBeenCalled(); + }); + + it('accepts a firebaseProject option that agrees with .firebaserc', async () => { + const options = { firebaseProject: 'production-project' }; + expect(await chooseFirebaseProject(context, targetUnderOneProject, 'my-app', options)).toBe('production-project'); + }); + + it('stops when the firebaseProject option disagrees with .firebaserc', async () => { + const options = { firebaseProject: 'default-project' }; + await expectAsync(chooseFirebaseProject(context, targetUnderOneProject, 'my-app', options)) + .toBeRejectedWithError(conflict); + }); + + it('stops when the firebaseProject option is set and .firebaserc has no project', async () => { + const options = { firebaseProject: 'production-project' }; + await expectAsync(chooseFirebaseProject(context, {}, 'my-app', options)).toBeRejectedWithError(conflict); + }); + + it('stops when neither file has a project', async () => { + await expectAsync(chooseFirebaseProject(context, {}, 'my-app', {})) + .toBeRejectedWithError(/Cannot determine the Firebase Project/); + }); + + }); + + describe('for an App Hosting deploy', () => { + + const options = { appHostingBackend: 'my-backend' }; + + it('is the default project, whatever project has the Hosting target name', async () => { + expect(await chooseFirebaseProject(context, targetUnderOneProject, 'my-app', options)).toBe('default-project'); + }); + + it('is the default project with the target name under several projects, and asks nothing', async () => { + setTerminal(true); + expect(await chooseFirebaseProject(context, targetUnderSeveralProjects, 'my-app', options)).toBe('production-project'); + expect(prompt).not.toHaveBeenCalled(); + }); + + }); + + describe('with the target name under several Firebase projects', () => { + + it('is the firebaseProject option when it is one of them, with no terminal', async () => { + const options = { firebaseProject: 'staging-project' }; + expect(await chooseFirebaseProject(context, targetUnderSeveralProjects, 'my-app', options)).toBe('staging-project'); + }); + + it('is the firebaseProject option when it is one of them, and asks nothing at a terminal', async () => { + setTerminal(true); + prompt.and.resolveTo({ projectId: 'dev-project' }); + const options = { firebaseProject: 'staging-project' }; + + expect(await chooseFirebaseProject(context, targetUnderSeveralProjects, 'my-app', options)).toBe('staging-project'); + + expect(prompt).not.toHaveBeenCalled(); + }); + + it('stops when the firebaseProject option is none of them', async () => { + const options = { firebaseProject: 'default-project' }; + await expectAsync(chooseFirebaseProject(context, targetUnderSeveralProjects, 'my-app', options)) + .toBeRejectedWithError(conflict); + }); + + it('with no terminal, deploys nowhere and says how to choose a project', async () => { + const error = spyOn(context.logger, 'error'); + + expect(await chooseFirebaseProject(context, targetUnderSeveralProjects, 'my-app', {})).toBeUndefined(); + + expect(prompt).not.toHaveBeenCalled(); + const message: string = error.calls.mostRecent().args[0]; + expect(message).toContain('the Hosting target "my-app" under more than one Firebase project'); + expect(message).toContain('(dev-project, staging-project, production-project)'); + expect(message).toContain('add "firebaseProject": "" to the deploy options of "my-app" in angular.json'); + expect(message).toContain('ng deploy --firebase-project='); + }); + + it('at a terminal, asks one list question with those projects as the choices, starting on the default project', async () => { + setTerminal(true); + + await chooseFirebaseProject(context, targetUnderSeveralProjects, 'my-app', {}); + + expect(prompt).toHaveBeenCalledTimes(1); + expect(prompt.calls.mostRecent().args[0]).toEqual(jasmine.objectContaining({ + type: 'list', + name: 'projectId', + choices: ['dev-project', 'staging-project', 'production-project'], + default: 'production-project', + })); + }); + + it('at a terminal, deploys to the answer and says how to skip the question', async () => { + setTerminal(true); + const info = spyOn(context.logger, 'info'); + + expect(await chooseFirebaseProject(context, targetUnderSeveralProjects, 'my-app', {})).toBe('staging-project'); + + const message: string = info.calls.mostRecent().args[0]; + expect(message).toContain('To skip this question'); + expect(message).toContain('add "firebaseProject": "staging-project" to the deploy options of "my-app" in angular.json'); + expect(message).toContain('ng deploy --firebase-project=staging-project'); + }); + + }); + +}); diff --git a/src/schematics/deploy/firebaseProject.ts b/src/schematics/deploy/firebaseProject.ts new file mode 100644 index 000000000..7cc891ce3 --- /dev/null +++ b/src/schematics/deploy/firebaseProject.ts @@ -0,0 +1,102 @@ +/** + * @fileoverview Works out which Firebase project `ng deploy` deploys to. + * + * Two files have a say: + * + * - `.firebaserc`, the Firebase CLI's file, records the workspace's default project under + * `projects.default`. It also records, separately for each Firebase project, which Hosting site + * a Hosting target name refers to in that project. AngularFire uses the Angular project's name + * as the target name. + * - `angular.json` can specify the project, in the `firebaseProject` option of the Angular + * project's `deploy` entry. `ng deploy --firebase-project=` sets the same option. + * + * `.firebaserc` can have the target name under more than one Firebase project, for example a + * staging project and a production project. Nothing in that file then says which of them a + * deploy is meant for, so `ng deploy` only deploys to a project it was told about: the + * `firebaseProject` option, or the user's answer to a prompt question. + */ + +import { BuilderContext } from '@angular-devkit/architect'; +import inquirer from 'inquirer'; +import { projectsWithHostingTarget } from '../firebaserc.js'; +import { DeployBuilderSchema, FirebaseRc } from '../interfaces'; + +const projectConflictMessage = 'The Firebase Project specified by your angular.json or .firebaserc is in conflict'; + +/** The two ways to set the `firebaseProject` option, worded as the end of a sentence shown to the user. */ +const howToSetFirebaseProject = (angularProjectName: string, projectId: string): string => + `add "firebaseProject": "${projectId}" to the deploy options of "${angularProjectName}" in angular.json, ` + + `or run ng deploy --firebase-project=${projectId}`; + +/** + * Asks which Firebase project to deploy to. Asked only when `.firebaserc` has the Hosting target + * name under more than one Firebase project. + * @param projectIds the Firebase projects that have the target name, offered as the choices + * @param defaultProject the workspace's default project, which the cursor starts on when it is + * one of `projectIds` + */ +const firebaseProjectPrompt = async ( + angularProjectName: string, + projectIds: string[], + defaultProject: string | undefined, +): Promise => { + const { projectId } = await inquirer.prompt<{ projectId: string }>({ + type: 'list', + name: 'projectId', + choices: projectIds, + message: + `.firebaserc lists the Hosting target "${angularProjectName}" under more than one Firebase project. ` + + 'Which one should ng deploy use?', + default: defaultProject, + }); + return projectId; +}; + +/** + * Chooses the Firebase project to deploy the Angular project `angularProjectName` to. + * + * Returns undefined in one case, after printing why: `.firebaserc` has the Hosting target name + * under more than one Firebase project, the `firebaseProject` option is not set, and there is no + * terminal to ask the user in, as in an automated job. + */ +export const chooseFirebaseProject = async ( + context: BuilderContext, + firebaseRc: FirebaseRc, + angularProjectName: string, + options: DeployBuilderSchema, +): Promise => { + const defaultProject = firebaseRc.projects?.default; + + // App Hosting has no entry in .firebaserc, so no Hosting target name is looked up for it. + const hostingProjects = options.appHostingBackend ? [] : projectsWithHostingTarget(firebaseRc, angularProjectName); + + if (hostingProjects.length > 1) { + if (options.firebaseProject) { + if (!hostingProjects.includes(options.firebaseProject)) { throw new Error(projectConflictMessage); } + return options.firebaseProject; + } + + // With no terminal there is nobody to answer a question, so this stops with an error and does not ask. + if (!process.stdin.isTTY) { + context.logger.error( + `.firebaserc lists the Hosting target "${angularProjectName}" under more than one Firebase project ` + + `(${hostingProjects.join(', ')}), so ng deploy cannot tell which project to deploy to.\n` + + `To choose one, ${howToSetFirebaseProject(angularProjectName, '')}.` + ); + return undefined; + } + + const answer = await firebaseProjectPrompt(angularProjectName, hostingProjects, defaultProject); + context.logger.info(`To skip this question, ${howToSetFirebaseProject(angularProjectName, answer)}.`); + return answer; + } + + // One project has the target name, or none does and the default project is all there is. + const projectFromFirebaseRc: string | undefined = hostingProjects[0] ?? defaultProject; + const firebaseProject = options.firebaseProject || projectFromFirebaseRc; + if (!firebaseProject) { + throw new Error('Cannot determine the Firebase Project from your angular.json or .firebaserc'); + } + if (firebaseProject !== projectFromFirebaseRc) { throw new Error(projectConflictMessage); } + return firebaseProject; +}; diff --git a/src/schematics/deploy/schema.json b/src/schematics/deploy/schema.json index d9ebe7e00..b701a6d21 100644 --- a/src/schematics/deploy/schema.json +++ b/src/schematics/deploy/schema.json @@ -78,6 +78,17 @@ "description": "Runtime options for Cloud Functions. Read only by the Cloud Functions mode, which AngularFire 22 deprecates and AngularFire 23 removes.", "x-deprecated": "read only by the Cloud Functions mode of ng deploy, which AngularFire 22 deprecates and AngularFire 23 removes. Delete it unless ssr is true or 'cloud-functions'. Use Firebase App Hosting for server-rendered apps." }, + "version": { + "type": "number", + "description": "The deploy target format. 2 is what ng add @angular/fire writes. Leave it out only for targets that deploy server-side rendering to Cloud Functions or Cloud Run." + }, + "appHostingBackend": { + "type": "string", + "pattern": "^[a-z](?:[a-z0-9-]*[a-z0-9])?$", + "minLength": 3, + "maxLength": 30, + "description": "The Firebase App Hosting backend to deploy to. When set, ng deploy uploads the workspace to App Hosting, which builds it, instead of building locally and deploying to Firebase Hosting. The backend must also be listed under apphosting in firebase.json." + }, "preview": { "type": "boolean", "description": "Do not deploy the application, just set up the Firebase Function in the project output directory. Can be used for testing the Firebase Function with `firebase serve`." diff --git a/src/schematics/firebaseTools.ts b/src/schematics/firebaseTools.ts index a1aa63f39..c68eb5b20 100644 --- a/src/schematics/firebaseTools.ts +++ b/src/schematics/firebaseTools.ts @@ -19,6 +19,16 @@ export const getActiveAccount = (firebaseTools: FirebaseTools, projectRoot: stri // The minimum firebase-tools version the schematics require. const minFirebaseToolsVersion = '14.0.0'; +/** + * The oldest firebase-tools that `ng add` and `ng deploy` accept for App Hosting. Older versions + * report a failed App Hosting rollout as a successful deploy. + */ +export const appHostingMinVersion = '15.9.0'; + +/** Whether firebase-tools exposes its App Hosting commands and is at least `appHostingMinVersion`. */ +export const supportsAppHosting = (firebaseTools: FirebaseTools): boolean => + !!firebaseTools.apphosting && semverCompare(firebaseTools.cli.version(), appHostingMinVersion) >= 0; + export const getFirebaseTools = () => globalThis.firebaseTools ? Promise.resolve(globalThis.firebaseTools) : new Promise((resolve, reject) => { diff --git a/src/schematics/firebaserc.jasmine.ts b/src/schematics/firebaserc.jasmine.ts new file mode 100644 index 000000000..073311bf8 --- /dev/null +++ b/src/schematics/firebaserc.jasmine.ts @@ -0,0 +1,104 @@ +import { mkdtempSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import fsExtra from 'fs-extra'; +import { + hostingSiteFromRc, + hostingSitesOfOtherTargets, + projectsWithHostingTarget, + readFirebaseRc, +} from './firebaserc.js'; +import { FirebaseRc } from './interfaces.js'; +import 'jasmine'; + +/** Two Firebase projects that both give the target name `my-app` a site, as staging and production would. */ +const twoProjects: FirebaseRc = { + projects: { default: 'staging-project' }, + targets: { + 'staging-project': { hosting: { 'my-app': ['staging-site'], admin: ['admin-site'] } }, + 'production-project': { hosting: { 'my-app': ['production-site'] } }, + 'docs-project': { hosting: { docs: ['docs-site'] } }, + }, +}; + +/** A `.firebaserc` with a default project and no Hosting targets, as `ng add` leaves it with no deploy setup. */ +const onlyDefaultProject: FirebaseRc = { projects: { default: 'staging-project' } }; + +describe('projectsWithHostingTarget', () => { + + it('lists the projects that give the target name a site, in the order of the file', () => { + expect(projectsWithHostingTarget(twoProjects, 'my-app')).toEqual(['staging-project', 'production-project']); + }); + + it('is empty for a file with no targets', () => { + expect(projectsWithHostingTarget(onlyDefaultProject, 'my-app')).toEqual([]); + }); + +}); + +describe('hostingSiteFromRc', () => { + + it('is the site the project gives the target name', () => { + expect(hostingSiteFromRc(twoProjects, 'production-project', 'my-app')).toBe('production-site'); + }); + + it('is undefined when the project does not have the target name', () => { + expect(hostingSiteFromRc(twoProjects, 'docs-project', 'my-app')).toBeUndefined(); + }); + + it('is undefined when the file has targets for other projects only', () => { + expect(hostingSiteFromRc(twoProjects, 'new-project', 'my-app')).toBeUndefined(); + }); + + it('is undefined for a file with no targets', () => { + expect(hostingSiteFromRc(onlyDefaultProject, 'staging-project', 'my-app')).toBeUndefined(); + }); + +}); + +describe('hostingSitesOfOtherTargets', () => { + + it('pairs each site of the project with the other target name that has it', () => { + expect(hostingSitesOfOtherTargets(twoProjects, 'staging-project', 'my-app')).toEqual({ 'admin-site': 'admin' }); + }); + + it('is empty when the project has no other target name', () => { + expect(hostingSitesOfOtherTargets(twoProjects, 'production-project', 'my-app')).toEqual({}); + }); + + it('is empty when the file has targets for other projects only', () => { + expect(hostingSitesOfOtherTargets(twoProjects, 'new-project', 'my-app')).toEqual({}); + }); + + it('is empty for a file with no targets', () => { + expect(hostingSitesOfOtherTargets(onlyDefaultProject, 'staging-project', 'my-app')).toEqual({}); + }); + +}); + +describe('readFirebaseRc', () => { + let projectRoot: string; + + beforeEach(() => { + projectRoot = mkdtempSync(join(tmpdir(), 'angularfire-test-')); + }); + + afterEach(() => { + fsExtra.removeSync(projectRoot); + }); + + it('reads .firebaserc from the workspace root', () => { + writeFileSync(join(projectRoot, '.firebaserc'), JSON.stringify(twoProjects)); + expect(readFirebaseRc(projectRoot)).toEqual(twoProjects); + }); + + it('reads a missing file as empty', () => { + expect(readFirebaseRc(projectRoot)).toEqual({}); + }); + + it('reads a file that is not JSON as empty', () => { + writeFileSync(join(projectRoot, '.firebaserc'), '{ not json'); + expect(readFirebaseRc(projectRoot)).toEqual({}); + }); + +}); diff --git a/src/schematics/firebaserc.ts b/src/schematics/firebaserc.ts index b24895a09..e6b4b4dc2 100644 --- a/src/schematics/firebaserc.ts +++ b/src/schematics/firebaserc.ts @@ -2,28 +2,35 @@ import { readFileSync } from "fs"; import { join } from "path"; import { FirebaseRc } from "./interfaces"; -export const projectFromRc = ( - rc: FirebaseRc, - target: string -): [string | undefined, string | undefined] => { - const defaultProject = rc.projects?.default; - const project = Object.keys(rc.targets || {}).find( - (project) => !!rc.targets?.[project]?.hosting?.[target] - ); - const site = project && rc.targets?.[project]?.hosting?.[target]?.[0]; - return [project || defaultProject, site]; +/** + * The Firebase projects under which `.firebaserc` gives the Hosting target name `target` a site, + * in the order the file lists them. + */ +export const projectsWithHostingTarget = (rc: FirebaseRc, target: string): string[] => + Object.keys(rc.targets ?? {}).filter(project => !!rc.targets?.[project]?.hosting?.[target]); + +/** The Hosting site `.firebaserc` gives the target name `target` in the Firebase project `project`. */ +export const hostingSiteFromRc = (rc: FirebaseRc, project: string, target: string): string | undefined => + rc.targets?.[project]?.hosting?.[target]?.[0]; + +/** + * The Hosting sites of the Firebase project `project` that `.firebaserc` gives to a target name + * other than `target`. Each site id is paired with the target name that has it. + */ +export const hostingSitesOfOtherTargets = (rc: FirebaseRc, project: string, target: string): Record => { + const otherTargetBySite: Record = {}; + for (const [otherTarget, sites] of Object.entries(rc.targets?.[project]?.hosting ?? {})) { + if (otherTarget === target) { continue; } + for (const site of sites) { otherTargetBySite[site] = otherTarget; } + } + return otherTargetBySite; }; -export function getFirebaseProjectNameFromFs( - root: string, - target: string -): [string | undefined, string | undefined] { - const path = join(root, ".firebaserc"); +/** Reads `.firebaserc` from the workspace root. A missing or unreadable file reads as empty. */ +export const readFirebaseRc = (root: string): FirebaseRc => { try { - const buffer = readFileSync(path); - const rc: FirebaseRc = JSON.parse(buffer.toString()); - return projectFromRc(rc, target); + return JSON.parse(readFileSync(join(root, ".firebaserc")).toString()); } catch { - return [undefined, undefined]; + return {}; } -} +}; diff --git a/src/schematics/interfaces.ts b/src/schematics/interfaces.ts index 4ea3ff920..9f63f1808 100644 --- a/src/schematics/interfaces.ts +++ b/src/schematics/interfaces.ts @@ -48,8 +48,12 @@ export interface NgAddNormalizedOptions { ssrRegion: string|undefined; } +/** Where `ng add` sets up `ng deploy` to deploy to. `none` writes no deploy target. */ +export type DeployChoice = 'apphosting' | 'hosting' | 'none'; + export interface DeployOptions { project?: string; + deploy?: DeployChoice; } export interface FirebaseProject { @@ -89,6 +93,51 @@ export interface FirebaseSDKConfig { sdkConfig: Record; } +/** + * The options this package passes to Firebase CLI commands it calls as library functions. + * Build a new object for every call. The Firebase CLI adds fields of its own to the object it is + * given, and a later call fails on an object that already has them. + */ +export interface FirebaseToolsCommandOptions { + /** The Firebase project id to act on. */ + project?: string; + /** The workspace root. The Firebase CLI itself looks for firebase.json from `cwd` or the current directory. */ + projectRoot?: string; + cwd?: string; + /** The email of the signed-in account to act as. */ + account?: string; + /** A CI token to authenticate with, in place of a signed-in account. */ + token?: string; + /** True stops the Firebase CLI from asking the user questions of its own. */ + nonInteractive?: boolean; +} + +/** What the Firebase CLI needs to create an App Hosting backend without asking questions. */ +export interface AppHostingBackendCreateOptions extends FirebaseToolsCommandOptions { + /** The id of the new backend. */ + backend: string; + /** The Google Cloud region the backend runs in, such as `us-central1`. */ + primaryRegion: string; + /** The directory holding the app's package.json, relative to the uploaded workspace. */ + rootDir: string; + /** The id of the Firebase web app the backend is linked to. */ + app: string; +} + +/** + * A Firebase App Hosting backend, as the Firebase CLI's backend commands return it. A backend is + * what App Hosting deploys an app to. App Hosting builds the app from its source in Google Cloud + * and runs the app's Node.js server there, on Cloud Run, in the backend's region. + */ +export interface AppHostingBackend { + /** `projects//locations//backends/` */ + name: string; + /** The backend's address, without `https://`. */ + uri?: string; + /** Present when the backend deploys from a linked GitHub repository. */ + codebase?: { repository?: string }; +} + export interface FirebaseTools { projects: { list(options: any): Promise; @@ -108,6 +157,15 @@ export interface FirebaseTools { } }; + /** Missing when firebase-tools predates App Hosting or has its `apphosting` experiment off. */ + apphosting?: { + backends: { + list(options: FirebaseToolsCommandOptions): Promise; + create(options: AppHostingBackendCreateOptions): Promise; + get(backendId: string, options: FirebaseToolsCommandOptions): Promise; + } + }; + logger: { // firebase-tools v8 add: (...args: any[]) => any @@ -146,7 +204,11 @@ export interface FirebaseHostingConfig { public?: string; ignore?: string[]; target?: string; + site?: string; rewrites?: FirebaseHostingRewrite[]; + /** Written by AngularFire before 17.1. Firebase's web frameworks integration, which `public` replaces. */ + source?: string; + frameworksBackend?: unknown; } export type FirebaseFunctionsConfig = Record; @@ -160,15 +222,32 @@ export interface FirebaseFirestoreConfig { indexes?: string; } +/** One App Hosting backend as listed under `apphosting` in firebase.json. */ +export interface FirebaseAppHostingConfig { + /** The id of the backend that this entry holds the settings for. */ + backendId: string; + /** The directory holding the app's package.json, relative to firebase.json. */ + rootDir?: string; + /** Paths left out of the upload. */ + ignore?: string[]; + /** + * False makes the Firebase CLI skip the backend `backendId` when it deploys. True tells the CLI + * that uploading local files to that backend is intended although it is connected to a GitHub + * repository. + */ + alwaysDeployFromSource?: boolean; +} + export interface FirebaseJSON { hosting?: FirebaseHostingConfig[] | FirebaseHostingConfig; + apphosting?: FirebaseAppHostingConfig[] | FirebaseAppHostingConfig; functions?: FirebaseFunctionsConfig; firestore?: FirebaseFirestoreConfig; dataconnect?: DataConnectConfig; } export interface FirebaseRcTarget { - hosting: Record; + hosting?: Record; } export interface FirebaseRc { @@ -198,6 +277,8 @@ export interface DeployBuilderSchema { /** @deprecated Read only by the Cloud Functions mode, which will be removed in AngularFire 23. */ CF3v2?: boolean; version?: number; + /** The App Hosting backend to deploy to. When set, `ng deploy` deploys there instead of to Hosting. */ + appHostingBackend?: string; } export interface CloudRunOptions { diff --git a/src/schematics/setup/appHosting.ts b/src/schematics/setup/appHosting.ts new file mode 100644 index 000000000..a4bd3d6fe --- /dev/null +++ b/src/schematics/setup/appHosting.ts @@ -0,0 +1,134 @@ +/** + * @fileoverview The Firebase App Hosting part of `ng add`: checking that the installed Firebase + * CLI can set App Hosting up, saying what App Hosting requires of the Firebase project, and + * choosing or creating the backend that `ng deploy` will deploy to. + * + * A backend is what App Hosting deploys an app to. An Angular app built with server-side + * rendering includes a Node.js server program that renders pages. App Hosting builds the app + * from its source in Google Cloud and runs that program there, on Cloud Run, in the region the + * backend was created in. + */ + +import { SchematicContext, SchematicsException } from '@angular-devkit/schematics'; +import { appHostingMinVersion, supportsAppHosting } from '../firebaseTools.js'; +import { FirebaseTools, FirebaseToolsCommandOptions } from '../interfaces.js'; +import { alreadyDeploysLocalFiles, backendIdFromProjectName } from './deployConfigs.js'; +import { appHostingBackendPrompt } from './deployPrompts.js'; +import { confirmPrompt } from './prompts.js'; + +/** What a Firebase project needs before App Hosting works in it, as a sentence to show the user. */ +export const appHostingRequirements = (projectId: string): string => + 'Firebase App Hosting needs the Blaze pricing plan ' + + `(https://console.firebase.google.com/project/${projectId}/usage/details), ` + + 'its Terms of Service accepted in the Firebase console, and, for the first deploy to a region, ' + + 'an account with the Owner or IAM Admin role on the project.'; + +/** Stops `ng add` when the installed firebase-tools cannot set up App Hosting. */ +export const assertAppHostingSetupSupported = (firebaseTools: FirebaseTools): void => { + if (!supportsAppHosting(firebaseTools)) { + throw new SchematicsException( + `Setting up App Hosting needs firebase-tools ${appHostingMinVersion} or newer with its ` + + `App Hosting commands enabled, and this is ${firebaseTools.cli.version()}. ` + + 'Nothing was set up, the selected features included. Upgrade firebase-tools, then run ' + + 'ng add @angular/fire again. To set up the features without upgrading, run it again and ' + + 'choose Firebase Hosting or "Don\'t set up deployment".' + ); + } +}; + +/** What `selectAppHostingBackend` needs to know about the `ng add` run it is part of. */ +export interface AppHostingSetupRequest { + /** The Firebase project the backend belongs to. */ + projectId: string; + /** The workspace root on disk. */ + projectRoot: string; + /** The email of the signed-in Firebase account to act as. */ + account: string; + /** The Firebase web app a new backend is linked to. */ + webAppId: string; + /** Used to suggest an id for a new backend. */ + angularProjectName: string; + /** The backend the app already deploys to, if any. The cursor starts on it in the list of backends. */ + existingBackendId: string | undefined; +} + +/** The backend `ng deploy` will deploy to, as chosen during `ng add`. */ +export interface AppHostingSetup { + backendId: string; + /** + * True when the backend is connected to a GitHub repository and the user agreed that + * `ng deploy` uploads local files to it anyway. Written to firebase.json, which is where the + * Firebase CLI looks for that answer. + */ + alwaysDeployFromSource: boolean; +} + +/** + * Asks which App Hosting backend `ng deploy` should deploy to, and creates it when the user + * asks for a new one. + * + * A backend can be connected to a GitHub repository, and App Hosting then deploys it from each + * commit pushed there. Uploading local files to such a backend replaces what GitHub last + * deployed, so the user is asked to confirm. Returns undefined when they decline, meaning no + * backend was chosen. + */ +export const selectAppHostingBackend = async ( + firebaseTools: FirebaseTools, + context: SchematicContext, + request: AppHostingSetupRequest, +): Promise => { + const { projectId, projectRoot, account, webAppId, angularProjectName, existingBackendId } = request; + + /* A function instead of one shared object. Each Firebase CLI call needs a new options object. + * `nonInteractive` keeps the CLI from asking its own questions. */ + const newCallOptions = (): FirebaseToolsCommandOptions => ( + { project: projectId, projectRoot, account, nonInteractive: true } + ); + + /* Billing, Terms of Service and permissions are the usual reasons these calls fail, and the + * Firebase CLI's own error does not always say so. Every failure repeats the requirements. */ + const failure = (action: string, error: Error) => new SchematicsException( + `Could not ${action} for project ${projectId}: ${error.message}\n${appHostingRequirements(projectId)}` + ); + + // `assertAppHostingSetupSupported` has already checked that these commands exist. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const { backends: backendCommands } = firebaseTools.apphosting!; + + const backends = await backendCommands.list(newCallOptions()).catch((error: Error) => { + throw failure('list App Hosting backends', error); + }); + + const suggestedBackendId = backendIdFromProjectName(angularProjectName); + const choice = await appHostingBackendPrompt(backends, suggestedBackendId, existingBackendId); + + // A region is set only when the user asked for a new backend. + if (choice.newBackendRegion) { + context.logger.info(`Creating App Hosting backend ${choice.backendId} in ${choice.newBackendRegion}...`); + await backendCommands.create({ + ...newCallOptions(), + backend: choice.backendId, + primaryRegion: choice.newBackendRegion, + rootDir: '.', + app: webAppId, + }).catch((error: Error) => { + throw failure(`create the App Hosting backend ${choice.backendId}`, error); + }); + return { backendId: choice.backendId, alwaysDeployFromSource: false }; + } + + if (choice.linkedToGitHub) { + // The user agreed to this for the same backend in an earlier run, so it is not asked again. + if (alreadyDeploysLocalFiles(projectRoot, choice.backendId)) { + return { backendId: choice.backendId, alwaysDeployFromSource: true }; + } + + const deployLocalFiles = await confirmPrompt( + `${choice.backendId} deploys from a GitHub repository today. ng deploy uploads your local ` + + 'files instead, which replaces what GitHub last rolled out. Deploy local files to it?', + ); + return deployLocalFiles ? { backendId: choice.backendId, alwaysDeployFromSource: true } : undefined; + } + + return { backendId: choice.backendId, alwaysDeployFromSource: false }; +}; diff --git a/src/schematics/setup/appHostingRegions.ts b/src/schematics/setup/appHostingRegions.ts new file mode 100644 index 000000000..8cf408687 --- /dev/null +++ b/src/schematics/setup/appHostingRegions.ts @@ -0,0 +1,13 @@ +/** + * @fileoverview The Firebase App Hosting regions `ng add` offers for a new backend. + * Generated by `npm run update-regions`. Do not edit by hand. + */ + +export const appHostingRegions = [ + { id: "asia-east1", name: "Taiwan" }, + { id: "asia-southeast1", name: "Singapore" }, + { id: "europe-west4", name: "Netherlands" }, + { id: "us-central1", name: "Iowa" }, + { id: "us-east4", name: "Northern Virginia" }, + { id: "us-east5", name: "Columbus" }, +]; diff --git a/src/schematics/setup/deployConfigs.jasmine.ts b/src/schematics/setup/deployConfigs.jasmine.ts new file mode 100644 index 000000000..1048584b8 --- /dev/null +++ b/src/schematics/setup/deployConfigs.jasmine.ts @@ -0,0 +1,693 @@ +import { mkdtempSync, readFileSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { logging } from '@angular-devkit/core'; +import { HostTree, SchematicContext } from '@angular-devkit/schematics'; +import fsExtra from 'fs-extra'; +import { BuildTargetDefinition } from '../buildOptions.js'; +import { FirebaseRc } from '../interfaces.js'; +import { + alreadyDeploysLocalFiles, + backendIdFromProjectName, + deployBuilder, + existingAppHostingBackend, + existingDeployChoice, + existingFirebaseProject, + firebaseProjectForDeployOption, + firebaseRcForSetup, + isValidBackendId, + setAppHostingInFirebaseJson, + setDeployTarget, + setHostingInFirebaseJson, + setHostingTargetInFirebaseRc, + unnamedHostingEntryToReplace, +} from './deployConfigs.js'; +import 'jasmine'; + +const context = { logger: new logging.Logger('test') } as unknown as SchematicContext; + +/** A `deploy` entry as `ng add` writes it for Firebase Hosting. */ +const hostingDeployEntry: BuildTargetDefinition = { builder: deployBuilder, options: { version: 2 } }; + +/** A `deploy` entry as `ng add` writes it for Firebase App Hosting. */ +const appHostingDeployEntry: BuildTargetDefinition = { + builder: deployBuilder, + options: { version: 2, appHostingBackend: 'my-backend' }, +}; + +/** A `deploy` entry that belongs to another tool. */ +const otherToolDeployEntry: BuildTargetDefinition = { + builder: 'angular-cli-ghpages:deploy', + options: { appHostingBackend: 'not-ours', firebaseProject: 'not-ours' }, +}; + +describe('existingAppHostingBackend', () => { + + it('is the backend of an AngularFire deploy entry for App Hosting', () => { + expect(existingAppHostingBackend(appHostingDeployEntry)).toBe('my-backend'); + }); + + it('is undefined for an AngularFire deploy entry for Hosting', () => { + expect(existingAppHostingBackend(hostingDeployEntry)).toBeUndefined(); + }); + + it('is undefined for the deploy entry of another tool', () => { + expect(existingAppHostingBackend(otherToolDeployEntry)).toBeUndefined(); + }); + + it('is undefined for a project with no deploy entry', () => { + expect(existingAppHostingBackend(undefined)).toBeUndefined(); + }); + +}); + +describe('existingDeployChoice', () => { + + it('is apphosting for a deploy entry with a backend', () => { + expect(existingDeployChoice(appHostingDeployEntry)).toBe('apphosting'); + }); + + it('is hosting for a deploy entry with version 2 and no backend', () => { + expect(existingDeployChoice(hostingDeployEntry)).toBe('hosting'); + }); + + it('is hosting for an AngularFire deploy entry with no options', () => { + expect(existingDeployChoice({ builder: deployBuilder })).toBe('hosting'); + }); + + it('is none for an entry that deploys its server to Cloud Run the older way, with ssr and no version', () => { + expect(existingDeployChoice({ builder: deployBuilder, options: { ssr: 'cloud-run' } })).toBe('none'); + }); + + it('is none for an entry that deploys its server to Cloud Functions the older way', () => { + expect(existingDeployChoice({ builder: deployBuilder, options: { ssr: true } })).toBe('none'); + }); + + it('is hosting for an entry with ssr once it has version 2', () => { + expect(existingDeployChoice({ builder: deployBuilder, options: { ssr: true, version: 2 } })).toBe('hosting'); + }); + + it('is undefined for the deploy entry of another tool', () => { + expect(existingDeployChoice(otherToolDeployEntry)).toBeUndefined(); + }); + + it('is undefined for a project with no deploy entry', () => { + expect(existingDeployChoice(undefined)).toBeUndefined(); + }); + +}); + +describe('existingFirebaseProject', () => { + + /** The target name `my-app` under one project, which is not the default project. */ + const targetUnderOneProject: FirebaseRc = { + projects: { default: 'default-project' }, + targets: { 'production-project': { hosting: { 'my-app': ['production-site'] } } }, + }; + + /** The target name `my-app` under two projects, neither of which is the default project. */ + const targetUnderTwoProjects: FirebaseRc = { + projects: { default: 'default-project' }, + targets: { + 'staging-project': { hosting: { 'my-app': ['staging-site'] } }, + 'production-project': { hosting: { 'my-app': ['production-site'] } }, + }, + }; + + it('is the default project for an App Hosting entry, whatever Hosting targets the file has', () => { + expect(existingFirebaseProject(appHostingDeployEntry, targetUnderOneProject, 'my-app')).toBe('default-project'); + }); + + it('is the one project that has the target name', () => { + expect(existingFirebaseProject(hostingDeployEntry, targetUnderOneProject, 'my-app')).toBe('production-project'); + }); + + it('is the firebaseProject option when the target name is under two projects', () => { + const deployEntry: BuildTargetDefinition = { + builder: deployBuilder, + options: { version: 2, firebaseProject: 'production-project' }, + }; + expect(existingFirebaseProject(deployEntry, targetUnderTwoProjects, 'my-app')).toBe('production-project'); + }); + + it('is the default project when the target name is under two projects and no option chooses', () => { + expect(existingFirebaseProject(hostingDeployEntry, targetUnderTwoProjects, 'my-app')).toBe('default-project'); + }); + + it('is the default project when the option is a project without the target name', () => { + const deployEntry: BuildTargetDefinition = { + builder: deployBuilder, + options: { version: 2, firebaseProject: 'retired-project' }, + }; + expect(existingFirebaseProject(deployEntry, targetUnderTwoProjects, 'my-app')).toBe('default-project'); + }); + + it('ignores the firebaseProject option of another tool', () => { + const deployEntry: BuildTargetDefinition = { + builder: 'angular-cli-ghpages:deploy', + options: { firebaseProject: 'production-project' }, + }; + expect(existingFirebaseProject(deployEntry, targetUnderTwoProjects, 'my-app')).toBe('default-project'); + }); + + it('is the first project with the target name when the file has no default project', () => { + const firebaseRc: FirebaseRc = { + projects: { staging: 'staging-project', production: 'production-project' }, + targets: targetUnderTwoProjects.targets, + }; + expect(existingFirebaseProject(hostingDeployEntry, firebaseRc, 'my-app')).toBe('staging-project'); + }); + + it('is the default project for a file with no targets', () => { + const firebaseRc: FirebaseRc = { projects: { default: 'default-project' } }; + expect(existingFirebaseProject(undefined, firebaseRc, 'my-app')).toBe('default-project'); + }); + + it('is undefined when there is no .firebaserc content', () => { + expect(existingFirebaseProject(undefined, {}, 'my-app')).toBeUndefined(); + }); + +}); + +describe('the writers of firebase.json and .firebaserc', () => { + let projectRoot: string; + + beforeEach(() => { + projectRoot = mkdtempSync(join(tmpdir(), 'angularfire-test-')); + }); + + afterEach(() => { + fsExtra.removeSync(projectRoot); + }); + + const writeOnDisk = (fileName: string, content: unknown) => + writeFileSync(join(projectRoot, fileName), JSON.stringify(content)); + + const readFromDisk = (fileName: string) => + JSON.parse(readFileSync(join(projectRoot, fileName)).toString()); + + describe('setHostingTargetInFirebaseRc', () => { + + it('creates .firebaserc with the target name under the project', () => { + setHostingTargetInFirebaseRc(projectRoot, 'my-project', 'my-app', 'my-site'); + expect(readFromDisk('.firebaserc')).toEqual({ + targets: { 'my-project': { hosting: { 'my-app': ['my-site'] } } }, + }); + }); + + it('keeps the default project, the other target names, the other kinds of target and the other projects', () => { + writeOnDisk('.firebaserc', { + projects: { default: 'my-project' }, + targets: { + 'my-project': { hosting: { admin: ['admin-site'] }, storage: { uploads: ['my-bucket'] } }, + 'other-project': { hosting: { 'my-app': ['other-site'] } }, + }, + }); + setHostingTargetInFirebaseRc(projectRoot, 'my-project', 'my-app', 'my-site'); + expect(readFromDisk('.firebaserc')).toEqual({ + projects: { default: 'my-project' }, + targets: { + 'my-project': { hosting: { admin: ['admin-site'], 'my-app': ['my-site'] }, storage: { uploads: ['my-bucket'] } }, + 'other-project': { hosting: { 'my-app': ['other-site'] } }, + }, + }); + }); + + it('replaces the site the target name had in the project', () => { + writeOnDisk('.firebaserc', { targets: { 'my-project': { hosting: { 'my-app': ['old-site'] } } } }); + setHostingTargetInFirebaseRc(projectRoot, 'my-project', 'my-app', 'new-site'); + expect(readFromDisk('.firebaserc').targets['my-project'].hosting['my-app']).toEqual(['new-site']); + }); + + it('stops with the path of a .firebaserc that cannot be parsed, and the reason', () => { + writeFileSync(join(projectRoot, '.firebaserc'), '{ not json'); + expect(() => setHostingTargetInFirebaseRc(projectRoot, 'my-project', 'my-app', 'my-site')) + .toThrowError(/Error when parsing .*\.firebaserc: .*JSON/); + }); + + }); + + describe('firebaseRcForSetup', () => { + + it('reads .firebaserc from the workspace root', () => { + writeOnDisk('.firebaserc', { projects: { default: 'my-project' } }); + expect(firebaseRcForSetup(projectRoot)).toEqual({ projects: { default: 'my-project' } }); + }); + + it('reads a missing file as empty', () => { + expect(firebaseRcForSetup(projectRoot)).toEqual({}); + }); + + it('stops with the path of a file that cannot be parsed', () => { + writeFileSync(join(projectRoot, '.firebaserc'), '{ not json'); + expect(() => firebaseRcForSetup(projectRoot)).toThrowError(/Error when parsing .*\.firebaserc/); + }); + + }); + + describe('firebaseProjectForDeployOption', () => { + + it('is the project when the file has the target name under two projects', () => { + writeOnDisk('.firebaserc', { + targets: { + 'staging-project': { hosting: { 'my-app': ['staging-site'] } }, + 'production-project': { hosting: { 'my-app': ['production-site'] } }, + }, + }); + expect(firebaseProjectForDeployOption(projectRoot, 'production-project', 'my-app')).toBe('production-project'); + }); + + it('is undefined when the file has the target name under one project', () => { + writeOnDisk('.firebaserc', { + targets: { + 'staging-project': { hosting: { admin: ['admin-site'] } }, + 'production-project': { hosting: { 'my-app': ['production-site'] } }, + }, + }); + expect(firebaseProjectForDeployOption(projectRoot, 'production-project', 'my-app')).toBeUndefined(); + }); + + it('is undefined when there is no .firebaserc', () => { + expect(firebaseProjectForDeployOption(projectRoot, 'production-project', 'my-app')).toBeUndefined(); + }); + + }); + + describe('unnamedHostingEntryToReplace', () => { + + it('is the lone entry with no target name that firebase init hosting writes', () => { + writeOnDisk('firebase.json', { hosting: { public: 'public', ignore: ['firebase.json'] } }); + expect(unnamedHostingEntryToReplace(projectRoot, 'my-app')).toEqual({ public: 'public', ignore: ['firebase.json'] }); + }); + + it('is the lone entry with no target name when hosting is written as a list', () => { + writeOnDisk('firebase.json', { hosting: [{ public: 'public' }] }); + expect(unnamedHostingEntryToReplace(projectRoot, 'my-app')).toEqual({ public: 'public' }); + }); + + it('is undefined when an entry already has the target name', () => { + writeOnDisk('firebase.json', { hosting: [{ target: 'my-app', public: 'dist/my-app/browser' }] }); + expect(unnamedHostingEntryToReplace(projectRoot, 'my-app')).toBeUndefined(); + }); + + it('is undefined when the entry with the target name comes after the entry of another app', () => { + writeOnDisk('firebase.json', { + hosting: [{ target: 'admin', public: 'dist/admin/browser' }, { target: 'my-app', public: 'dist/my-app/browser' }], + }); + expect(unnamedHostingEntryToReplace(projectRoot, 'my-app')).toBeUndefined(); + }); + + it('is undefined when the lone entry has another target name', () => { + writeOnDisk('firebase.json', { hosting: { target: 'admin', public: 'dist/admin/browser' } }); + expect(unnamedHostingEntryToReplace(projectRoot, 'my-app')).toBeUndefined(); + }); + + it('is undefined when the lone entry deploys to a site by its id', () => { + writeOnDisk('firebase.json', { hosting: { site: 'my-site', public: 'public' } }); + expect(unnamedHostingEntryToReplace(projectRoot, 'my-app')).toBeUndefined(); + }); + + it('is undefined when an entry with no target name is one of several', () => { + writeOnDisk('firebase.json', { hosting: [{ public: 'public' }, { target: 'admin', public: 'dist/admin/browser' }] }); + expect(unnamedHostingEntryToReplace(projectRoot, 'my-app')).toBeUndefined(); + }); + + it('is undefined when there is no firebase.json', () => { + expect(unnamedHostingEntryToReplace(projectRoot, 'my-app')).toBeUndefined(); + }); + + }); + + describe('setHostingInFirebaseJson', () => { + + it('creates firebase.json with an entry that serves the build and falls back to the client-side page', () => { + setHostingInFirebaseJson(projectRoot, 'my-app', 'dist/my-app/browser', 'index.html'); + expect(readFromDisk('firebase.json')).toEqual({ + hosting: [{ + target: 'my-app', + public: 'dist/my-app/browser', + ignore: ['firebase.json', '**/.*', '**/node_modules/**'], + rewrites: [{ source: '**', destination: '/index.html' }], + }], + }); + }); + + it('adds its entry beside the entry of another target name and keeps the other settings of the file', () => { + const adminEntry = { target: 'admin', public: 'dist/admin/browser' }; + writeOnDisk('firebase.json', { firestore: { rules: 'firestore.rules' }, hosting: adminEntry }); + setHostingInFirebaseJson(projectRoot, 'my-app', 'dist/my-app/browser', 'index.html'); + const firebaseJson = readFromDisk('firebase.json'); + expect(firebaseJson.firestore).toEqual({ rules: 'firestore.rules' }); + expect(firebaseJson.hosting.length).toBe(2); + expect(firebaseJson.hosting[0]).toEqual(adminEntry); + expect(firebaseJson.hosting[1].target).toBe('my-app'); + }); + + it('rewrites its own entry from an earlier run, keeping what the user added to it', () => { + writeOnDisk('firebase.json', { + hosting: [{ + target: 'my-app', + public: 'dist/old-folder', + ignore: ['firebase.json', 'drafts/**'], + headers: [{ source: '**', headers: [{ key: 'Cache-Control', value: 'no-cache' }] }], + rewrites: [ + { source: '**', destination: '/index.html' }, + { source: '/api/**', destination: '/api.html' }, + ], + }], + }); + setHostingInFirebaseJson(projectRoot, 'my-app', 'dist/my-app/browser', 'index.csr.html'); + expect(readFromDisk('firebase.json')).toEqual({ + hosting: [{ + target: 'my-app', + public: 'dist/my-app/browser', + ignore: ['firebase.json', 'drafts/**'], + headers: [{ source: '**', headers: [{ key: 'Cache-Control', value: 'no-cache' }] }], + rewrites: [ + { source: '/api/**', destination: '/api.html' }, + { source: '**', destination: '/index.csr.html' }, + ], + }], + }); + }); + + it('rewrites its own entry when it comes after the entry of another app, which it leaves alone', () => { + const adminEntry = { + target: 'admin', + public: 'dist/admin/browser', + headers: [{ source: '**', headers: [{ key: 'X-Frame-Options', value: 'DENY' }] }], + }; + writeOnDisk('firebase.json', { + hosting: [adminEntry, { target: 'my-app', public: 'dist/old-folder', cleanUrls: true }], + }); + setHostingInFirebaseJson(projectRoot, 'my-app', 'dist/my-app/browser', 'index.html'); + expect(readFromDisk('firebase.json')).toEqual({ + hosting: [adminEntry, { + target: 'my-app', + public: 'dist/my-app/browser', + cleanUrls: true, + ignore: ['firebase.json', '**/.*', '**/node_modules/**'], + rewrites: [{ source: '**', destination: '/index.html' }], + }], + }); + }); + + it('drops an earlier catch-all rewrite that sent every URL to a function', () => { + writeOnDisk('firebase.json', { + hosting: [{ target: 'my-app', public: 'dist/my-app/browser', rewrites: [{ source: '**', function: 'ssr' }] }], + }); + setHostingInFirebaseJson(projectRoot, 'my-app', 'dist/my-app/browser', 'index.html'); + expect(readFromDisk('firebase.json').hosting[0].rewrites).toEqual([{ source: '**', destination: '/index.html' }]); + }); + + it('turns a lone entry with no target name into its own entry', () => { + writeOnDisk('firebase.json', { hosting: { public: 'public', cleanUrls: true } }); + setHostingInFirebaseJson(projectRoot, 'my-app', 'dist/my-app/browser', 'index.html'); + expect(readFromDisk('firebase.json')).toEqual({ + hosting: [{ + target: 'my-app', + public: 'dist/my-app/browser', + cleanUrls: true, + ignore: ['firebase.json', '**/.*', '**/node_modules/**'], + rewrites: [{ source: '**', destination: '/index.html' }], + }], + }); + }); + + it('adds its entry beside a lone entry that deploys to a site by its id', () => { + const siteEntry = { site: 'marketing-site', public: 'public' }; + writeOnDisk('firebase.json', { hosting: siteEntry }); + setHostingInFirebaseJson(projectRoot, 'my-app', 'dist/my-app/browser', 'index.html'); + const hostingEntries = readFromDisk('firebase.json').hosting; + expect(hostingEntries.length).toBe(2); + expect(hostingEntries[0]).toEqual(siteEntry); + }); + + it('removes the source and frameworksBackend settings that AngularFire wrote before 17.1', () => { + writeOnDisk('firebase.json', { + hosting: [{ target: 'my-app', source: '.', frameworksBackend: { region: 'us-central1' } }], + }); + setHostingInFirebaseJson(projectRoot, 'my-app', 'dist/my-app/browser', 'index.html'); + const entry = readFromDisk('firebase.json').hosting[0]; + expect(entry.source).toBeUndefined(); + expect(entry.frameworksBackend).toBeUndefined(); + expect(entry.public).toBe('dist/my-app/browser'); + }); + + }); + + describe('alreadyDeploysLocalFiles', () => { + + it('is true when the entry of the backend has alwaysDeployFromSource set to true', () => { + writeOnDisk('firebase.json', { apphosting: { backendId: 'my-backend', alwaysDeployFromSource: true } }); + expect(alreadyDeploysLocalFiles(projectRoot, 'my-backend')).toBeTrue(); + }); + + it('is false when the entry of the backend does not have the setting', () => { + writeOnDisk('firebase.json', { apphosting: { backendId: 'my-backend' } }); + expect(alreadyDeploysLocalFiles(projectRoot, 'my-backend')).toBeFalse(); + }); + + it('is false when the entry of the backend has the setting set to false', () => { + writeOnDisk('firebase.json', { apphosting: { backendId: 'my-backend', alwaysDeployFromSource: false } }); + expect(alreadyDeploysLocalFiles(projectRoot, 'my-backend')).toBeFalse(); + }); + + it('is false when only the entry of another backend has the setting', () => { + writeOnDisk('firebase.json', { + apphosting: [{ backendId: 'other-backend', alwaysDeployFromSource: true }, { backendId: 'my-backend' }], + }); + expect(alreadyDeploysLocalFiles(projectRoot, 'my-backend')).toBeFalse(); + }); + + it('is false when there is no firebase.json', () => { + expect(alreadyDeploysLocalFiles(projectRoot, 'my-backend')).toBeFalse(); + }); + + }); + + describe('setAppHostingInFirebaseJson', () => { + + const defaultIgnore = ['node_modules', '.git', '/dist', '.angular', 'firebase-debug.log']; + + it('creates firebase.json with one entry for the backend', () => { + setAppHostingInFirebaseJson(projectRoot, 'my-backend', false); + expect(readFromDisk('firebase.json')).toEqual({ + apphosting: { backendId: 'my-backend', rootDir: '.', ignore: defaultIgnore }, + }); + }); + + it('writes alwaysDeployFromSource for a backend the user agreed to deploy local files to', () => { + setAppHostingInFirebaseJson(projectRoot, 'my-backend', true); + expect(readFromDisk('firebase.json').apphosting.alwaysDeployFromSource).toBeTrue(); + }); + + it('keeps the settings the user changed in the entry of the backend', () => { + const changedEntry = { backendId: 'my-backend', rootDir: 'apps/web', ignore: ['node_modules', 'docs'], localBuild: true }; + writeOnDisk('firebase.json', { apphosting: changedEntry }); + setAppHostingInFirebaseJson(projectRoot, 'my-backend', false); + expect(readFromDisk('firebase.json')).toEqual({ apphosting: changedEntry }); + }); + + it('rewrites the entry of the backend when it comes after the entry of another backend, which it leaves alone', () => { + const entries = [ + { backendId: 'other-backend', rootDir: 'apps/admin', ignore: ['admin-only'] }, + { backendId: 'my-backend', rootDir: 'apps/web', ignore: ['web-only'] }, + ]; + writeOnDisk('firebase.json', { apphosting: entries }); + setAppHostingInFirebaseJson(projectRoot, 'my-backend', false); + expect(readFromDisk('firebase.json')).toEqual({ apphosting: entries }); + }); + + it('lists a second backend beside the first and keeps the other settings of the file', () => { + const otherEntry = { backendId: 'other-backend', rootDir: 'apps/admin' }; + writeOnDisk('firebase.json', { hosting: [{ target: 'docs', public: 'docs' }], apphosting: otherEntry }); + setAppHostingInFirebaseJson(projectRoot, 'my-backend', false); + expect(readFromDisk('firebase.json')).toEqual({ + hosting: [{ target: 'docs', public: 'docs' }], + apphosting: [otherEntry, { backendId: 'my-backend', rootDir: '.', ignore: defaultIgnore }], + }); + }); + + it('stops with the path of a firebase.json that cannot be parsed, leaving it as it was', () => { + writeFileSync(join(projectRoot, 'firebase.json'), '{ not json'); + expect(() => setAppHostingInFirebaseJson(projectRoot, 'my-backend', false)) + .toThrowError(/Error when parsing .*firebase\.json/); + expect(readFileSync(join(projectRoot, 'firebase.json')).toString()).toBe('{ not json'); + }); + + }); + +}); + +describe('setDeployTarget', () => { + + /** An angular.json in memory with the application `my-app`, and `deployEntry` as its deploy entry when given. */ + const workspaceWith = (deployEntry?: Record): HostTree => { + const architect: Record = { build: { builder: '@angular/build:application', options: {} } }; + if (deployEntry) { architect.deploy = deployEntry; } + + const tree = new HostTree(); + tree.create('angular.json', JSON.stringify({ + version: 1, + projects: { 'my-app': { root: '', projectType: 'application', architect } }, + })); + return tree; + }; + + const deployEntryIn = (tree: HostTree) => + JSON.parse(tree.readText('angular.json')).projects['my-app'].architect.deploy; + + const hostingSettings = { appHostingBackend: undefined, firebaseProject: undefined }; + + it('adds a deploy entry for Hosting to a project that has none', async () => { + const tree = workspaceWith(); + await setDeployTarget('my-app', hostingSettings)(tree, context); + expect(deployEntryIn(tree)).toEqual({ builder: '@angular/fire:deploy', options: { version: 2 } }); + }); + + it('writes the backend for App Hosting', async () => { + const tree = workspaceWith(); + await setDeployTarget('my-app', { appHostingBackend: 'my-backend', firebaseProject: undefined })(tree, context); + expect(deployEntryIn(tree).options).toEqual({ version: 2, appHostingBackend: 'my-backend' }); + }); + + it('writes the firebaseProject option when given one', async () => { + const tree = workspaceWith(); + await setDeployTarget('my-app', { appHostingBackend: undefined, firebaseProject: 'my-project' })(tree, context); + expect(deployEntryIn(tree).options).toEqual({ version: 2, firebaseProject: 'my-project' }); + }); + + it('keeps the other options and the configurations of an earlier AngularFire entry', async () => { + const tree = workspaceWith({ + builder: '@angular/fire:deploy', + options: { buildTarget: 'my-app:build:staging' }, + configurations: { production: { buildTarget: 'my-app:build:production' } }, + defaultConfiguration: 'production', + }); + await setDeployTarget('my-app', hostingSettings)(tree, context); + expect(deployEntryIn(tree)).toEqual({ + builder: '@angular/fire:deploy', + options: { buildTarget: 'my-app:build:staging', version: 2 }, + configurations: { production: { buildTarget: 'my-app:build:production' } }, + defaultConfiguration: 'production', + }); + }); + + it('replaces the backend of an earlier entry', async () => { + const tree = workspaceWith({ builder: '@angular/fire:deploy', options: { version: 2, appHostingBackend: 'old-backend' } }); + await setDeployTarget('my-app', { appHostingBackend: 'new-backend', firebaseProject: undefined })(tree, context); + expect(deployEntryIn(tree).options).toEqual({ version: 2, appHostingBackend: 'new-backend' }); + }); + + it('replaces the firebaseProject option of an earlier entry', async () => { + const tree = workspaceWith({ builder: '@angular/fire:deploy', options: { version: 2, firebaseProject: 'old-project' } }); + await setDeployTarget('my-app', { appHostingBackend: undefined, firebaseProject: 'new-project' })(tree, context); + expect(deployEntryIn(tree).options).toEqual({ version: 2, firebaseProject: 'new-project' }); + }); + + it('writes the firebaseProject option into an earlier entry that had none', async () => { + const tree = workspaceWith({ builder: '@angular/fire:deploy', options: { version: 2 } }); + await setDeployTarget('my-app', { appHostingBackend: undefined, firebaseProject: 'new-project' })(tree, context); + expect(deployEntryIn(tree).options).toEqual({ version: 2, firebaseProject: 'new-project' }); + }); + + it('removes the backend when an App Hosting entry is set up for Hosting', async () => { + const tree = workspaceWith({ builder: '@angular/fire:deploy', options: { version: 2, appHostingBackend: 'my-backend' } }); + await setDeployTarget('my-app', hostingSettings)(tree, context); + expect(deployEntryIn(tree).options).toEqual({ version: 2 }); + }); + + it('removes the firebaseProject and firebaseHostingSite options left from an earlier setup', async () => { + const tree = workspaceWith({ + builder: '@angular/fire:deploy', + options: { version: 2, firebaseProject: 'old-project', firebaseHostingSite: 'old-site' }, + }); + await setDeployTarget('my-app', hostingSettings)(tree, context); + expect(deployEntryIn(tree).options).toEqual({ version: 2 }); + }); + + it('replaces the deploy entry of another tool whole', async () => { + const tree = workspaceWith({ + builder: 'angular-cli-ghpages:deploy', + options: { baseHref: '/my-app/' }, + configurations: { production: { noBuild: true } }, + }); + await setDeployTarget('my-app', hostingSettings)(tree, context); + expect(deployEntryIn(tree)).toEqual({ builder: '@angular/fire:deploy', options: { version: 2 } }); + }); + + it('stops when the workspace does not have the project', async () => { + const tree = workspaceWith(); + const run = async () => { await setDeployTarget('missing-app', hostingSettings)(tree, context); }; + await expectAsync(run()).toBeRejectedWithError(/"missing-app" is not defined/); + }); + +}); + +describe('isValidBackendId', () => { + + it('accepts lowercase letters, numbers and hyphens that start with a letter', () => { + expect(isValidBackendId('a77-ssr-apphosting')).toBeTrue(); + }); + + it('accepts an id that ends with a number', () => { + expect(isValidBackendId('store-v2')).toBeTrue(); + }); + + it('rejects an underscore and a dot', () => { + expect(isValidBackendId('my_app')).toBeFalse(); + expect(isValidBackendId('my.app')).toBeFalse(); + }); + + it('accepts 3 characters and rejects 2', () => { + expect(isValidBackendId('abc')).toBeTrue(); + expect(isValidBackendId('ab')).toBeFalse(); + }); + + it('accepts 30 characters and rejects 31', () => { + expect(isValidBackendId('a'.repeat(30))).toBeTrue(); + expect(isValidBackendId('a'.repeat(31))).toBeFalse(); + }); + + it('rejects an uppercase letter', () => { + expect(isValidBackendId('My-app')).toBeFalse(); + }); + + it('rejects an id that starts with a number', () => { + expect(isValidBackendId('3d-viewer')).toBeFalse(); + }); + + it('rejects an id that ends with a hyphen', () => { + expect(isValidBackendId('my-app-')).toBeFalse(); + }); + +}); + +describe('backendIdFromProjectName', () => { + + it('is the project name when that is already a valid id', () => { + expect(backendIdFromProjectName('a77-ssr-apphosting')).toBe('a77-ssr-apphosting'); + }); + + it('lowercases the project name', () => { + expect(backendIdFromProjectName('MyApp')).toBe('myapp'); + }); + + it('turns the scope and slash of a scoped project name into hyphens', () => { + expect(backendIdFromProjectName('@acme/store-front')).toBe('acme-store-front'); + }); + + it('cuts a long project name to 30 characters', () => { + expect(backendIdFromProjectName('customer-account-management-portal')).toBe('customer-account-management-po'); + }); + + it('drops a hyphen that the cut leaves at the end', () => { + expect(backendIdFromProjectName('customer-account-management-x-portal')).toBe('customer-account-management-x'); + }); + + it('is undefined when the project name is too short to be an id', () => { + expect(backendIdFromProjectName('ab')).toBeUndefined(); + }); + +}); diff --git a/src/schematics/setup/deployConfigs.ts b/src/schematics/setup/deployConfigs.ts new file mode 100644 index 000000000..7e3b772a5 --- /dev/null +++ b/src/schematics/setup/deployConfigs.ts @@ -0,0 +1,394 @@ +/** + * @fileoverview Reads and writes the configuration `ng deploy` needs, during `ng add`. + * + * Three files are involved, and each writer below writes one piece of one of them: + * + * - `angular.json` gets a `deploy` entry for the Angular project. It tells the Angular CLI that + * `ng deploy` runs AngularFire's deploy builder, and with which options. + * - `firebase.json` says what to upload. It is the Firebase CLI's own configuration file, which + * the builder hands the deploy to. + * - `.firebaserc` says where to upload it. It is also the Firebase CLI's, and records which + * Firebase project this workspace uses. + * + * The terms used in this file: + * + * - Firebase project (`projectId`): the user's project in the Firebase console. `.firebaserc` + * lists the one the workspace uses under `projects.default`, the "default project". + * - Hosting site (`siteId`): one `.web.app` address in a Firebase project, where + * Firebase Hosting serves uploaded static files. A project can have several. + * - Hosting target name: a name of our choosing that `firebase.json` uses to refer to a site, + * in place of the site's real id. `.firebaserc` then says which real site that name refers + * to, separately for each Firebase project. + * For example: + * - `firebase.json` says "upload these files to `my-app`" + * - `.firebaserc` says "in the project `my-project`, `my-app` is the site `my-project-prod`". + * Keeping the real id out of `firebase.json` lets the same file deploy to a different site in + * another project. AngularFire uses the Angular project's name as the target name. + * - Hosting entry: one object under the `hosting` key of `firebase.json`. It tells Firebase + * Hosting which folder of files to upload and which site to serve them on, either by the + * site's real id (`site`) or by a Hosting target name (`target`). The key holds one entry or + * a list of entries. + * - App Hosting backend (`backendId`): what Firebase App Hosting deploys to. A Hosting site only + * serves files that were built beforehand. For a backend, App Hosting takes the app's source, + * builds it in Google Cloud, and runs the Node.js server program that an Angular app with + * server-side rendering includes. That program runs on Cloud Run, in the backend's region, + * and is what renders pages on the server. + * + * `firebase.json` and `.firebaserc` are read and written on the real filesystem, not through the + * schematic's Tree, because the Firebase CLI rewrites both on disk during the same `ng add` run. + * Call these writers after the last Firebase CLI call that touches those files. + */ + +import { existsSync, readFileSync, writeFileSync } from 'fs'; +import { join } from 'path'; +import { Rule, SchematicsException } from '@angular-devkit/schematics'; +import { TargetDefinition, updateWorkspace } from '@schematics/angular/utility'; +import { BuildTargetDefinition } from '../buildOptions.js'; +import { stringifyFormatted } from '../common.js'; +import { projectsWithHostingTarget } from '../firebaserc.js'; +import { + DeployChoice, FirebaseAppHostingConfig, FirebaseHostingConfig, FirebaseJSON, FirebaseRc, +} from '../interfaces.js'; + +/** The name angular.json uses for AngularFire's deploy builder. */ +export const deployBuilder = '@angular/fire:deploy'; + +/** + * The App Hosting backend that the Angular project's existing `deploy` entry in `angular.json` + * deploys to. Undefined when the entry deploys to Firebase Hosting, belongs to another tool, or + * does not exist. + */ +export const existingAppHostingBackend = (deployTarget: BuildTargetDefinition | undefined): string | undefined => + deployTarget?.builder === deployBuilder ? deployTarget.options?.appHostingBackend : undefined; + +/** + * Where the Angular project's existing `deploy` entry in `angular.json` already deploys to, as + * the answer to `ng add`'s deploy question that would keep it. Undefined when the project has no + * `deploy` entry, or has another tool's. + */ +export const existingDeployChoice = (deployTarget: BuildTargetDefinition | undefined): DeployChoice | undefined => { + if (deployTarget?.builder !== deployBuilder) { return undefined; } + if (existingAppHostingBackend(deployTarget)) { return 'apphosting'; } + + /* Without `version: 2`, an entry with `ssr` set deploys the app's server to Cloud Functions or + * Cloud Run. Setting up Hosting or App Hosting would end that, so only `none` keeps it. */ + const { version, ssr } = deployTarget.options ?? {}; + const deploysServerWithoutVersion2 = (!version || version < 2) && !!ssr; + return deploysServerWithoutVersion2 ? 'none' : 'hosting'; +}; + +/** + * The Firebase project that `ng deploy` deploys the Angular project to today, as far as the + * project's `deploy` entry and `.firebaserc` say. `ng add` starts its project question on it, so + * that pressing Enter keeps the project. Undefined when the files point to no project. + */ +export const existingFirebaseProject = ( + deployTarget: BuildTargetDefinition | undefined, + firebaseRc: FirebaseRc, + hostingTargetName: string, +): string | undefined => { + const defaultProject = firebaseRc.projects?.default; + + // An App Hosting deploy goes to the default project, whatever Hosting targets the file still has. + if (existingAppHostingBackend(deployTarget)) { return defaultProject; } + + const hostingProjects = projectsWithHostingTarget(firebaseRc, hostingTargetName); + if (hostingProjects.length === 1) { return hostingProjects[0]; } + + // With the target name under several projects, the `firebaseProject` deploy option decides. + const firebaseProjectOption: unknown = + deployTarget?.builder === deployBuilder ? deployTarget.options?.firebaseProject : undefined; + if (typeof firebaseProjectOption === 'string' && hostingProjects.includes(firebaseProjectOption)) { + return firebaseProjectOption; + } + return defaultProject ?? hostingProjects[0]; +}; + +/** Reads a JSON file from disk, returning `whenMissing` if the file does not exist. */ +const readJsonFromDisk = (path: string, whenMissing: Content): Content => { + if (!existsSync(path)) { return whenMissing; } + try { + return JSON.parse(readFileSync(path).toString()); + } catch (error) { + throw new SchematicsException(`Error when parsing ${path}: ${error.message}`); + } +}; + +/** firebase.json allows one entry or a list of entries in several places. This always gives a list. */ +const asArray = (value: Entry | Entry[] | undefined): Entry[] => + value === undefined ? [] : Array.isArray(value) ? value : [value]; + +/** + * Tells `ng deploy` which Hosting site to deploy the app to, by adding an entry to `.firebaserc`. + * `firebase.json` refers to the site only by the name `hostingTargetName`. This entry supplies + * the real site: it says that in the Firebase project `projectId`, the name `hostingTargetName` + * refers to the site whose id is `siteId`. + */ +export const setHostingTargetInFirebaseRc = ( + projectRoot: string, + projectId: string, + hostingTargetName: string, + siteId: string, +): void => { + const path = join(projectRoot, '.firebaserc'); + const firebaseRc = readJsonFromDisk(path, {}); + const targetsByProject = firebaseRc.targets ?? {}; + + // Add the name under the chosen project, keeping whatever else that project already maps. + const projectTargets = targetsByProject[projectId] ?? {}; + const hostingTargets = projectTargets.hosting ?? {}; + hostingTargets[hostingTargetName] = [siteId]; + projectTargets.hosting = hostingTargets; + targetsByProject[projectId] = projectTargets; + + firebaseRc.targets = targetsByProject; + writeFileSync(path, stringifyFormatted(firebaseRc)); +}; + +/** + * Reads `.firebaserc` for `ng add`, which writes the file back at the end of the run. A file + * that cannot be parsed stops the run here with an error, before anything is created. + */ +export const firebaseRcForSetup = (projectRoot: string): FirebaseRc => + readJsonFromDisk(join(projectRoot, '.firebaserc'), {}); + +/** + * The value to give the `firebaseProject` deploy option, once `.firebaserc` has been written. + * That is `projectId` when the file has `hostingTargetName` under more than one Firebase project, + * because `ng deploy` cannot tell from the file which of them to use and would have to ask. + * Undefined when the file has the name under one Firebase project only. `ng deploy` then deploys + * to that project and does not need the option. + */ +export const firebaseProjectForDeployOption = ( + projectRoot: string, + projectId: string, + hostingTargetName: string, +): string | undefined => { + const firebaseRc = readJsonFromDisk(join(projectRoot, '.firebaserc'), {}); + return projectsWithHostingTarget(firebaseRc, hostingTargetName).length > 1 ? projectId : undefined; +}; + +const defaultHostingIgnore = ['firebase.json', '**/.*', '**/node_modules/**']; + +/** + * Finds the Hosting entry that setting up `hostingTargetName` rewrites, and returns its position + * in `hostingEntries`, or -1 when a new entry is added to the list instead. + * + * An existing entry is rewritten in two cases: + * + * - An entry already has the target name `hostingTargetName`. It is this Angular project's own + * entry from an earlier `ng add`, and adding another would give the same name two entries. + * - The file's only entry has no target name and no site, which is what `firebase init hosting` + * writes. The Firebase CLI deploys such an entry to the project's default site, but only while + * it is the file's single entry. In a list of entries, the CLI gives an entry with no target + * name and no site nowhere to deploy to. Adding this Angular project's entry would turn the + * file into such a list, so the existing entry is rewritten instead of being kept beside it. + */ +const indexOfHostingEntryToReplace = (hostingEntries: FirebaseHostingConfig[], hostingTargetName: string): number => { + const sameNameIndex = hostingEntries.findIndex(entry => entry.target === hostingTargetName); + if (sameNameIndex !== -1) { return sameNameIndex; } + + const hasLoneUnnamedEntry = + hostingEntries.length === 1 && !hostingEntries[0].target && !hostingEntries[0].site; + return hasLoneUnnamedEntry ? 0 : -1; +}; + +/** + * The lone Hosting entry with no target name in `firebase.json`, when setting up + * `hostingTargetName` would replace it. `ng add` asks the user before doing that, because the + * entry may be there for something other than this Angular project. Undefined when there is no + * such entry, or when an entry already has this target name. + */ +export const unnamedHostingEntryToReplace = ( + projectRoot: string, + hostingTargetName: string, +): FirebaseHostingConfig | undefined => { + const firebaseJson = readJsonFromDisk(join(projectRoot, 'firebase.json'), {}); + const hostingEntries = asArray(firebaseJson.hosting); + + const replacedIndex = indexOfHostingEntryToReplace(hostingEntries, hostingTargetName); + if (replacedIndex === -1) { return undefined; } + + const replacedEntry = hostingEntries[replacedIndex]; + return replacedEntry.target === hostingTargetName ? undefined : replacedEntry; +}; + +/** + * Writes the Hosting entry for `hostingTargetName` in `firebase.json`. The entry tells Firebase + * Hosting two things. First, to upload the files in `publicDirectory`. Second, to serve + * `clientSidePage` for any URL that matches no uploaded file, so that the Angular router can + * handle that URL in the browser. + */ +export const setHostingInFirebaseJson = ( + projectRoot: string, + hostingTargetName: string, + publicDirectory: string, + clientSidePage: string, +): void => { + const path = join(projectRoot, 'firebase.json'); + const firebaseJson = readJsonFromDisk(path, {}); + const hostingEntries = asArray(firebaseJson.hosting); + + const replacedIndex = indexOfHostingEntryToReplace(hostingEntries, hostingTargetName); + const replacedEntry = replacedIndex === -1 ? undefined : hostingEntries[replacedIndex]; + + // Start from the replaced entry, so settings the user added to it (headers, redirects) survive. + const entry: FirebaseHostingConfig = { ...replacedEntry }; + + // AngularFire before 17.1 wrote these two settings. The Firebase CLI rejects `source` beside `public`. + delete entry.source; + delete entry.frameworksBackend; + + entry.target = hostingTargetName; + entry.public = publicDirectory; + entry.ignore = replacedEntry?.ignore ?? defaultHostingIgnore; + + /* Hosting uses the first rewrite that matches a URL, so the catch-all goes last, after any + * rewrites the user already had. An earlier catch-all is dropped so there is only one. */ + const otherRewrites = (replacedEntry?.rewrites ?? []).filter(rewrite => rewrite.source !== '**'); + entry.rewrites = [...otherRewrites, { source: '**', destination: `/${clientSidePage}` }]; + + if (replacedIndex === -1) { + hostingEntries.push(entry); + } else { + hostingEntries[replacedIndex] = entry; + } + firebaseJson.hosting = hostingEntries; + writeFileSync(path, stringifyFormatted(firebaseJson)); +}; + +/** What App Hosting should not upload: files it rebuilds or installs itself, and local leftovers. */ +const appHostingIgnore = ['node_modules', '.git', '/dist', '.angular', 'firebase-debug.log']; + +/** + * Whether `firebase.json` already says that local files are deployed to the backend `backendId` + * although it is connected to a GitHub repository. The user agreed to that in an earlier + * `ng add` run, so the question is not asked again. + */ +export const alreadyDeploysLocalFiles = (projectRoot: string, backendId: string): boolean => { + const firebaseJson = readJsonFromDisk(join(projectRoot, 'firebase.json'), {}); + const entry = asArray(firebaseJson.apphosting).find(candidate => candidate.backendId === backendId); + return entry?.alwaysDeployFromSource === true; +}; + +/** + * Lists the App Hosting backend `backendId` in `firebase.json`, which is where the Firebase CLI + * looks for the backends it may deploy to. + * @param alwaysDeployFromSource true for a backend that is connected to a GitHub repository, + * to tell the Firebase CLI that uploading local files to it is intended + */ +export const setAppHostingInFirebaseJson = ( + projectRoot: string, + backendId: string, + alwaysDeployFromSource: boolean, +): void => { + const path = join(projectRoot, 'firebase.json'); + const firebaseJson = readJsonFromDisk(path, {}); + const backendEntries = asArray(firebaseJson.apphosting); + const existingIndex = backendEntries.findIndex(entry => entry.backendId === backendId); + const existingEntry = existingIndex === -1 ? undefined : backendEntries[existingIndex]; + + // Start from the backend's existing entry, so settings the user changed in it survive. + const entry: FirebaseAppHostingConfig = { ...existingEntry, backendId }; + + // The directory holding package.json. The Firebase CLI uploads the whole workspace regardless. + entry.rootDir = existingEntry?.rootDir ?? '.'; + + entry.ignore = existingEntry?.ignore ?? appHostingIgnore; + if (alwaysDeployFromSource) { entry.alwaysDeployFromSource = true; } + + if (existingIndex === -1) { + backendEntries.push(entry); + } else { + backendEntries[existingIndex] = entry; + } + + // A single backend is written as one object, and several as a list. + firebaseJson.apphosting = backendEntries.length === 1 ? backendEntries[0] : backendEntries; + writeFileSync(path, stringifyFormatted(firebaseJson)); +}; + +/** What `setDeployTarget` writes into the options of the `deploy` entry. */ +interface DeployTargetSettings { + /** The App Hosting backend to deploy to, or undefined to deploy to Firebase Hosting. */ + appHostingBackend: string | undefined; + /** + * The value for the `firebaseProject` option, which specifies the Firebase project that + * `ng deploy` deploys to. Undefined removes the option, when `.firebaserc` is enough to + * identify the project. + */ + firebaseProject: string | undefined; +} + +/** + * Writes the Angular project's `deploy` entry in `angular.json`, which makes `ng deploy` run + * AngularFire's deploy builder. + */ +export const setDeployTarget = (projectName: string, settings: DeployTargetSettings): Rule => + updateWorkspace(workspace => { + const { appHostingBackend, firebaseProject } = settings; + + const project = workspace.projects.get(projectName); + if (!project) { + throw new SchematicsException(`The Angular project "${projectName}" is not defined in this workspace`); + } + + /* An earlier AngularFire `deploy` entry is kept, with its options and its configurations, which + * the user may have added to. Another tool's entry would mean nothing to this builder, so it + * is replaced. */ + const existing = project.targets.get('deploy'); + const earlierEntry = existing?.builder === deployBuilder ? existing : undefined; + const options: NonNullable = { ...earlierEntry?.options }; + + // 2 selects the builder's current behavior. Without it the builder takes its legacy paths. + options.version = 2; + + // Present means App Hosting and absent means Hosting, so a switch to Hosting has to remove it. + if (appHostingBackend) { + options.appHostingBackend = appHostingBackend; + } else { + delete options.appHostingBackend; + } + + /* `ng deploy` stops with an error when this option differs from the site `.firebaserc` has + * for the app. A value left from an earlier setup would do that right after a run that + * picked another site, so the earlier value is never kept. */ + delete options.firebaseHostingSite; + + /* The `firebaseProject` option specifies the Firebase project that `ng deploy` deploys to. A + * value left from an earlier `ng add` run with another project would send deploys to that + * project, or stop them with an error, so the earlier value is never kept. */ + if (firebaseProject) { + options.firebaseProject = firebaseProject; + } else { + delete options.firebaseProject; + } + + // Only the options of an earlier entry are written, which leaves its configurations as they are. + if (earlierEntry) { + earlierEntry.options = options; + } else { + project.targets.set('deploy', { builder: deployBuilder, options }); + } + }); + +// Kept in step with the `appHostingBackend` pattern in deploy/schema.json. +const backendIdPattern = /^[a-z](?:[a-z0-9-]*[a-z0-9])?$/; + +/** + * Whether App Hosting accepts `backendId` as the id of a new backend. The Firebase CLI applies + * this rule only when it asks for the id itself, which it does not do for `ng add`. + */ +export const isValidBackendId = (backendId: string): boolean => + backendId.length >= 3 && backendId.length <= 30 && backendIdPattern.test(backendId); + +/** A backend id suggested from the Angular project name, or undefined when none can be derived. */ +export const backendIdFromProjectName = (projectName: string): string | undefined => { + const candidate = projectName + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^[^a-z]+/, '') + .slice(0, 30) + .replace(/-+$/, ''); + return isValidBackendId(candidate) ? candidate : undefined; +}; diff --git a/src/schematics/setup/deployPrompts.ts b/src/schematics/setup/deployPrompts.ts new file mode 100644 index 000000000..b3d4bd827 --- /dev/null +++ b/src/schematics/setup/deployPrompts.ts @@ -0,0 +1,235 @@ +/** + * @fileoverview The questions `ng add` asks to set up `ng deploy`: where to deploy, and then + * which Firebase Hosting site or which Firebase App Hosting backend. `sitePrompt` also lists the + * project's Hosting sites and creates a new one when asked. The others only ask and return the + * answers, which `appHosting.ts` and `index.ts` act on. + */ + +import inquirer from 'inquirer'; +import { shortSiteName } from '../common.js'; +import { getFirebaseTools } from '../firebaseTools.js'; +import { + AppHostingBackend, DeployChoice, FirebaseHostingSite, FirebaseProject, FirebaseToolsCommandOptions, +} from '../interfaces.js'; +import { appHostingRegions } from './appHostingRegions.js'; +import { isValidBackendId } from './deployConfigs.js'; +import { NEW_OPTION } from './prompts.js'; + +const deployPromptMessage = 'How do you want to deploy this app?'; + +/** + * Asks where `ng deploy` should deploy the app. + * @param preselected the choice the cursor starts on + */ +export const deployPrompt = async (preselected: DeployChoice): Promise => { + const choices: { name: string, value: DeployChoice }[] = [ + { name: 'Firebase App Hosting (server-side rendering)', value: 'apphosting' }, + { name: 'Firebase Hosting (static and client-rendered apps)', value: 'hosting' }, + { name: "Don't set up deployment", value: 'none' }, + ]; + const { deploy } = await inquirer.prompt<{ deploy: DeployChoice }>({ + type: 'list', + name: 'deploy', + choices, + message: deployPromptMessage, + default: preselected, + }); + return deploy; +}; + +/** + * Asks for the id of a new Hosting site. + * @param suggestedId offered as the answer that pressing Enter gives, when there is one + */ +const newSiteIdPrompt = async (message: string, suggestedId: string | undefined): Promise => { + const { siteId } = await inquirer.prompt<{ siteId: string }>({ + type: 'input', + name: 'siteId', + message, + default: suggestedId, + validate: (input: string) => !!input.trim() || 'Please provide a site id.', + }); + return siteId; +}; + +/** + * Asks which Firebase Hosting site of `project` the app should deploy to. A site is one + * `.web.app` address. The user can pick an existing site or create a new one. For a + * project with no site yet, the user is asked for the id of its first site. + * @param projectRoot the workspace root on disk + * @param existingSiteId the site the app already deploys to, if any, which the cursor starts on + * @param otherTargetBySite the project's sites that another Hosting target name already deploys + * to, each paired with that target name. They are marked in the list, and the cursor does not + * start on one, because two apps deploying to one site replace each other. + */ +export const sitePrompt = async ( + project: FirebaseProject, + projectRoot: string, + existingSiteId: string | undefined, + otherTargetBySite: Record, +): Promise => { + const firebaseTools = await getFirebaseTools(); + const { projectId } = project; + + // A function instead of one shared object. Each Firebase CLI call needs a new options object. + const newCallOptions = (): FirebaseToolsCommandOptions => ({ project: projectId, projectRoot }); + + const createSite = (siteId: string) => + firebaseTools.hosting.sites.create(siteId, { ...newCallOptions(), nonInteractive: true }); + + const { sites } = await firebaseTools.hosting.sites.list(newCallOptions()); + + // A project's first site stays its default site for good, so the user chooses its id. + if (sites.length === 0) { + const firstSiteId = await newSiteIdPrompt( + 'This Firebase project has no Hosting site yet. Please provide a unique, URL-friendly id ' + + 'for its first site (.web.app):', + projectId, + ); + return createSite(firstSiteId); + } + + const otherTargetOf = (site: FirebaseHostingSite): string | undefined => { + const siteId = shortSiteName(site); + return siteId ? otherTargetBySite[siteId] : undefined; + }; + const existingSiteChoices = sites.map(site => { + const otherTarget = otherTargetOf(site); + const usedBy = otherTarget ? ` [used by ${otherTarget}]` : ''; + return { name: `${shortSiteName(site)} (${site.defaultUrl})${usedBy}`, value: site }; + }); + + // The cursor starts on the app's own site. Without one, it starts on a site no other app uses. + const existingSite = sites.find(candidate => shortSiteName(candidate) === existingSiteId); + const defaultSite = sites.find(candidate => candidate.type === 'DEFAULT_SITE'); + const unusedSite = [defaultSite, ...sites].find(candidate => !!candidate && !otherTargetOf(candidate)); + + const { site } = await inquirer.prompt<{ site: FirebaseHostingSite | typeof NEW_OPTION }>({ + type: 'list', + name: 'site', + choices: [...existingSiteChoices, { name: '[CREATE NEW SITE]', value: NEW_OPTION }], + message: 'Please select a Hosting site:', + default: existingSite ?? unusedSite ?? NEW_OPTION, + }); + if (site !== NEW_OPTION) { return site; } + + const newSiteId = await newSiteIdPrompt( + 'Please provide a unique, URL-friendly id for the site (.web.app):', + undefined, + ); + return createSite(newSiteId); +}; + +/** The id the user gave a backend, which is the last segment of its full resource name. */ +const backendIdOf = (backend: AppHostingBackend): string => backend.name.split('/').pop() ?? backend.name; + +/** What the user answered when asked which App Hosting backend to deploy to. */ +export interface AppHostingBackendChoice { + backendId: string; + /** The region to create the backend in. Undefined when an existing backend was chosen. */ + newBackendRegion?: string; + /** + * Whether the chosen backend is connected to a GitHub repository, in which case App Hosting + * currently deploys it from that repository's commits. Always false for a new backend. + */ + linkedToGitHub: boolean; +} + +/** + * Asks the user to pick one of the project's existing backends or to create a new one. + * @param existingBackendId the backend the app already deploys to, if any, which the cursor starts on + */ +const chooseBackendPrompt = async ( + backends: AppHostingBackend[], + existingBackendId: string | undefined, +): Promise => { + const existingBackendChoices = backends.map(backend => ({ + name: backend.codebase?.repository + ? `${backendIdOf(backend)} (deploys from GitHub today)` + : backendIdOf(backend), + value: backend, + })); + const { backend } = await inquirer.prompt<{ backend: AppHostingBackend | typeof NEW_OPTION }>({ + type: 'list', + name: 'backend', + choices: [...existingBackendChoices, { name: '[CREATE NEW BACKEND]', value: NEW_OPTION }], + message: 'Please select an App Hosting backend:', + // Without a backend of the app's own, the cursor starts on creating one, not on another app's backend. + default: backends.find(candidate => backendIdOf(candidate) === existingBackendId) ?? NEW_OPTION, + }); + return backend; +}; + +/** + * Asks for the id of a new backend, refusing ids App Hosting would reject or the project already uses. + * @param takenIds the ids of the project's existing backends + * @param suggestedId offered as the default answer when it is not taken + */ +const newBackendIdPrompt = async (takenIds: string[], suggestedId: string | undefined): Promise => { + const validate = (input: string): string | true => { + if (!isValidBackendId(input)) { + return 'Use 3 to 30 lowercase letters, numbers and hyphens, starting with a letter and not ending with a hyphen.'; + } + if (takenIds.includes(input)) { + return `This project already has a backend named ${input}.`; + } + return true; + }; + const suggestionIsFree = suggestedId !== undefined && !takenIds.includes(suggestedId); + const { backendId } = await inquirer.prompt<{ backendId: string }>({ + type: 'input', + name: 'backendId', + message: 'Please provide an id for the new backend [3-30 characters: lowercase letters, numbers, hyphens]:', + default: suggestionIsFree ? suggestedId : undefined, + validate, + }); + return backendId; +}; + +/** The region the cursor starts on in the region question. */ +const preselectedRegion = 'us-east4'; + +/** Asks which region a new backend should run in: one from the known list, or one typed by hand. */ +const regionPrompt = async (): Promise => { + const knownRegionChoices = appHostingRegions.map(({ id, name }) => ({ name: `${id} (${name})`, value: id })); + const { region } = await inquirer.prompt<{ region: string }>({ + type: 'list', + name: 'region', + choices: [...knownRegionChoices, { name: '[ANOTHER REGION]', value: NEW_OPTION }], + message: 'Please select a region for the backend:', + default: preselectedRegion, + }); + if (region !== NEW_OPTION) { return region; } + + // The known list is refreshed at release time, so a region newer than the release is typed in. + const { typedRegion } = await inquirer.prompt<{ typedRegion: string }>({ + type: 'input', + name: 'typedRegion', + message: 'Please provide the region id, such as us-central1:', + validate: (input: string) => /^[a-z]+-[a-z]+\d+$/.test(input) || 'A region id looks like us-central1.', + }); + return typedRegion; +}; + +/** + * Asks which App Hosting backend the app should deploy to. + * @param backends the project's existing backends + * @param suggestedBackendId the default id offered if the user creates a new backend + * @param existingBackendId the backend the app already deploys to, if any, which the cursor starts on + */ +export const appHostingBackendPrompt = async ( + backends: AppHostingBackend[], + suggestedBackendId: string | undefined, + existingBackendId: string | undefined, +): Promise => { + // With no existing backends there is nothing to pick from, so go straight to creating one. + const selected = backends.length === 0 ? NEW_OPTION : await chooseBackendPrompt(backends, existingBackendId); + + if (selected !== NEW_OPTION) { + return { backendId: backendIdOf(selected), linkedToGitHub: !!selected.codebase?.repository }; + } + + const backendId = await newBackendIdPrompt(backends.map(backendIdOf), suggestedBackendId); + const newBackendRegion = await regionPrompt(); + return { backendId, newBackendRegion, linkedToGitHub: false }; +}; diff --git a/src/schematics/setup/index.jasmine.ts b/src/schematics/setup/index.jasmine.ts new file mode 100644 index 000000000..c61a9a6c0 --- /dev/null +++ b/src/schematics/setup/index.jasmine.ts @@ -0,0 +1,868 @@ +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { logging, normalize, virtualFs } from '@angular-devkit/core'; +import { NodeJsSyncHost } from '@angular-devkit/core/node'; +import { HostTree, SchematicContext, callRule } from '@angular-devkit/schematics'; +import fsExtra from 'fs-extra'; +import inquirer from 'inquirer'; +import { firstValueFrom } from 'rxjs'; +import { commandHost } from '../duplicatePackages/index.js'; +import { + AppHostingBackend, DeployOptions, FEATURES, FirebaseApp, FirebaseHostingSite, FirebaseProject, FirebaseTools, +} from '../interfaces.js'; +import { NEW_OPTION } from './prompts.js'; +import { ngAddSetupProject } from './index.js'; +import 'jasmine'; + +/* + * These specs run the whole `ng add` setup function. Nothing reaches Firebase: firebase-tools is + * the stand-in built by `newFirebaseTools`, and the user's answers come from `answers`. Each + * spec runs in its own temporary workspace folder, because the setup reads and writes + * firebase.json and .firebaserc on disk. + */ + +const PROJECT_ID = 'my-project'; +const account = { email: 'someone@example.com' }; + +const projectNamed = (projectId: string): FirebaseProject => ({ + projectId, + projectNumber: '1', + displayName: projectId, + name: `projects/${projectId}`, + resources: {}, + state: 'ACTIVE', +}); + +const webApp: FirebaseApp = { + name: `projects/${PROJECT_ID}/webApps/1:1:web:abc`, + displayName: 'Web app', + platform: 'WEB', + appId: '1:1:web:abc', + namespace: '', +}; + +const siteNamed = (siteId: string, type = 'USER_SITE'): FirebaseHostingSite => ({ + name: `projects/${PROJECT_ID}/sites/${siteId}`, + defaultUrl: `https://${siteId}.web.app`, + type, + appId: undefined, +}); + +/** A backend as firebase-tools lists it. `repository` makes it one that deploys from GitHub. */ +const backendNamed = (backendId: string, repository?: string): AppHostingBackend => { + const backend: AppHostingBackend = { name: `projects/${PROJECT_ID}/locations/us-central1/backends/${backendId}` }; + if (repository) { backend.codebase = { repository }; } + return backend; +}; + +/** The build options of a client-rendered app, and of an app that renders pages on a server. */ +const clientRendered = { browser: 'src/main.ts' }; +const serverRendered = { browser: 'src/main.ts', outputMode: 'server', server: 'src/main.server.ts', ssr: { entry: 'src/server.ts' } }; + +const deployQuestionChoices = [ + { name: 'Firebase App Hosting (server-side rendering)', value: 'apphosting' }, + { name: 'Firebase Hosting (static and client-rendered apps)', value: 'hosting' }, + { name: "Don't set up deployment", value: 'none' }, +]; + +/** One question as the setup hands it to inquirer. */ +interface AskedQuestion { + name: string; + type?: string; + message?: string; + default?: unknown; + choices?: unknown[]; + validate?: (input: string) => unknown; +} + +const isAskedQuestion = (value: unknown): value is AskedQuestion => + typeof value === 'object' && value !== null && 'name' in value; + +const isChoiceWithValue = (choice: unknown): choice is { name?: string, value: unknown } => + typeof choice === 'object' && choice !== null && 'value' in choice; + +/** The answers a list question offers. A choice is a plain value, or an object that carries one as `value`. */ +const valuesOffered = (question: AskedQuestion): unknown[] => + (question.choices ?? []).map(choice => isChoiceWithValue(choice) ? choice.value : choice); + +/** The label of each choice of a list question, as the user reads it. */ +const labelsOffered = (question: AskedQuestion | undefined): unknown[] => + (question?.choices ?? []).map(choice => isChoiceWithValue(choice) ? choice.name : choice); + +/** What the user answers to a question: a fixed answer, or a function of the question. */ +type Answer = unknown | ((question: AskedQuestion) => unknown); + +/** + * Accepts whatever the cursor starts on, which is what pressing Enter does. A list question with + * no starting answer starts on its first choice. + */ +const pressEnter = (question: AskedQuestion): unknown => { + if (question.default !== undefined || question.type !== 'list') { return question.default; } + return valuesOffered(question)[0]; +}; + +describe('ng add setup: deployment', () => { + /** The temporary workspace folder of the spec. */ + let root: string; + let context: SchematicContext; + + /** + * What the stand-in firebase-tools reports for the Firebase project. Specs change these before + * running. The default site is listed second, so that "the default site" and "the first site + * listed" are different sites. + */ + let projects: FirebaseProject[]; + let secondSite: FirebaseHostingSite; + let defaultSite: FirebaseHostingSite; + let sites: FirebaseHostingSite[]; + let backends: AppHostingBackend[]; + let firebaseTools: FirebaseTools; + + /** The App Hosting backend commands of the stand-in firebase-tools, kept apart so specs can spy on them. */ + let backendCommands: NonNullable['backends']; + + /** The user's answer for each question, by the question's name. A question not listed gets Enter. */ + let answers: Record; + + /** Every question asked, in order, and every line logged. */ + let asked: AskedQuestion[]; + let logged: { level: string, message: string }[]; + + const newFirebaseTools = (): FirebaseTools => { + const login = Object.assign(() => Promise.resolve(account), { + list: () => Promise.resolve([{ user: account }]), + add: () => Promise.resolve(account), + use: () => Promise.resolve(account.email), + }); + return { + cli: { version: () => '15.28.1' }, + login, + projects: { + list: () => Promise.resolve(projects), + create: () => Promise.reject(new Error('not expected in these specs')), + }, + apps: { + list: () => Promise.resolve([webApp]), + create: () => Promise.reject(new Error('not expected in these specs')), + sdkconfig: () => Promise.resolve({ fileName: '_', fileContents: '', sdkConfig: {} }), + }, + hosting: { + sites: { + list: () => Promise.resolve({ sites }), + create: (siteId: string) => Promise.resolve(siteNamed(siteId)), + }, + }, + apphosting: { backends: backendCommands }, + init: () => Promise.resolve(), + deploy: () => Promise.resolve(), + use: () => Promise.resolve(), + serve: () => Promise.resolve(), + logger: { add: () => undefined, logger: { add: () => undefined } }, + }; + }; + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'angularfire-test-')); + + projects = [projectNamed(PROJECT_ID), projectNamed('other-project')]; + secondSite = siteNamed('second-site'); + defaultSite = siteNamed(PROJECT_ID, 'DEFAULT_SITE'); + sites = [secondSite, defaultSite]; + backends = []; + backendCommands = { + list: () => Promise.resolve(backends), + create: () => Promise.resolve({}), + get: () => Promise.resolve(undefined), + }; + firebaseTools = newFirebaseTools(); + globalThis.firebaseTools = firebaseTools; + + asked = []; + answers = { features: [], user: account, projectId: PROJECT_ID, appId: webApp.appId }; + const answerAsTheUser = (question: unknown) => { + if (!isAskedQuestion(question)) { throw new Error('The setup asked something that is not one question'); } + asked.push(question); + const answer = question.name in answers ? answers[question.name] : pressEnter; + const given: unknown = typeof answer === 'function' ? answer(question) : answer; + + // A user can only pick what a list shows, so an answer that is not among the choices fails the spec. + if (question.type === 'list' && !valuesOffered(question).includes(given)) { + throw new Error(`The answer to the question "${question.name}" is not one of its choices`); + } + return Promise.resolve({ [question.name]: given }); + }; + + // The cast is for inquirer's second, callback-taking form of `prompt`, which the setup never uses. + spyOn(inquirer, 'prompt').and.callFake(answerAsTheUser as unknown as typeof inquirer.prompt); + + // The duplicate-package check would start the package manager in the temporary folder. + spyOn(commandHost, 'run').and.returnValue({ stdout: '', status: 0, failure: undefined }); + + logged = []; + const logger = new logging.Logger('test'); + logger.subscribe(entry => { logged.push({ level: entry.level, message: entry.message }); }); + context = { logger } as unknown as SchematicContext; + }); + + afterEach(() => { + globalThis.firebaseTools = undefined; + fsExtra.removeSync(root); + }); + + const writeInWorkspace = (fileName: string, content: unknown) => + writeFileSync(join(root, fileName), JSON.stringify(content)); + + const readFromWorkspace = (fileName: string) => JSON.parse(readFileSync(join(root, fileName)).toString()); + + /** Writes angular.json with the application `app`, and `deployEntry` as its deploy entry when given. */ + const writeAngularJson = ( + buildOptions: Record, + deployEntry?: Record, + otherProjects: Record = {}, + ) => { + const architect: Record = { build: { builder: '@angular/build:application', options: buildOptions } }; + if (deployEntry) { architect.deploy = deployEntry; } + const app = { root: '', projectType: 'application', architect }; + writeInWorkspace('angular.json', { version: 1, projects: { app, ...otherProjects } }); + }; + + const newTree = () => new HostTree(new virtualFs.ScopedHost(new NodeJsSyncHost(), normalize(root))); + + /** Runs the setup for the application `app` and returns the tree, which holds the new angular.json. */ + const runSetup = async (options: DeployOptions = { project: 'app' }): Promise => { + const tree = newTree(); + const rule = await ngAddSetupProject(options)(tree, context); + if (rule) { await firstValueFrom(callRule(rule, tree, context)); } + return tree; + }; + + /** + * Runs the setup with a feature selected, up to the point where it hands back its edits to the + * app's own files, and does not make those edits. They need the app's source files, which the + * temporary workspace does not have. + */ + const runSetupWithAFeature = async (options: DeployOptions = { project: 'app' }): Promise => { + answers.features = [FEATURES.Authentication]; + await ngAddSetupProject(options)(newTree(), context); + }; + + const deployEntryIn = (tree: HostTree) => JSON.parse(tree.readText('/angular.json')).projects.app.architect.deploy; + + /** The question with the name `name`, as it was asked. */ + const question = (name: string): AskedQuestion | undefined => asked.find(candidate => candidate.name === name); + + const askedNames = () => asked.map(candidate => candidate.name); + + /** Everything logged at `level`, as one text. */ + const logAt = (level: string) => logged.filter(entry => entry.level === level).map(entry => entry.message).join('\n'); + + const defaultHostingEntry = (clientSidePage: string) => ({ + target: 'app', + public: 'dist/app/browser', + ignore: ['firebase.json', '**/.*', '**/node_modules/**'], + rewrites: [{ source: '**', destination: `/${clientSidePage}` }], + }); + + const angularFireDeployEntry = (options: Record) => ({ builder: '@angular/fire:deploy', options }); + + describe('with no deployment', () => { + + it('and no features, says there is nothing to do, asks nothing about Firebase and writes nothing', async () => { + writeAngularJson(clientRendered); + const listProjects = spyOn(firebaseTools.projects, 'list').and.callThrough(); + + const tree = await runSetup({ project: 'app', deploy: 'none' }); + + expect(askedNames()).toEqual(['features']); + expect(logAt('warn')).toContain('so there is nothing to do'); + expect(listProjects).not.toHaveBeenCalled(); + expect(existsSync(join(root, 'firebase.json'))).toBeFalse(); + expect(existsSync(join(root, '.firebaserc'))).toBeFalse(); + expect(deployEntryIn(tree)).toBeUndefined(); + }); + + it('and a feature, sets the feature up: asks for the project and the web app, and nothing about deployment', async () => { + writeAngularJson(serverRendered); + answers.deploy = 'none'; + const listBackends = spyOn(backendCommands, 'list').and.callThrough(); + const listSites = spyOn(firebaseTools.hosting.sites, 'list').and.callThrough(); + + await runSetupWithAFeature(); + + expect(askedNames()).toEqual(['features', 'deploy', 'user', 'projectId', 'appId']); + expect(logAt('warn')).not.toContain('so there is nothing to do'); + expect(logAt('info')).not.toContain('No features were selected'); + expect(listBackends).not.toHaveBeenCalled(); + expect(listSites).not.toHaveBeenCalled(); + expect(readFromWorkspace('firebase.json')).toEqual({}); + expect(readFromWorkspace('.firebaserc')).toEqual({ projects: { default: PROJECT_ID } }); + }); + + it('does not ask about the deploy entry of another tool', async () => { + const otherEntry = { builder: 'angular-cli-ghpages:deploy', options: { baseHref: '/app/' } }; + writeAngularJson(clientRendered, otherEntry); + answers.deploy = 'none'; + await runSetup(); + expect(askedNames()).toEqual(['features', 'deploy']); + }); + + }); + + describe('the deploy question', () => { + + it('offers App Hosting, Hosting and no deployment, each under its own label', async () => { + writeAngularJson(clientRendered); + await runSetup(); + expect(question('deploy')?.choices).toEqual(deployQuestionChoices); + }); + + it('starts on Firebase Hosting for a client-rendered app with no deploy setup', async () => { + writeAngularJson(clientRendered); + await runSetup(); + expect(question('deploy')?.default).toBe('hosting'); + }); + + it('starts on Firebase App Hosting for a server-rendered app with no deploy setup', async () => { + writeAngularJson(serverRendered); + await runSetup(); + expect(question('deploy')?.default).toBe('apphosting'); + }); + + it('starts on Firebase App Hosting for an app that renders on a server only in its production configuration', async () => { + const build = { + builder: '@angular/build:application', + options: clientRendered, + configurations: { production: serverRendered }, + }; + const app = { root: '', projectType: 'application', architect: { build } }; + writeInWorkspace('angular.json', { version: 1, projects: { app } }); + answers.deploy = 'hosting'; + + await runSetup(); + + expect(question('deploy')?.default).toBe('apphosting'); + expect(logAt('warn')).toContain('which Firebase Hosting cannot run'); + }); + + it('starts on what the project already deploys with, whatever kind of app it is', async () => { + writeAngularJson(serverRendered, angularFireDeployEntry({ version: 2 })); + await runSetup(); + expect(question('deploy')?.default).toBe('hosting'); + }); + + it('is not asked when the deploy option is given', async () => { + writeAngularJson(serverRendered); + const tree = await runSetup({ project: 'app', deploy: 'hosting' }); + expect(question('deploy')).toBeUndefined(); + expect(deployEntryIn(tree).options).toEqual({ version: 2 }); + }); + + it('asks before replacing the deploy entry of another tool, and keeps it on a no', async () => { + const otherEntry = { builder: 'angular-cli-ghpages:deploy', options: { baseHref: '/app/' } }; + writeAngularJson(clientRendered, otherEntry); + answers.deploy = 'hosting'; + answers.confirmed = false; + + const tree = await runSetup(); + + expect(question('confirmed')?.message).toContain('already deploys with angular-cli-ghpages:deploy'); + expect(logAt('info')).toContain('Keeping the existing deploy target. Deployment was not set up.'); + expect(deployEntryIn(tree)).toEqual(otherEntry); + expect(existsSync(join(root, 'firebase.json'))).toBeFalse(); + }); + + it('replaces the deploy entry of another tool on a yes', async () => { + writeAngularJson(clientRendered, { builder: 'angular-cli-ghpages:deploy', options: { baseHref: '/app/' } }); + answers.deploy = 'hosting'; + answers.confirmed = true; + + const tree = await runSetup(); + + expect(deployEntryIn(tree)).toEqual(angularFireDeployEntry({ version: 2 })); + }); + + }); + + describe('Firebase Hosting', () => { + + it('sets up a client-rendered app: the three files, and no question about a web app', async () => { + writeAngularJson(clientRendered); + const listSites = spyOn(firebaseTools.hosting.sites, 'list').and.callThrough(); + + const tree = await runSetup(); + + expect(askedNames()).toEqual(['features', 'deploy', 'user', 'projectId', 'site']); + expect(listSites).toHaveBeenCalledOnceWith(jasmine.objectContaining({ project: PROJECT_ID })); + expect(readFromWorkspace('.firebaserc')).toEqual({ + projects: { default: PROJECT_ID }, + targets: { [PROJECT_ID]: { hosting: { app: [PROJECT_ID] } } }, + }); + expect(readFromWorkspace('firebase.json')).toEqual({ hosting: [defaultHostingEntry('index.html')] }); + expect(deployEntryIn(tree)).toEqual(angularFireDeployEntry({ version: 2 })); + expect(logAt('info')).toContain('Deployment is set up. Run ng deploy to deploy your app.'); + expect(logAt('info')).toContain('No features were selected, so only deployment is being set up.'); + }); + + it('prints none of the notes meant for other setups', async () => { + writeAngularJson(clientRendered); + + await runSetup(); + + expect(logAt('warn')).not.toContain('which Firebase Hosting cannot run'); + expect(logAt('warn')).not.toContain('built once per locale'); + expect(logAt('warn')).not.toContain('ng deploy still deploys this app'); + expect(logAt('info')).not.toContain('Firebase App Hosting needs'); + }); + + it('asks for the web app as well when a feature is selected', async () => { + writeAngularJson(clientRendered); + const sdkConfig = spyOn(firebaseTools.apps, 'sdkconfig').and.callThrough(); + + await runSetupWithAFeature(); + + expect(askedNames()).toEqual(['features', 'deploy', 'user', 'projectId', 'appId', 'site']); + expect(sdkConfig).toHaveBeenCalledOnceWith('web', webApp.appId, jasmine.anything()); + expect(logAt('info')).not.toContain('No features were selected'); + }); + + it('works with a firebase-tools that is too old for App Hosting', async () => { + writeAngularJson(clientRendered); + firebaseTools.cli = { version: () => '15.8.0' }; + const tree = await runSetup(); + expect(deployEntryIn(tree)).toEqual(angularFireDeployEntry({ version: 2 })); + }); + + it('warns that Hosting cannot run a server, and serves the client-side page of a server-rendered build', async () => { + writeAngularJson(serverRendered); + answers.deploy = 'hosting'; + + await runSetup(); + + expect(logAt('warn')).toContain('which Firebase Hosting cannot run'); + expect(readFromWorkspace('firebase.json')).toEqual({ hosting: [defaultHostingEntry('index.csr.html')] }); + }); + + it('warns about a build that is localized', async () => { + writeAngularJson({ ...clientRendered, localize: true }); + await runSetup(); + expect(logAt('warn')).toContain('built once per locale'); + }); + + it('starts the site question on the default site of the project, and offers creating one', async () => { + writeAngularJson(clientRendered); + + await runSetup(); + + expect(question('site')?.default).toBe(defaultSite); + expect(labelsOffered(question('site'))).toEqual([ + 'second-site (https://second-site.web.app)', + `${PROJECT_ID} (https://${PROJECT_ID}.web.app)`, + '[CREATE NEW SITE]', + ]); + }); + + it('starts the site question on the site the app already deploys to, without marking it as used', async () => { + writeAngularJson(clientRendered, angularFireDeployEntry({ version: 2 })); + writeInWorkspace('.firebaserc', { + projects: { default: PROJECT_ID }, + targets: { [PROJECT_ID]: { hosting: { app: ['second-site'] } } }, + }); + + await runSetup(); + + expect(question('site')?.default).toBe(secondSite); + expect(labelsOffered(question('site'))[0]).toBe('second-site (https://second-site.web.app)'); + }); + + it('starts the project and site questions on what the app deploys to, when that is not the default project', async () => { + writeAngularJson(clientRendered, angularFireDeployEntry({ version: 2 })); + writeInWorkspace('.firebaserc', { + projects: { default: PROJECT_ID }, + targets: { 'other-project': { hosting: { app: ['second-site'] } } }, + }); + answers.projectId = pressEnter; + + await runSetup(); + + expect(question('projectId')?.default).toBe('other-project'); + expect(question('site')?.default).toBe(secondSite); + }); + + it('marks a site that another target name deploys to, and does not start on it', async () => { + writeAngularJson(clientRendered); + writeInWorkspace('.firebaserc', { + projects: { default: PROJECT_ID }, + targets: { [PROJECT_ID]: { hosting: { admin: [PROJECT_ID] } } }, + }); + + await runSetup(); + + expect(labelsOffered(question('site'))[1]).toBe(`${PROJECT_ID} (https://${PROJECT_ID}.web.app) [used by admin]`); + expect(question('site')?.default).toBe(secondSite); + }); + + it('starts on creating a site when another target name deploys to every site of the project', async () => { + writeAngularJson(clientRendered); + sites = [defaultSite]; + writeInWorkspace('.firebaserc', { + projects: { default: PROJECT_ID }, + targets: { [PROJECT_ID]: { hosting: { admin: [PROJECT_ID] } } }, + }); + answers.siteId = 'app-site'; + + await runSetup(); + + expect(question('site')?.default).toBe(NEW_OPTION); + expect(readFromWorkspace('.firebaserc').targets[PROJECT_ID].hosting).toEqual({ admin: [PROJECT_ID], app: ['app-site'] }); + }); + + it('creates the site the user asks for and deploys to it', async () => { + writeAngularJson(clientRendered); + answers.site = NEW_OPTION; + answers.siteId = 'brand-new-site'; + const createSite = spyOn(firebaseTools.hosting.sites, 'create').and.callThrough(); + + await runSetup(); + + expect(createSite).toHaveBeenCalledOnceWith('brand-new-site', jasmine.objectContaining({ project: PROJECT_ID })); + expect(readFromWorkspace('.firebaserc').targets[PROJECT_ID].hosting.app).toEqual(['brand-new-site']); + expect(question('siteId')?.validate?.(' ')).toBe('Please provide a site id.'); + expect(question('siteId')?.validate?.('brand-new-site')).toBeTrue(); + }); + + it('asks for the id of the first site of a project that has none, suggesting the project id', async () => { + writeAngularJson(clientRendered); + sites = []; + answers.siteId = 'first-site'; + const createSite = spyOn(firebaseTools.hosting.sites, 'create').and.callThrough(); + + await runSetup(); + + expect(question('site')).toBeUndefined(); + expect(question('siteId')?.default).toBe(PROJECT_ID); + expect(createSite).toHaveBeenCalledOnceWith('first-site', jasmine.objectContaining({ project: PROJECT_ID })); + }); + + it('changes nothing on a second run where the user presses Enter at every question', async () => { + writeAngularJson(clientRendered); + answers.site = secondSite; + const firstTree = await runSetup(); + const firebaseJsonAfterFirstRun = readFromWorkspace('firebase.json'); + const firebaseRcAfterFirstRun = readFromWorkspace('.firebaserc'); + writeAngularJson(clientRendered, deployEntryIn(firstTree)); + + delete answers.site; + answers.projectId = pressEnter; + asked = []; + const secondTree = await runSetup(); + + expect(question('deploy')?.default).toBe('hosting'); + expect(question('projectId')?.default).toBe(PROJECT_ID); + expect(question('site')?.default).toBe(secondSite); + expect(readFromWorkspace('firebase.json')).toEqual(firebaseJsonAfterFirstRun); + expect(readFromWorkspace('.firebaserc')).toEqual(firebaseRcAfterFirstRun); + expect(deployEntryIn(secondTree)).toEqual(deployEntryIn(firstTree)); + }); + + it('writes the firebaseProject option when the target name ends up under two Firebase projects', async () => { + writeAngularJson(clientRendered); + writeInWorkspace('.firebaserc', { + projects: { default: 'other-project' }, + targets: { 'other-project': { hosting: { app: ['other-site'] } } }, + }); + + const tree = await runSetup(); + + expect(deployEntryIn(tree).options).toEqual({ version: 2, firebaseProject: PROJECT_ID }); + expect(readFromWorkspace('.firebaserc').targets['other-project']).toEqual({ hosting: { app: ['other-site'] } }); + }); + + describe('with a lone Hosting entry that has no target name in firebase.json', () => { + const unnamedEntry = { public: 'public', headers: [{ source: '**', headers: [] }] }; + + beforeEach(() => { + writeAngularJson(clientRendered); + writeInWorkspace('firebase.json', { hosting: unnamedEntry }); + }); + + it('asks right after the deploy question whether to use that entry', async () => { + answers.confirmed = true; + await runSetup(); + expect(askedNames().slice(0, 3)).toEqual(['features', 'deploy', 'confirmed']); + expect(question('confirmed')?.message).toContain('has a Hosting entry with no target name (it serves "public")'); + }); + + it('turns that entry into the entry of the app on a yes', async () => { + answers.confirmed = true; + await runSetup(); + const hostingEntries = readFromWorkspace('firebase.json').hosting; + expect(hostingEntries.length).toBe(1); + expect(hostingEntries[0]).toEqual(jasmine.objectContaining({ + target: 'app', + public: 'dist/app/browser', + headers: unnamedEntry.headers, + })); + }); + + it('leaves firebase.json alone, sets up no deployment and says how to go on, on a no', async () => { + answers.confirmed = false; + const tree = await runSetup(); + expect(readFromWorkspace('firebase.json')).toEqual({ hosting: unnamedEntry }); + expect(deployEntryIn(tree)).toBeUndefined(); + expect(logAt('info')).toContain('Deployment was not set up.'); + expect(logAt('info')).toContain('firebase target:apply hosting '); + expect(question('site')).toBeUndefined(); + }); + + it('does not ask about that entry when the user chooses App Hosting', async () => { + writeAngularJson(serverRendered); + const tree = await runSetup(); + expect(question('confirmed')).toBeUndefined(); + expect(deployEntryIn(tree).options.appHostingBackend).toBe('app'); + expect(readFromWorkspace('firebase.json').hosting).toEqual(unnamedEntry); + }); + + }); + + }); + + describe('Firebase App Hosting', () => { + + beforeEach(() => { + writeAngularJson(serverRendered); + }); + + it('sets up a server-rendered app: creates the backend the user describes and writes the three files', async () => { + answers.backendId = 'web-frontend'; + const listBackends = spyOn(backendCommands, 'list').and.callThrough(); + const createBackend = spyOn(backendCommands, 'create').and.callThrough(); + const callOptions = { project: PROJECT_ID, projectRoot: root, account: account.email, nonInteractive: true }; + + const tree = await runSetup(); + + expect(askedNames()).toEqual(['features', 'deploy', 'user', 'projectId', 'appId', 'backendId', 'region']); + expect(listBackends).toHaveBeenCalledOnceWith(callOptions); + expect(createBackend).toHaveBeenCalledOnceWith({ + ...callOptions, + backend: 'web-frontend', + primaryRegion: 'us-east4', + rootDir: '.', + app: webApp.appId, + }); + expect(readFromWorkspace('firebase.json')).toEqual({ + apphosting: { + backendId: 'web-frontend', + rootDir: '.', + ignore: ['node_modules', '.git', '/dist', '.angular', 'firebase-debug.log'], + }, + }); + expect(readFromWorkspace('.firebaserc')).toEqual({ projects: { default: PROJECT_ID } }); + expect(deployEntryIn(tree)).toEqual(angularFireDeployEntry({ version: 2, appHostingBackend: 'web-frontend' })); + expect(logAt('warn')).not.toContain('ng deploy still deploys this app'); + }); + + it('says what App Hosting needs of the chosen Firebase project', async () => { + await runSetup(); + expect(logAt('info')).toContain('Firebase App Hosting needs the Blaze pricing plan'); + expect(logAt('info')).toContain(`https://console.firebase.google.com/project/${PROJECT_ID}/usage/details`); + }); + + it('suggests the project name as the id of a new backend and us-east4 as its region', async () => { + await runSetup(); + expect(question('backendId')?.default).toBe('app'); + expect(question('region')?.default).toBe('us-east4'); + }); + + it('refuses a backend id the project already uses, and one App Hosting would reject', async () => { + backends = [backendNamed('taken-backend')]; + answers.backend = NEW_OPTION; + + await runSetup(); + + const validate = question('backendId')?.validate; + expect(validate?.('taken-backend')).toBe('This project already has a backend named taken-backend.'); + expect(validate?.('My_Backend')).toMatch(/^Use 3 to 30 lowercase letters, numbers and hyphens/); + expect(validate?.('free-backend')).toBeTrue(); + }); + + it('creates the backend in a region the user types', async () => { + answers.region = NEW_OPTION; + answers.typedRegion = 'europe-west9'; + const createBackend = spyOn(backendCommands, 'create').and.callThrough(); + + await runSetup(); + + expect(createBackend.calls.mostRecent().args[0].primaryRegion).toBe('europe-west9'); + expect(question('typedRegion')?.validate?.('europe-west9')).toBeTrue(); + expect(question('typedRegion')?.validate?.('Iowa')).toBe('A region id looks like us-central1.'); + }); + + it('starts the backend question on creating one, not on a backend of another app', async () => { + backends = [backendNamed('another-app')]; + await runSetup(); + expect(question('backend')?.default).toBe(NEW_OPTION); + expect(labelsOffered(question('backend'))).toEqual(['another-app', '[CREATE NEW BACKEND]']); + }); + + it('starts the backend question on the backend the app already deploys to, and sets it up again without creating one', async () => { + writeAngularJson(serverRendered, angularFireDeployEntry({ version: 2, appHostingBackend: 'mine' })); + backends = [backendNamed('another-app'), backendNamed('mine')]; + const createBackend = spyOn(backendCommands, 'create').and.callThrough(); + + const tree = await runSetup(); + + expect(question('deploy')?.default).toBe('apphosting'); + expect(question('backend')?.default).toBe(backends[1]); + expect(question('confirmed')).toBeUndefined(); + expect(createBackend).not.toHaveBeenCalled(); + expect(readFromWorkspace('firebase.json').apphosting).toEqual(jasmine.objectContaining({ backendId: 'mine' })); + expect(readFromWorkspace('firebase.json').apphosting.alwaysDeployFromSource).toBeUndefined(); + expect(deployEntryIn(tree).options).toEqual({ version: 2, appHostingBackend: 'mine' }); + expect(logAt('info')).toContain('Deployment is set up. Run ng deploy to deploy your app.'); + }); + + it('writes the newly chosen Firebase project as the default when an App Hosting app is set up again', async () => { + writeAngularJson(serverRendered, angularFireDeployEntry({ version: 2, appHostingBackend: 'mine' })); + writeInWorkspace('.firebaserc', { projects: { default: 'other-project' } }); + backends = [backendNamed('mine')]; + + await runSetup(); + + expect(readFromWorkspace('.firebaserc').projects.default).toBe(PROJECT_ID); + expect(logAt('warn')).not.toContain('ng deploy still deploys this app'); + }); + + it('stops before any question about Firebase when firebase-tools is too old for App Hosting', async () => { + firebaseTools.cli = { version: () => '15.8.0' }; + const listProjects = spyOn(firebaseTools.projects, 'list').and.callThrough(); + + await expectAsync(runSetup()).toBeRejectedWithError(/Setting up App Hosting needs firebase-tools 15\.9\.0 or newer/); + + expect(askedNames()).toEqual(['features', 'deploy']); + expect(listProjects).not.toHaveBeenCalled(); + expect(existsSync(join(root, 'firebase.json'))).toBeFalse(); + }); + + it('says to check the build script when the workspace has a second application', async () => { + const admin = { root: 'projects/admin', projectType: 'application', architect: {} }; + writeAngularJson(serverRendered, undefined, { admin }); + await runSetup(); + expect(logAt('warn')).toContain('make sure the build script in package.json builds "app"'); + }); + + it('does not say that for a workspace whose other project is a library', async () => { + const library = { root: 'projects/ui', projectType: 'library', architect: {} }; + writeAngularJson(serverRendered, undefined, { library }); + await runSetup(); + expect(logAt('warn')).not.toContain('make sure the build script'); + }); + + describe('with a backend that deploys from GitHub', () => { + + beforeEach(() => { + backends = [backendNamed('from-github', 'my-org-my-repo')]; + answers.backend = backends[0]; + }); + + it('says so in the list of backends', async () => { + await runSetup(); + expect(labelsOffered(question('backend'))).toEqual(['from-github (deploys from GitHub today)', '[CREATE NEW BACKEND]']); + }); + + it('asks before deploying local files to it, and records a yes for firebase-tools', async () => { + answers.confirmed = true; + const tree = await runSetup(); + expect(question('confirmed')?.message).toContain('from-github deploys from a GitHub repository today'); + expect(readFromWorkspace('firebase.json').apphosting.alwaysDeployFromSource).toBeTrue(); + expect(deployEntryIn(tree).options.appHostingBackend).toBe('from-github'); + }); + + it('sets up no deployment on a no', async () => { + answers.confirmed = false; + const tree = await runSetup(); + expect(deployEntryIn(tree)).toBeUndefined(); + expect(readFromWorkspace('firebase.json').apphosting).toBeUndefined(); + expect(logAt('info')).toContain('Deployment was not set up.'); + }); + + it('does not ask again on a later run, once firebase.json records the yes', async () => { + writeInWorkspace('firebase.json', { apphosting: { backendId: 'from-github', alwaysDeployFromSource: true } }); + const tree = await runSetup(); + expect(question('confirmed')).toBeUndefined(); + expect(deployEntryIn(tree).options.appHostingBackend).toBe('from-github'); + }); + + }); + + describe('when the list of backends cannot be read', () => { + + beforeEach(() => { + spyOn(backendCommands, 'list').and.rejectWith(new Error('billing is not enabled')); + }); + + it('says why deployment was not set up, and what App Hosting needs', async () => { + await runSetup(); + expect(logAt('warn')).toContain(`Deployment was not set up: Could not list App Hosting backends for project ${PROJECT_ID}: billing is not enabled`); + expect(logAt('warn')).toContain('Firebase App Hosting needs the Blaze pricing plan'); + expect(logAt('warn')).toContain('Run ng add @angular/fire again to set up deployment.'); + }); + + it('finishes the run with the chosen project written as default and no deploy entry', async () => { + writeInWorkspace('.firebaserc', { projects: { default: 'other-project' } }); + const tree = await runSetup(); + expect(readFromWorkspace('.firebaserc')).toEqual({ projects: { default: PROJECT_ID } }); + expect(deployEntryIn(tree)).toBeUndefined(); + expect(logAt('warn')).not.toContain('ng deploy still deploys this app'); + }); + + }); + + describe('when the backend cannot be created', () => { + + beforeEach(() => { + spyOn(backendCommands, 'create').and.rejectWith(new Error('billing is not enabled')); + }); + + it('says why deployment was not set up, and what App Hosting needs', async () => { + await runSetup(); + expect(logAt('warn')).toContain(`Deployment was not set up: Could not create the App Hosting backend app for project ${PROJECT_ID}: billing is not enabled`); + expect(logAt('warn')).toContain('Firebase App Hosting needs the Blaze pricing plan'); + }); + + it('writes no deploy setup for the backend that does not exist', async () => { + const tree = await runSetup(); + expect(deployEntryIn(tree)).toBeUndefined(); + expect(readFromWorkspace('firebase.json')).toEqual({}); + expect(logAt('info')).not.toContain('Deployment is set up.'); + }); + + }); + + describe('when an app that deploys to App Hosting gets no deployment set up in this run', () => { + + beforeEach(() => { + writeAngularJson(serverRendered, angularFireDeployEntry({ version: 2, appHostingBackend: 'from-github' })); + writeInWorkspace('.firebaserc', { projects: { default: 'other-project' } }); + backends = [backendNamed('from-github', 'my-org-my-repo')]; + answers.confirmed = false; + }); + + it('keeps the default project the app deploys to, and says so when another project was chosen', async () => { + await runSetup(); + expect(readFromWorkspace('.firebaserc').projects.default).toBe('other-project'); + expect(logAt('warn')).toContain('ng deploy still deploys this app to the Firebase project other-project'); + }); + + it('says nothing about it when the same project was chosen', async () => { + answers.projectId = 'other-project'; + await runSetup(); + expect(readFromWorkspace('.firebaserc').projects.default).toBe('other-project'); + expect(logAt('warn')).not.toContain('ng deploy still deploys this app'); + }); + + }); + + }); + +}); diff --git a/src/schematics/setup/index.ts b/src/schematics/setup/index.ts index 03db70fd3..c0795b25c 100644 --- a/src/schematics/setup/index.ts +++ b/src/schematics/setup/index.ts @@ -1,28 +1,52 @@ import { readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; import { asWindowsPath, normalize } from '@angular-devkit/core'; -import { SchematicContext, Tree, chain } from '@angular-devkit/schematics'; +import { Rule, SchematicContext, Tree, chain } from '@angular-devkit/schematics'; import { addRootProvider } from '@schematics/angular/utility'; -import { getActiveAccount, getFirebaseTools } from '../firebaseTools'; +import { + BuildTargetDefinition, browserOutputDirectory, clientSidePage, localizedBuildHostingWarning, + productionBuildOptions, rendersOnServer, +} from '../buildOptions.js'; +import { shortSiteName } from '../common.js'; +import { getActiveAccount, getFirebaseTools } from '../firebaseTools.js'; +import { hostingSiteFromRc, hostingSitesOfOtherTargets } from '../firebaserc.js'; import { DataConnectConnectorConfig, - DeployOptions, FEATURES, FirebaseApp, FirebaseJSON, FirebaseProject, -} from '../interfaces'; + DeployChoice, DeployOptions, FEATURES, FirebaseApp, FirebaseJSON, FirebaseProject, FirebaseTools, + WorkspaceProject, +} from '../interfaces.js'; import { addIgnoreFiles, featureToRules, - getFirebaseProjectNameFromHost, getProject, + getWorkspace, parseDataConnectConfig, setupTanstackDependencies, -} from '../utils'; -import { warnAboutDuplicateFirebase } from './duplicateWarning'; +} from '../utils.js'; +import { appHostingRequirements, assertAppHostingSetupSupported, selectAppHostingBackend } from './appHosting.js'; +import { + deployBuilder, + existingAppHostingBackend, + existingDeployChoice, + existingFirebaseProject, + firebaseProjectForDeployOption, + firebaseRcForSetup, + setAppHostingInFirebaseJson, + setDeployTarget, + setHostingInFirebaseJson, + setHostingTargetInFirebaseRc, + unnamedHostingEntryToReplace, +} from './deployConfigs.js'; +import { deployPrompt, sitePrompt } from './deployPrompts.js'; +import { warnAboutDuplicateFirebase } from './duplicateWarning.js'; import { addFirestoreToFirebaseJson, createFirestoreStarterFiles, setDefaultProjectInFirebaseRc, -} from './firebaseConfigs'; -import { appPrompt, featuresPrompt, featuresPromptMessage, projectPrompt, userPrompt } from './prompts'; +} from './firebaseConfigs.js'; +import { + appPrompt, confirmPrompt, featuresPrompt, featuresPromptMessage, projectPrompt, userPrompt, +} from './prompts.js'; // FirebaseOptions keys — apps.sdkconfig responses include management-API extras that initializeApp() rejects. const firebaseOptionsKeys = [ @@ -58,6 +82,209 @@ export const setupProject = } }; +/** + * `firebase.json` can hold a lone Hosting entry with no target name, which is what + * `firebase init hosting` writes. Setting up Hosting would turn that entry into this Angular + * project's entry, and it may be there for something else, so this asks the user first. + * @returns false when the user wants that entry left alone, after telling them how to go on. + * True when they agree, and when there is no such entry to ask about. + */ +const mayReplaceUnnamedHostingEntry = async ( + projectRoot: string, + angularProjectName: string, + context: SchematicContext, +): Promise => { + const unnamedEntry = unnamedHostingEntryToReplace(projectRoot, angularProjectName); + if (!unnamedEntry) { return true; } + + const servedDirectory = unnamedEntry.public ? ` (it serves "${unnamedEntry.public}")` : ''; + const replace = await confirmPrompt( + `firebase.json has a Hosting entry with no target name${servedDirectory}. ` + + `Use that entry for the app "${angularProjectName}"? Its settings will be changed to serve this app.`, + ); + if (replace) { return true; } + + context.logger.info( + 'Deployment was not set up. To keep that Hosting entry for something else, give it a "target" ' + + 'name in firebase.json and link that name to its site with "firebase target:apply hosting ' + + ' ". Then run ng add @angular/fire again and choose a different site for this app.' + ); + return false; +}; + +/** + * Decides where `ng deploy` should deploy the app: the `--deploy` option when it was given, + * otherwise the user's answer. The cursor starts on what the project already deploys with, so + * that pressing Enter changes nothing. For a project with no deploy setup yet, it starts on App + * Hosting when the app uses server-side rendering and on Hosting when it does not. + * + * Returns `none` when the user declines one of the two questions that follow a deploy answer: + * replacing another tool's `deploy` entry, and using a lone Hosting entry with no target name. + * @param projectRoot the workspace root on disk + */ +const chooseDeployChoice = async ( + options: DeployOptions, + ngProject: WorkspaceProject, + angularProjectName: string, + projectRoot: string, + context: SchematicContext, +): Promise => { + const rendersPagesOnServer = rendersOnServer(productionBuildOptions(ngProject.architect?.build)); + const choiceForNewSetup: DeployChoice = rendersPagesOnServer ? 'apphosting' : 'hosting'; + const preselected = existingDeployChoice(ngProject.architect?.deploy) ?? choiceForNewSetup; + + const choice = options.deploy ?? await deployPrompt(preselected); + if (choice === 'none') { return choice; } + + // Setting up deployment overwrites the project's `deploy` entry, which may belong to another tool. + const existingDeployBuilder = ngProject.architect?.deploy?.builder; + if (existingDeployBuilder && existingDeployBuilder !== deployBuilder) { + const replace = await confirmPrompt( + `This project already deploys with ${existingDeployBuilder}. Replace that deploy target?`, + ); + if (!replace) { + context.logger.info('Keeping the existing deploy target. Deployment was not set up.'); + return 'none'; + } + } + + // Asked here, before the sign-in and project questions, because a no ends the deploy setup. + if (choice === 'hosting' && !await mayReplaceUnnamedHostingEntry(projectRoot, angularProjectName, context)) { + return 'none'; + } + + return choice; +}; + +/** The place `ng deploy` will deploy to: a Firebase Hosting site, or a Firebase App Hosting backend. */ +type DeployDestination = + | { kind: 'hosting', siteId: string } + | { kind: 'apphosting', backendId: string, alwaysDeployFromSource: boolean }; + +/** What `chooseDeployDestination` needs to know about the `ng add` run it is part of. */ +interface DeployDestinationRequest { + /** The Firebase project chosen earlier in the run. */ + firebaseProject: FirebaseProject; + /** The web app chosen earlier in the run. A new App Hosting backend is linked to it. */ + firebaseApp: FirebaseApp | undefined; + /** The workspace root on disk. */ + projectRoot: string; + /** The email of the signed-in Firebase account. */ + account: string; + /** The Angular project being set up. Its name is also its Hosting target name. */ + angularProjectName: string; + /** The App Hosting backend the Angular project's `deploy` entry already deploys to, if any. */ + existingBackendId: string | undefined; +} + +/** + * Asks which Hosting site or which App Hosting backend to deploy to, according to + * `deployChoice`, creating it when the user asks for a new one. Returns undefined when there is + * nothing to deploy to: the choice was `none`, or the user backed out along the way. + */ +const chooseDeployDestination = async ( + deployChoice: DeployChoice, + firebaseTools: FirebaseTools, + context: SchematicContext, + request: DeployDestinationRequest, +): Promise => { + const { firebaseProject, firebaseApp, projectRoot, account, angularProjectName, existingBackendId } = request; + + if (deployChoice === 'hosting') { + const firebaseRc = firebaseRcForSetup(projectRoot); + const { projectId } = firebaseProject; + const existingSiteId = hostingSiteFromRc(firebaseRc, projectId, angularProjectName); + const otherTargetBySite = hostingSitesOfOtherTargets(firebaseRc, projectId, angularProjectName); + const site = await sitePrompt(firebaseProject, projectRoot, existingSiteId, otherTargetBySite); + const siteId = shortSiteName(site); + return siteId ? { kind: 'hosting', siteId } : undefined; + } + + if (deployChoice === 'apphosting' && firebaseApp) { + const backend = await selectAppHostingBackend(firebaseTools, context, { + projectId: firebaseProject.projectId, + projectRoot, + account, + webAppId: firebaseApp.appId, + angularProjectName, + existingBackendId, + }); + if (backend) { return { kind: 'apphosting', ...backend }; } + + context.logger.info('Deployment was not set up.'); + } + + return undefined; +}; + +/** What `writeFirebaseDeployConfig` needs to know about the workspace it writes to. */ +interface FirebaseDeployConfigRequest { + /** The workspace root on disk. */ + projectRoot: string; + /** The Firebase project being deployed to. */ + projectId: string; + /** The Angular project being set up. Its name is also its Hosting target name. */ + angularProjectName: string; + /** The Angular project's `build` entry from angular.json. */ + buildTarget: BuildTargetDefinition | undefined; + /** Whether angular.json has an application besides this Angular project. */ + hasOtherApplications: boolean; +} + +/** Whether the workspace's angular.json has an application other than `angularProjectName`. */ +const workspaceHasOtherApplications = (host: Tree, angularProjectName: string): boolean => { + const { workspace } = getWorkspace(host); + return Object.entries(workspace.projects).some( + ([projectName, project]) => projectName !== angularProjectName && project.projectType === 'application' + ); +}; + +/** + * Writes the chosen deploy destination into the Firebase CLI's two files on disk, firebase.json + * and .firebaserc. The `deploy` entry in angular.json is written separately, through the Tree. + */ +const writeFirebaseDeployConfig = ( + destination: DeployDestination, + context: SchematicContext, + request: FirebaseDeployConfigRequest, +): void => { + const { projectRoot, projectId, angularProjectName, buildTarget, hasOtherApplications } = request; + + if (destination.kind === 'apphosting') { + setAppHostingInFirebaseJson(projectRoot, destination.backendId, destination.alwaysDeployFromSource); + + // App Hosting builds with the `build` script and is not told which Angular project to build. + if (hasOtherApplications) { + context.logger.warn( + 'This workspace has more than one application. Firebase App Hosting builds the app by ' + + 'running "npm run build", so make sure the build script in package.json builds ' + + `"${angularProjectName}", for example "ng build ${angularProjectName}".` + ); + } + return; + } + + // Firebase Hosting serves files, so it needs to know where the build puts them. + const buildOptions = productionBuildOptions(buildTarget); + setHostingTargetInFirebaseRc(projectRoot, projectId, angularProjectName, destination.siteId); + setHostingInFirebaseJson( + projectRoot, + angularProjectName, + browserOutputDirectory(angularProjectName, buildTarget), + clientSidePage(buildOptions), + ); + + if (rendersOnServer(buildOptions)) { + context.logger.warn( + 'This app uses server-side rendering, which Firebase Hosting cannot run: every route that ' + + 'is not prerendered will load as a client-rendered page. Choose Firebase App Hosting to ' + + 'keep server-side rendering.' + ); + } + + if (buildOptions.localize) { context.logger.warn(localizedBuildHostingWarning); } +}; + export const ngAddSetupProject = ( options: DeployOptions ) => async (host: Tree, context: SchematicContext) => { @@ -72,20 +299,37 @@ export const ngAddSetupProject = ( const features = await featuresPrompt(); - if (features.length === 0) { + const { project: ngProject, projectName: ngProjectName } = getProject(options, host); + const deployChoice = await chooseDeployChoice(options, ngProject, ngProjectName, projectRoot, context); + + /* Said in both branches below. Pressing Enter at the features prompt without pressing Space + * first selects nothing, which is easy to do by mistake. */ + const howToSelectFeatures = + `At the "${featuresPromptMessage}" prompt, use the arrow keys to move, ` + + 'press Space to select each feature you want, then Enter to confirm.'; + + if (features.length === 0 && deployChoice === 'none') { context.logger.warn( - 'No features were selected, so there is nothing to set up. ' + - `At the "${featuresPromptMessage}" prompt, use the arrow keys to move, ` + - 'press Space to select each feature you want, then Enter to confirm. ' + - 'Re-run ng add @angular/fire to try again.' + 'No features were selected and no deployment was set up, so there is nothing to do. ' + + `${howToSelectFeatures} Re-run ng add @angular/fire to try again.` ); } else { + if (features.length === 0) { + context.logger.info( + 'No features were selected, so only deployment is being set up. To add features, run ' + + `ng add @angular/fire again. ${howToSelectFeatures}` + ); + } + const firebaseTools = await getFirebaseTools(); + // Before any Firebase call, so an unsupported firebase-tools changes nothing. + if (deployChoice === 'apphosting') { assertAppHostingSetupSupported(firebaseTools); } + // Add the firebase files if they don't exist already so login.use works if (!host.exists('/firebase.json')) { writeFileSync(join(projectRoot, 'firebase.json'), '{}'); } - + let firebaseJson: FirebaseJSON = JSON.parse( readFileSync(join(projectRoot, "firebase.json")).toString() ); @@ -96,11 +340,10 @@ export const ngAddSetupProject = ( await firebaseTools.login.use(user.email, { projectRoot }); } - const { projectName: ngProjectName } = getProject(options, host); - - const [ defaultProjectName ] = getFirebaseProjectNameFromHost(host, ngProjectName); - - const firebaseProject = await projectPrompt(defaultProjectName, { projectRoot, account: user.email }); + // The question starts on the project `ng deploy` uses today, so that pressing Enter keeps it. + const firebaseRcAtStart = firebaseRcForSetup(projectRoot); + const startingProject = existingFirebaseProject(ngProject.architect?.deploy, firebaseRcAtStart, ngProjectName); + const firebaseProject = await projectPrompt(startingProject, { projectRoot, account: user.email }); let firebaseApp: FirebaseApp|undefined; let sdkConfig: Record|undefined; @@ -110,9 +353,38 @@ export const ngAddSetupProject = ( firebaseJsonConfig: firebaseJson, firebaseJsonPath: projectRoot }; - if (features.length) { + if (deployChoice === 'apphosting') { + context.logger.info(appHostingRequirements(firebaseProject.projectId)); + } + + // An App Hosting backend is linked to a web app, so App Hosting needs one even with no features. + if (features.length || deployChoice === 'apphosting') { firebaseApp = await appPrompt(firebaseProject, undefined, { projectRoot }); + setupConfig.firebaseApp = firebaseApp; + } + + /* The deploy destination is chosen, and created when new, before the Data Connect init below + * writes files. A failure here stops only the deploy setup. The run goes on, so the selected + * features are still set up, as they are when the user declines a deploy question. */ + let deployDestination: DeployDestination | undefined; + try { + deployDestination = await chooseDeployDestination(deployChoice, firebaseTools, context, { + firebaseProject, + firebaseApp, + projectRoot, + account: user.email, + angularProjectName: ngProjectName, + existingBackendId: existingAppHostingBackend(ngProject.architect?.deploy), + }); + } catch (error) { + context.logger.warn( + `Deployment was not set up: ${error.message}\n` + + 'Run ng add @angular/fire again to set up deployment.' + ); + } + + if (features.length && firebaseApp) { const result = await firebaseTools.apps.sdkconfig('web', firebaseApp.appId, { nonInteractive: true, projectRoot }); sdkConfig = Object.fromEntries( @@ -121,7 +393,6 @@ export const ngAddSetupProject = ( .map(key => [key, result.sdkConfig[key]]) ); setupConfig.sdkConfig = sdkConfig; - setupConfig.firebaseApp = firebaseApp; // set up data connect locally if data connect hasn't already been initialized. if(features.includes(FEATURES.DataConnect)) { if (!firebaseJson.dataconnect) { @@ -174,11 +445,53 @@ export const ngAddSetupProject = ( // ran first this snapshot would see it and skip creating the files it points at. createFirestoreStarterFiles(host, context, features, firebaseJsonAfterInit); + /* An App Hosting deploy goes to the default project. When this run set up no deployment, an + * App Hosting setup from an earlier run has to keep deploying where it did, so the default + * project stays as it was. */ + const earlierDefaultProject = firebaseRcAtStart.projects?.default; + const keepsAppHostingProject = + !deployDestination && !!existingAppHostingBackend(ngProject.architect?.deploy) && !!earlierDefaultProject; + const defaultProject = keepsAppHostingProject ? earlierDefaultProject : firebaseProject.projectId; + if (keepsAppHostingProject && earlierDefaultProject !== firebaseProject.projectId) { + context.logger.warn( + `ng deploy still deploys this app to the Firebase project ${earlierDefaultProject}, which ` + + 'stays the default project in .firebaserc because deployment was not set up in this run.' + ); + } + // Both write the real filesystem, after the last firebaseTools.init call — init writes // .firebaserc and rewrites firebase.json on disk during the run. - setDefaultProjectInFirebaseRc(projectRoot, firebaseProject.projectId); + setDefaultProjectInFirebaseRc(projectRoot, defaultProject); addFirestoreToFirebaseJson(projectRoot, context, features); - return setupProject(host, context, features, setupConfig); + // After the calls above for the same reason: these also write firebase.json and .firebaserc on disk. + if (deployDestination) { + writeFirebaseDeployConfig(deployDestination, context, { + projectRoot, + projectId: firebaseProject.projectId, + angularProjectName: ngProjectName, + buildTarget: ngProject.architect?.build, + hasOtherApplications: workspaceHasOtherApplications(host, ngProjectName), + }); + } + + // The edits to the app's own files, made through the Tree: the providers, then the deploy entry. + const rules: Rule[] = []; + const featureRule = setupProject(host, context, features, setupConfig); + if (featureRule) { rules.push(featureRule); } + if (deployDestination) { + const appHostingBackend = deployDestination.kind === 'apphosting' ? deployDestination.backendId : undefined; + + // Only a Hosting setup needs the `firebaseProject` option. This reads the .firebaserc written above. + let firebaseProjectOption: string | undefined; + if (deployDestination.kind === 'hosting') { + firebaseProjectOption = firebaseProjectForDeployOption(projectRoot, firebaseProject.projectId, ngProjectName); + } + + const deployTargetSettings = { appHostingBackend, firebaseProject: firebaseProjectOption }; + rules.push(setDeployTarget(ngProjectName, deployTargetSettings)); + context.logger.info('Deployment is set up. Run ng deploy to deploy your app.'); + } + return chain(rules); } }; diff --git a/src/schematics/setup/prompts.ts b/src/schematics/setup/prompts.ts index e1a4389ba..0ebd356f2 100644 --- a/src/schematics/setup/prompts.ts +++ b/src/schematics/setup/prompts.ts @@ -1,14 +1,20 @@ import { spawnSync } from 'child_process'; -import * as fuzzy from 'fuzzy'; -import * as inquirer from 'inquirer'; -import { getActiveAccount, getFirebaseTools } from '../firebaseTools'; -import { FEATURES, FirebaseApp, FirebaseProject, featureOptions } from '../interfaces'; -import { shortAppId } from '../utils'; +import fuzzy from 'fuzzy'; +import inquirer from 'inquirer'; +import inquirerAutocompletePrompt from 'inquirer-autocomplete-prompt'; +import { getActiveAccount, getFirebaseTools } from '../firebaseTools.js'; +import { FEATURES, FirebaseApp, FirebaseProject, featureOptions } from '../interfaces.js'; +import { shortAppId } from '../utils.js'; - -inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt')); -const NEW_OPTION = '~~angularfire-new~~'; +inquirer.registerPrompt('autocomplete', inquirerAutocompletePrompt); + +/** + * The value of the extra choice that a prompt adds to its list of existing items, such as + * "create a new one", "another region" or "log in with another account". No real id can equal + * it, so a prompt can tell that choice apart from a pick of something that already exists. + */ +export const NEW_OPTION = '~~angularfire-new~~'; // `fuzzy` passes either the original list of projects or an internal object // which contains the project as a property. @@ -78,6 +84,16 @@ type Prompt = (questions: { name: K, source: (...a const autocomplete: Prompt = (questions) => inquirer.prompt(questions); +/** Asks a yes-or-no question. Pressing Enter answers no. */ +export const confirmPrompt = async (message: string): Promise => { + const { confirmed } = await inquirer.prompt<{ confirmed: boolean }>({ + type: 'confirm', + name: 'confirmed', + message, + default: false, + }); + return confirmed; +}; export const featuresPromptMessage = 'What features would you like to setup?'; diff --git a/src/schematics/setup/schema.json b/src/schematics/setup/schema.json index 5b1ce2c4f..6de401271 100644 --- a/src/schematics/setup/schema.json +++ b/src/schematics/setup/schema.json @@ -10,6 +10,11 @@ "$default": { "$source": "projectName" } + }, + "deploy": { + "type": "string", + "enum": ["apphosting", "hosting", "none"], + "description": "Where ng deploy should deploy the app: Firebase App Hosting (apphosting), Firebase Hosting (hosting), or no deploy setup (none). Asked interactively when omitted." } }, "required": [] diff --git a/src/schematics/utils.ts b/src/schematics/utils.ts index 36fab88c6..96df9b113 100644 --- a/src/schematics/utils.ts +++ b/src/schematics/utils.ts @@ -9,9 +9,9 @@ import { } from "@angular-devkit/schematics"; import { NodePackageInstallTask } from "@angular-devkit/schematics/tasks/index.js"; import { addRootProvider } from "@schematics/angular/utility"; +import { parse as parseJsonWithComments } from "jsonc-parser"; import { parse } from "yaml"; import { overwriteIfExists, safeReadJSON, stringifyFormatted } from "./common.js"; -import { projectFromRc } from "./firebaserc.js"; import { ConnectorConfig, ConnectorYaml, @@ -20,7 +20,6 @@ import { DeployOptions, FEATURES, FirebaseApp, - FirebaseRc, PackageJson, Workspace, } from "./interfaces"; @@ -39,10 +38,7 @@ export function getWorkspace(host: Tree): { throw new SchematicsException(`Could not find angular.json`); } - - const { parse } = require("jsonc-parser"); - - const workspace = parse(configBuffer.toString()) as Workspace | undefined; + const workspace = parseJsonWithComments(configBuffer.toString()) as Workspace | undefined; if (!workspace) { throw new SchematicsException("Could not parse angular.json"); } @@ -79,18 +75,6 @@ export const getProject = (options: DeployOptions, host: Tree) => { return { project, projectName }; }; -export function getFirebaseProjectNameFromHost( - host: Tree, - target: string -): [string | undefined, string | undefined] { - const buffer = host.read("/.firebaserc"); - if (!buffer) { - return [undefined, undefined]; - } - const rc: FirebaseRc = JSON.parse(buffer.toString()); - return projectFromRc(rc, target); -} - // TODO rewrite using typescript export function addFixesToServer(host: Tree) { const serverPath = `/server.ts`; diff --git a/src/schematics/workspace.ts b/src/schematics/workspace.ts index 754eeca42..2e4d1b95f 100644 --- a/src/schematics/workspace.ts +++ b/src/schematics/workspace.ts @@ -40,7 +40,7 @@ export const lockfiles: [PackageManager, string][] = [ * (a workspace `package.json`, an `angular.json`), so callers branch on the result instead of * wrapping every call. */ -export const readJson = (path: string): unknown => { +export const readJson = (path: string): Content | undefined => { try { /* jsonc, not JSON.parse: Angular tolerates comments in angular.json and this repo already * reads it that way (`utils.ts`). Strict parsing silently dropped a commented file's diff --git a/tools/update-app-hosting-regions.mts b/tools/update-app-hosting-regions.mts new file mode 100644 index 000000000..9094b38af --- /dev/null +++ b/tools/update-app-hosting-regions.mts @@ -0,0 +1,79 @@ +/** + * @fileoverview Refreshes the list of Firebase App Hosting regions that `ng add` offers when it + * creates a backend. A maintainer runs it before a release, signed in to the Firebase CLI: + * `npm run update-regions -- `. It rewrites + * `src/schematics/setup/appHostingRegions.ts`, which is committed like any other source file. + * + * Node runs this file as it is, without a compile step, so it uses only TypeScript syntax that + * Node can remove on its own (types and annotations). + */ + +import { execSync } from 'node:child_process'; +import { writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { join } from 'node:path'; + +/** One region as the App Hosting API's `projects//locations` response lists it. */ +export interface AppHostingLocation { + locationId: string; + displayName?: string; +} + +const regionsFile = join(import.meta.dirname, '..', 'src', 'schematics', 'setup', 'appHostingRegions.ts'); + +/** Builds the TypeScript source of `appHostingRegions.ts` from the API's list of regions. */ +export const regionsFileContent = (locations: AppHostingLocation[]): string => { + const regions = locations + .map(({ locationId, displayName }) => ({ id: locationId, name: displayName || locationId })) + .sort((first, second) => first.id.localeCompare(second.id)); + const lines = regions.map(({ id, name }) => ` { id: ${JSON.stringify(id)}, name: ${JSON.stringify(name)} },`); + return [ + '/**', + ' * @fileoverview The Firebase App Hosting regions `ng add` offers for a new backend.', + ' * Generated by `npm run update-regions`. Do not edit by hand.', + ' */', + '', + 'export const appHostingRegions = [', + ...lines, + '];', + '', + ].join('\n'); +}; + +/** + * Fetches the regions with the Firebase CLI's signed-in account. No Firebase CLI command lists + * them, so this loads the globally installed firebase-tools' own modules. + * @param projectId any Firebase project the signed-in account can read + */ +const fetchLocations = async (projectId: string): Promise => { + const firebaseToolsRoot = join(execSync('npm root -g').toString().trim(), 'firebase-tools'); + const loadFirebaseToolsModule = createRequire(join(firebaseToolsRoot, 'package.json')); + const { getGlobalDefaultAccount } = loadFirebaseToolsModule('./lib/auth'); + const { requireAuth } = loadFirebaseToolsModule('./lib/requireAuth'); + const { listLocations } = loadFirebaseToolsModule('./lib/gcp/apphosting'); + + const account = getGlobalDefaultAccount(); + await requireAuth({ user: account?.user, tokens: account?.tokens }); + return listLocations(projectId); +}; + +const main = async (): Promise => { + const projectId = process.argv[2]; + if (!projectId) { + throw new Error('Usage: npm run update-regions -- '); + } + const locations = await fetchLocations(projectId); + if (!locations.length) { + throw new Error(`The App Hosting API returned no regions for project ${projectId}.`); + } + writeFileSync(regionsFile, regionsFileContent(locations)); + console.log(`Wrote ${locations.length} regions to ${regionsFile}`); +}; + +// Only when run as a script, so importing this file fetches nothing. +if (import.meta.main) { + main().catch((error: Error) => { + console.error(error.message); + process.exit(1); + }); +}