fix: built with commit undefined

fix #9
This commit is contained in:
Minsu Lee
2019-12-03 00:41:38 +09:00
parent e9d3e9f63c
commit 1506158235
47 changed files with 868 additions and 477 deletions

View File

@@ -111,7 +111,7 @@ async function createCommentOnCommit () {
if (commitDeployment) {
deploymentUrl = commitDeployment.url
deploymentCommit = commitDeployment.meta.commit
deploymentCommit = commitDeployment.meta.githubCommitSha
} else {
const {
data: {
@@ -125,7 +125,7 @@ async function createCommentOnCommit () {
if (lastBranchDeployment) {
deploymentUrl = lastBranchDeployment.url
deploymentCommit = lastBranchDeployment.meta.commit
deploymentCommit = lastBranchDeployment.meta.githubCommitSha
} else {
const {
data: {
@@ -139,7 +139,7 @@ async function createCommentOnCommit () {
if (lastDeployment) {
deploymentUrl = lastDeployment.url
deploymentCommit = lastDeployment.meta.commit
deploymentCommit = lastDeployment.meta.githubCommitSha
}
}
}
@@ -192,7 +192,7 @@ async function createCommentOnPullRequest () {
if (commitDeployment) {
deploymentUrl = commitDeployment.url
deploymentCommit = commitDeployment.meta.commit
deploymentCommit = commitDeployment.meta.githubCommitSha
} else {
const {
data: {
@@ -206,7 +206,7 @@ async function createCommentOnPullRequest () {
if (lastBranchDeployment) {
deploymentUrl = lastBranchDeployment.url
deploymentCommit = lastBranchDeployment.meta.commit
deploymentCommit = lastBranchDeployment.meta.githubCommitSha
} else {
const {
data: {
@@ -220,7 +220,7 @@ async function createCommentOnPullRequest () {
if (lastDeployment) {
deploymentUrl = lastDeployment.url
deploymentCommit = lastDeployment.meta.commit
deploymentCommit = lastDeployment.meta.githubCommitSha
}
}
}

8
node_modules/now/README.md generated vendored
View File

@@ -2,19 +2,19 @@
[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit)
## Usage
## Usages
To install the latest version of Now CLI, visit [zeit.co/download](https://zeit.co/download) or run this command:
```
```bash
npm i -g now
```
To quickly start a new project, run the following commands:
```
now init # Pick an example project to clone
cd <PROJECT> # Change directory to the newly created project
now init # Pick an example project
cd <PROJECT> # Change directory to the new project
now dev # Run locally during development
now # Deploy to the cloud
```

BIN
node_modules/now/dist/builders.tar.gz generated vendored

Binary file not shown.

View File

@@ -1,12 +1,13 @@
import { PackageJson, Builder } from './types';
import { PackageJson, Builder, BuilderFunctions } from './types';
interface ErrorResponse {
code: string;
message: string;
}
interface Options {
tag?: 'canary' | 'latest' | string;
functions?: BuilderFunctions;
}
export declare function ignoreApiFilter(file: string): boolean;
export declare function getIgnoreApiFilter(optionsOrBuilders: Options | Builder[]): (file: string) => boolean;
export declare function sortFiles(fileA: string, fileB: string): number;
export declare function detectBuilders(files: string[], pkg?: PackageJson | undefined | null, options?: Options): Promise<{
builders: Builder[] | null;

View File

@@ -2,18 +2,21 @@
import { File } from './types';
interface FileBlobOptions {
mode?: number;
contentType?: string;
data: string | Buffer;
}
interface FromStreamOptions {
mode?: number;
contentType?: string;
stream: NodeJS.ReadableStream;
}
export default class FileBlob implements File {
type: 'FileBlob';
mode: number;
data: string | Buffer;
constructor({ mode, data }: FileBlobOptions);
static fromStream({ mode, stream }: FromStreamOptions): Promise<FileBlob>;
contentType: string | undefined;
constructor({ mode, contentType, data }: FileBlobOptions);
static fromStream({ mode, contentType, stream, }: FromStreamOptions): Promise<FileBlob>;
toStream(): NodeJS.ReadableStream;
}
export {};

View File

@@ -2,10 +2,12 @@
import { File } from './types';
interface FileFsRefOptions {
mode?: number;
contentType?: string;
fsPath: string;
}
interface FromStreamOptions {
mode: number;
contentType?: string;
stream: NodeJS.ReadableStream;
fsPath: string;
}
@@ -13,9 +15,10 @@ declare class FileFsRef implements File {
type: 'FileFsRef';
mode: number;
fsPath: string;
constructor({ mode, fsPath }: FileFsRefOptions);
static fromFsPath({ mode, fsPath, }: FileFsRefOptions): Promise<FileFsRef>;
static fromStream({ mode, stream, fsPath, }: FromStreamOptions): Promise<FileFsRef>;
contentType: string | undefined;
constructor({ mode, contentType, fsPath }: FileFsRefOptions);
static fromFsPath({ mode, contentType, fsPath, }: FileFsRefOptions): Promise<FileFsRef>;
static fromStream({ mode, contentType, stream, fsPath, }: FromStreamOptions): Promise<FileFsRef>;
toStreamAsync(): Promise<NodeJS.ReadableStream>;
toStream(): NodeJS.ReadableStream;
}

View File

@@ -3,14 +3,16 @@ import { File } from './types';
interface FileRefOptions {
mode?: number;
digest: string;
contentType?: string;
mutable?: boolean;
}
export default class FileRef implements File {
type: 'FileRef';
mode: number;
digest: string;
contentType: string | undefined;
private mutable;
constructor({ mode, digest, mutable }: FileRefOptions);
constructor({ mode, digest, contentType, mutable, }: FileRefOptions);
toStreamAsync(): Promise<NodeJS.ReadableStream>;
toStream(): NodeJS.ReadableStream;
}

View File

@@ -1,7 +1,7 @@
import FileBlob from './file-blob';
import FileFsRef from './file-fs-ref';
import FileRef from './file-ref';
import { Lambda, createLambda } from './lambda';
import { Lambda, createLambda, getLambdaOptionsFromFunction } from './lambda';
import { Prerender } from './prerender';
import download, { DownloadedFiles } from './fs/download';
import getWriteableDirectory from './fs/get-writable-directory';
@@ -12,6 +12,8 @@ import streamToBuffer from './fs/stream-to-buffer';
import shouldServe from './should-serve';
import { detectBuilders } from './detect-builders';
import { detectRoutes } from './detect-routes';
import DetectorFilesystem from './detectors/filesystem';
import debug from './debug';
export { FileBlob, FileFsRef, FileRef, Lambda, createLambda, Prerender, download, DownloadedFiles, getWriteableDirectory, glob, rename, spawnAsync, installDependencies, runPackageJsonScript, runNpmInstall, runBundleInstall, runPipInstall, runShellScript, getNodeVersion, getSpawnOptions, streamToBuffer, shouldServe, detectBuilders, detectRoutes, debug, };
export { FileBlob, FileFsRef, FileRef, Lambda, DetectorFilesystem, createLambda, Prerender, download, DownloadedFiles, getWriteableDirectory, glob, rename, spawnAsync, installDependencies, runPackageJsonScript, runNpmInstall, runBundleInstall, runPipInstall, runShellScript, getNodeVersion, getSpawnOptions, streamToBuffer, shouldServe, detectBuilders, detectRoutes, debug, getLambdaOptionsFromFunction, };
export { detectDefaults } from './detectors';
export * from './types';

View File

@@ -1,5 +1,5 @@
/// <reference types="node" />
import { Files } from './types';
import { Files, Config } from './types';
interface Environment {
[key: string]: string;
}
@@ -7,22 +7,33 @@ interface LambdaOptions {
zipBuffer: Buffer;
handler: string;
runtime: string;
memory?: number;
maxDuration?: number;
environment: Environment;
}
interface CreateLambdaOptions {
files: Files;
handler: string;
runtime: string;
memory?: number;
maxDuration?: number;
environment?: Environment;
}
interface GetLambdaOptionsFromFunctionOptions {
sourceFile: string;
config?: Config;
}
export declare class Lambda {
type: 'Lambda';
zipBuffer: Buffer;
handler: string;
runtime: string;
memory?: number;
maxDuration?: number;
environment: Environment;
constructor({ zipBuffer, handler, runtime, environment }: LambdaOptions);
constructor({ zipBuffer, handler, runtime, maxDuration, memory, environment, }: LambdaOptions);
}
export declare function createLambda({ files, handler, runtime, environment, }: CreateLambdaOptions): Promise<Lambda>;
export declare function createLambda({ files, handler, runtime, memory, maxDuration, environment, }: CreateLambdaOptions): Promise<Lambda>;
export declare function createZip(files: Files): Promise<Buffer>;
export declare function getLambdaOptionsFromFunction({ sourceFile, config, }: GetLambdaOptionsFromFunctionOptions): Promise<Pick<LambdaOptions, 'memory' | 'maxDuration'>>;
export {};

View File

@@ -5,14 +5,14 @@ import { Lambda } from './lambda';
interface PrerenderOptions {
expiration: number;
lambda: Lambda;
fallback: FileBlob | FileFsRef | FileRef;
fallback: FileBlob | FileFsRef | FileRef | null;
group?: number;
}
export declare class Prerender {
type: 'Prerender';
expiration: number;
lambda: Lambda;
fallback: FileBlob | FileFsRef | FileRef;
fallback: FileBlob | FileFsRef | FileRef | null;
group?: number;
constructor({ expiration, lambda, fallback, group }: PrerenderOptions);
}

162
node_modules/now/dist/dist/types.d.ts generated vendored
View File

@@ -1,12 +1,14 @@
/// <reference types="node" />
import FileRef from './file-ref';
import FileFsRef from './file-fs-ref';
import DetectorFilesystem from './detectors/filesystem';
export interface Env {
[name: string]: string | undefined;
}
export interface File {
type: string;
mode: number;
contentType?: string;
toStream: () => NodeJS.ReadableStream;
/**
* The absolute path to the file in the filesystem
@@ -30,7 +32,7 @@ export interface Route {
export interface Config {
[key: string]: string | string[] | boolean | number | {
[key: string]: string;
} | undefined;
} | BuilderFunctions | undefined;
maxLambdaSize?: string;
includeFiles?: string | string[];
bundle?: boolean;
@@ -42,6 +44,7 @@ export interface Config {
import?: {
[key: string]: string;
};
functions?: BuilderFunctions;
}
export interface Meta {
isDev?: boolean;
@@ -163,23 +166,99 @@ export interface ShouldServeOptions {
*/
config: Config;
}
/**
* Credit to Iain Reid, MIT license.
* Source: https://gist.github.com/iainreid820/5c1cc527fe6b5b7dba41fec7fe54bf6e
*/
declare namespace PackageJson {
/**
* An author or contributor
*/
interface Author {
name: string;
email?: string;
homepage?: string;
}
/**
* A map of exposed bin commands
*/
interface BinMap {
[commandName: string]: string;
}
/**
* A bugs link
*/
interface Bugs {
email: string;
url: string;
}
interface Config {
name?: string;
config?: unknown;
}
/**
* A map of dependencies
*/
interface DependencyMap {
[dependencyName: string]: string;
}
/**
* CommonJS package structure
*/
interface Directories {
lib?: string;
bin?: string;
man?: string;
doc?: string;
example?: string;
}
interface Engines {
node?: string;
npm?: string;
}
interface PublishConfig {
registry?: string;
}
/**
* A project repository
*/
interface Repository {
type: string;
url: string;
}
interface ScriptsMap {
[scriptName: string]: string;
}
}
export interface PackageJson {
name?: string;
version?: string;
engines?: {
[key: string]: string;
node: string;
npm: string;
};
scripts?: {
[key: string]: string;
};
dependencies?: {
[key: string]: string;
};
devDependencies?: {
[key: string]: string;
};
readonly name?: string;
readonly version?: string;
readonly description?: string;
readonly keywords?: string[];
readonly homepage?: string;
readonly bugs?: string | PackageJson.Bugs;
readonly license?: string;
readonly author?: string | PackageJson.Author;
readonly contributors?: string[] | PackageJson.Author[];
readonly files?: string[];
readonly main?: string;
readonly bin?: string | PackageJson.BinMap;
readonly man?: string | string[];
readonly directories?: PackageJson.Directories;
readonly repository?: string | PackageJson.Repository;
readonly scripts?: PackageJson.ScriptsMap;
readonly config?: PackageJson.Config;
readonly dependencies?: PackageJson.DependencyMap;
readonly devDependencies?: PackageJson.DependencyMap;
readonly peerDependencies?: PackageJson.DependencyMap;
readonly optionalDependencies?: PackageJson.DependencyMap;
readonly bundledDependencies?: string[];
readonly engines?: PackageJson.Engines;
readonly os?: string[];
readonly cpu?: string[];
readonly preferGlobal?: boolean;
readonly private?: boolean;
readonly publishConfig?: PackageJson.PublishConfig;
}
export interface NodeVersion {
major: number;
@@ -191,3 +270,52 @@ export interface Builder {
src: string;
config?: Config;
}
export interface BuilderFunctions {
[key: string]: {
memory?: number;
maxDuration?: number;
runtime?: string;
includeFiles?: string;
excludeFiles?: string;
};
}
export interface NowRewrite {
source: string;
destination: string;
}
export interface NowRedirect {
source: string;
destination: string;
statusCode?: number;
}
export interface NowHeader {
source: string;
headers: NowHeaderKeyValue[];
}
export interface NowHeaderKeyValue {
key: string;
value: string;
}
export declare type Detector = (params: DetectorParameters) => Promise<DetectorResult>;
export interface DetectorParameters {
fs: DetectorFilesystem;
detectors?: Detector[];
pkgDetectors?: Detector[];
}
export interface DetectorOutput {
buildCommand: string[];
buildDirectory: string;
buildEnv?: Env;
devCommand?: string[];
devEnv?: Env;
minNodeRange?: string;
cachePattern?: string;
routes?: Route[];
cleanUrls?: boolean;
rewrites?: NowRewrite[];
redirects?: NowRedirect[];
headers?: NowHeader[];
trailingSlash?: boolean;
}
export declare type DetectorResult = DetectorOutput | false;
export {};

2
node_modules/now/dist/index.js generated vendored

File diff suppressed because one or more lines are too long

2
node_modules/now/dist/index.js.map generated vendored

File diff suppressed because one or more lines are too long

View File

@@ -230,7 +230,7 @@ func (mc *MockLambdaContext) ProcessEvents() {
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
client.Timeout = time.Second * 1
client.Timeout = 0
_, err = client.Do(req)
if err != nil {
log.Fatal(fmt.Errorf("Error sending response: %s", err))

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
@@ -31,7 +32,7 @@ function init({ cacheDir }) {
const bootstrapDir = path_1.join(GOPATH, 'src', 'bootstrap');
yield fs_extra_1.mkdirp(bootstrapDir);
yield fs_extra_1.copyFile(source, path_1.join(bootstrapDir, 'bootstrap.go'));
const go = _go({ cwd: bootstrapDir, env: Object.assign({}, process.env, { GOPATH }) });
const go = _go({ cwd: bootstrapDir, env: Object.assign(Object.assign({}, process.env), { GOPATH }) });
const bootstrap = path_1.join(cacheDir, 'bootstrap');
debug('Compiling Go runtime binary %o -> %o', source, bootstrap);
yield go('get');

View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/go1.x/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,+BAA4B;AAC5B,kDAA0B;AAC1B,kDAAgC;AAEhC,uCAAoD;AAEpD,MAAM,KAAK,GAAG,eAAW,CAAC,0BAA0B,CAAC,CAAC;AAEtD,SAAS,GAAG,CAAC,IAAI;IAChB,OAAO,SAAS,EAAE,CAAC,GAAG,IAAI;QACzB,KAAK,CAAC,SAAS,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACzC,OAAO,eAAK,CAAC,IAAI,EAAE,IAAI,kBAAI,KAAK,EAAE,SAAS,IAAK,IAAI,EAAG,CAAC;IACzD,CAAC,CAAC;AACH,CAAC;AAED,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,MAAM,GAAG,WAAI,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;QAE9C,gCAAgC;QAChC,MAAM,MAAM,GAAG,WAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAEpC,oEAAoE;QACpE,MAAM,YAAY,GAAG,WAAI,CAAC,MAAM,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;QACtD,MAAM,iBAAM,CAAC,YAAY,CAAC,CAAC;QAC3B,MAAM,mBAAQ,CAAC,MAAM,EAAE,WAAI,CAAC,YAAY,EAAE,cAAc,CAAC,CAAC,CAAC;QAE3D,MAAM,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,GAAG,oBAAO,OAAO,CAAC,GAAG,IAAE,MAAM,GAAE,EAAE,CAAC,CAAC;QACvE,MAAM,SAAS,GAAG,WAAI,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;QAC9C,KAAK,CAAC,sCAAsC,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;QACjE,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;QAChB,MAAM,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,cAAc,CAAC,CAAC;QAEnD,uCAAuC;QACvC,MAAM,iBAAM,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;CAAA;AAnBD,oBAmBC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/go1.x/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,+BAA4B;AAC5B,kDAA0B;AAC1B,kDAAgC;AAEhC,uCAAoD;AAEpD,MAAM,KAAK,GAAG,eAAW,CAAC,0BAA0B,CAAC,CAAC;AAEtD,SAAS,GAAG,CAAC,IAAI;IAChB,OAAO,SAAS,EAAE,CAAC,GAAG,IAAI;QACzB,KAAK,CAAC,SAAS,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACzC,OAAO,eAAK,CAAC,IAAI,EAAE,IAAI,kBAAI,KAAK,EAAE,SAAS,IAAK,IAAI,EAAG,CAAC;IACzD,CAAC,CAAC;AACH,CAAC;AAED,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,MAAM,GAAG,WAAI,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;QAE9C,gCAAgC;QAChC,MAAM,MAAM,GAAG,WAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAEpC,oEAAoE;QACpE,MAAM,YAAY,GAAG,WAAI,CAAC,MAAM,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;QACtD,MAAM,iBAAM,CAAC,YAAY,CAAC,CAAC;QAC3B,MAAM,mBAAQ,CAAC,MAAM,EAAE,WAAI,CAAC,YAAY,EAAE,cAAc,CAAC,CAAC,CAAC;QAE3D,MAAM,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,GAAG,kCAAO,OAAO,CAAC,GAAG,KAAE,MAAM,GAAE,EAAE,CAAC,CAAC;QACvE,MAAM,SAAS,GAAG,WAAI,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;QAC9C,KAAK,CAAC,sCAAsC,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;QACjE,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;QAChB,MAAM,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,cAAc,CAAC,CAAC;QAEnD,uCAAuC;QACvC,MAAM,iBAAM,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;CAAA;AAnBD,oBAmBC"}

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

File diff suppressed because one or more lines are too long

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs10.x/index.ts"],"names":[],"mappings":";;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,0BAAW,CAAC,QAAQ,EAAE,SAAS,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs10.x/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,0BAAW,CAAC,QAAQ,EAAE,SAAS,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs6.10/index.ts"],"names":[],"mappings":";;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,0BAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC;SAC/B,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs6.10/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,0BAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC;SAC/B,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs8.10/index.ts"],"names":[],"mappings":";;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,0BAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC;SAC/B,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs8.10/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,0BAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC;SAC/B,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python2.7/index.ts"],"names":[],"mappings":";;;;;;;;;;AACA,yDAAqD;AACrD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,8BAAa,CAAC,QAAQ,EAAE,QAAQ,CAAC;SACjC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python2.7/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,yDAAqD;AACrD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,8BAAa,CAAC,QAAQ,EAAE,QAAQ,CAAC;SACjC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python3.6/index.ts"],"names":[],"mappings":";;;;;;;;;;AACA,yDAAqD;AACrD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,8BAAa,CAAC,QAAQ,EAAE,OAAO,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python3.6/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,yDAAqD;AACrD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,8BAAa,CAAC,QAAQ,EAAE,OAAO,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python3.7/index.ts"],"names":[],"mappings":";;;;;;;;;;AACA,yDAAqD;AACrD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,8BAAa,CAAC,QAAQ,EAAE,OAAO,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python3.7/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,yDAAqD;AACrD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,8BAAa,CAAC,QAAQ,EAAE,OAAO,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View File

@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python3/index.ts"],"names":[],"mappings":";;;;;;;;;;AACA,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,QAAiB;;QAC3C,MAAM,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;CAAA;AAFD,oBAEC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python3/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,QAAiB;;QAC3C,MAAM,4BAAiB,CAAC,mBAAQ,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;CAAA;AAFD,oBAEC"}

View File

@@ -4,11 +4,11 @@ import { Deployment } from '../../types';
import {
DeploymentNotFound,
DeploymentPermissionDenied,
InvalidDeploymentId
InvalidDeploymentId,
} from '../errors-ts';
import mapCertError from '../certs/map-cert-error';
type APIVersion = 'v5' | 'v9';
type APIVersion = 'v5' | 'v10';
export default async function getDeploymentByIdOrHost(
client: Client,
@@ -58,9 +58,7 @@ async function getDeploymentById(
}
type Response = {
deployment: {
id: string;
};
id: string;
};
async function getDeploymentByHost(
@@ -69,7 +67,9 @@ async function getDeploymentByHost(
apiVersion: APIVersion
) {
const response = await client.fetch<Response>(
`/v4/now/hosts/${encodeURIComponent(host)}?resolve=1&noState=1`
`/v10/now/deployments/get?url=${encodeURIComponent(
host
)}&resolve=1&noState=1`
);
return getDeploymentById(client, response.deployment.id, apiVersion);
return getDeploymentById(client, response.id, apiVersion);
}

View File

@@ -6,7 +6,7 @@ import {
createDeployment,
createLegacyDeployment,
DeploymentOptions,
} from '../../../../now-client';
} from 'now-client/dist';
import wait from '../output/wait';
import { Output } from '../output';
// @ts-ignore
@@ -45,9 +45,11 @@ export default async function processDeployment({
const opts: DeploymentOptions = {
...requestBody,
debug: now._debug,
apiUrl: now._apiUrl,
};
if (!legacy) {
let queuedSpinner = null;
let buildSpinner = null;
let deploySpinner = null;
@@ -113,15 +115,29 @@ export default async function processDeployment({
} else {
process.stdout.write(`https://${event.payload.url}`);
}
if (queuedSpinner === null) {
queuedSpinner = wait('Queued...');
}
}
if (event.type === 'build-state-changed') {
if (
event.type === 'build-state-changed' &&
event.payload.readyState === 'BUILDING'
) {
if (queuedSpinner) {
queuedSpinner();
}
if (buildSpinner === null) {
buildSpinner = wait('Building...');
}
}
if (event.type === 'all-builds-completed') {
if (queuedSpinner) {
queuedSpinner();
}
if (buildSpinner) {
buildSpinner();
}
@@ -131,10 +147,12 @@ export default async function processDeployment({
// Handle error events
if (event.type === 'error') {
if (queuedSpinner) {
queuedSpinner();
}
if (buildSpinner) {
buildSpinner();
}
if (deploySpinner) {
deploySpinner();
}
@@ -143,7 +161,13 @@ export default async function processDeployment({
}
// Handle ready event
if (event.type === 'ready') {
if (event.type === 'alias-assigned') {
if (queuedSpinner) {
queuedSpinner();
}
if (buildSpinner) {
buildSpinner();
}
if (deploySpinner) {
deploySpinner();
}

View File

@@ -2,6 +2,7 @@ import chalk from 'chalk';
import execa from 'execa';
import semver from 'semver';
import pipe from 'promisepipe';
import retry from 'async-retry';
import npa from 'npm-package-arg';
import { extract } from 'tar-fs';
import { createHash } from 'crypto';
@@ -20,7 +21,7 @@ import {
} from 'fs-extra';
import pkg from '../../../package.json';
import { NoBuilderCacheError, BuilderCacheCleanError } from '../errors-ts';
import { NoBuilderCacheError } from '../errors-ts';
import wait from '../output/wait';
import { Output } from '../output';
import { getDistTag } from '../get-dist-tag';
@@ -29,6 +30,8 @@ import * as staticBuilder from './static-builder';
import { BuilderWithPackage } from './types';
import { getBundledBuilders } from './get-bundled-builders';
declare const __non_webpack_require__: typeof require;
const registryTypes = new Set(['version', 'tag', 'range']);
const localBuilders: { [key: string]: BuilderWithPackage } = {
@@ -137,24 +140,6 @@ export async function prepareBuilderModulePath() {
return cachedBuilderPath;
}
// Is responsible for cleaning the cache
export async function cleanCacheDir(output: Output): Promise<void> {
const cacheDir = await cacheDirPromise;
try {
output.log(chalk`{magenta Deleting} ${cacheDir}`);
await remove(cacheDir);
} catch (err) {
throw new BuilderCacheCleanError(cacheDir, err.message);
}
try {
await remove(funCacheDir);
output.log(chalk`{magenta Deleting} ${funCacheDir}`);
} catch (err) {
throw new BuilderCacheCleanError(funCacheDir, err.message);
}
}
function getNpmVersion(use = ''): string {
const parsed = npa(use);
if (registryTypes.has(parsed.type)) {
@@ -230,13 +215,13 @@ export async function installBuilders(
}
const yarnPath = join(yarnDir, 'yarn');
const buildersPkgPath = join(builderDir, 'package.json');
const buildersPkg = await readJSON(buildersPkgPath);
const buildersPkgBefore = await readJSON(buildersPkgPath);
packages.push(getBuildUtils(packages));
// Filter out any packages that come packaged with `now-cli`
const packagesToInstall = packages.filter(p =>
filterPackage(p, distTag, buildersPkg)
filterPackage(p, distTag, buildersPkgBefore)
);
if (packagesToInstall.length === 0) {
@@ -247,24 +232,40 @@ export async function installBuilders(
const stopSpinner = wait(
`Installing builders: ${packagesToInstall.sort().join(', ')}`
);
try {
await execa(
process.execPath,
[
yarnPath,
'add',
'--exact',
'--no-lockfile',
'--non-interactive',
...packagesToInstall,
],
{
cwd: builderDir,
}
await retry(
() =>
execa(
process.execPath,
[
yarnPath,
'add',
'--exact',
'--no-lockfile',
'--non-interactive',
...packagesToInstall,
],
{
cwd: builderDir,
}
),
{ retries: 2 }
);
} finally {
stopSpinner();
}
const updatedPackages: string[] = [];
const buildersPkgAfter = await readJSON(buildersPkgPath);
for (const [name, version] of Object.entries(buildersPkgAfter.dependencies)) {
if (version !== buildersPkgBefore.dependencies[name]) {
output.debug(`Builder "${name}" updated to version \`${version}\``);
updatedPackages.push(name);
}
}
purgeRequireCache(updatedPackages, builderDir, output);
}
export async function updateBuilders(
@@ -283,19 +284,23 @@ export async function updateBuilders(
packages.push(getBuildUtils(packages));
await execa(
process.execPath,
[
yarnPath,
'add',
'--exact',
'--no-lockfile',
'--non-interactive',
...packages.filter(p => p !== '@now/static'),
],
{
cwd: builderDir,
}
await retry(
() =>
execa(
process.execPath,
[
yarnPath,
'add',
'--exact',
'--no-lockfile',
'--non-interactive',
...packages.filter(p => p !== '@now/static'),
],
{
cwd: builderDir,
}
),
{ retries: 2 }
);
const updatedPackages: string[] = [];
@@ -307,6 +312,8 @@ export async function updateBuilders(
}
}
purgeRequireCache(updatedPackages, builderDir, output);
return updatedPackages;
}
@@ -382,3 +389,25 @@ function hasBundledBuilders(dependencies: { [name: string]: string }): boolean {
}
return true;
}
function purgeRequireCache(
packages: string[],
builderDir: string,
output: Output
) {
const _require =
typeof __non_webpack_require__ === 'function'
? __non_webpack_require__
: require;
// The `require()` cache for the builder's assets must be purged
const packagesPaths = packages.map(b => join(builderDir, 'node_modules', b));
for (const id of Object.keys(_require.cache)) {
for (const path of packagesPaths) {
if (id.startsWith(path)) {
output.debug(`Purging require cache for "${id}"`);
delete _require.cache[id];
}
}
}
}

View File

@@ -2,6 +2,7 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import ms from 'ms';
import bytes from 'bytes';
import { promisify } from 'util';
import { delimiter, dirname, join } from 'path';
import { fork, ChildProcess } from 'child_process';
import { createFunction } from '@zeit/fun';
@@ -10,8 +11,8 @@ import stripAnsi from 'strip-ansi';
import chalk from 'chalk';
import which from 'which';
import plural from 'pluralize';
import ora, { Ora } from 'ora';
import minimatch from 'minimatch';
import _treeKill from 'tree-kill';
import { Output } from '../output';
import highlight from '../output/highlight';
@@ -27,8 +28,11 @@ import {
BuildResult,
BuilderInputs,
BuilderOutput,
BuildResultV3,
BuilderOutputs,
} from './types';
import { normalizeRoutes } from '@now/routing-utils';
import getUpdateCommand from '../get-update-command';
interface BuildMessage {
type: string;
@@ -40,7 +44,7 @@ interface BuildMessageResult extends BuildMessage {
error?: object;
}
const isLogging = new WeakSet<ChildProcess>();
const treeKill = promisify(_treeKill);
let nodeBinPromise: Promise<string>;
@@ -48,20 +52,13 @@ async function getNodeBin(): Promise<string> {
return which.sync('node', { nothrow: true }) || process.execPath;
}
function pipeChildLogging(child: ChildProcess): void {
if (!isLogging.has(child)) {
child.stdout!.pipe(process.stdout);
child.stderr!.pipe(process.stderr);
isLogging.add(child);
}
}
async function createBuildProcess(
match: BuildMatch,
buildEnv: EnvConfig,
workPath: string,
output: Output,
yarnPath?: string
yarnPath?: string,
debugEnabled: boolean = false
): Promise<ChildProcess> {
if (!nodeBinPromise) {
nodeBinPromise = getNodeBin();
@@ -70,21 +67,33 @@ async function createBuildProcess(
nodeBinPromise,
builderModulePathPromise,
]);
// Ensure that `node` is in the builder's `PATH`
let PATH = `${dirname(execPath)}${delimiter}${process.env.PATH}`;
// Ensure that `yarn` is in the builder's `PATH`
if (yarnPath) {
PATH = `${yarnPath}${delimiter}${PATH}`;
}
const env: EnvConfig = {
...process.env,
PATH,
...buildEnv,
NOW_REGION: 'dev1',
};
// Builders won't show debug logs by default.
// The `NOW_BUILDER_DEBUG` env variable enables them.
if (debugEnabled) {
env.NOW_BUILDER_DEBUG = '1';
}
const buildProcess = fork(modulePath, [], {
cwd: workPath,
env: {
...process.env,
PATH,
...buildEnv,
NOW_REGION: 'dev1',
},
env,
execPath,
execArgv: [],
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
});
match.buildProcess = buildProcess;
@@ -95,9 +104,6 @@ async function createBuildProcess(
match.buildProcess = undefined;
});
buildProcess.stdout!.setEncoding('utf8');
buildProcess.stderr!.setEncoding('utf8');
return new Promise((resolve, reject) => {
// The first message that the builder process sends is the `ready` event
buildProcess.once('message', ({ type }) => {
@@ -149,7 +155,8 @@ export async function executeBuild(
buildEnv,
workPath,
devServer.output,
yarnPath
yarnPath,
debug
);
}
@@ -168,93 +175,47 @@ export async function executeBuild(
},
};
let buildResultOrOutputs: BuilderOutputs | BuildResult;
let buildResultOrOutputs: BuilderOutputs | BuildResult | BuildResultV3;
if (buildProcess) {
let spinLogger;
let spinner: Ora | undefined;
const fullLogs: string[] = [];
buildProcess.send({
type: 'build',
builderName: pkg.name,
buildParams,
});
if (isInitialBuild && !debug && process.stdout.isTTY) {
const logTitle = `${chalk.bold(
`Preparing ${chalk.underline(entrypoint)} for build`
)}:`;
spinner = ora(logTitle).start();
spinLogger = (data: Buffer) => {
const rawLog = stripAnsi(data.toString());
fullLogs.push(rawLog);
const lines = rawLog.replace(/\s+$/, '').split('\n');
const spinText = `${logTitle} ${lines[lines.length - 1]}`;
const maxCols = process.stdout.columns || 80;
const overflow = stripAnsi(spinText).length + 2 - maxCols;
spinner!.text =
overflow > 0 ? `${spinText.slice(0, -overflow - 3)}...` : spinText;
};
buildProcess!.stdout!.on('data', spinLogger);
buildProcess!.stderr!.on('data', spinLogger);
} else {
pipeChildLogging(buildProcess!);
}
try {
buildProcess.send({
type: 'build',
builderName: pkg.name,
buildParams,
});
buildResultOrOutputs = await new Promise((resolve, reject) => {
function onMessage({ type, result, error }: BuildMessageResult) {
cleanup();
if (type === 'buildResult') {
if (result) {
resolve(result);
} else if (error) {
reject(Object.assign(new Error(), error));
}
} else {
reject(new Error(`Got unexpected message type: ${type}`));
buildResultOrOutputs = await new Promise((resolve, reject) => {
function onMessage({ type, result, error }: BuildMessageResult) {
cleanup();
if (type === 'buildResult') {
if (result) {
resolve(result);
} else if (error) {
reject(Object.assign(new Error(), error));
}
} else {
reject(new Error(`Got unexpected message type: ${type}`));
}
function onExit(code: number | null, signal: string | null) {
cleanup();
const err = new Error(
`Builder exited with ${signal || code} before sending build result`
);
reject(err);
}
function cleanup() {
buildProcess!.removeListener('exit', onExit);
buildProcess!.removeListener('message', onMessage);
}
buildProcess!.on('exit', onExit);
buildProcess!.on('message', onMessage);
});
} catch (err) {
if (spinner) {
spinner.stop();
spinner = undefined;
console.log(fullLogs.join(''));
}
throw err;
} finally {
if (spinLogger) {
buildProcess.stdout!.removeListener('data', spinLogger);
buildProcess.stderr!.removeListener('data', spinLogger);
function onExit(code: number | null, signal: string | null) {
cleanup();
const err = new Error(
`Builder exited with ${signal || code} before sending build result`
);
reject(err);
}
if (spinner) {
spinner.stop();
function cleanup() {
buildProcess!.removeListener('exit', onExit);
buildProcess!.removeListener('message', onMessage);
}
pipeChildLogging(buildProcess!);
}
buildProcess!.on('exit', onExit);
buildProcess!.on('message', onMessage);
});
} else {
buildResultOrOutputs = await builder.build(buildParams);
}
// Sort out build result to builder v2 shape
if (builder.version === undefined) {
if (!builder.version || builder.version === 1) {
// `BuilderOutputs` map was returned (Now Builder v1 behavior)
result = {
output: buildResultOrOutputs as BuilderOutputs,
@@ -265,13 +226,81 @@ export async function executeBuild(
? buildResultOrOutputs.distPath
: undefined,
};
} else {
} else if (builder.version === 2) {
result = buildResultOrOutputs as BuildResult;
} else if (builder.version === 3) {
const { output, ...rest } = buildResultOrOutputs as BuildResultV3;
if (!output || (output as BuilderOutput).type !== 'Lambda') {
throw new Error('The result of "builder.build()" must be a `Lambda`');
}
if (output.maxDuration) {
throw new Error(
'The result of "builder.build()" must not contain `memory`'
);
}
if (output.memory) {
throw new Error(
'The result of "builder.build()" must not contain `maxDuration`'
);
}
for (const [src, func] of Object.entries(config.functions || {})) {
if (src === entrypoint || minimatch(entrypoint, src)) {
if (func.maxDuration) {
output.maxDuration = func.maxDuration;
}
if (func.memory) {
output.memory = func.memory;
}
break;
}
}
result = {
...rest,
output: {
[entrypoint]: output,
},
} as BuildResult;
} else {
throw new Error(
`Now CLI does not support builder version ${
builder.version
}.\nPlease run \`${await getUpdateCommand()}\` to update Now CLI.`
);
}
// Normalize Builder Routes
const normalized = normalizeRoutes(result.routes);
if (normalized.error) {
throw new Error(normalized.error.message);
} else {
result.routes = normalized.routes || [];
}
const { output } = result;
// Mimic fmeta-util and convert cleanUrls
if (nowConfig.cleanUrls) {
Object.entries(output)
.filter(([name, value]) => name.endsWith('.html'))
.forEach(([name, value]) => {
const cleanName = name.slice(0, -5);
delete output[name];
output[cleanName] = value;
if (value.type === 'FileBlob' || value.type === 'FileFsRef') {
value.contentType = value.contentType || 'text/html; charset=utf-8';
}
});
}
// Convert the JSON-ified output map back into their corresponding `File`
// subclass type instances.
const output = result.output as BuilderOutputs;
for (const name of Object.keys(output)) {
const obj = output[name] as File;
let lambda: Lambda;
@@ -343,7 +372,7 @@ export async function executeBuild(
Code: { ZipFile: asset.zipBuffer },
Handler: asset.handler,
Runtime: asset.runtime,
MemorySize: 3008,
MemorySize: asset.memory || 3008,
Environment: {
Variables: {
...nowConfig.env,
@@ -445,3 +474,35 @@ export async function getBuildMatches(
return matches;
}
export async function shutdownBuilder(
match: BuildMatch,
{ debug }: Output
): Promise<void> {
const ops: Promise<void>[] = [];
if (match.buildProcess) {
const { pid } = match.buildProcess;
debug(`Killing builder sub-process with PID ${pid}`);
const killPromise = treeKill(pid)
.then(() => {
debug(`Killed builder with PID ${pid}`);
})
.catch((err: Error) => {
debug(`Failed to kill builder with PID ${pid}: ${err}`);
});
ops.push(killPromise);
delete match.buildProcess;
}
if (match.buildOutput) {
for (const asset of Object.values(match.buildOutput)) {
if (asset.type === 'Lambda' && asset.fn) {
debug(`Shutting down Lambda function`);
ops.push(asset.fn.destroy());
}
}
}
await Promise.all(ops);
}

View File

@@ -4,7 +4,13 @@ import PCRE from 'pcre-to-regexp';
import isURL from './is-url';
import DevServer from './server';
import { HttpHeadersConfig, RouteConfig, RouteResult } from './types';
import {
HttpHeadersConfig,
RouteConfig,
RouteResult,
NowConfig,
} from './types';
import { isHandler } from '@now/routing-utils';
export function resolveRouteParameters(
str: string,
@@ -40,9 +46,8 @@ export default async function(
let idx = -1;
for (const routeConfig of routes) {
idx++;
let { src, headers, methods, handle } = routeConfig;
if (handle) {
if (handle === 'filesystem' && devServer) {
if (isHandler(routeConfig)) {
if (routeConfig.handle === 'filesystem' && devServer) {
if (await devServer.hasFilesystem(reqPathname)) {
break;
}
@@ -50,18 +55,12 @@ export default async function(
continue;
}
let { src, headers, methods } = routeConfig;
if (Array.isArray(methods) && reqMethod && !methods.includes(reqMethod)) {
continue;
}
if (!src.startsWith('^')) {
src = `^${src}`;
}
if (!src.endsWith('$')) {
src = `${src}$`;
}
const keys: string[] = [];
const matcher = PCRE(`%${src}%i`, keys);
const match =

View File

@@ -13,6 +13,7 @@ import serveHandler from 'serve-handler';
import { watch, FSWatcher } from 'chokidar';
import { parse as parseDotenv } from 'dotenv';
import { basename, dirname, extname, join } from 'path';
import { getTransformedRoutes } from '@now/routing-utils';
import directoryTemplate from 'serve-handler/src/directory';
import {
@@ -36,13 +37,22 @@ import {
staticFiles as getFiles,
getAllProjectFiles,
} from '../get-files';
import { validateNowConfigBuilds, validateNowConfigRoutes } from './validate';
import {
validateNowConfigBuilds,
validateNowConfigRoutes,
validateNowConfigCleanUrls,
validateNowConfigHeaders,
validateNowConfigRedirects,
validateNowConfigRewrites,
validateNowConfigTrailingSlash,
validateNowConfigFunctions,
} from './validate';
import isURL from './is-url';
import devRouter from './router';
import getMimeType from './mime-type';
import { getYarnPath } from './yarn-installer';
import { executeBuild, getBuildMatches } from './builder';
import { executeBuild, getBuildMatches, shutdownBuilder } from './builder';
import { generateErrorMessage, generateHttpStatusDescription } from './errors';
import {
builderDirPromise,
@@ -78,15 +88,6 @@ interface FSEvent {
path: string;
}
interface NodeRequire {
(id: string): any;
cache: {
[name: string]: any;
};
}
declare const __non_webpack_require__: NodeRequire;
function sortBuilders(buildA: Builder, buildB: Builder) {
if (buildA && buildA.use && buildA.use.startsWith('@now/static-build')) {
return 1;
@@ -140,6 +141,7 @@ export default class DevServer {
this.cachedNowConfig = null;
this.server = http.createServer(this.devServerHandler);
this.server.timeout = 0; // Disable timeout
this.serverUrlPrinted = false;
this.stopping = false;
this.buildMatches = new Map();
@@ -347,13 +349,18 @@ export default class DevServer {
}
// Delete build matches that no longer exists
const ops: Promise<void>[] = [];
for (const src of this.buildMatches.keys()) {
if (!sources.includes(src)) {
this.output.debug(`Removing build match for "${src}"`);
// TODO: shutdown lambda functions
const match = this.buildMatches.get(src);
if (match) {
ops.push(shutdownBuilder(match, this.output));
}
this.buildMatches.delete(src);
}
}
await Promise.all(ops);
// Add the new matches to the `buildMatches` map
const blockingBuilds: Promise<void>[] = [];
@@ -402,25 +409,6 @@ export default class DevServer {
return;
}
const _require =
typeof __non_webpack_require__ === 'function'
? __non_webpack_require__
: require;
// The `require()` cache for the builder's assets must be purged
const builderDir = await builderDirPromise;
const updatedBuilderPaths = updatedBuilders.map(b =>
join(builderDir, 'node_modules', b)
);
for (const id of Object.keys(_require.cache)) {
for (const path of updatedBuilderPaths) {
if (id.startsWith(path)) {
this.output.debug(`Purging require cache for "${id}"`);
delete _require.cache[id];
}
}
}
// Delete any build matches that have the old builder required already
for (const buildMatch of this.buildMatches.values()) {
const {
@@ -429,6 +417,7 @@ export default class DevServer {
} = buildMatch;
if (pkg.name === '@now/static') continue;
if (pkg.name && updatedBuilders.includes(pkg.name)) {
shutdownBuilder(buildMatch, this.output);
this.buildMatches.delete(src);
this.output.debug(`Invalidated build match for "${src}"`);
}
@@ -485,7 +474,6 @@ export default class DevServer {
isInitialLoad: boolean = false
): Promise<NowConfig> {
if (canUseCache && this.cachedNowConfig) {
this.output.debug('Using cached `now.json` config');
return this.cachedNowConfig;
}
@@ -518,18 +506,29 @@ export default class DevServer {
}
}
const allFiles = await getAllProjectFiles(this.cwd, this.output);
const files = allFiles.filter(this.filter);
this.output.debug(
`Found ${allFiles.length} and ` +
`filtered out ${allFiles.length - files.length} files`
);
await this.validateNowConfig(config);
const { error: routeError, routes: maybeRoutes } = getTransformedRoutes({
nowConfig: config,
});
if (routeError) {
this.output.error(routeError.message);
await this.exit();
}
config.routes = maybeRoutes || [];
// no builds -> zero config
if (!config.builds || config.builds.length === 0) {
const allFiles = await getAllProjectFiles(this.cwd, this.output);
const files = allFiles.filter(this.filter);
this.output.debug(
`Found ${allFiles.length} and ` +
`filtered out ${allFiles.length - files.length} files`
);
const { builders, warnings, errors } = await detectBuilders(files, pkg, {
tag: getDistTag(cliVersion) === 'canary' ? 'canary' : 'latest',
functions: config.functions,
});
if (errors) {
@@ -599,25 +598,32 @@ export default class DevServer {
return pkg;
}
async tryValidateOrExit(
config: NowConfig,
validate: (c: NowConfig) => string | null
): Promise<void> {
const message = validate(config);
if (message) {
this.output.error(message);
await this.exit(1);
}
}
async validateNowConfig(config: NowConfig): Promise<void> {
if (config.version === 1) {
this.output.error('Only `version: 2` is supported by `now dev`');
await this.exit(1);
}
const buildsError = validateNowConfigBuilds(config);
if (buildsError) {
this.output.error(buildsError);
await this.exit(1);
}
const routesError = validateNowConfigRoutes(config);
if (routesError) {
this.output.error(routesError);
await this.exit(1);
}
await this.tryValidateOrExit(config, validateNowConfigBuilds);
await this.tryValidateOrExit(config, validateNowConfigRoutes);
await this.tryValidateOrExit(config, validateNowConfigCleanUrls);
await this.tryValidateOrExit(config, validateNowConfigHeaders);
await this.tryValidateOrExit(config, validateNowConfigRedirects);
await this.tryValidateOrExit(config, validateNowConfigRewrites);
await this.tryValidateOrExit(config, validateNowConfigTrailingSlash);
await this.tryValidateOrExit(config, validateNowConfigFunctions);
}
validateEnvConfig(
@@ -729,10 +735,12 @@ export default class DevServer {
this.yarnPath,
this.output
)
.then(updatedBuilders =>
this.invalidateBuildMatches(nowConfig, updatedBuilders)
)
.then(updatedBuilders => {
this.updateBuildersPromise = null;
this.invalidateBuildMatches(nowConfig, updatedBuilders);
})
.catch(err => {
this.updateBuildersPromise = null;
this.output.error(`Failed to update builders: ${err.message}`);
this.output.debug(err.stack);
});
@@ -831,22 +839,18 @@ export default class DevServer {
const ops: Promise<void>[] = [];
for (const match of this.buildMatches.values()) {
if (!match.buildOutput) continue;
for (const asset of Object.values(match.buildOutput)) {
if (asset.type === 'Lambda' && asset.fn) {
ops.push(asset.fn.destroy());
}
}
ops.push(shutdownBuilder(match, this.output));
}
ops.push(close(this.server));
if (this.watcher) {
this.output.debug(`Closing file watcher`);
this.watcher.close();
}
if (this.updateBuildersPromise) {
this.output.debug(`Waiting for builders update to complete`);
ops.push(this.updateBuildersPromise);
}
@@ -1102,7 +1106,7 @@ export default class DevServer {
}
const method = req.method || 'GET';
this.output.log(`${chalk.bold(method)} ${req.url}`);
this.output.debug(`${chalk.bold(method)} ${req.url}`);
try {
const nowConfig = await this.getNowConfig();
@@ -1184,7 +1188,7 @@ export default class DevServer {
if (status) {
res.statusCode = status;
if ([301, 302, 303].includes(status)) {
if (300 <= status && status <= 399) {
await this.sendRedirect(
req,
res,
@@ -1253,12 +1257,12 @@ export default class DevServer {
}
}
let foundAsset = findAsset(match, requestPath);
let foundAsset = findAsset(match, requestPath, nowConfig);
if ((!foundAsset || this.shouldRebuild(req)) && callLevel === 0) {
await this.triggerBuild(match, buildRequestPath, req);
// Since the `asset` was re-built, resolve it again to get the new asset
foundAsset = findAsset(match, requestPath);
foundAsset = findAsset(match, requestPath, nowConfig);
}
if (!foundAsset) {
@@ -1267,7 +1271,10 @@ export default class DevServer {
}
const { asset, assetKey } = foundAsset;
this.output.debug(`Serving asset: [${asset.type}] ${assetKey}`);
this.output.debug(
`Serving asset: [${asset.type}] ${assetKey} ${(asset as any)
.contentType || ''}`
);
/* eslint-disable no-case-declarations */
switch (asset.type) {
@@ -1281,7 +1288,7 @@ export default class DevServer {
headers: [
{
key: 'Content-Type',
value: getMimeType(assetKey),
value: asset.contentType || getMimeType(assetKey),
},
],
},
@@ -1291,7 +1298,7 @@ export default class DevServer {
case 'FileBlob':
const headers: http.OutgoingHttpHeaders = {
'Content-Length': asset.data.length,
'Content-Type': getMimeType(assetKey),
'Content-Type': asset.contentType || getMimeType(assetKey),
};
this.setResponseHeaders(res, nowRequestId, headers);
res.end(asset.data);
@@ -1452,25 +1459,6 @@ export default class DevServer {
return true;
}
/**
* Serve project directory as a static deployment.
*/
serveProjectAsStatic = async (
req: http.IncomingMessage,
res: http.ServerResponse,
nowRequestId: string
) => {
const filePath = req.url ? req.url.replace(/^\//, '') : '';
if (filePath && typeof this.files[filePath] === 'undefined') {
await this.send404(req, res, nowRequestId);
return;
}
this.setResponseHeaders(res, nowRequestId);
return serveStaticFile(req, res, this.cwd, { cleanUrls: true });
};
async hasFilesystem(dest: string): Promise<boolean> {
const requestPath = dest.replace(/^\//, '');
if (
@@ -1587,13 +1575,40 @@ async function shouldServe(
isFilesystem?: boolean
): Promise<boolean> {
const {
src: entrypoint,
src,
config,
builderWithPkg: { builder },
} = match;
if (typeof builder.shouldServe === 'function') {
const nowConfig = await devServer.getNowConfig();
const cleanSrc = src.endsWith('.html') ? src.slice(0, -5) : src;
const trimmedPath = requestPath.endsWith('/')
? requestPath.slice(0, -1)
: requestPath;
if (
nowConfig.cleanUrls &&
nowConfig.trailingSlash &&
cleanSrc === trimmedPath
) {
// Mimic fmeta-util and convert cleanUrls and trailingSlash
return true;
} else if (
nowConfig.cleanUrls &&
!nowConfig.trailingSlash &&
cleanSrc === requestPath
) {
// Mimic fmeta-util and convert cleanUrls
return true;
} else if (
!nowConfig.cleanUrls &&
nowConfig.trailingSlash &&
src === trimmedPath
) {
// Mimic fmeta-util and convert trailingSlash
return true;
} else if (typeof builder.shouldServe === 'function') {
const shouldServe = await builder.shouldServe({
entrypoint,
entrypoint: src,
files,
config,
requestPath,
@@ -1602,7 +1617,7 @@ async function shouldServe(
if (shouldServe) {
return true;
}
} else if (findAsset(match, requestPath)) {
} else if (findAsset(match, requestPath, nowConfig)) {
// If there's no `shouldServe()` function, then look up if there's
// a matching build asset on the `match` that has already been built.
return true;
@@ -1640,7 +1655,8 @@ async function findMatchingRoute(
function findAsset(
match: BuildMatch,
requestPath: string
requestPath: string,
nowConfig: NowConfig
): { asset: BuilderOutput; assetKey: string } | void {
if (!match.buildOutput) {
return;
@@ -1648,6 +1664,10 @@ function findAsset(
let assetKey: string = requestPath.replace(/\/$/, '');
let asset = match.buildOutput[requestPath];
if (nowConfig.trailingSlash && requestPath.endsWith('/')) {
asset = match.buildOutput[requestPath.slice(0, -1)];
}
// In the case of an index path, fall back to iterating over the
// builder outputs and doing an "is index" check until a match is found.
if (!asset) {

View File

@@ -7,7 +7,9 @@ import {
FileFsRef,
Lambda,
PackageJson,
BuilderFunctions,
} from '@now/build-utils';
import { NowRedirect, NowRewrite, NowHeader, Route } from '@now/routing-utils';
import { Output } from '../output';
export interface DevServerOptions {
@@ -27,15 +29,7 @@ export interface BuildMatch extends BuildConfig {
buildProcess?: ChildProcess;
}
export interface RouteConfig {
src: string;
dest: string;
methods?: string[];
headers?: HttpHeadersConfig;
status?: number;
handle?: string;
continue?: boolean;
}
export type RouteConfig = Route;
export interface NowConfig {
name?: string;
@@ -47,6 +41,12 @@ export interface NowConfig {
builds?: BuildConfig[];
routes?: RouteConfig[];
files?: string[];
cleanUrls?: boolean;
rewrites?: NowRewrite[];
redirects?: NowRedirect[];
headers?: NowHeader[];
trailingSlash?: boolean;
functions?: BuilderFunctions;
}
export interface HttpHandler {
@@ -100,7 +100,7 @@ export interface BuilderConfigAttr {
}
export interface Builder {
version?: 2;
version?: 1 | 2 | 3 | 4;
config?: BuilderConfigAttr;
build(
params: BuilderParams
@@ -122,6 +122,20 @@ export interface BuildResult {
distPath?: string;
}
export interface BuildResultV3 {
output: Lambda;
routes: RouteConfig[];
watch: string[];
distPath?: string;
}
export interface BuildResultV4 {
output: { [filePath: string]: Lambda };
routes: RouteConfig[];
watch: string[];
distPath?: string;
}
export interface ShouldServeParams {
files: BuilderInputs;
entrypoint: string;

View File

@@ -1,5 +1,12 @@
import Ajv from 'ajv';
import { schema as routesSchema } from '@now/routing-utils';
import {
routesSchema,
cleanUrlsSchema,
headersSchema,
redirectsSchema,
rewritesSchema,
trailingSlashSchema,
} from '@now/routing-utils';
import { NowConfig } from './types';
const ajv = new Ajv();
@@ -28,40 +35,94 @@ const buildsSchema = {
},
};
const functionsSchema = {
type: 'object',
minProperties: 1,
maxProperties: 50,
additionalProperties: false,
patternProperties: {
'^.{1,256}$': {
type: 'object',
additionalProperties: false,
properties: {
runtime: {
type: 'string',
maxLength: 256,
},
memory: {
enum: Object.keys(Array.from({ length: 50 }))
.slice(2, 48)
.map(x => Number(x) * 64),
},
maxDuration: {
type: 'number',
minimum: 1,
maximum: 900,
},
},
},
},
};
const validateBuilds = ajv.compile(buildsSchema);
const validateRoutes = ajv.compile(routesSchema);
const validateCleanUrls = ajv.compile(cleanUrlsSchema);
const validateHeaders = ajv.compile(headersSchema);
const validateRedirects = ajv.compile(redirectsSchema);
const validateRewrites = ajv.compile(rewritesSchema);
const validateTrailingSlash = ajv.compile(trailingSlashSchema);
const validateFunctions = ajv.compile(functionsSchema);
export function validateNowConfigBuilds({ builds }: NowConfig) {
if (!builds) {
export function validateNowConfigBuilds(config: NowConfig) {
return validateKey(config, 'builds', validateBuilds);
}
export function validateNowConfigRoutes(config: NowConfig) {
return validateKey(config, 'routes', validateRoutes);
}
export function validateNowConfigCleanUrls(config: NowConfig) {
return validateKey(config, 'cleanUrls', validateCleanUrls);
}
export function validateNowConfigHeaders(config: NowConfig) {
return validateKey(config, 'headers', validateHeaders);
}
export function validateNowConfigRedirects(config: NowConfig) {
return validateKey(config, 'redirects', validateRedirects);
}
export function validateNowConfigRewrites(config: NowConfig) {
return validateKey(config, 'rewrites', validateRewrites);
}
export function validateNowConfigTrailingSlash(config: NowConfig) {
return validateKey(config, 'trailingSlash', validateTrailingSlash);
}
export function validateNowConfigFunctions(config: NowConfig) {
return validateKey(config, 'functions', validateFunctions);
}
function validateKey(
config: NowConfig,
key: keyof NowConfig,
validate: Ajv.ValidateFunction
) {
const value = config[key];
if (!value) {
return null;
}
if (!validateBuilds(builds)) {
if (!validateBuilds.errors) {
if (!validate(value)) {
if (!validate.errors) {
return null;
}
const error = validateBuilds.errors[0];
const error = validate.errors[0];
return `Invalid \`builds\` property: ${error.dataPath} ${error.message}`;
}
return null;
}
export function validateNowConfigRoutes({ routes }: NowConfig) {
if (!routes) {
return null;
}
if (!validateRoutes(routes)) {
if (!validateRoutes.errors) {
return null;
}
const error = validateRoutes.errors[0];
return `Invalid \`routes\` property: ${error.dataPath} ${error.message}`;
return `Invalid \`${key}\` property: ${error.dataPath} ${error.message}`;
}
return null;

View File

@@ -784,6 +784,19 @@ export class CantFindConfig extends NowError<
}
}
export class WorkingDirectoryDoesNotExist extends NowError<
'CWD_DOES_NOT_EXIST',
{}
> {
constructor() {
super({
code: 'CWD_DOES_NOT_EXIST',
meta: {},
message: 'The current working directory does not exist.',
});
}
}
export class FileNotFound extends NowError<'FILE_NOT_FOUND', { file: string }> {
constructor(file: string) {
super({
@@ -1073,19 +1086,6 @@ export class NoBuilderCacheError extends NowError<'NO_BUILDER_CACHE', {}> {
}
}
export class BuilderCacheCleanError extends NowError<
'BUILDER_CACHE_CLEAN_FAILED',
{ path: string }
> {
constructor(path: string, message: string) {
super({
code: 'BUILDER_CACHE_CLEAN_FAILED',
message: `Error cleaning builder cache: ${message}`,
meta: { path },
});
}
}
export class LambdaSizeExceededError extends NowError<
'MAX_LAMBDA_SIZE_EXCEEDED',
{ size: number; maxLambdaSize: number }

View File

@@ -1,5 +1,9 @@
import path from 'path';
import { CantParseJSONFile, CantFindConfig } from './errors-ts';
import {
CantParseJSONFile,
CantFindConfig,
WorkingDirectoryDoesNotExist,
} from './errors-ts';
import humanizePath from './humanize-path';
import readJSONFile from './read-json-file';
import readPackage from './read-package';
@@ -8,13 +12,25 @@ import { Output } from './output';
let config: Config;
export default async function getConfig(output: Output, configFile?: string) {
const localPath = process.cwd();
export default async function getConfig(
output: Output,
configFile?: string
): Promise<Config | Error> {
// If config was already read, just return it
if (config) {
return config;
}
let localPath: string;
try {
localPath = process.cwd();
} catch (err) {
if (err.code === 'ENOENT') {
return new WorkingDirectoryDoesNotExist();
}
throw err;
}
// First try with the config supplied by the user via --local-config
if (configFile) {
const localFilePath = path.resolve(localPath, configFile);

View File

@@ -20,27 +20,31 @@ export default async function promptBool(label: string, options: Options = {}) {
noChar = 'n',
stdin = process.stdin,
stdout = process.stdout,
trailing = ''
trailing = '',
} = options;
return new Promise(resolve => {
const isRaw = Boolean(stdin.isRaw);
const isRaw = Boolean(stdin && stdin.isRaw);
if (stdin.setRawMode) {
stdin.setRawMode(true);
if (stdin) {
if (stdin.setRawMode) {
stdin.setRawMode(true);
}
stdin.resume();
}
stdin.resume();
function restore() {
stdout.write(trailing);
if (stdin.setRawMode) {
stdin.setRawMode(isRaw);
}
if (stdin) {
if (stdin.setRawMode) {
stdin.setRawMode(isRaw);
}
stdin.pause();
stdin.removeListener('data', onData);
stdin.pause();
stdin.removeListener('data', onData);
}
}
function onData(buffer: Buffer) {
@@ -70,9 +74,12 @@ export default async function promptBool(label: string, options: Options = {}) {
defaultValue === null
? `[${yesChar}|${noChar}]`
: defaultValue
? `[${chalk.bold(yesChar.toUpperCase())}|${noChar}]`
: `[${yesChar}|${chalk.bold(noChar.toUpperCase())}]`;
? `[${chalk.bold(yesChar.toUpperCase())}|${noChar}]`
: `[${yesChar}|${chalk.bold(noChar.toUpperCase())}]`;
stdout.write(`${chalk.gray('>')} ${label} ${chalk.gray(defaultText)} `);
stdin.on('data', onData);
if (stdin) {
stdin.on('data', onData);
}
});
}

View File

@@ -12,7 +12,7 @@ const ESCAPES = {
CTRL_C: '\u0003',
BACKSPACE: '\u0008',
CTRL_H: '\u007F',
CARRIAGE: '\r'
CARRIAGE: '\r',
};
const formatCC = (data: string) =>
@@ -40,48 +40,46 @@ declare type TextParams = {
forceLowerCase?: boolean;
};
export default function text(
{
label = '',
initialValue = '',
// If false, the `- label` will be printed as `✖ label` in red
// Until the first keypress
valid = true,
// Can be:
// - `false`, which does nothing
// - `cc`, for credit cards
// - `date`, for dates in the mm / yyyy format
mask = false,
placeholder = '',
abortSequences = new Set(['\x03']),
eraseSequences = new Set([ESCAPES.BACKSPACE, ESCAPES.CTRL_H]),
resolveChars = new Set([ESCAPES.CARRIAGE]),
stdin = process.stdin,
stdout = process.stdout,
// Char to print before resolving/rejecting the promise
// If `false`, nothing will be printed
trailing = ansiEscapes.eraseLines(1),
// Gets called on each keypress;
// `data` contains the current keypress;
// `futureValue` contains the current value + the
// Keypress in the correct place
// eslint-disable-next-line @typescript-eslint/no-unused-vars
validateKeypress = (data, futureValue) => true, // eslint-disable-line no-unused-vars
// Get's called before the promise is resolved
// Returning `false` here will prevent the user from submiting the value
// eslint-disable-next-line @typescript-eslint/no-unused-vars
validateValue = (data: string) => true, // eslint-disable-line no-unused-vars
// Receives the value of the input and should return a string
// Or false if no autocomplion is available
// eslint-disable-next-line @typescript-eslint/no-unused-vars
autoComplete = (value: string) => false, // eslint-disable-line no-unused-vars
// Tab
// Right arrow
autoCompleteChars = new Set(['\t', '\x1b[C']),
// If true, converts everything the user types to to lowercase
forceLowerCase = false
}: TextParams = {}
): Promise<string> {
export default function text({
label = '',
initialValue = '',
// If false, the `- label` will be printed as `✖ label` in red
// Until the first keypress
valid = true,
// Can be:
// - `false`, which does nothing
// - `cc`, for credit cards
// - `date`, for dates in the mm / yyyy format
mask = false,
placeholder = '',
abortSequences = new Set(['\x03']),
eraseSequences = new Set([ESCAPES.BACKSPACE, ESCAPES.CTRL_H]),
resolveChars = new Set([ESCAPES.CARRIAGE]),
stdin = process.stdin,
stdout = process.stdout,
// Char to print before resolving/rejecting the promise
// If `false`, nothing will be printed
trailing = ansiEscapes.eraseLines(1),
// Gets called on each keypress;
// `data` contains the current keypress;
// `futureValue` contains the current value + the
// Keypress in the correct place
// eslint-disable-next-line @typescript-eslint/no-unused-vars
validateKeypress = (data, futureValue) => true, // eslint-disable-line no-unused-vars
// Get's called before the promise is resolved
// Returning `false` here will prevent the user from submiting the value
// eslint-disable-next-line @typescript-eslint/no-unused-vars
validateValue = (data: string) => true, // eslint-disable-line no-unused-vars
// Receives the value of the input and should return a string
// Or false if no autocomplion is available
// eslint-disable-next-line @typescript-eslint/no-unused-vars
autoComplete = (value: string) => false, // eslint-disable-line no-unused-vars
// Tab
// Right arrow
autoCompleteChars = new Set(['\t', '\x1b[C']),
// If true, converts everything the user types to to lowercase
forceLowerCase = false,
}: TextParams = {}): Promise<string> {
return new Promise((resolve, reject) => {
const isRaw = process.stdin.isRaw || false;
@@ -124,19 +122,23 @@ export default function text(
regex = new RegExp(`(${regexStr})`, 'g');
}
if (stdin.setRawMode) {
stdin.setRawMode(true);
}
stdin.resume();
function restore() {
if (stdin) {
if (stdin.setRawMode) {
stdin.setRawMode(isRaw);
stdin.setRawMode(true);
}
stdin.pause();
stdin.removeListener('data', onData);
stdin.resume();
}
function restore() {
if (stdin) {
if (stdin.setRawMode) {
stdin.setRawMode(isRaw);
}
stdin.pause();
stdin.removeListener('data', onData);
}
if (trailing) {
stdout.write(trailing);
@@ -288,6 +290,8 @@ export default function text(
}
}
stdin.on('data', onData);
if (stdin) {
stdin.on('data', onData);
}
});
}

45
node_modules/now/package.json generated vendored
View File

@@ -1,32 +1,27 @@
{
"_args": [
[
"now@16.3.1",
"/Users/lms/dietfriends/now-deploy-preview-comment"
]
],
"_from": "now@16.3.1",
"_id": "now@16.3.1",
"_from": "now@^16.6.0",
"_id": "now@16.6.0",
"_inBundle": false,
"_integrity": "sha512-bn+xHUiPRH1YRfe/hSo5WZUskOLX3igL4PTe9gnoLaUoq9ZuBQw5/6A4gG4VvW2HVQLgeRkp2OASfYnjuD+lcQ==",
"_integrity": "sha512-OHWgh7QOgXi7IDI68yJ7SBTcQZr8rFGdM4w2W5CdOyCoISletVhb1+KO4g4iBQGVFVNp1W6hv4qJGAOODmib5Q==",
"_location": "/now",
"_phantomChildren": {},
"_requested": {
"type": "version",
"type": "range",
"registry": true,
"raw": "now@16.3.1",
"raw": "now@^16.6.0",
"name": "now",
"escapedName": "now",
"rawSpec": "16.3.1",
"rawSpec": "^16.6.0",
"saveSpec": null,
"fetchSpec": "16.3.1"
"fetchSpec": "^16.6.0"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/now/-/now-16.3.1.tgz",
"_spec": "16.3.1",
"_where": "/Users/lms/dietfriends/now-deploy-preview-comment",
"_resolved": "https://registry.npmjs.org/now/-/now-16.6.0.tgz",
"_shasum": "09c7752eacfe6a2f571b8be378a685b2b066a9fc",
"_spec": "now@^16.6.0",
"_where": "/Users/amond/side-project/now-deployment",
"ava": {
"compileEnhancements": false,
"extensions": [
@@ -43,6 +38,8 @@
"bugs": {
"url": "https://github.com/zeit/now/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "The command-line interface for Now",
"devDependencies": {
"@sentry/node": "5.5.0",
@@ -53,7 +50,6 @@
"@types/debug": "0.0.31",
"@types/dotenv": "6.1.1",
"@types/escape-html": "0.0.20",
"@types/execa": "0.9.0",
"@types/fs-extra": "5.0.5",
"@types/glob": "7.1.1",
"@types/http-proxy": "1.16.2",
@@ -76,7 +72,7 @@
"@types/which": "1.3.1",
"@types/write-json-file": "2.2.1",
"@zeit/dockerignore": "0.0.5",
"@zeit/fun": "0.10.2",
"@zeit/fun": "0.10.4",
"@zeit/ncc": "0.18.5",
"@zeit/source-map-support": "0.6.2",
"ajv": "6.10.2",
@@ -108,7 +104,7 @@
"epipebomb": "1.0.0",
"escape-html": "1.0.3",
"esm": "3.1.4",
"execa": "1.0.0",
"execa": "3.2.0",
"fs-extra": "7.0.1",
"glob": "7.1.2",
"http-proxy": "1.17.0",
@@ -125,7 +121,6 @@
"mri": "1.1.0",
"ms": "2.1.2",
"node-fetch": "1.7.3",
"now-client": "./packages/now-client",
"npm-package-arg": "6.1.0",
"nyc": "13.2.0",
"ora": "3.4.0",
@@ -152,8 +147,9 @@
"through2": "2.0.3",
"title": "3.4.1",
"tmp-promise": "1.0.3",
"tree-kill": "1.2.1",
"ts-node": "8.3.0",
"typescript": "3.2.4",
"typescript": "3.6.4",
"universal-analytics": "0.4.20",
"update-check": "1.5.3",
"utility-types": "2.1.0",
@@ -164,13 +160,13 @@
"yarn": "1.17.3"
},
"engines": {
"node": ">= 8.11"
"node": ">= 8"
},
"files": [
"dist",
"scripts/preinstall.js"
],
"gitHead": "500c36f5d4bb861487da841d828e68b58da9390e",
"gitHead": "21fe0a2006a5a241c7f0e92ea0a428ece278910e",
"homepage": "https://zeit.co",
"license": "Apache-2.0",
"name": "now",
@@ -207,8 +203,9 @@
"prepublishOnly": "yarn build",
"test-integration": "ava test/integration.js --serial --fail-fast",
"test-integration-now-dev": "ava test/dev/integration.js --serial --fail-fast --verbose",
"test-integration-v1": "ava test/integration-v1.js --serial --fail-fast",
"test-lint": "eslint . --ext .ts,.js --ignore-path ../../.eslintignore",
"test-unit": "nyc ava test/*unit.js --serial --fail-fast --verbose"
},
"version": "16.3.1"
"version": "16.6.0"
}

8
package-lock.json generated
View File

@@ -1,5 +1,5 @@
{
"name": "now-deploy-preview-comment",
"name": "now-deployment",
"requires": true,
"lockfileVersion": 1,
"dependencies": {
@@ -270,9 +270,9 @@
"integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA=="
},
"now": {
"version": "16.3.1",
"resolved": "https://registry.npmjs.org/now/-/now-16.3.1.tgz",
"integrity": "sha512-bn+xHUiPRH1YRfe/hSo5WZUskOLX3igL4PTe9gnoLaUoq9ZuBQw5/6A4gG4VvW2HVQLgeRkp2OASfYnjuD+lcQ=="
"version": "16.6.0",
"resolved": "https://registry.npmjs.org/now/-/now-16.6.0.tgz",
"integrity": "sha512-OHWgh7QOgXi7IDI68yJ7SBTcQZr8rFGdM4w2W5CdOyCoISletVhb1+KO4g4iBQGVFVNp1W6hv4qJGAOODmib5Q=="
},
"npm-run-path": {
"version": "2.0.2",

View File

@@ -11,7 +11,7 @@
"@actions/github": "^1.1.0",
"axios": "~0.18.1",
"common-tags": "^1.8.0",
"now": "^16.3.1"
"now": "^16.6.0"
},
"devDependencies": {},
"engines": {