Skip to content

feat(deploy): More deploy options #2647

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions docs/deploy/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,56 @@ We'll create the function and a `package.json` in your project output directory.
## Step 3: customization

To customize the deployment flow, you can use the configuration files you're already familiar with from `firebase-tools`. You can find more in the [firebase documentation](https://firebase.google.com/docs/hosting/full-config).

### Configuring Cloud Functions

Setting `functionsNodeVersion` and `functionsRuntimeOptions` in your `angular.json` allow you to custimze the version of Node.js Cloud Functions is running and run-time settings like timeout, VPC connectors, and memory.

```json
"deploy": {
"builder": "@angular/fire:deploy",
"options": {
"functionsNodeVersion": 12,
"functionsRuntimeOptions": {
"memory": "2GB",
"timeoutSeconds": 10,
"vpcConnector": "my-vpc-connector",
"vpcConnectorEgressSettings": "PRIVATE_RANGES_ONLY"
}
}
}
```

### Working with multiple Firebase Projects

If you have multiple build targets and deploy targets, it is possible to specify them in your `angular.json` or `workspace.json`.

It is possible to use either your project name or project alias in `firebaseProject`. The setting provided here is equivalent to passing a project name or alias to `firebase deploy --project projectNameOrAlias`.

The `buildTarget` simply points to an existing build configuration for your project. Most projects have a default configuration and a production configuration (commonly activated by using the `--prod` flag) but it is possible to specify as many build configurations as needed.

You may specify a `buildTarget` and `firebaseProject` in your `options` as follows:

```json
"deploy": {
"builder": "@angular/fire:deploy",
"options": {
"buildTarget": "projectName:build",
"firebaseProject": "developmentProject"
},
"configurations": {
"production": {
"buildTarget": "projectName:build:production",
"firebaseProject": "productionProject"
}
}
}
```

The above configuration specifies the following:

1. `ng deploy` will deploy the default project with default configuration.
2. `ng deploy projectName` will deploy the specified project with default configuration.
3. `ng deploy projectName --prod` or `ng deploy projectName --configuration='production'` will deploy `projectName` with production build settings to your production environment.

All of the options are optional. If you do not specify a `buildTarget`, it defaults to a production build (`projectName:build:production`). If you do not specify a `firebaseProject`, it defaults to the first matching deploy target found in your `.firebaserc` (where your projectName is the same as your Firebase deploy target name). The `configurations` section is also optional.
6 changes: 5 additions & 1 deletion sample/angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,11 @@
"deploy": {
"builder": "@angular/fire:deploy",
"options": {
"ssr": true
"ssr": true,
"functionsNodeVersion": 12,
"functionsRuntimeOptions": {
"memory": "1GB"
}
}
}
}
Expand Down
47 changes: 37 additions & 10 deletions src/schematics/deploy/actions.jasmine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,19 +82,19 @@ describe('Deploy Angular apps', () => {

it('should call login', async () => {
const spy = spyOn(firebaseMock, 'login');
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, false);
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, { preview: false });
expect(spy).toHaveBeenCalled();
});

it('should not call login', async () => {
const spy = spyOn(firebaseMock, 'login');
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, false, FIREBASE_TOKEN);
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, { preview: false }, FIREBASE_TOKEN);
expect(spy).not.toHaveBeenCalled();
});

