mirror of
https://github.com/LukeHagar/vercel.git
synced 2025-12-11 12:57:46 +00:00
Compare commits
33 Commits
@now/build
...
@now/pytho
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89172a6e89 | ||
|
|
e8f1dbaa46 | ||
|
|
16b5b6fdf3 | ||
|
|
3bab29ff76 | ||
|
|
d675d2e668 | ||
|
|
2dda88e676 | ||
|
|
5a0090eb1f | ||
|
|
d438b4ec4e | ||
|
|
f8810fd7e6 | ||
|
|
a642cfea96 | ||
|
|
2daa20a9f2 | ||
|
|
4d5c0c40f0 | ||
|
|
29051681df | ||
|
|
96d5e81538 | ||
|
|
9ba9dd6949 | ||
|
|
b362d57270 | ||
|
|
4ff95e1718 | ||
|
|
ef02bedd4d | ||
|
|
ed68a09c3e | ||
|
|
ac7ae5fc5d | ||
|
|
9727b1f020 | ||
|
|
2dc454f15f | ||
|
|
4463af5c7a | ||
|
|
c00fb37cf6 | ||
|
|
4deb426f9c | ||
|
|
008b04413a | ||
|
|
f177ba46e9 | ||
|
|
c030fce589 | ||
|
|
50a5150bb5 | ||
|
|
0578ccf47e | ||
|
|
e32cd36ded | ||
|
|
6ac0ab121c | ||
|
|
05db2e6a73 |
38
errors/now-static-build-failed-to-detect-a-server.md
Normal file
38
errors/now-static-build-failed-to-detect-a-server.md
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# `@now/static-build` Failed to detect a server running
|
||||||
|
|
||||||
|
#### Why This Warning Occurred
|
||||||
|
|
||||||
|
When running `now dev`, the `@now/static-build` builder proxies relevant HTTP
|
||||||
|
requests to the server that is created by the `now-dev` script in the
|
||||||
|
`package.json` file.
|
||||||
|
|
||||||
|
In order for `now dev` to know which port the server is running on, the builder
|
||||||
|
is provided a `$PORT` environment variable that the server *must* bind to. The
|
||||||
|
error "Failed to detect a server running on port" is printed if the builder fails
|
||||||
|
to detect a server listening on that specific port within five minutes.
|
||||||
|
|
||||||
|
#### Possible Ways to Fix It
|
||||||
|
|
||||||
|
Please ensure that your `now-dev` script binds the spawned development server on
|
||||||
|
the provided `$PORT` that the builder expects the server to bind to.
|
||||||
|
|
||||||
|
For example, if you are using Gatsby, your `now-dev` script must use the `-p`
|
||||||
|
(port) option to bind to the `$PORT` specified from the builder:
|
||||||
|
|
||||||
|
```
|
||||||
|
{
|
||||||
|
...
|
||||||
|
"scripts": {
|
||||||
|
...
|
||||||
|
"now-dev": "gatsby develop -p $PORT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Consult your static builder program's `--help` or documentation to figure out what
|
||||||
|
the command line flag to bind to a specific port is (in many cases, it is one of:
|
||||||
|
`-p` / `-P` / `--port`).
|
||||||
|
|
||||||
|
### Useful Links
|
||||||
|
|
||||||
|
- [`@now/static-build` Local Development Documentation](https://zeit.co/docs/v2/deployments/official-builders/static-build-now-static-build#local-development)
|
||||||
@@ -1,5 +1,37 @@
|
|||||||
|
const childProcess = require('child_process');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const command = 'git diff HEAD~1 --name-only';
|
||||||
|
const diff = childProcess.execSync(command).toString();
|
||||||
|
|
||||||
|
const changed = diff
|
||||||
|
.split('\n')
|
||||||
|
.filter(item => Boolean(item) && item.includes('packages/'))
|
||||||
|
.map(item => path.relative('packages', item).split('/')[0]);
|
||||||
|
|
||||||
|
const matches = [];
|
||||||
|
|
||||||
|
if (changed.length > 0) {
|
||||||
|
console.log('The following packages have changed:');
|
||||||
|
|
||||||
|
changed.map((item) => {
|
||||||
|
matches.push(item);
|
||||||
|
console.log(item);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
matches.push('now-node');
|
||||||
|
console.log(`No packages changed, defaulting to ${matches[0]}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const testMatch = Array.from(new Set(matches)).map(
|
||||||
|
item => `**/${item}/**/?(*.)+(spec|test).[jt]s?(x)`,
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
testEnvironment: 'node',
|
testEnvironment: 'node',
|
||||||
|
testMatch,
|
||||||
collectCoverageFrom: [
|
collectCoverageFrom: [
|
||||||
'packages/(!test)/**/*.{js,jsx}',
|
'packages/(!test)/**/*.{js,jsx}',
|
||||||
'!**/node_modules/**',
|
'!**/node_modules/**',
|
||||||
|
|||||||
@@ -125,7 +125,15 @@ export async function downloadGo(
|
|||||||
// If we found GOPATH in ENV, or default `Go` path exists
|
// If we found GOPATH in ENV, or default `Go` path exists
|
||||||
// asssume that user have `Go` installed
|
// asssume that user have `Go` installed
|
||||||
if (isUserGo || process.env.GOPATH !== undefined) {
|
if (isUserGo || process.env.GOPATH !== undefined) {
|
||||||
return createGo(dir, platform, arch);
|
const { stdout } = await execa('go', ['version']);
|
||||||
|
|
||||||
|
if (parseInt(stdout.split('.')[1]) >= 11) {
|
||||||
|
return createGo(dir, platform, arch);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(
|
||||||
|
`Your current ${stdout} doesn't support Go Modules. Please update.`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
// Check `Go` bin in builder CWD
|
// Check `Go` bin in builder CWD
|
||||||
const isGoExist = await pathExists(join(dir, 'bin'));
|
const isGoExist = await pathExists(join(dir, 'bin'));
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { join, sep, dirname } from 'path';
|
import { join, sep, dirname, basename } from 'path';
|
||||||
import { readFile, writeFile, pathExists, move } from 'fs-extra';
|
import { readFile, writeFile, pathExists, move, copy } from 'fs-extra';
|
||||||
|
import { homedir } from 'os';
|
||||||
|
import execa from 'execa';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
glob,
|
glob,
|
||||||
@@ -29,6 +31,18 @@ interface BuildParamsType extends BuildOptions {
|
|||||||
meta: BuildParamsMeta;
|
meta: BuildParamsMeta;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Initialize private git repo for Go Modules
|
||||||
|
async function initPrivateGit(credentials: string) {
|
||||||
|
await execa('git', [
|
||||||
|
'config',
|
||||||
|
'--global',
|
||||||
|
'credential.helper',
|
||||||
|
`store --file ${join(homedir(), '.git-credentials')}`,
|
||||||
|
]);
|
||||||
|
|
||||||
|
await writeFile(join(homedir(), '.git-credentials'), credentials);
|
||||||
|
}
|
||||||
|
|
||||||
export const version = 2;
|
export const version = 2;
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
@@ -39,8 +53,14 @@ export async function build({
|
|||||||
files,
|
files,
|
||||||
entrypoint,
|
entrypoint,
|
||||||
config,
|
config,
|
||||||
|
workPath,
|
||||||
meta = {} as BuildParamsMeta,
|
meta = {} as BuildParamsMeta,
|
||||||
}: BuildParamsType) {
|
}: BuildParamsType) {
|
||||||
|
if (process.env.GIT_CREDENTIALS && !meta.isDev) {
|
||||||
|
console.log('Initialize Git credentials...');
|
||||||
|
await initPrivateGit(process.env.GIT_CREDENTIALS);
|
||||||
|
}
|
||||||
|
|
||||||
console.log('Downloading user files...');
|
console.log('Downloading user files...');
|
||||||
const entrypointArr = entrypoint.split(sep);
|
const entrypointArr = entrypoint.split(sep);
|
||||||
|
|
||||||
@@ -49,26 +69,12 @@ export async function build({
|
|||||||
getWriteableDirectory(),
|
getWriteableDirectory(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (meta.isDev) {
|
|
||||||
const devGoPath = `dev${entrypointArr[entrypointArr.length - 1]}`;
|
|
||||||
const goPathArr = goPath.split(sep);
|
|
||||||
goPathArr.pop();
|
|
||||||
goPathArr.push(devGoPath);
|
|
||||||
goPath = goPathArr.join(sep);
|
|
||||||
}
|
|
||||||
|
|
||||||
const srcPath = join(goPath, 'src', 'lambda');
|
const srcPath = join(goPath, 'src', 'lambda');
|
||||||
const downloadedFiles = await download(files, srcPath);
|
let downloadedFiles;
|
||||||
const input = dirname(downloadedFiles[entrypoint].fsPath);
|
if (meta.isDev) {
|
||||||
var includedFiles: Files = {};
|
downloadedFiles = await download(files, workPath, meta);
|
||||||
|
} else {
|
||||||
if (config && config.includeFiles) {
|
downloadedFiles = await download(files, srcPath);
|
||||||
for (const pattern of config.includeFiles) {
|
|
||||||
const files = await glob(pattern, input);
|
|
||||||
for (const assetName of Object.keys(files)) {
|
|
||||||
includedFiles[assetName] = files[assetName];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Parsing AST for "${entrypoint}"`);
|
console.log(`Parsing AST for "${entrypoint}"`);
|
||||||
@@ -90,18 +96,71 @@ Learn more: https://zeit.co/docs/v2/deployments/official-builders/go-now-go/#ent
|
|||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const entrypointDirnameDev = dirname(downloadedFiles[entrypoint].fsPath);
|
||||||
const parsedAnalyzed = JSON.parse(analyzed) as Analyzed;
|
const parsedAnalyzed = JSON.parse(analyzed) as Analyzed;
|
||||||
|
|
||||||
|
if (meta.isDev) {
|
||||||
|
const base = dirname(downloadedFiles['now.json'].fsPath);
|
||||||
|
const destNow = join(
|
||||||
|
base,
|
||||||
|
'.now',
|
||||||
|
'cache',
|
||||||
|
basename(entrypoint, '.go'),
|
||||||
|
'src',
|
||||||
|
'lambda'
|
||||||
|
);
|
||||||
|
const goMod = await pathExists(join(entrypointDirnameDev, 'go.mod'));
|
||||||
|
|
||||||
|
// this will ensure Go rebuilt fast
|
||||||
|
goPath = join(base, '.now', 'cache', basename(entrypoint, '.go'));
|
||||||
|
|
||||||
|
for (const file of parsedAnalyzed.watch) {
|
||||||
|
if (entrypointArr.length > 0) {
|
||||||
|
await copy(
|
||||||
|
join(base, dirname(entrypoint), file),
|
||||||
|
join(destNow, dirname(entrypoint), file)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (goMod) {
|
||||||
|
await copy(
|
||||||
|
join(entrypointDirnameDev, 'go.mod'),
|
||||||
|
join(destNow, dirname(entrypoint), 'go.mod')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await copy(join(base, file), join(destNow, file));
|
||||||
|
|
||||||
|
if (goMod) {
|
||||||
|
await copy(
|
||||||
|
join(entrypointDirnameDev, 'go.mod'),
|
||||||
|
join(destNow, 'go.mod')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
downloadedFiles = await glob('**', destNow);
|
||||||
|
}
|
||||||
|
|
||||||
|
const entrypointDirname = dirname(downloadedFiles[entrypoint].fsPath);
|
||||||
|
const input = entrypointDirname;
|
||||||
|
var includedFiles: Files = {};
|
||||||
|
|
||||||
|
if (config && config.includeFiles) {
|
||||||
|
for (const pattern of config.includeFiles) {
|
||||||
|
const files = await glob(pattern, input);
|
||||||
|
for (const assetName of Object.keys(files)) {
|
||||||
|
includedFiles[assetName] = files[assetName];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const handlerFunctionName = parsedAnalyzed.functionName;
|
const handlerFunctionName = parsedAnalyzed.functionName;
|
||||||
console.log(
|
console.log(
|
||||||
`Found exported function "${handlerFunctionName}" in "${entrypoint}"`
|
`Found exported function "${handlerFunctionName}" in "${entrypoint}"`
|
||||||
);
|
);
|
||||||
|
|
||||||
// we need `main.go` in the same dir as the entrypoint,
|
|
||||||
// otherwise `go build` will refuse to build
|
|
||||||
const entrypointDirname = dirname(downloadedFiles[entrypoint].fsPath);
|
|
||||||
|
|
||||||
// check if package name other than main
|
// check if package name other than main
|
||||||
|
// using `go.mod` way building the handler
|
||||||
const packageName = parsedAnalyzed.packageName;
|
const packageName = parsedAnalyzed.packageName;
|
||||||
const isGoModExist = await pathExists(join(entrypointDirname, 'go.mod'));
|
const isGoModExist = await pathExists(join(entrypointDirname, 'go.mod'));
|
||||||
if (packageName !== 'main') {
|
if (packageName !== 'main') {
|
||||||
@@ -228,6 +287,9 @@ Learn more: https://zeit.co/docs/v2/deployments/official-builders/go-now-go/#ent
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
// legacy mode
|
||||||
|
// we need `main.go` in the same dir as the entrypoint,
|
||||||
|
// otherwise `go build` will refuse to build
|
||||||
const go = await createGo(
|
const go = await createGo(
|
||||||
goPath,
|
goPath,
|
||||||
process.platform,
|
process.platform,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@now/go",
|
"name": "@now/go",
|
||||||
"version": "0.4.6",
|
"version": "0.5.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
|
|||||||
@@ -10,9 +10,22 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ignoredFoldersRegex []*regexp.Regexp
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
ignoredFolders := []string{"vendor", "testdata", ".now"}
|
||||||
|
|
||||||
|
// Build the regex that matches if a path contains the respective ignored folder
|
||||||
|
// The pattern will look like: (.*/)?vendor/.*, which matches every path that contains a vendor folder
|
||||||
|
for _, folder := range ignoredFolders {
|
||||||
|
ignoredFoldersRegex = append(ignoredFoldersRegex, regexp.MustCompile("(.*/)?"+folder+"/.*"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type analyze struct {
|
type analyze struct {
|
||||||
PackageName string `json:"packageName"`
|
PackageName string `json:"packageName"`
|
||||||
FuncName string `json:"functionName"`
|
FuncName string `json:"functionName"`
|
||||||
@@ -40,8 +53,9 @@ func visit(files *[]string) filepath.WalkFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// we don't need Dirs, or test files
|
// we don't need Dirs, or test files
|
||||||
// we only want `.go` files
|
// we only want `.go` files. Further, we ignore
|
||||||
if info.IsDir() || itf || filepath.Ext(path) != ".go" {
|
// every file that is in one of the ignored folders.
|
||||||
|
if info.IsDir() || itf || filepath.Ext(path) != ".go" || isInIgnoredFolder(path) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,6 +64,19 @@ func visit(files *[]string) filepath.WalkFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isInIgnoredFolder checks if the given path is in one of the ignored folders.
|
||||||
|
func isInIgnoredFolder(path string) bool {
|
||||||
|
// Make sure the regex works for Windows paths
|
||||||
|
path = filepath.ToSlash(path)
|
||||||
|
|
||||||
|
for _, pattern := range ignoredFoldersRegex {
|
||||||
|
if pattern.MatchString(path) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// return unique file
|
// return unique file
|
||||||
func unique(files []string) []string {
|
func unique(files []string) []string {
|
||||||
encountered := map[string]bool{}
|
encountered := map[string]bool{}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@now/next",
|
"name": "@now/next",
|
||||||
"version": "0.3.2",
|
"version": "0.4.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"main": "./dist/index",
|
"main": "./dist/index",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
"directory": "packages/now-next"
|
"directory": "packages/now-next"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@now/node-bridge": "^1.1.2",
|
"@now/node-bridge": "^1.1.3",
|
||||||
"fs-extra": "^7.0.0",
|
"fs-extra": "^7.0.0",
|
||||||
"get-port": "^5.0.0",
|
"get-port": "^5.0.0",
|
||||||
"resolve-from": "^5.0.0",
|
"resolve-from": "^5.0.0",
|
||||||
|
|||||||
@@ -155,14 +155,13 @@ export const build = async ({
|
|||||||
entrypoint,
|
entrypoint,
|
||||||
meta = {} as BuildParamsMeta,
|
meta = {} as BuildParamsMeta,
|
||||||
}: BuildParamsType): Promise<{
|
}: BuildParamsType): Promise<{
|
||||||
routes?: any[];
|
routes?: { src: string; dest: string }[];
|
||||||
output: Files;
|
output: Files;
|
||||||
watch?: string[];
|
watch?: string[];
|
||||||
childProcesses: ChildProcess[];
|
childProcesses: ChildProcess[];
|
||||||
}> => {
|
}> => {
|
||||||
validateEntrypoint(entrypoint);
|
validateEntrypoint(entrypoint);
|
||||||
|
|
||||||
const routes: any[] = [];
|
|
||||||
const entryDirectory = path.dirname(entrypoint);
|
const entryDirectory = path.dirname(entrypoint);
|
||||||
const entryPath = path.join(workPath, entryDirectory);
|
const entryPath = path.join(workPath, entryDirectory);
|
||||||
const dotNext = path.join(entryPath, '.next');
|
const dotNext = path.join(entryPath, '.next');
|
||||||
@@ -191,6 +190,10 @@ export const build = async ({
|
|||||||
console.log(`${name} Installing dependencies...`);
|
console.log(`${name} Installing dependencies...`);
|
||||||
await runNpmInstall(entryPath, ['--prefer-offline']);
|
await runNpmInstall(entryPath, ['--prefer-offline']);
|
||||||
|
|
||||||
|
if (!process.env.NODE_ENV) {
|
||||||
|
process.env.NODE_ENV = 'development';
|
||||||
|
}
|
||||||
|
|
||||||
// The runtime env vars consist of the base `process.env` vars, but with the
|
// The runtime env vars consist of the base `process.env` vars, but with the
|
||||||
// build env vars removed, and the runtime env vars mixed in afterwards
|
// build env vars removed, and the runtime env vars mixed in afterwards
|
||||||
const runtimeEnv: EnvConfig = Object.assign({}, process.env);
|
const runtimeEnv: EnvConfig = Object.assign({}, process.env);
|
||||||
@@ -285,7 +288,9 @@ export const build = async ({
|
|||||||
await unlinkFile(path.join(entryPath, '.npmrc'));
|
await unlinkFile(path.join(entryPath, '.npmrc'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const routes: { src: string; dest: string }[] = [];
|
||||||
const lambdas: { [key: string]: Lambda } = {};
|
const lambdas: { [key: string]: Lambda } = {};
|
||||||
|
const staticPages: { [key: string]: FileFsRef } = {};
|
||||||
|
|
||||||
if (isLegacy) {
|
if (isLegacy) {
|
||||||
const filesAfterBuild = await glob('**', entryPath);
|
const filesAfterBuild = await glob('**', entryPath);
|
||||||
@@ -377,10 +382,21 @@ export const build = async ({
|
|||||||
fsPath: path.join(__dirname, 'launcher.js'),
|
fsPath: path.join(__dirname, 'launcher.js'),
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
const pages = await glob(
|
const pagesDir = path.join(entryPath, '.next', 'serverless', 'pages');
|
||||||
'**/*.js',
|
|
||||||
path.join(entryPath, '.next', 'serverless', 'pages')
|
const pages = await glob('**/*.js', pagesDir);
|
||||||
);
|
const staticPageFiles = await glob('**/*.html', pagesDir);
|
||||||
|
|
||||||
|
Object.keys(staticPageFiles).forEach((page: string) => {
|
||||||
|
const staticRoute = path.join(entryDirectory, page);
|
||||||
|
staticPages[staticRoute] = staticPageFiles[page];
|
||||||
|
|
||||||
|
const pathname = page.replace(/\.html$/, '');
|
||||||
|
routes.push({
|
||||||
|
src: `^${path.join('/', entryDirectory, pathname)}$`,
|
||||||
|
dest: path.join('/', staticRoute),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const pageKeys = Object.keys(pages);
|
const pageKeys = Object.keys(pages);
|
||||||
|
|
||||||
@@ -469,10 +485,11 @@ export const build = async ({
|
|||||||
output: {
|
output: {
|
||||||
...publicFiles,
|
...publicFiles,
|
||||||
...lambdas,
|
...lambdas,
|
||||||
|
...staticPages,
|
||||||
...staticFiles,
|
...staticFiles,
|
||||||
...staticDirectoryFiles,
|
...staticDirectoryFiles,
|
||||||
},
|
},
|
||||||
routes: [],
|
routes,
|
||||||
watch: [],
|
watch: [],
|
||||||
childProcesses: [],
|
childProcesses: [],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@now/node-bridge",
|
"name": "@now/node-bridge",
|
||||||
"version": "1.1.2",
|
"version": "1.1.3",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"main": "./index.js",
|
"main": "./index.js",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { AddressInfo } from 'net';
|
import { AddressInfo } from 'net';
|
||||||
import { APIGatewayProxyEvent } from 'aws-lambda';
|
import { APIGatewayProxyEvent, Context } from 'aws-lambda';
|
||||||
import {
|
import {
|
||||||
Server,
|
Server,
|
||||||
IncomingHttpHeaders,
|
IncomingHttpHeaders,
|
||||||
OutgoingHttpHeaders,
|
OutgoingHttpHeaders,
|
||||||
request
|
request,
|
||||||
} from 'http';
|
} from 'http';
|
||||||
|
|
||||||
interface NowProxyEvent {
|
interface NowProxyEvent {
|
||||||
@@ -133,25 +133,25 @@ export class Bridge {
|
|||||||
|
|
||||||
return this.server.listen({
|
return this.server.listen({
|
||||||
host: '127.0.0.1',
|
host: '127.0.0.1',
|
||||||
port: 0
|
port: 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async launcher(
|
async launcher(
|
||||||
event: NowProxyEvent | APIGatewayProxyEvent
|
event: NowProxyEvent | APIGatewayProxyEvent,
|
||||||
|
context: Context
|
||||||
): Promise<NowProxyResponse> {
|
): Promise<NowProxyResponse> {
|
||||||
|
context.callbackWaitsForEmptyEventLoop = false;
|
||||||
const { port } = await this.listening;
|
const { port } = await this.listening;
|
||||||
|
|
||||||
const { isApiGateway, method, path, headers, body } = normalizeEvent(
|
const { isApiGateway, method, path, headers, body } = normalizeEvent(event);
|
||||||
event
|
|
||||||
);
|
|
||||||
|
|
||||||
const opts = {
|
const opts = {
|
||||||
hostname: '127.0.0.1',
|
hostname: '127.0.0.1',
|
||||||
port,
|
port,
|
||||||
path,
|
path,
|
||||||
method,
|
method,
|
||||||
headers
|
headers,
|
||||||
};
|
};
|
||||||
|
|
||||||
// eslint-disable-next-line consistent-return
|
// eslint-disable-next-line consistent-return
|
||||||
@@ -175,7 +175,7 @@ export class Bridge {
|
|||||||
statusCode: response.statusCode || 200,
|
statusCode: response.statusCode || 200,
|
||||||
headers: response.headers,
|
headers: response.headers,
|
||||||
body: bodyBuffer.toString('base64'),
|
body: bodyBuffer.toString('base64'),
|
||||||
encoding: 'base64'
|
encoding: 'base64',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -16,56 +16,70 @@ test('port binding', async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('`APIGatewayProxyEvent` normalizing', async () => {
|
test('`APIGatewayProxyEvent` normalizing', async () => {
|
||||||
const server = new Server((req, res) => res.end(
|
const server = new Server((req, res) =>
|
||||||
JSON.stringify({
|
res.end(
|
||||||
method: req.method,
|
JSON.stringify({
|
||||||
path: req.url,
|
method: req.method,
|
||||||
headers: req.headers,
|
path: req.url,
|
||||||
}),
|
headers: req.headers,
|
||||||
));
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
const bridge = new Bridge(server);
|
const bridge = new Bridge(server);
|
||||||
bridge.listen();
|
bridge.listen();
|
||||||
const result = await bridge.launcher({
|
const context = {};
|
||||||
httpMethod: 'GET',
|
const result = await bridge.launcher(
|
||||||
headers: { foo: 'bar' },
|
{
|
||||||
path: '/apigateway',
|
httpMethod: 'GET',
|
||||||
body: null,
|
headers: { foo: 'bar' },
|
||||||
});
|
path: '/apigateway',
|
||||||
|
body: null,
|
||||||
|
},
|
||||||
|
context
|
||||||
|
);
|
||||||
assert.equal(result.encoding, 'base64');
|
assert.equal(result.encoding, 'base64');
|
||||||
assert.equal(result.statusCode, 200);
|
assert.equal(result.statusCode, 200);
|
||||||
const body = JSON.parse(Buffer.from(result.body, 'base64').toString());
|
const body = JSON.parse(Buffer.from(result.body, 'base64').toString());
|
||||||
assert.equal(body.method, 'GET');
|
assert.equal(body.method, 'GET');
|
||||||
assert.equal(body.path, '/apigateway');
|
assert.equal(body.path, '/apigateway');
|
||||||
assert.equal(body.headers.foo, 'bar');
|
assert.equal(body.headers.foo, 'bar');
|
||||||
|
assert.equal(context.callbackWaitsForEmptyEventLoop, false);
|
||||||
|
|
||||||
server.close();
|
server.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('`NowProxyEvent` normalizing', async () => {
|
test('`NowProxyEvent` normalizing', async () => {
|
||||||
const server = new Server((req, res) => res.end(
|
const server = new Server((req, res) =>
|
||||||
JSON.stringify({
|
res.end(
|
||||||
method: req.method,
|
JSON.stringify({
|
||||||
path: req.url,
|
method: req.method,
|
||||||
headers: req.headers,
|
path: req.url,
|
||||||
}),
|
headers: req.headers,
|
||||||
));
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
const bridge = new Bridge(server);
|
const bridge = new Bridge(server);
|
||||||
bridge.listen();
|
bridge.listen();
|
||||||
const result = await bridge.launcher({
|
const context = { callbackWaitsForEmptyEventLoop: true };
|
||||||
Action: 'Invoke',
|
const result = await bridge.launcher(
|
||||||
body: JSON.stringify({
|
{
|
||||||
method: 'POST',
|
Action: 'Invoke',
|
||||||
headers: { foo: 'baz' },
|
body: JSON.stringify({
|
||||||
path: '/nowproxy',
|
method: 'POST',
|
||||||
body: 'body=1',
|
headers: { foo: 'baz' },
|
||||||
}),
|
path: '/nowproxy',
|
||||||
});
|
body: 'body=1',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
context
|
||||||
|
);
|
||||||
assert.equal(result.encoding, 'base64');
|
assert.equal(result.encoding, 'base64');
|
||||||
assert.equal(result.statusCode, 200);
|
assert.equal(result.statusCode, 200);
|
||||||
const body = JSON.parse(Buffer.from(result.body, 'base64').toString());
|
const body = JSON.parse(Buffer.from(result.body, 'base64').toString());
|
||||||
assert.equal(body.method, 'POST');
|
assert.equal(body.method, 'POST');
|
||||||
assert.equal(body.path, '/nowproxy');
|
assert.equal(body.path, '/nowproxy');
|
||||||
assert.equal(body.headers.foo, 'baz');
|
assert.equal(body.headers.foo, 'baz');
|
||||||
|
assert.equal(context.callbackWaitsForEmptyEventLoop, false);
|
||||||
|
|
||||||
server.close();
|
server.close();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@now/node-server",
|
"name": "@now/node-server",
|
||||||
"version": "0.7.2",
|
"version": "0.7.3",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
"directory": "packages/now-node-server"
|
"directory": "packages/now-node-server"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@now/node-bridge": "^1.1.2",
|
"@now/node-bridge": "^1.1.3",
|
||||||
"@zeit/ncc": "0.18.5",
|
"@zeit/ncc": "0.18.5",
|
||||||
"fs-extra": "7.0.1"
|
"fs-extra": "7.0.1"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@now/node",
|
"name": "@now/node",
|
||||||
"version": "0.7.2",
|
"version": "0.7.3",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"main": "./dist/index",
|
"main": "./dist/index",
|
||||||
"repository": {
|
"repository": {
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
"directory": "packages/now-node"
|
"directory": "packages/now-node"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@now/node-bridge": "^1.1.2",
|
"@now/node-bridge": "^1.1.3",
|
||||||
"@zeit/ncc": "0.18.5",
|
"@zeit/ncc": "0.18.5",
|
||||||
"fs-extra": "7.0.1"
|
"fs-extra": "7.0.1"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { join, dirname } from 'path';
|
import { join, dirname, basename } from 'path';
|
||||||
import execa from 'execa';
|
import execa from 'execa';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { promisify } from 'util';
|
import { promisify } from 'util';
|
||||||
@@ -73,7 +73,16 @@ export const build = async ({
|
|||||||
meta = {},
|
meta = {},
|
||||||
}: BuildOptions) => {
|
}: BuildOptions) => {
|
||||||
console.log('downloading files...');
|
console.log('downloading files...');
|
||||||
const downloadedFiles = await download(originalFiles, workPath, meta);
|
let downloadedFiles = await download(originalFiles, workPath, meta);
|
||||||
|
|
||||||
|
if (meta.isDev) {
|
||||||
|
const base = dirname(downloadedFiles['now.json'].fsPath);
|
||||||
|
const destNow = join(base, '.now', 'cache', basename(entrypoint, '.py'));
|
||||||
|
await download(downloadedFiles, destNow);
|
||||||
|
downloadedFiles = await glob('**', destNow);
|
||||||
|
workPath = destNow;
|
||||||
|
}
|
||||||
|
|
||||||
const foundLockFile = 'Pipfile.lock' in downloadedFiles;
|
const foundLockFile = 'Pipfile.lock' in downloadedFiles;
|
||||||
const pyUserBase = await getWriteableDirectory();
|
const pyUserBase = await getWriteableDirectory();
|
||||||
process.env.PYTHONUSERBASE = pyUserBase;
|
process.env.PYTHONUSERBASE = pyUserBase;
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ _now_imported, _now_is_legacy = _now_get_import()
|
|||||||
if _now_is_legacy:
|
if _now_is_legacy:
|
||||||
print('using HTTP Handler')
|
print('using HTTP Handler')
|
||||||
from http.server import HTTPServer
|
from http.server import HTTPServer
|
||||||
|
from urllib.parse import unquote
|
||||||
import requests
|
import requests
|
||||||
import _thread
|
import _thread
|
||||||
server = HTTPServer(('', 0), _now_imported)
|
server = HTTPServer(('', 0), _now_imported)
|
||||||
@@ -30,7 +31,7 @@ if _now_is_legacy:
|
|||||||
_thread.start_new_thread(server.handle_request, ())
|
_thread.start_new_thread(server.handle_request, ())
|
||||||
|
|
||||||
payload = json.loads(event['body'])
|
payload = json.loads(event['body'])
|
||||||
path = payload['path']
|
path = unquote(payload['path'])
|
||||||
headers = payload['headers']
|
headers = payload['headers']
|
||||||
method = payload['method']
|
method = payload['method']
|
||||||
encoding = payload.get('encoding')
|
encoding = payload.get('encoding')
|
||||||
@@ -53,10 +54,7 @@ if _now_is_legacy:
|
|||||||
else:
|
else:
|
||||||
print('using Web Server Gateway Interface (WSGI)')
|
print('using Web Server Gateway Interface (WSGI)')
|
||||||
import sys
|
import sys
|
||||||
try:
|
from urllib.parse import urlparse, unquote
|
||||||
from urllib.parse import urlparse
|
|
||||||
except ImportError:
|
|
||||||
from urlparse import urlparse
|
|
||||||
from werkzeug._compat import BytesIO
|
from werkzeug._compat import BytesIO
|
||||||
from werkzeug._compat import string_types
|
from werkzeug._compat import string_types
|
||||||
from werkzeug._compat import to_bytes
|
from werkzeug._compat import to_bytes
|
||||||
@@ -75,13 +73,14 @@ else:
|
|||||||
if isinstance(body, string_types):
|
if isinstance(body, string_types):
|
||||||
body = to_bytes(body, charset='utf-8')
|
body = to_bytes(body, charset='utf-8')
|
||||||
|
|
||||||
urlinfo = urlparse(payload['path'])
|
path = unquote(payload['path'])
|
||||||
|
query = urlparse(path).query
|
||||||
|
|
||||||
environ = {
|
environ = {
|
||||||
'CONTENT_LENGTH': str(len(body)),
|
'CONTENT_LENGTH': str(len(body)),
|
||||||
'CONTENT_TYPE': headers.get('content-type', ''),
|
'CONTENT_TYPE': headers.get('content-type', ''),
|
||||||
'PATH_INFO': payload['path'],
|
'PATH_INFO': path,
|
||||||
'QUERY_STRING': urlinfo.query,
|
'QUERY_STRING': query,
|
||||||
'REMOTE_ADDR': headers.get(
|
'REMOTE_ADDR': headers.get(
|
||||||
'x-forwarded-for', headers.get(
|
'x-forwarded-for', headers.get(
|
||||||
'x-real-ip', payload.get(
|
'x-real-ip', payload.get(
|
||||||
@@ -102,7 +101,7 @@ else:
|
|||||||
}
|
}
|
||||||
|
|
||||||
for key, value in environ.items():
|
for key, value in environ.items():
|
||||||
if isinstance(value, string_types):
|
if isinstance(value, string_types) and key != 'QUERY_STRING':
|
||||||
environ[key] = wsgi_encoding_dance(value)
|
environ[key] = wsgi_encoding_dance(value)
|
||||||
|
|
||||||
for key, value in headers.items():
|
for key, value in headers.items():
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@now/python",
|
"name": "@now/python",
|
||||||
"version": "0.2.2",
|
"version": "0.2.4",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|||||||
7
packages/now-python/test/fixtures/09-url-params/custom.py
vendored
Normal file
7
packages/now-python/test/fixtures/09-url-params/custom.py
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
from flask import Flask, Response, __version__
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
@app.route('/', defaults={'path': ''})
|
||||||
|
@app.route('/<path:path>')
|
||||||
|
def catch_all(path):
|
||||||
|
return Response("path=%s" %(path), mimetype='text/html')
|
||||||
7
packages/now-python/test/fixtures/09-url-params/index.py
vendored
Normal file
7
packages/now-python/test/fixtures/09-url-params/index.py
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
from flask import Flask, Response, __version__
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
@app.route('/', defaults={'path': ''})
|
||||||
|
@app.route('/<path:path>')
|
||||||
|
def catch_all(path):
|
||||||
|
return Response("path=%s" %(path), mimetype='text/html')
|
||||||
13
packages/now-python/test/fixtures/09-url-params/now.json
vendored
Normal file
13
packages/now-python/test/fixtures/09-url-params/now.json
vendored
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"version": 2,
|
||||||
|
"builds": [
|
||||||
|
{ "src": "*.py", "use": "@now/python" }
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{ "src": "/another", "dest": "custom.py" }
|
||||||
|
],
|
||||||
|
"probes": [
|
||||||
|
{ "path": "/?hello=/", "mustContain": "path=?hello=/" },
|
||||||
|
{ "path": "/another?hello=/", "mustContain": "path=another?hello=/" }
|
||||||
|
]
|
||||||
|
}
|
||||||
1
packages/now-python/test/fixtures/09-url-params/requirements.txt
vendored
Normal file
1
packages/now-python/test/fixtures/09-url-params/requirements.txt
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
Flask==1.0.2
|
||||||
8
packages/now-python/test/fixtures/10-url-params-http-handler/custom.py
vendored
Normal file
8
packages/now-python/test/fixtures/10-url-params-http-handler/custom.py
vendored
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
from http.server import BaseHTTPRequestHandler
|
||||||
|
|
||||||
|
class handler(BaseHTTPRequestHandler):
|
||||||
|
def do_GET(self):
|
||||||
|
self.send_response(200)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(str("path=").encode()+self.path.encode())
|
||||||
|
return
|
||||||
8
packages/now-python/test/fixtures/10-url-params-http-handler/index.py
vendored
Normal file
8
packages/now-python/test/fixtures/10-url-params-http-handler/index.py
vendored
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
from http.server import BaseHTTPRequestHandler
|
||||||
|
|
||||||
|
class handler(BaseHTTPRequestHandler):
|
||||||
|
def do_GET(self):
|
||||||
|
self.send_response(200)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(str("path=").encode()+self.path.encode())
|
||||||
|
return
|
||||||
13
packages/now-python/test/fixtures/10-url-params-http-handler/now.json
vendored
Normal file
13
packages/now-python/test/fixtures/10-url-params-http-handler/now.json
vendored
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"version": 2,
|
||||||
|
"builds": [
|
||||||
|
{ "src": "*.py", "use": "@now/python" }
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{ "src": "/another", "dest": "custom.py" }
|
||||||
|
],
|
||||||
|
"probes": [
|
||||||
|
{ "path": "/?hello=/", "mustContain": "path=/?hello=/" },
|
||||||
|
{ "path": "/another?hello=/", "mustContain": "path=/another?hello=/" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -88,7 +88,7 @@ exports.build = async ({
|
|||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Failed to detect a server running on port ${devPort}`,
|
`Failed to detect a server running on port ${devPort}.\nDetails: https://err.sh/zeit/now-builders/now-static-build-failed-to-detect-a-server`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,7 +101,7 @@ exports.build = async ({
|
|||||||
}
|
}
|
||||||
routes.push({
|
routes.push({
|
||||||
src: `${srcBase}/(.*)`,
|
src: `${srcBase}/(.*)`,
|
||||||
dest: `http://localhost:${devPort}${srcBase}/$1`,
|
dest: `http://localhost:${devPort}/$1`,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
if (meta.isDev) {
|
if (meta.isDev) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@now/static-build",
|
"name": "@now/static-build",
|
||||||
"version": "0.5.5",
|
"version": "0.5.7",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
|
|||||||
Reference in New Issue
Block a user