it('should invoke the builder', async () => {
const spy = spyOn(context, 'scheduleTarget').and.callThrough();
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, false);
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, { preview: false });
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledWith({
target: 'build',
Expand All @@ -109,14 +109,14 @@ describe('Deploy Angular apps', () => {
options: {}
};
const spy = spyOn(context, 'scheduleTarget').and.callThrough();
await deploy(firebaseMock, context, buildTarget, undefined, FIREBASE_PROJECT, false);
await deploy(firebaseMock, context, buildTarget, undefined, FIREBASE_PROJECT, { preview: false });
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledWith({ target: 'prerender', project: PROJECT }, {});
});

it('should invoke firebase.deploy', async () => {
const spy = spyOn(firebaseMock, 'deploy').and.callThrough();
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, false, FIREBASE_TOKEN);
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, { preview: false }, FIREBASE_TOKEN);
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledWith({
cwd: 'cwd',
Expand All @@ -128,7 +128,7 @@ describe('Deploy Angular apps', () => {
describe('error handling', () => {
it('throws if there is no firebase project', async () => {
try {
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, undefined, false);
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, undefined, { preview: false });
} catch (e) {
console.log(e);
expect(e.message).toMatch(/Cannot find firebase project/);
Expand All @@ -138,7 +138,7 @@ describe('Deploy Angular apps', () => {
it('throws if there is no target project', async () => {
context.target = undefined;
try {
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, false);
await deploy(firebaseMock, context, STATIC_BUILD_TARGET, undefined, FIREBASE_PROJECT, { preview: false });
} catch (e) {
expect(e.message).toMatch(/Cannot execute the build target/);
}
Expand All @@ -151,7 +151,16 @@ describe('universal deployment', () => {

it('should create a firebase function', async () => {
const spy = spyOn(fsHost, 'writeFileSync');
await deployToFunction(firebaseMock, context, '/home/user', STATIC_BUILD_TARGET, SERVER_BUILD_TARGET, false, undefined, fsHost);
await deployToFunction(
firebaseMock,
context,
'/home/user',
STATIC_BUILD_TARGET,
SERVER_BUILD_TARGET,
{ preview: false },
undefined,
fsHost
);

expect(spy).toHaveBeenCalledTimes(2);

Expand All @@ -164,7 +173,16 @@ describe('universal deployment', () => {

it('should rename the index.html file in the nested dist', async () => {
const spy = spyOn(fsHost, 'renameSync');
await deployToFunction(firebaseMock, context, '/home/user', STATIC_BUILD_TARGET, SERVER_BUILD_TARGET, false, undefined, fsHost);
await deployToFunction(
firebaseMock,
context,
'/home/user',
STATIC_BUILD_TARGET,
SERVER_BUILD_TARGET,
{ preview: false },
undefined,
fsHost
);

expect(spy).toHaveBeenCalledTimes(1);

Expand All @@ -178,7 +196,16 @@ describe('universal deployment', () => {

it('should invoke firebase.deploy', async () => {
const spy = spyOn(firebaseMock, 'deploy');
await deployToFunction(firebaseMock, context, '/home/user', STATIC_BUILD_TARGET, SERVER_BUILD_TARGET, false, undefined, fsHost);
await deployToFunction(
firebaseMock,
context,
'/home/user',
STATIC_BUILD_TARGET,
SERVER_BUILD_TARGET,
{ preview: false },
undefined,
fsHost
);

expect(spy).toHaveBeenCalledTimes(1);
});
Expand Down
46 changes: 26 additions & 20 deletions src/schematics/deploy/actions.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { BuilderContext, targetFromTargetString } from '@angular-devkit/architect';
import { BuildTarget, FirebaseTools, FSHost } from '../interfaces';
import { BuildTarget, DeployBuilderSchema, FirebaseTools, FSHost } from '../interfaces';
import { existsSync, readFileSync, renameSync, writeFileSync } from 'fs';
import { copySync, removeSync } from 'fs-extra';
import { dirname, join } from 'path';
import { execSync } from 'child_process';
import { defaultFunction, defaultPackage, NODE_VERSION } from './functions-templates';
import { defaultFunction, defaultPackage } from './functions-templates';
import { satisfies } from 'semver';
import * as open from 'open';

export type DeployBuilderOptions = DeployBuilderSchema | Record<string, string>;

const escapeRegExp = (str: string) => str.replace(/[\-\[\]\/{}()*+?.\\^$|]/g, '\\$&');

const moveSync = (src: string, dest: string) => {
Expand All @@ -19,11 +21,11 @@ const deployToHosting = (
firebaseTools: FirebaseTools,
context: BuilderContext,
workspaceRoot: string,
preview: boolean,
options: DeployBuilderOptions,
firebaseToken?: string,
) => {

if (preview) {
if (options.preview) {
const port = 5000; // TODO make this configurable

setTimeout(() => {
Expand Down Expand Up @@ -71,10 +73,10 @@ const getVersionRange = (v: number) => `^${v}.0.0`;

const findPackageVersion = (name: string) => {
const match = execSync(`npm list ${name}`).toString().match(` ${escapeRegExp(name)}@.+\\w`);
return match ? match[0].split(`${name}@`)[1] : null;
return match ? match[0].split(`${name}@`)[1].split(/\s/)[0] : null;
};

const getPackageJson = (context: BuilderContext, workspaceRoot: string) => {
const getPackageJson = (context: BuilderContext, workspaceRoot: string, options: DeployBuilderOptions) => {
const dependencies = {
'firebase-admin': 'latest',
'firebase-functions': 'latest'
Expand Down Expand Up @@ -111,7 +113,7 @@ const getPackageJson = (context: BuilderContext, workspaceRoot: string) => {
});
}
} // TODO should we throw?
return defaultPackage(dependencies, devDependencies);
return defaultPackage(dependencies, devDependencies, options);
};

export const deployToFunction = async (
Expand All @@ -120,15 +122,10 @@ export const deployToFunction = async (
workspaceRoot: string,
staticBuildTarget: BuildTarget,
serverBuildTarget: BuildTarget,
preview: boolean,
options: DeployBuilderOptions,
firebaseToken?: string,
fsHost: FSHost = defaultFsHost,
fsHost: FSHost = defaultFsHost
) => {
if (!satisfies(process.versions.node, getVersionRange(NODE_VERSION))) {
context.logger.warn(
`⚠️ Your Node.js version (${process.versions.node}) does not match the Firebase Functions runtime (${NODE_VERSION}).`
);
}

const staticBuildOptions = await context.getTargetOptions(targetFromTargetString(staticBuildTarget.name));
if (!staticBuildOptions.outputPath || typeof staticBuildOptions.outputPath !== 'string') {
Expand Down Expand Up @@ -156,22 +153,31 @@ export const deployToFunction = async (
fsHost.moveSync(staticOut, newClientPath);
fsHost.moveSync(serverOut, newServerPath);

const packageJson = getPackageJson(context, workspaceRoot, options);
const nodeVersion = JSON.parse(packageJson).engines.node;

if (!satisfies(process.versions.node, getVersionRange(nodeVersion))) {
context.logger.warn(
`⚠️ Your Node.js version (${process.versions.node}) does not match the Firebase Functions runtime (${nodeVersion}).`
);
}

fsHost.writeFileSync(
join(dirname(serverOut), 'package.json'),
getPackageJson(context, workspaceRoot)
packageJson
);

fsHost.writeFileSync(
join(dirname(serverOut), 'index.js'),
defaultFunction(serverOut)
defaultFunction(serverOut, options)
);

fsHost.renameSync(
join(newClientPath, 'index.html'),
join(newClientPath, 'index.original.html')
);

if (preview) {
if (options.preview) {
const port = 5000; // TODO make this configurable

setTimeout(() => {
Expand Down Expand Up @@ -211,7 +217,7 @@ export default async function deploy(
staticBuildTarget: BuildTarget,
serverBuildTarget: BuildTarget | undefined,
firebaseProject: string,
preview: boolean,
options: DeployBuilderOptions,
firebaseToken?: string,
) {
if (!firebaseToken) {
Expand Down Expand Up @@ -266,15 +272,15 @@ export default async function deploy(
context.workspaceRoot,
staticBuildTarget,
serverBuildTarget,
preview,
options,
firebaseToken,
);
} else {
await deployToHosting(
firebaseTools,
context,
context.workspaceRoot,
preview,
options,
firebaseToken,
);
}
Expand Down
14 changes: 5 additions & 9 deletions src/schematics/deploy/builder.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect';
import deploy from './actions';
import { BuildTarget, DeployBuilderSchema } from '../interfaces';
import deploy, { DeployBuilderOptions } from './actions';
import { BuildTarget } from '../interfaces';
import { getFirebaseProjectName } from '../utils';

type DeployBuilderOptions = DeployBuilderSchema & Record<string, string>;

// Call the createBuilder() function to create a builder. This mirrors
// createJobHandler() but add typings specific to Architect Builders.
Expand All @@ -13,7 +12,7 @@ export default createBuilder(
throw new Error('Cannot deploy the application without a target');
}

const firebaseProject = getFirebaseProjectName(
const firebaseProject = options.firebaseProject || getFirebaseProjectName(
context.workspaceRoot,
context.target.project
);
Expand All @@ -27,10 +26,7 @@ export default createBuilder(
let serverBuildTarget: BuildTarget | undefined;
if (options.ssr) {
serverBuildTarget = {
name: options.universalBuildTarget || `${context.target.project}:server:production`,
options: {
bundleDependencies: 'all'
}
name: options.universalBuildTarget || `${context.target.project}:server:production`
};
}

Expand All @@ -41,7 +37,7 @@ export default createBuilder(
staticBuildTarget,
serverBuildTarget,
firebaseProject,
!!options.preview,
options,
process.env.FIREBASE_TOKEN,
);
} catch (e) {
Expand Down
Loading