Compare commits

..

44 Commits

Author SHA1 Message Date
Igor Klopov
77d445af71 Publish
- @now/bash@0.1.1
 - @now/build-utils@0.4.32
 - @now/cgi@0.0.15
 - @now/go@0.2.12
 - @now/html-minifier@1.0.7
 - @now/lambda@0.4.9
 - @now/md@0.4.9
 - @now/mdx-deck@0.4.18
 - @now/next@0.0.84
 - @now/node-bridge@0.1.10
 - @now/node-server@0.4.26
 - @now/node@0.4.28
 - @now/optipng@0.4.8
 - @now/php-bridge@0.4.13
 - @now/php@0.4.13
 - @now/static-build@0.4.17
 - @now/wordpress@0.4.14
2019-01-20 01:14:09 +03:00
Igor Klopov
79251ad180 [lerna] trying to set the order of package to publish 2019-01-20 00:01:16 +03:00
Igor Klopov
a215dc9103 [node-server] update tests for latest ncc 2019-01-19 23:23:44 +03:00
Nathan Rajlich
ea7d8f0f6c Update @zeit/ncc to v0.11.0 (#172) 2019-01-19 19:30:20 +03:00
Igor Klopov
2232efc984 fix misleading 'running npm install' messages in logs 2019-01-15 00:54:24 +03:00
Igor Klopov
b64ce0f3c0 [now-node] fix test for content-length 2019-01-14 03:27:15 +03:00
Igor Klopov
74233d50ad now/node: bump ncc 2019-01-12 05:20:37 +03:00
Nathan Rajlich
8aebec9fc3 Publish
- @now/bash@0.1.0
2019-01-10 12:27:59 -08:00
Igor Klopov
54584b7763 [tests] support NOW_TOKEN env var 2019-01-09 20:44:20 +03:00
Igor Klopov
d163fcbd71 [now-node-server] test for default content-type 2019-01-09 20:16:58 +03:00
Tim Neutkens
04c2996c76 [now-next] Add test for monorepo 2019-01-09 15:07:54 +01:00
Igor Klopov
2b69b898ed Publish
- @now/build-utils@0.4.32-canary.6
 - @now/node-bridge@0.1.10-canary.2
 - @now/node-server@0.4.26-canary.7
 - @now/node@0.4.28-canary.6
2019-01-08 01:42:13 +03:00
Igor Klopov
846aa11d6a now/node-bridge: postpone rejecting, let express print the error 2019-01-08 01:22:01 +03:00
Nathan Rajlich
a314a74479 Publish
- @now/bash@0.0.4-canary.2
2019-01-04 18:34:29 -08:00
Nathan Rajlich
40f029a72c [now-bash] Pipe response to jq stdin and use long options
Otherwise `jq` errors out with "arguments too long" when the response
body base64 is too large.

The long options are just for maintainability.
2019-01-04 18:33:56 -08:00
Nathan Rajlich
493d8a778f [now-bash] Update static-binaries to v1.0.0 2019-01-04 18:33:56 -08:00
Nathan Rajlich
cb5dcb658f [now-bash] Remove final build tree output
It's not necessary and can be too noisey if the lambda has a lot of files.
2019-01-04 18:33:56 -08:00
Nathan Rajlich
d77287d07b [now-bash] Add .editorconfig file 2019-01-04 18:33:56 -08:00
Igor Klopov
61d66bd957 Publish
- @now/build-utils@0.4.32-canary.5
 - @now/next@0.0.84-canary.0
2019-01-03 16:52:48 +03:00
Igor Klopov
ae73df9e3c build-utils: account google cloud functions 2019-01-03 16:29:55 +03:00
Tim Neutkens
cb09ae5bbf Publish
- @now/next@0.0.83
2019-01-03 11:56:29 +01:00
Tim Neutkens
a28eeacdaa Publish
- @now/build-utils@0.4.32-canary.4
 - @now/cgi@0.0.15-canary.0
 - @now/go@0.2.12-canary.0
 - @now/html-minifier@1.0.7-canary.0
 - @now/lambda@0.4.9-canary.0
 - @now/md@0.4.9-canary.0
 - @now/mdx-deck@0.4.18-canary.1
 - @now/next@0.0.83-canary.0
 - @now/node-bridge@0.1.10-canary.1
 - @now/node-server@0.4.26-canary.6
 - @now/node@0.4.28-canary.5
 - @now/optipng@0.4.8-canary.0
 - @now/php-bridge@0.4.13-canary.1
 - @now/php@0.4.13-canary.2
 - @now/static-build@0.4.17-canary.0
 - @now/wordpress@0.4.14-canary.1
2019-01-02 17:48:58 +01:00
Tim Neutkens
dd9d46d555 Add Next.js serverless target instead of lambdas build (#150)
* Give test more time

* Implement legacy flag

* Move tests

* Add test for new builder

* Add serverless target flow

* Remove prepareCache

* Add semver check

* Upgrade for latest Next.js canary
2019-01-02 17:48:01 +01:00
Igor Klopov
4472331ee0 tests: use token factory endpoint 2019-01-01 03:17:27 +03:00
Tim Neutkens
ac69836b44 Publish
- @now/next@0.0.82
2018-12-27 13:28:44 +01:00
Steven
15949a4ab4 Add missing license to package.json (#147) 2018-12-27 13:13:49 +01:00
Igor Klopov
697ada9d73 now-node: tests for content-length 2018-12-24 07:51:18 +03:00
Igor Klopov
cafbe30fa3 Publish
- @now/next@0.0.82-canary.1
 - @now/node-bridge@0.1.10-canary.0
 - @now/node-server@0.4.26-canary.5
 - @now/node@0.4.28-canary.4
2018-12-24 07:21:38 +03:00
Igor Klopov
583ebcc526 node-bridge: set content-length in response if user sets it 2018-12-24 06:57:17 +03:00
Connor Davis
52d1bd410c Lock Next.js Version (#145)
* Update utils.js

* Update utils.test.js

* Update utils.test.js

* Temp Commit

* Revert Temp Commit
2018-12-23 11:19:37 +01:00
Nathan Rajlich
11d0753bc1 Publish
- @now/bash@0.0.4-canary.1
 - @now/build-utils@0.4.32-canary.3
2018-12-21 13:46:41 -08:00
Nathan Rajlich
538710fe56 [now-bash] make the curl calls to AWS API silent (#142)
* [now-bash] make the `curl` calls to AWS API silent

Also log the exit status of the `handler` function.

* Remove `echo Request-Id`
2018-12-21 13:44:57 -08:00
Nathan Rajlich
2828c89e8d [now-bash] add stdio: inherit to builder.sh script (#143)
So that the build logs of the bash script are sent to the deployment
logs.
2018-12-21 13:44:42 -08:00
Igor Klopov
e40b45a939 tests: Accept = application/json for all api calls 2018-12-21 03:07:33 +03:00
Igor Klopov
38ba8a36fc Publish
- @now/build-utils@0.4.32-canary.2
 - @now/wordpress@0.4.14-canary.0
2018-12-21 00:59:08 +03:00
Igor Klopov
0323c505a3 now/build-utils: fix cross-install inssue in yarn in-memory cache 2018-12-20 09:03:52 +03:00
Igor Klopov
17ee07f4f6 now/build-utils: add cross-install test 2018-12-20 08:53:29 +03:00
Igor Klopov
0a6ada77ac now/wordpress: support non-root placement (monorepo) 2018-12-19 14:38:42 +03:00
Igor Klopov
4d817dd67d update yarn.lock file to avoid 'lerna ERR! EUNCOMMIT' 2018-12-19 01:55:54 +03:00
Igor Klopov
9682a7cc0b now/wordpress: release 0.4.13 manually 2018-12-18 10:25:24 +03:00
Igor Klopov
3456f23b3e now/wordpress: make latest.zip the default 2018-12-18 10:24:16 +03:00
Igor Klopov
800ca2cb0e Publish
- @now/php@0.4.13-canary.1
 - @now/wordpress@0.4.13-canary.1
2018-12-18 10:09:34 +03:00
Igor Klopov
ba54b4d706 now/wordpress: don't test it yet 2018-12-18 10:09:16 +03:00
Igor Klopov
e9482d66a9 now/php: dummy changes 2018-12-18 10:00:49 +03:00
80 changed files with 988 additions and 317 deletions

View File

@@ -2,7 +2,24 @@
"npmClient": "yarn",
"useWorkspaces": true,
"packages": [
"packages/*"
"packages/now-build-utils",
"packages/now-node-bridge",
"packages/now-php-bridge",
"packages/now-bash",
"packages/now-cgi",
"packages/now-go",
"packages/now-html-minifier",
"packages/now-lambda",
"packages/now-md",
"packages/now-mdx-deck",
"packages/now-next",
"packages/now-node",
"packages/now-node-server",
"packages/now-optipng",
"packages/now-php",
"packages/now-python",
"packages/now-static-build",
"packages/now-wordpress"
],
"command": {
"publish": {

View File

@@ -0,0 +1,32 @@
root = true
[*]
indent_style = tab
indent_size = 4
tab_width = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.json.example,*.gyp,*.yml}]
indent_style = space
indent_size = 2
[*.py]
indent_style = space
indent_size = 4
[*.md]
trim_trailing_whitespace = false
# Ideal settings - some plugins might support these.
[*.js]
quote_type = single
[{*.c,*.cc,*.h,*.hh,*.cpp,*.hpp,*.m,*.mm,*.mpp,*.js,*.java,*.go,*.rs,*.php,*.ng,*.jsx,*.ts,*.d,*.cs,*.swift}]
curly_bracket_next_line = false
spaces_around_operators = true
spaces_around_brackets = outside
# close enough to 1TB
indent_brace_style = K&R

View File

@@ -38,12 +38,3 @@ if ! declare -f handler > /dev/null; then
echo "ERROR: A \`handler\` function must be defined in \"$ENTRYPOINT\"!" >&2
exit 1
fi
# Show a tree of the final lambda build
show_tree() {
import "static-binaries@0.0.6"
static_binaries tree
echo "Final lambda file tree:"
tree -a .
}
IMPORT_DEBUG= IMPORT_CACHE="$(mktemp -d)" show_tree

View File

@@ -38,6 +38,7 @@ exports.build = async ({ files, entrypoint, config }) => {
await execa(builderPath, [entrypoint], {
env,
cwd: workDir,
stdio: 'inherit',
});
const lambda = await createLambda({

View File

@@ -1,6 +1,6 @@
{
"name": "@now/bash",
"version": "0.0.4-canary.0",
"version": "0.1.1",
"description": "Now 2.0 builder for HTTP endpoints written in Bash",
"main": "index.js",
"author": "Nathan Rajlich <nate@zeit.co>",

View File

@@ -1,4 +1,4 @@
import "static-binaries@0.0.6"
import "static-binaries@1.0.0"
static_binaries jq
# These get reset upon each request
@@ -35,11 +35,10 @@ _lambda_runtime_next() {
# Get an event
local event
event="$(mktemp)"
_lambda_runtime_api invocation/next -D "$headers" | jq -r '.body' > "$event"
_lambda_runtime_api invocation/next -D "$headers" | jq --raw-output --monochrome-output '.body' > "$event"
local request_id
request_id="$(grep -Fi Lambda-Runtime-Aws-Request-Id "$headers" | tr -d '[:space:]' | cut -d: -f2)"
echo "Request-Id: $request_id" >&2
rm -f "$headers"
# Execute the handler function from the script
@@ -62,28 +61,25 @@ _lambda_runtime_next() {
if [ "$exit_code" -eq 0 ]; then
# Send the response
local response
response="$(jq -cnMr \
jq --raw-input --raw-output --compact-output --slurp --monochrome-output \
--arg statusCode "$(cat "$_STATUS_CODE")" \
--argjson headers "$(cat "$_HEADERS")" \
--arg body "$(base64 --wrap=0 < "$body")" \
'{statusCode:$statusCode|tonumber, headers:$headers, encoding:"base64", body:$body}')"
'{statusCode:$statusCode|tonumber, headers:$headers, encoding:"base64", body:.|@base64}' < "$body" \
| _lambda_runtime_api "invocation/$request_id/response" -X POST -d @- > /dev/null
rm -f "$body" "$_HEADERS"
_lambda_runtime_api "invocation/$request_id/response" -X POST -d "$response"
else
local error
error='{"exitCode":'"$exit_code"'}'
_lambda_runtime_api "invocation/$request_id/error" -X POST -d "$error"
echo "\`handler\` function return code: $exit_code"
_lambda_runtime_api "invocation/$request_id/error" -X POST -d @- > /dev/null <<< '{"exitCode":'"$exit_code"'}'
fi
}
_lambda_runtime_body() {
if [ "$(jq -r '.body | type' < "$1")" = "string" ]; then
if [ "$(jq -r '.encoding' < "$1")" = "base64" ]; then
jq -r '.body' < "$1" | base64 -d
if [ "$(jq --raw-output '.body | type' < "$1")" = "string" ]; then
if [ "$(jq --raw-output '.encoding' < "$1")" = "base64" ]; then
jq --raw-output '.body' < "$1" | base64 -d
else
# assume plain-text body
jq -r '.body' < "$1"
jq --raw-output '.body' < "$1"
fi
fi
}

View File

@@ -56,7 +56,7 @@ class FileRef {
const resp = await fetch(url);
if (!resp.ok) {
const error = new BailableError(
`${resp.status} ${resp.statusText}`,
`download: ${resp.status} ${resp.statusText} for ${url}`,
);
if (resp.status === 403) error.bail = true;
throw error;

View File

@@ -14,15 +14,15 @@ const cachePath = spawnSync(yarnPath, ['cache', 'dir'])
spawnSync(yarnPath, ['cache', 'clean']);
const vfs = new MemoryFileSystem();
function isOutsideCachePath(filename) {
function isInsideCachePath(filename) {
const relative = path.relative(cachePath, filename);
return relative.startsWith('..');
return !relative.startsWith('..');
}
const saveCreateWriteStream = fs.createWriteStream;
fs.createWriteStream = (...args) => {
const filename = args[0];
if (isOutsideCachePath(filename)) {
if (!isInsideCachePath(filename)) {
return saveCreateWriteStream.call(fs, ...args);
}
@@ -42,7 +42,7 @@ fs.createWriteStream = (...args) => {
const saveReadFile = fs.readFile;
fs.readFile = (...args) => {
const filename = args[0];
if (isOutsideCachePath(filename)) {
if (!isInsideCachePath(filename)) {
return saveReadFile.call(fs, ...args);
}
@@ -60,23 +60,34 @@ fs.readFile = (...args) => {
const saveCopyFile = fs.copyFile;
fs.copyFile = (...args) => {
const src = args[0];
if (isOutsideCachePath(src)) {
return saveCopyFile.call(fs, ...args);
}
const dest = args[1];
const callback = args[args.length - 1];
const buffer = vfs.readFileSync(src);
return fs.writeFile(dest, buffer, callback);
if (isInsideCachePath(src) && !isInsideCachePath(dest)) {
const buffer = vfs.readFileSync(src);
return fs.writeFile(dest, buffer, callback);
}
if (!isInsideCachePath(src) && isInsideCachePath(dest)) {
const buffer = fs.readFileSync(src);
vfs.mkdirpSync(path.dirname(dest));
fs.writeFileSync(dest, Buffer.alloc(0));
return vfs.writeFile(dest, buffer, callback);
}
return saveCopyFile.call(fs, ...args);
};
const saveWriteFile = fs.writeFile;
fs.writeFile = (...args) => {
const filename = args[0];
if (isOutsideCachePath(filename)) {
if (!isInsideCachePath(filename)) {
return saveWriteFile.call(fs, ...args);
}
vfs.mkdirpSync(path.dirname(filename));
fs.writeFileSync(filename, Buffer.alloc(0));
return vfs.writeFile(...args);
};

View File

@@ -1,8 +1,8 @@
const path = require('path');
const fs = require('fs-extra');
const dev = !process.env.AWS_EXECUTION_ENV;
const TMP_PATH = dev ? path.join(process.cwd(), 'tmp') : '/tmp';
const prod = process.env.AWS_EXECUTION_ENV || process.env.X_GOOGLE_CODE_LOCATION;
const TMP_PATH = prod ? '/tmp' : path.join(__dirname, 'tmp');
module.exports = async function getWritableDirectory() {
const name = Math.floor(Math.random() * 0x7fffffff).toString(16);

View File

@@ -3,6 +3,9 @@ const fs = require('fs-extra');
const path = require('path');
const { spawn } = require('child_process');
const prod = process.env.AWS_EXECUTION_ENV
|| process.env.X_GOOGLE_CODE_LOCATION;
function spawnAsync(command, args, cwd) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { stdio: 'inherit', cwd });
@@ -52,7 +55,7 @@ async function scanParentDirs(destPath, scriptName) {
return { hasScript, hasPackageLockJson };
}
async function runNpmInstall(destPath, args = []) {
async function installDependencies(destPath, args = []) {
assert(path.isAbsolute(destPath));
let commandArgs = args;
@@ -63,7 +66,7 @@ async function runNpmInstall(destPath, args = []) {
commandArgs = args.filter(a => a !== '--prefer-offline');
await spawnAsync('npm', ['install'].concat(commandArgs), destPath);
await spawnAsync('npm', ['cache', 'clean', '--force'], destPath);
} else if (process.env.AWS_EXECUTION_ENV) {
} else if (prod) {
console.log('using memory-fs for yarn cache');
await spawnAsync(
'node',
@@ -99,6 +102,7 @@ async function runPackageJsonScript(destPath, scriptName) {
module.exports = {
runShellScript,
runNpmInstall,
installDependencies,
runNpmInstall: installDependencies,
runPackageJsonScript,
};

View File

@@ -1,6 +1,7 @@
{
"name": "@now/build-utils",
"version": "0.4.32-canary.1",
"version": "0.4.32",
"license": "MIT",
"dependencies": {
"async-retry": "1.2.3",
"async-sema": "2.1.4",

View File

@@ -0,0 +1,5 @@
const cowsay = require('cowsay').say;
module.exports = (req, resp) => {
resp.end(cowsay({ text: 'cross-cow:RANDOMNESS_PLACEHOLDER' }));
};

View File

@@ -0,0 +1,5 @@
{
"dependencies": {
"lib": "../lib"
}
}

View File

@@ -0,0 +1,7 @@
{
"name": "lib",
"version": "0.0.1",
"dependencies": {
"cowsay": "*"
}
}

View File

@@ -0,0 +1,9 @@
{
"version": 2,
"builds": [
{ "src": "api/index.js", "use": "@now/node" }
],
"probes": [
{ "path": "/api/index.js", "mustContain": "cross-cow:RANDOMNESS_PLACEHOLDER" }
]
}

View File

@@ -1,6 +1,7 @@
{
"name": "@now/cgi",
"version": "0.0.14",
"version": "0.0.15",
"license": "MIT",
"scripts": {
"test": "best -I test/*.js",
"prepublish": "./build.sh"

View File

@@ -1,6 +1,7 @@
{
"name": "@now/go",
"version": "0.2.11",
"version": "0.2.12",
"license": "MIT",
"scripts": {
"test": "best -I test/*.js",
"prepublish": "./build.sh"

View File

@@ -1,6 +1,7 @@
{
"name": "@now/html-minifier",
"version": "1.0.6",
"version": "1.0.7",
"license": "MIT",
"dependencies": {
"html-minifier": "3.5.21"
},

View File

@@ -1,6 +1,7 @@
{
"name": "@now/lambda",
"version": "0.4.8",
"version": "0.4.9",
"license": "MIT",
"peerDependencies": {
"@now/build-utils": ">=0.0.1"
},

View File

@@ -1,6 +1,7 @@
{
"name": "@now/md",
"version": "0.4.8",
"version": "0.4.9",
"license": "MIT",
"dependencies": {
"rehype-document": "^2.2.0",
"rehype-format": "^2.3.0",

View File

@@ -15,7 +15,7 @@ exports.build = async ({ files, entrypoint, workPath }) => {
const packageJson = { dependencies: { 'mdx-deck': '1.7.15' } };
const packageJsonPath = path.join(workPath, 'package.json');
await writeFile(packageJsonPath, JSON.stringify(packageJson));
console.log('running npm install...');
console.log('installing dependencies...');
process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD = '1'; // TODO opts argument for runNpmInstall
await runNpmInstall(path.dirname(packageJsonPath), [
'--prod',

View File

@@ -1,6 +1,7 @@
{
"name": "@now/mdx-deck",
"version": "0.4.18-canary.0",
"version": "0.4.18",
"license": "MIT",
"peerDependencies": {
"@now/build-utils": ">=0.0.1"
},

View File

@@ -9,12 +9,13 @@ const {
runPackageJsonScript,
} = require('@now/build-utils/fs/run-user-scripts.js');
const glob = require('@now/build-utils/fs/glob.js');
const semver = require('semver');
const nextLegacyVersions = require('./legacy-versions');
const {
excludeFiles,
validateEntrypoint,
includeOnlyEntryDirectory,
moveEntryDirectoryToRoot,
excludeLockFiles,
normalizePackageJson,
excludeStaticDirectory,
onlyStaticDirectory,
@@ -88,113 +89,226 @@ exports.build = async ({ files, workPath, entrypoint }) => {
filesOnlyEntryDirectory,
entryDirectory,
);
const filesWithoutLockfiles = excludeLockFiles(filesWithEntryDirectoryRoot);
const filesWithoutStaticDirectory = excludeStaticDirectory(
filesWithoutLockfiles,
filesWithEntryDirectoryRoot,
);
const downloadedFiles = await download(filesWithoutStaticDirectory, workPath);
console.log('normalizing package.json');
const packageJson = normalizePackageJson(
await readPackageJson(downloadedFiles),
);
console.log('normalized package.json result: ', packageJson);
await writePackageJson(workPath, packageJson);
const pkg = await readPackageJson(downloadedFiles);
let nextVersion;
if (pkg.dependencies && pkg.dependencies.next) {
nextVersion = pkg.dependencies.next;
} else if (pkg.devDependencies && pkg.devDependencies.next) {
nextVersion = pkg.devDependencies.next;
}
if (!nextVersion) {
throw new Error(
'No Next.js version could be detected in "package.json". Make sure `"next"` is installed in "dependencies" or "devDependencies"',
);
}
const isLegacy = (() => {
// If version is using the dist-tag instead of a version range
if (nextVersion === 'canary' || nextVersion === 'latest') {
return false;
}
// If the version is an exact match with the legacy versions
if (nextLegacyVersions.indexOf(nextVersion) !== -1) {
return true;
}
const maxSatisfying = semver.maxSatisfying(nextLegacyVersions, nextVersion);
// When the version can't be matched with legacy versions, so it must be a newer version
if (maxSatisfying === null) {
return false;
}
return true;
})();
console.log(`MODE: ${isLegacy ? 'legacy' : 'serverless'}`);
if (isLegacy) {
try {
await unlink(path.join(workPath, 'yarn.lock'));
} catch (err) {
console.log('no yarn.lock removed');
}
try {
await unlink(path.join(workPath, 'package-lock.json'));
} catch (err) {
console.log('no package-lock.json removed');
}
console.warn(
"WARNING: your application is being deployed in @now/next's legacy mode.",
);
console.log('normalizing package.json');
const packageJson = normalizePackageJson(pkg);
console.log('normalized package.json result: ', packageJson);
await writePackageJson(workPath, packageJson);
} else if (!pkg.scripts || !pkg.scripts['now-build']) {
console.warn(
'WARNING: "now-build" script not found. Adding \'"now-build": "next build"\' to "package.json" automatically',
);
pkg.scripts = {
'now-build': 'next build',
...(pkg.scripts || {}),
};
console.log('normalized package.json result: ', pkg);
await writePackageJson(workPath, pkg);
}
if (process.env.NPM_AUTH_TOKEN) {
console.log('found NPM_AUTH_TOKEN in environment, creating .npmrc');
await writeNpmRc(workPath, process.env.NPM_AUTH_TOKEN);
}
console.log('running npm install...');
console.log('installing dependencies...');
await runNpmInstall(workPath, ['--prefer-offline']);
console.log('running user script...');
await runPackageJsonScript(workPath, 'now-build');
console.log('running npm install --production...');
await runNpmInstall(workPath, ['--prefer-offline', '--production']);
if (isLegacy) {
console.log('running npm install --production...');
await runNpmInstall(workPath, ['--prefer-offline', '--production']);
}
if (process.env.NPM_AUTH_TOKEN) {
await unlink(path.join(workPath, '.npmrc'));
}
const filesAfterBuild = await glob('**', workPath);
console.log('preparing lambda files...');
let buildId;
try {
buildId = await readFile(path.join(workPath, '.next', 'BUILD_ID'), 'utf8');
} catch (err) {
console.error(
'BUILD_ID not found in ".next". The "package.json" "build" script did not run "next build"',
);
throw new Error('Missing BUILD_ID');
}
const dotNextRootFiles = await glob('.next/*', workPath);
const dotNextServerRootFiles = await glob('.next/server/*', workPath);
const nodeModules = excludeFiles(
await glob('node_modules/**', workPath),
file => file.startsWith('node_modules/.cache'),
);
const launcherFiles = {
'now__bridge.js': new FileFsRef({ fsPath: require('@now/node-bridge') }),
};
const nextFiles = {
...nodeModules,
...dotNextRootFiles,
...dotNextServerRootFiles,
...launcherFiles,
};
if (filesAfterBuild['next.config.js']) {
nextFiles['next.config.js'] = filesAfterBuild['next.config.js'];
}
const pages = await glob(
'**/*.js',
path.join(workPath, '.next', 'server', 'static', buildId, 'pages'),
);
const launcherPath = path.join(__dirname, 'launcher.js');
const launcherData = await readFile(launcherPath, 'utf8');
const lambdas = {};
await Promise.all(
Object.keys(pages).map(async (page) => {
// These default pages don't have to be handled as they'd always 404
if (['_app.js', '_error.js', '_document.js'].includes(page)) {
return;
}
const pathname = page.replace(/\.js$/, '');
const launcher = launcherData.replace(
'PATHNAME_PLACEHOLDER',
`/${pathname.replace(/(^|\/)index$/, '')}`,
if (isLegacy) {
const filesAfterBuild = await glob('**', workPath);
console.log('preparing lambda files...');
let buildId;
try {
buildId = await readFile(
path.join(workPath, '.next', 'BUILD_ID'),
'utf8',
);
} catch (err) {
console.error(
'BUILD_ID not found in ".next". The "package.json" "build" script did not run "next build"',
);
throw new Error('Missing BUILD_ID');
}
const dotNextRootFiles = await glob('.next/*', workPath);
const dotNextServerRootFiles = await glob('.next/server/*', workPath);
const nodeModules = excludeFiles(
await glob('node_modules/**', workPath),
file => file.startsWith('node_modules/.cache'),
);
const launcherFiles = {
'now__bridge.js': new FileFsRef({ fsPath: require('@now/node-bridge') }),
};
const nextFiles = {
...nodeModules,
...dotNextRootFiles,
...dotNextServerRootFiles,
...launcherFiles,
};
if (filesAfterBuild['next.config.js']) {
nextFiles['next.config.js'] = filesAfterBuild['next.config.js'];
}
const pages = await glob(
'**/*.js',
path.join(workPath, '.next', 'server', 'static', buildId, 'pages'),
);
const launcherPath = path.join(__dirname, 'legacy-launcher.js');
const launcherData = await readFile(launcherPath, 'utf8');
const pageFiles = {
[`.next/server/static/${buildId}/pages/_document.js`]: filesAfterBuild[
`.next/server/static/${buildId}/pages/_document.js`
],
[`.next/server/static/${buildId}/pages/_app.js`]: filesAfterBuild[
`.next/server/static/${buildId}/pages/_app.js`
],
[`.next/server/static/${buildId}/pages/_error.js`]: filesAfterBuild[
`.next/server/static/${buildId}/pages/_error.js`
],
[`.next/server/static/${buildId}/pages/${page}`]: filesAfterBuild[
`.next/server/static/${buildId}/pages/${page}`
],
};
await Promise.all(
Object.keys(pages).map(async (page) => {
// These default pages don't have to be handled as they'd always 404
if (['_app.js', '_error.js', '_document.js'].includes(page)) {
return;
}
console.log(`Creating lambda for page: "${page}"...`);
lambdas[path.join(entryDirectory, pathname)] = await createLambda({
files: {
...nextFiles,
...pageFiles,
'now__launcher.js': new FileBlob({ data: launcher }),
},
handler: 'now__launcher.launcher',
runtime: 'nodejs8.10',
});
console.log(`Created lambda for page: "${page}"`);
}),
);
const pathname = page.replace(/\.js$/, '');
const launcher = launcherData.replace(
'PATHNAME_PLACEHOLDER',
`/${pathname.replace(/(^|\/)index$/, '')}`,
);
const pageFiles = {
[`.next/server/static/${buildId}/pages/_document.js`]: filesAfterBuild[
`.next/server/static/${buildId}/pages/_document.js`
],
[`.next/server/static/${buildId}/pages/_app.js`]: filesAfterBuild[
`.next/server/static/${buildId}/pages/_app.js`
],
[`.next/server/static/${buildId}/pages/_error.js`]: filesAfterBuild[
`.next/server/static/${buildId}/pages/_error.js`
],
[`.next/server/static/${buildId}/pages/${page}`]: filesAfterBuild[
`.next/server/static/${buildId}/pages/${page}`
],
};
console.log(`Creating lambda for page: "${page}"...`);
lambdas[path.join(entryDirectory, pathname)] = await createLambda({
files: {
...nextFiles,
...pageFiles,
'now__launcher.js': new FileBlob({ data: launcher }),
},
handler: 'now__launcher.launcher',
runtime: 'nodejs8.10',
});
console.log(`Created lambda for page: "${page}"`);
}),
);
} else {
console.log('preparing lambda files...');
const launcherFiles = {
'now__bridge.js': new FileFsRef({ fsPath: require('@now/node-bridge') }),
'now__launcher.js': new FileFsRef({
fsPath: path.join(__dirname, 'launcher.js'),
}),
};
const pages = await glob(
'**/*.js',
path.join(workPath, '.next', 'serverless', 'pages'),
);
const pageKeys = Object.keys(pages);
if (pageKeys.length === 0) {
throw new Error(
'No serverless pages were built. https://err.sh/zeit/now-builders/now-next-no-serverless-pages-built',
);
}
await Promise.all(
pageKeys.map(async (page) => {
// These default pages don't have to be handled as they'd always 404
if (['_app.js', '_error.js', '_document.js'].includes(page)) {
return;
}
const pathname = page.replace(/\.js$/, '');
console.log(`Creating lambda for page: "${page}"...`);
lambdas[path.join(entryDirectory, pathname)] = await createLambda({
files: {
...launcherFiles,
'page.js': pages[page],
},
handler: 'now__launcher.launcher',
runtime: 'nodejs8.10',
});
console.log(`Created lambda for page: "${page}"`);
}),
);
}
const nextStaticFiles = await glob(
'**',
@@ -208,7 +322,7 @@ exports.build = async ({ files, workPath, entrypoint }) => {
{},
);
const nextStaticDirectory = onlyStaticDirectory(filesWithoutLockfiles);
const nextStaticDirectory = onlyStaticDirectory(filesWithEntryDirectoryRoot);
const staticDirectoryFiles = Object.keys(nextStaticDirectory).reduce(
(mappedFiles, file) => ({
...mappedFiles,
@@ -219,41 +333,3 @@ exports.build = async ({ files, workPath, entrypoint }) => {
return { ...lambdas, ...staticFiles, ...staticDirectoryFiles };
};
exports.prepareCache = async ({
files, entrypoint, cachePath, workPath,
}) => {
console.log('downloading user files...');
const entryDirectory = path.dirname(entrypoint);
const filesOnlyEntryDirectory = includeOnlyEntryDirectory(
files,
entryDirectory,
);
const filesWithEntryDirectoryRoot = moveEntryDirectoryToRoot(
filesOnlyEntryDirectory,
entryDirectory,
);
const filesWithoutLockfiles = excludeLockFiles(filesWithEntryDirectoryRoot);
const filesWithoutStaticDirectory = excludeStaticDirectory(
filesWithoutLockfiles,
);
await download(filesWithoutStaticDirectory, workPath);
await download(await glob('.next/**', workPath), cachePath);
await download(await glob('node_modules/**', workPath), cachePath);
console.log('.next folder contents', await glob('.next/**', cachePath));
console.log(
'.cache folder contents',
await glob('node_modules/.cache/**', cachePath),
);
console.log('running npm install...');
await runNpmInstall(cachePath);
return {
...(await glob('.next/records.json', cachePath)),
...(await glob('.next/server/records.json', cachePath)),
...(await glob('node_modules/**', cachePath)),
...(await glob('yarn.lock', cachePath)),
};
};

View File

@@ -1,19 +1,13 @@
process.env.NODE_ENV = 'production';
const { Server } = require('http');
const next = require('next-server');
const url = require('url');
const { Bridge } = require('./now__bridge.js');
const page = require('./page.js');
const bridge = new Bridge();
bridge.port = 3000;
process.env.NODE_ENV = 'production';
const app = next({});
const server = new Server((req, res) => {
const parsedUrl = url.parse(req.url, true);
app.render(req, res, 'PATHNAME_PLACEHOLDER', parsedUrl.query, parsedUrl);
});
const server = new Server(page.render);
server.listen(bridge.port);
exports.launcher = bridge.launcher;

View File

@@ -0,0 +1,19 @@
const { Server } = require('http');
const next = require('next-server');
const url = require('url');
const { Bridge } = require('./now__bridge.js');
const bridge = new Bridge();
bridge.port = 3000;
process.env.NODE_ENV = 'production';
const app = next({});
const server = new Server((req, res) => {
const parsedUrl = url.parse(req.url, true);
app.render(req, res, 'PATHNAME_PLACEHOLDER', parsedUrl.query, parsedUrl);
});
server.listen(bridge.port);
exports.launcher = bridge.launcher;

View File

@@ -0,0 +1,336 @@
module.exports = [
'0.1.0',
'0.1.1',
'0.2.0',
'0.2.1',
'0.2.2',
'0.2.3',
'0.2.4',
'0.2.5',
'0.2.6',
'0.2.7',
'0.2.8',
'0.2.9',
'0.2.10',
'0.2.11',
'0.2.12',
'0.2.13',
'0.2.14',
'0.3.0',
'0.3.1',
'0.3.2',
'0.3.3',
'0.4.0',
'0.4.1',
'0.9.9',
'0.9.10',
'0.9.11',
'1.0.0',
'1.0.1',
'1.0.2',
'1.1.0',
'1.1.1',
'1.1.2',
'1.2.0',
'1.2.1',
'1.2.2',
'1.2.3',
'2.0.0-beta.0',
'2.0.0-beta.1',
'2.0.0-beta.2',
'2.0.0-beta.3',
'2.0.0-beta.4',
'2.0.0-beta.5',
'2.0.0-beta.6',
'2.0.0-beta.7',
'2.0.0-beta.8',
'2.0.0-beta.9',
'2.0.0-beta.10',
'2.0.0-beta.11',
'2.0.0-beta.12',
'2.0.0-beta.13',
'2.0.0-beta.14',
'2.0.0-beta.15',
'2.0.0-beta.16',
'2.0.0-beta.17',
'2.0.0-beta.18',
'2.0.0-beta.19',
'2.0.0-beta.20',
'2.0.0-beta.21',
'2.0.0-beta.22',
'2.0.0-beta.23',
'2.0.0-beta.24',
'2.0.0-beta.25',
'2.0.0-beta.26',
'2.0.0-beta.27',
'2.0.0-beta.28',
'2.0.0-beta.29',
'2.0.0-beta.30',
'2.0.0-beta.31',
'2.0.0-beta.32',
'2.0.0-beta.33',
'2.0.0-beta.34',
'2.0.0-beta.35',
'2.0.0-beta.36',
'2.0.0-beta.37',
'2.0.0-beta.38',
'2.0.0-beta.39',
'2.0.0-beta.40',
'2.0.0-beta.41',
'2.0.0-beta.42',
'2.0.0',
'2.0.1',
'2.1.0',
'2.1.1',
'2.2.0',
'2.3.0-alpha1',
'2.3.0',
'2.3.1',
'2.4.0',
'2.4.1',
'2.4.2',
'2.4.3',
'2.4.4',
'2.4.5',
'2.4.6',
'2.4.7',
'2.4.8',
'2.4.9',
'3.0.0-beta1',
'3.0.0-beta10',
'3.0.0-beta11',
'3.0.0-beta12',
'3.0.0-beta13',
'3.0.0-beta14',
'3.0.0-beta15',
'3.0.0-beta16',
'3.0.0-beta2',
'3.0.0-beta3',
'3.0.0-beta4',
'3.0.0-beta5',
'3.0.0-beta6',
'3.0.0-beta7',
'3.0.0-beta8',
'3.0.0-beta9',
'3.0.1-beta.1',
'3.0.1-beta.2',
'3.0.1-beta.3',
'3.0.1-beta.4',
'3.0.1-beta.5',
'3.0.1-beta.6',
'3.0.1-beta.7',
'3.0.1-beta.8',
'3.0.1-beta.9',
'3.0.1-beta.10',
'3.0.1-beta.11',
'3.0.1-beta.12',
'3.0.1-beta.13',
'3.0.1-beta.14',
'3.0.1-beta.15',
'3.0.1-beta.16',
'3.0.1-beta.17',
'3.0.1-beta.18',
'3.0.1-beta.19',
'3.0.1-beta.20',
'3.0.1-beta.21',
'3.0.1',
'3.0.2',
'3.0.3',
'3.0.4',
'3.0.5',
'3.0.6',
'3.1.0',
'3.2.0',
'3.2.1',
'3.2.2',
'3.2.3',
'4.0.0-beta.1',
'4.0.0-beta.2',
'4.0.0-beta.3',
'4.0.0-beta.4',
'4.0.0-beta.5',
'4.0.0-beta.6',
'4.0.0',
'4.0.1',
'4.0.2',
'4.0.3',
'4.0.4',
'4.0.5',
'4.1.0',
'4.1.1',
'4.1.2',
'4.1.3',
'4.1.4-canary.1',
'4.1.4-canary.2',
'4.1.4',
'4.2.0-canary.1',
'4.2.0-zones.2',
'4.2.0',
'4.2.1',
'4.2.2',
'4.2.3',
'4.3.0-canary.1',
'4.3.0-universal-alpha.1',
'4.3.0-universal-alpha.2',
'4.3.0-universal-alpha.3',
'4.3.0-universal-alpha.4',
'4.3.0-zones.1',
'4.4.0-canary.2',
'4.4.0-canary.3',
'5.0.0-universal-alpha.1',
'5.0.0-universal-alpha.2',
'5.0.0-universal-alpha.3',
'5.0.0-universal-alpha.4',
'5.0.0-universal-alpha.5',
'5.0.0-universal-alpha.6',
'5.0.0-universal-alpha.7',
'5.0.0-universal-alpha.8',
'5.0.0-universal-alpha.9',
'5.0.0-universal-alpha.10',
'5.0.0-universal-alpha.11',
'5.0.0-universal-alpha.12',
'5.0.0-universal-alpha.13',
'5.0.0-universal-alpha.14',
'5.0.0-universal-alpha.15',
'5.0.0-universal-alpha.16',
'5.0.0-universal-alpha.17',
'5.0.0-universal-alpha.18',
'5.0.0-universal-alpha.19',
'5.0.0-universal-alpha.20',
'5.0.0-universal-alpha.21',
'5.0.0-universal-alpha.22',
'5.0.0-universal-alpha.23',
'5.0.0-zones.1',
'5.0.0',
'5.0.1-canary.1',
'5.0.1-canary.2',
'5.0.1-canary.3',
'5.0.1-canary.4',
'5.0.1-canary.5',
'5.0.1-canary.6',
'5.0.1-canary.7',
'5.0.1-canary.8',
'5.0.1-canary.9',
'5.0.1-canary.10',
'5.0.1-canary.11',
'5.0.1-canary.12',
'5.0.1-canary.13',
'5.0.1-canary.14',
'5.0.1-canary.15',
'5.0.1-canary.16',
'5.0.1-canary.17',
'5.1.0',
'6.0.0-canary.1',
'6.0.0-canary.2',
'6.0.0-canary.3',
'6.0.0-canary.4',
'6.0.0-canary.5',
'6.0.0-canary.6',
'6.0.0-canary.7',
'6.0.0',
'6.0.1-canary.0',
'6.0.1-canary.1',
'6.0.1-canary.2',
'6.0.1',
'6.0.2-canary.0',
'6.0.2',
'6.0.3-canary.0',
'6.0.3-canary.1',
'6.0.3',
'6.0.4-canary.0',
'6.0.4-canary.1',
'6.0.4-canary.2',
'6.0.4-canary.3',
'6.0.4-canary.4',
'6.0.4-canary.5',
'6.0.4-canary.6',
'6.0.4-canary.7',
'6.0.4-canary.8',
'6.0.4-canary.9',
'6.1.0-canary.0',
'6.1.0',
'6.1.1-canary.0',
'6.1.1-canary.1',
'6.1.1-canary.2',
'6.1.1-canary.3',
'6.1.1-canary.4',
'6.1.1-canary.5',
'6.1.1',
'6.1.2',
'7.0.0-canary.0',
'7.0.0-canary.1',
'7.0.0-canary.2',
'7.0.0-canary.3',
'7.0.0-canary.4',
'7.0.0-canary.5',
'7.0.0-canary.6',
'7.0.0-canary.7',
'7.0.0-canary.8',
'7.0.0-canary.9',
'7.0.0-canary.10',
'7.0.0-canary.11',
'7.0.0-canary.12',
'7.0.0-canary.13',
'7.0.0-canary.14',
'7.0.0-canary.15',
'7.0.0-canary.16',
'7.0.0-canary.18',
'7.0.0-canary.19',
'7.0.0-canary.20',
'7.0.0',
'7.0.1-canary.0',
'7.0.1-canary.1',
'7.0.1-canary.2',
'7.0.1-canary.3',
'7.0.1-canary.4',
'7.0.1-canary.5',
'7.0.1-canary.6',
'7.0.1',
'7.0.2-alpha.1',
'7.0.2-alpha.3',
'7.0.2-canary.5',
'7.0.2-canary.6',
'7.0.2-canary.7',
'7.0.2-canary.8',
'7.0.2-canary.9',
'7.0.2-canary.10',
'7.0.2-canary.11',
'7.0.2-canary.12',
'7.0.2-canary.13',
'7.0.2-canary.14',
'7.0.2-canary.15',
'7.0.2-canary.16',
'7.0.2-canary.17',
'7.0.2-canary.18',
'7.0.2-canary.19',
'7.0.2-canary.20',
'7.0.2-canary.21',
'7.0.2-canary.22',
'7.0.2-canary.23',
'7.0.2-canary.24',
'7.0.2-canary.25',
'7.0.2-canary.26',
'7.0.2-canary.27',
'7.0.2-canary.28',
'7.0.2-canary.29',
'7.0.2-canary.31',
'7.0.2-canary.33',
'7.0.2-canary.34',
'7.0.2-canary.35',
'7.0.2-canary.36',
'7.0.2-canary.37',
'7.0.2-canary.38',
'7.0.2-canary.39',
'7.0.2-canary.40',
'7.0.2-canary.41',
'7.0.2-canary.42',
'7.0.2-canary.43',
'7.0.2-canary.44',
'7.0.2-canary.45',
'7.0.2-canary.46',
'7.0.2-canary.47',
'7.0.2-canary.48',
'7.0.2-canary.49',
'7.0.2-canary.50',
'7.0.2',
];

View File

@@ -1,10 +1,12 @@
{
"name": "@now/next",
"version": "0.0.82-canary.0",
"version": "0.0.84",
"license": "MIT",
"dependencies": {
"@now/node-bridge": "0.1.4",
"execa": "^1.0.0",
"fs.promised": "^3.0.0"
"fs.promised": "^3.0.0",
"semver": "^5.6.0"
},
"peerDependencies": {
"@now/build-utils": ">=0.0.1"

View File

@@ -153,12 +153,12 @@ function normalizePackageJson(defaultPackageJson = {}) {
'react-dom': 'latest',
...dependencies, // override react if user provided it
// next-server is forced to canary
'next-server': 'canary',
'next-server': 'v7.0.2-canary.49',
},
devDependencies: {
...devDependencies,
// next is forced to canary
next: 'canary',
next: 'v7.0.2-canary.49',
// next-server is a dependency here
'next-server': undefined,
},

View File

@@ -1,7 +1,10 @@
const http = require('http');
function normalizeEvent(event) {
let isApiGateway = true;
if (event.Action === 'Invoke') {
isApiGateway = false;
const invokeEvent = JSON.parse(event.body);
const {
@@ -21,10 +24,7 @@ function normalizeEvent(event) {
}
return {
method,
path,
headers,
body,
isApiGateway, method, path, headers, body,
};
}
@@ -33,10 +33,7 @@ function normalizeEvent(event) {
} = event;
return {
method,
path,
headers,
body,
isApiGateway, method, path, headers, body,
};
}
@@ -58,7 +55,7 @@ class Bridge {
}
const {
method, path, headers, body,
isApiGateway, method, path, headers, body,
} = normalizeEvent(event);
const opts = {
@@ -73,20 +70,35 @@ class Bridge {
const response = res;
const respBodyChunks = [];
response.on('data', chunk => respBodyChunks.push(Buffer.from(chunk)));
response.on('error', error => reject(error));
response.on('error', reject);
response.on('end', () => {
const bodyBuffer = Buffer.concat(respBodyChunks);
delete response.headers.connection;
delete response.headers['content-length'];
if (isApiGateway) {
delete response.headers['content-length'];
} else
if (response.headers['content-length']) {
response.headers['content-length'] = bodyBuffer.length;
}
resolve({
statusCode: response.statusCode,
headers: response.headers,
body: Buffer.concat(respBodyChunks).toString('base64'),
body: bodyBuffer.toString('base64'),
encoding: 'base64',
});
});
});
req.on('error', (error) => {
setTimeout(() => {
// this lets express print the true error of why the connection was closed.
// it is probably 'Cannot set headers after they are sent to the client'
reject(error);
}, 2);
});
if (body) req.write(body);
req.end();
});

View File

@@ -1,6 +1,7 @@
{
"name": "@now/node-bridge",
"version": "0.1.9",
"version": "0.1.10",
"license": "MIT",
"peerDependencies": {
"@now/build-utils": ">=0.0.1"
}

View File

@@ -37,7 +37,7 @@ async function downloadInstallAndBundle(
console.log('downloading user files...');
const downloadedFiles = await download(files, userPath);
console.log('running npm install for user...');
console.log('installing dependencies for user\'s code...');
const entrypointFsDirname = path.join(userPath, path.dirname(entrypoint));
await runNpmInstall(entrypointFsDirname, npmArguments);
@@ -47,7 +47,7 @@ async function downloadInstallAndBundle(
'package.json': new FileBlob({
data: JSON.stringify({
dependencies: {
'@zeit/ncc': '0.6.0',
'@zeit/ncc': '0.11.0',
},
}),
}),
@@ -55,7 +55,7 @@ async function downloadInstallAndBundle(
nccPath,
);
console.log('running npm install for ncc...');
console.log('installing dependencies for ncc...');
await runNpmInstall(nccPath, npmArguments);
return [downloadedFiles, userPath, nccPath, entrypointFsDirname];
}
@@ -71,7 +71,8 @@ async function compile(workNccPath, downloadedFiles, entrypoint) {
preparedFiles[path.join('user', entrypoint)] = blob;
// eslint-disable-next-line no-restricted-syntax
for (const assetName of Object.keys(assets)) {
const blob2 = new FileBlob({ data: assets[assetName] });
const { source: data, permissions: mode } = assets[assetName];
const blob2 = new FileBlob({ data, mode });
preparedFiles[
path.join('user', path.dirname(entrypoint), assetName)
] = blob2;

View File

@@ -1,8 +1,9 @@
{
"name": "@now/node-server",
"version": "0.4.26-canary.4",
"version": "0.4.26",
"license": "MIT",
"dependencies": {
"@now/node-bridge": "^0.1.9",
"@now/node-bridge": "^0.1.10",
"fs-extra": "7.0.1"
},
"peerDependencies": {

View File

@@ -0,0 +1,7 @@
const http = require('http');
const server = http.createServer((req, resp) => {
resp.end('RANDOMNESS_PLACEHOLDER');
});
server.listen();

View File

@@ -0,0 +1,6 @@
{
"version": 2,
"builds": [
{ "src": "index.js", "use": "@now/node-server" }
]
}

View File

@@ -0,0 +1,7 @@
const assert = require('assert');
module.exports = async ({ deploymentUrl, fetch, randomness }) => {
const resp = await fetch(`https://${deploymentUrl}/`);
assert.equal(resp.headers.get('content-type'), null);
assert.equal(await resp.text(), randomness);
};

View File

@@ -2,7 +2,7 @@ const http = require('http');
const isBundled = require('./is-bundled.js');
const server = http.createServer((req, resp) => {
resp.end(isBundled() ? 'RANDOMNESS_PLACEHOLDER:with-bundle' : '');
resp.end(isBundled() ? 'RANDOMNESS_PLACEHOLDER:with-bundle' : 'WITHOUT-BUNDLE-THAT-IS-WRONG');
});
server.listen();

View File

@@ -1,3 +1,4 @@
const path = require('path');
module.exports = () => path.basename(__filename) === 'index.js';
// eslint-disable-next-line no-eval
module.exports = () => path.basename(eval('__filename')) === 'index.js';

View File

@@ -2,7 +2,7 @@ const http = require('http');
const isBundled = require('./is-bundled.js');
const server = http.createServer((req, resp) => {
resp.end(isBundled() ? '' : 'RANDOMNESS_PLACEHOLDER:without-bundle');
resp.end(isBundled() ? 'WITH-BUNDLE-THAT-IS-WRONG' : 'RANDOMNESS_PLACEHOLDER:without-bundle');
});
server.listen();

View File

@@ -1,3 +1,4 @@
const path = require('path');
module.exports = () => path.basename(__filename) === 'index.js';
// eslint-disable-next-line no-eval
module.exports = () => path.basename(eval('__filename')) === 'index.js';

View File

@@ -35,7 +35,7 @@ async function downloadInstallAndBundle(
console.log('downloading user files...');
const downloadedFiles = await download(files, userPath);
console.log('running npm install for user...');
console.log('installing dependencies for user\'s code...');
const entrypointFsDirname = path.join(userPath, path.dirname(entrypoint));
await runNpmInstall(entrypointFsDirname, npmArguments);
@@ -45,7 +45,7 @@ async function downloadInstallAndBundle(
'package.json': new FileBlob({
data: JSON.stringify({
dependencies: {
'@zeit/ncc': '0.6.0',
'@zeit/ncc': '0.11.0',
},
}),
}),
@@ -53,7 +53,7 @@ async function downloadInstallAndBundle(
nccPath,
);
console.log('running npm install for ncc...');
console.log('installing dependencies for ncc...');
await runNpmInstall(nccPath, npmArguments);
return [downloadedFiles, nccPath, entrypointFsDirname];
}
@@ -69,7 +69,8 @@ async function compile(workNccPath, downloadedFiles, entrypoint) {
preparedFiles[path.join('user', entrypoint)] = blob;
// eslint-disable-next-line no-restricted-syntax
for (const assetName of Object.keys(assets)) {
const blob2 = new FileBlob({ data: assets[assetName] });
const { source: data, permissions: mode } = assets[assetName];
const blob2 = new FileBlob({ data, mode });
preparedFiles[
path.join('user', path.dirname(entrypoint), assetName)
] = blob2;

View File

@@ -1,8 +1,9 @@
{
"name": "@now/node",
"version": "0.4.28-canary.3",
"version": "0.4.28",
"license": "MIT",
"dependencies": {
"@now/node-bridge": "^0.1.9",
"@now/node-bridge": "^0.1.10",
"fs-extra": "7.0.1"
},
"peerDependencies": {

View File

@@ -0,0 +1,8 @@
{
"version": 2,
"builds": [
{ "src": "test1.js", "use": "@now/node" },
{ "src": "test2.js", "use": "@now/node" },
{ "src": "test3.js", "use": "@now/node" }
]
}

View File

@@ -0,0 +1,31 @@
const assert = require('assert');
async function test1({ deploymentUrl, fetch, randomness }) {
const bodyMustBe = `${randomness}:content-length`;
const resp = await fetch(`https://${deploymentUrl}/test1.js`);
assert.equal(resp.status, 401);
assert.equal(await resp.text(), bodyMustBe);
assert.equal(resp.headers.get('content-length'), bodyMustBe.length);
}
async function test2({ deploymentUrl, fetch }) {
const bodyMustBe = '';
const resp = await fetch(`https://${deploymentUrl}/test2.js`);
assert.equal(resp.status, 401);
assert.equal(await resp.text(), bodyMustBe);
assert.equal(resp.headers.get('content-length'), bodyMustBe.length);
}
async function test3({ deploymentUrl, fetch, randomness }) {
const bodyMustBe = `${randomness}:content-length`;
const resp = await fetch(`https://${deploymentUrl}/test3.js`);
assert.equal(resp.status, 401);
assert.equal(await resp.text(), bodyMustBe);
assert.equal(resp.headers.get('content-length'), null);
}
module.exports = async ({ deploymentUrl, fetch, randomness }) => {
await test1({ deploymentUrl, fetch, randomness });
await test2({ deploymentUrl, fetch, randomness });
await test3({ deploymentUrl, fetch, randomness });
};

View File

@@ -0,0 +1,4 @@
module.exports = (_, resp) => {
resp.writeHead(401, { 'content-length': 4242 });
resp.end(`${process.env.RANDOMNESS_ENV_VAR}:content-length`);
};

View File

@@ -0,0 +1,4 @@
module.exports = (_, resp) => {
resp.writeHead(401, { 'content-length': 2 });
resp.end();
};

View File

@@ -0,0 +1,4 @@
module.exports = (_, resp) => {
resp.writeHead(401);
resp.end(`${process.env.RANDOMNESS_ENV_VAR}:content-length`);
};

View File

@@ -1,6 +1,7 @@
{
"name": "@now/optipng",
"version": "0.4.7",
"version": "0.4.8",
"license": "MIT",
"dependencies": {
"multipipe": "2.0.3",
"optipng": "1.1.0"

View File

@@ -1,6 +1,7 @@
{
"name": "@now/php-bridge",
"version": "0.4.13-canary.0",
"version": "0.4.13",
"license": "MIT",
"dependencies": {
"fastcgi-client": "0.0.1"
},

View File

@@ -12,7 +12,7 @@ exports.build = async ({ files, entrypoint }) => {
const userFiles = rename(files, name => path.join('user', name));
const bridgeFiles = await getFiles();
// TODO
// TODO config.extensions. OR php.ini from user
delete bridgeFiles['native/modules/mysqli.so'];
delete bridgeFiles['native/modules/libmysqlclient.so.16'];

View File

@@ -1,8 +1,9 @@
{
"name": "@now/php",
"version": "0.4.13-canary.0",
"version": "0.4.13",
"license": "MIT",
"dependencies": {
"@now/php-bridge": "^0.4.13-canary.0"
"@now/php-bridge": "^0.4.13"
},
"peerDependencies": {
"@now/build-utils": ">=0.0.1"

View File

@@ -1,6 +1,7 @@
{
"name": "@now/static-build",
"version": "0.4.16",
"version": "0.4.17",
"license": "MIT",
"peerDependencies": {
"@now/build-utils": ">=0.0.1"
},

View File

@@ -24,7 +24,7 @@ async function readReleaseUrl(releaseUrl) {
const prefixRegexp = /^wordpress\//;
function decompressBuffer(buffer) {
function decompressBuffer(buffer, mountpoint) {
return new Promise((resolve, reject) => {
const files = {};
@@ -52,7 +52,8 @@ function decompressBuffer(buffer) {
streamToBuffer(readStream).then((data) => {
assert(prefixRegexp.test(fileName), fileName);
const fileName2 = fileName.replace(prefixRegexp, '');
files[fileName2] = new FileBlob({ data });
const fileName3 = path.join(mountpoint, fileName2);
files[fileName3] = new FileBlob({ data });
zipfile.readEntry();
}).catch(reject);
});
@@ -68,22 +69,22 @@ const staticRegexps = [
];
exports.build = async ({ files, entrypoint, config }) => {
if (entrypoint !== 'wp-config.php') {
throw new Error(`Entrypoint must be "wp-config.php". Currently it is ${entrypoint}`);
}
if (!config.releaseUrl) {
throw new Error('Config must contain a "releaseUrl" for wordpress.zip');
if (path.basename(entrypoint) !== 'wp-config.php') {
throw new Error(`Entrypoint file name must be "wp-config.php". Currently it is ${entrypoint}`);
}
console.log('downloading release url...');
const releaseBuffer = await readReleaseUrl(config.releaseUrl);
const { releaseUrl = 'https://wordpress.org/latest.zip' } = config;
console.log(`downloading release url ${releaseUrl}...`);
const releaseBuffer = await readReleaseUrl(releaseUrl);
console.log('decompressing release url...');
const releaseFiles = await decompressBuffer(releaseBuffer);
const mountpoint = path.dirname(entrypoint);
const releaseFiles = await decompressBuffer(releaseBuffer, mountpoint);
const mergedFiles = { ...releaseFiles, ...files };
if (config.patchForPersistentConnections) {
const wpDbPhp = mergedFiles['wp-includes/wp-db.php'];
wpDbPhp.data = wpDbPhp.data.toString()
const wpDbPhp = path.join(mountpoint, 'wp-includes/wp-db.php');
const wpDbPhpBlob = mergedFiles[wpDbPhp];
wpDbPhpBlob.data = wpDbPhpBlob.data.toString()
.replace(/mysqli_real_connect\( \$this->dbh, \$host,/g,
'mysqli_real_connect( $this->dbh, \'p:\' . $host,');
}
@@ -106,5 +107,6 @@ exports.build = async ({ files, entrypoint, config }) => {
runtime: 'nodejs8.10',
});
return { ...staticFiles, ...{ 'index.php': lambda } };
const indexPhp = path.join(mountpoint, 'index.php');
return { ...staticFiles, ...{ [indexPhp]: lambda } };
};

View File

@@ -1,8 +1,9 @@
{
"name": "@now/wordpress",
"version": "0.4.13-canary.0",
"version": "0.4.14",
"license": "MIT",
"dependencies": {
"@now/php-bridge": "^0.4.13-canary.0",
"@now/php-bridge": "^0.4.13",
"node-fetch": "2.3.0",
"yauzl": "2.10.0"
},

View File

@@ -1,33 +0,0 @@
/* global beforeAll, expect, it, jest */
const fs = require('fs');
const path = require('path');
const {
packAndDeploy,
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
const buildUtilsUrl = '@canary';
let builderUrl;
beforeAll(async () => {
const builderPath = path.resolve(__dirname, '..');
builderUrl = await packAndDeploy(builderPath);
console.log('builderUrl', builderUrl);
});
const fixturesPath = path.resolve(__dirname, 'fixtures');
// eslint-disable-next-line no-restricted-syntax
for (const fixture of fs.readdirSync(fixturesPath)) {
// eslint-disable-next-line no-loop-func
it(`should build ${fixture}`, async () => {
await expect(
testDeployment(
{ builderUrl, buildUtilsUrl },
path.join(fixturesPath, fixture),
),
).resolves.toBeDefined();
});
}

View File

@@ -1,5 +0,0 @@
{
"dependencies": {
"isomorphic-unfetch": "latest"
}
}

View File

@@ -2,7 +2,6 @@
const path = require('path');
const runBuildLambda = require('../../lib/run-build-lambda');
const TWO_MINUTES = 120000;
const FOUR_MINUTES = 240000;
it(
@@ -18,14 +17,46 @@ it(
expect(hasUnderScoreAppStaticFile).toBeTruthy();
expect(hasUnderScoreErrorStaticFile).toBeTruthy();
},
TWO_MINUTES,
FOUR_MINUTES,
);
it(
'Should build the custom dependency test',
'Should build the monorepo example',
async () => {
const { buildResult } = await runBuildLambda(
path.join(__dirname, 'custom-dependency'),
path.join(__dirname, 'monorepo'),
);
expect(buildResult['www/index']).toBeDefined();
const filePaths = Object.keys(buildResult);
const hasUnderScoreAppStaticFile = filePaths.some(filePath => filePath.match(/static.*\/pages\/_app\.js$/));
const hasUnderScoreErrorStaticFile = filePaths.some(filePath => filePath.match(/static.*\/pages\/_error\.js$/));
expect(hasUnderScoreAppStaticFile).toBeTruthy();
expect(hasUnderScoreErrorStaticFile).toBeTruthy();
},
FOUR_MINUTES,
);
it(
'Should build the legacy standard example',
async () => {
const { buildResult } = await runBuildLambda(
path.join(__dirname, 'legacy-standard'),
);
expect(buildResult.index).toBeDefined();
const filePaths = Object.keys(buildResult);
const hasUnderScoreAppStaticFile = filePaths.some(filePath => filePath.match(/static.*\/pages\/_app\.js$/));
const hasUnderScoreErrorStaticFile = filePaths.some(filePath => filePath.match(/static.*\/pages\/_error\.js$/));
expect(hasUnderScoreAppStaticFile).toBeTruthy();
expect(hasUnderScoreErrorStaticFile).toBeTruthy();
},
FOUR_MINUTES,
);
it(
'Should build the legacy custom dependency test',
async () => {
const { buildResult } = await runBuildLambda(
path.join(__dirname, 'legacy-custom-dependency'),
);
expect(buildResult.index).toBeDefined();
},
@@ -37,6 +68,7 @@ it('Should throw when package.json or next.config.js is not the "src"', async ()
await runBuildLambda(
path.join(__dirname, 'no-package-json-and-next-config'),
);
throw new Error('did not throw');
} catch (err) {
expect(err.message).toMatch(/package\.json/);
}
@@ -46,7 +78,7 @@ it(
'Should build the static-files test',
async () => {
const { buildResult } = await runBuildLambda(
path.join(__dirname, 'static-files'),
path.join(__dirname, 'legacy-static-files'),
);
expect(buildResult['static/test.txt']).toBeDefined();
},

View File

@@ -0,0 +1,6 @@
{
"dependencies": {
"isomorphic-unfetch": "latest",
"next": "7.0.0"
}
}

View File

@@ -0,0 +1,5 @@
{
"dependencies": {
"next": "^7.0.2"
}
}

View File

@@ -0,0 +1 @@
module.exports = {};

View File

@@ -0,0 +1,6 @@
{
"version": 2,
"builds": [
{"src": "next.config.js", "use": "@now/next"}
]
}

View File

@@ -0,0 +1,5 @@
{
"dependencies": {
"next": "7.0.2"
}
}

View File

@@ -0,0 +1 @@
export default () => 'Index page';

View File

@@ -0,0 +1,6 @@
{
"version": 2,
"builds": [
{ "src": "www/package.json", "use": "@now/next" }
]
}

View File

@@ -0,0 +1,3 @@
module.exports = {
target: 'serverless',
};

View File

@@ -0,0 +1,11 @@
{
"name": "monorepo",
"dependencies": {
"next": "^8.0.0-canary.2",
"react": "^16.7.0",
"react-dom": "^16.7.0"
},
"scripts": {
"now-build": "next build"
}
}

View File

@@ -0,0 +1 @@
export default () => 'Index page';

View File

@@ -1 +1,3 @@
module.exports = {};
module.exports = {
target: 'serverless',
};

View File

@@ -0,0 +1,7 @@
{
"dependencies": {
"next": "canary",
"react": "latest",
"react-dom": "latest"
}
}

View File

@@ -1 +1 @@
export default () => 'Index page';
export default () => 'Hello World!';

View File

@@ -107,21 +107,25 @@ async function deploymentGet (deploymentId) {
return await resp.json();
}
let token;
async function fetchWithAuth (url, opts = {}) {
if (!opts.headers) opts.headers = {};
if (!opts.headers.Authorization) {
let token;
if (process.env.NOW_AUTH_TOKENS) {
const tokens = process.env.NOW_AUTH_TOKENS.split(',');
if (process.env.CIRCLE_BUILD_NUM) {
token = tokens[Number(process.env.CIRCLE_BUILD_NUM) % tokens.length];
if (!token) {
const { NOW_TOKEN, NOW_TOKEN_FACTORY_URL } = process.env;
if (NOW_TOKEN) {
token = NOW_TOKEN;
} else
if (NOW_TOKEN_FACTORY_URL) {
const resp = await fetch(NOW_TOKEN_FACTORY_URL);
token = (await resp.json()).token;
} else {
token = tokens[Math.floor(Math.random() * tokens.length)];
const authJsonPath = path.join(homedir(), '.now/auth.json');
token = require(authJsonPath).token;
}
} else {
const authJsonPath = path.join(homedir(), '.now/auth.json');
token = require(authJsonPath).token;
}
opts.headers.Authorization = `Bearer ${token}`;
@@ -140,6 +144,12 @@ async function fetchApi (url, opts = {}) {
if (body) console.log(encodeURIComponent(body).slice(0, 80));
}
if (!opts.headers) opts.headers = {};
if (!opts.headers.Accept) {
opts.headers.Accept = 'application/json';
}
return await fetch(urlWithHost, opts);
}

View File

@@ -94,7 +94,7 @@ async function testDeployment ({ builderUrl, buildUtilsUrl }, fixturePath) {
const probeJsFullPath = path.resolve(fixturePath, 'probe.js');
if (await fs.exists(probeJsFullPath)) {
await require(probeJsFullPath)({ deploymentUrl, fetch });
await require(probeJsFullPath)({ deploymentUrl, fetch, randomness });
}
return { deploymentId, deploymentUrl };
@@ -112,11 +112,9 @@ async function nowDeployIndexTgz (file) {
async function fetchDeploymentUrl (url, opts) {
for (let i = 0; i < 500; i += 1) {
const resp = await fetch(url, opts);
if (resp.status === 200) {
const text = await resp.text();
if (!text.includes('Join Free')) {
return text;
}
const text = await resp.text();
if (text && !text.includes('Join Free')) {
return text;
}
await new Promise((r) => setTimeout(r, 1000));

View File

@@ -208,12 +208,12 @@ describe('normalizePackageJson', () => {
const result = normalizePackageJson();
expect(result).toEqual({
dependencies: {
'next-server': 'canary',
'next-server': 'v7.0.2-canary.49',
react: 'latest',
'react-dom': 'latest',
},
devDependencies: {
next: 'canary',
next: 'v7.0.2-canary.49',
},
scripts: {
'now-build':
@@ -225,12 +225,12 @@ describe('normalizePackageJson', () => {
it('should work with a package.json being supplied', () => {
const defaultPackage = {
dependencies: {
'next-server': 'canary',
'next-server': 'v7.0.2-canary.49',
react: 'latest',
'react-dom': 'latest',
},
devDependencies: {
next: 'canary',
next: 'v7.0.2-canary.49',
},
scripts: {
'now-build': 'next build',
@@ -239,12 +239,12 @@ describe('normalizePackageJson', () => {
const result = normalizePackageJson(defaultPackage);
expect(result).toEqual({
dependencies: {
'next-server': 'canary',
'next-server': 'v7.0.2-canary.49',
react: 'latest',
'react-dom': 'latest',
},
devDependencies: {
next: 'canary',
next: 'v7.0.2-canary.49',
},
scripts: {
'now-build':
@@ -264,12 +264,12 @@ describe('normalizePackageJson', () => {
const result = normalizePackageJson(defaultPackage);
expect(result).toEqual({
dependencies: {
'next-server': 'canary',
'next-server': 'v7.0.2-canary.49',
react: 'latest',
'react-dom': 'latest',
},
devDependencies: {
next: 'canary',
next: 'v7.0.2-canary.49',
},
scripts: {
'now-build':
@@ -289,12 +289,12 @@ describe('normalizePackageJson', () => {
const result = normalizePackageJson(defaultPackage);
expect(result).toEqual({
dependencies: {
'next-server': 'canary',
'next-server': 'v7.0.2-canary.49',
react: 'latest',
'react-dom': 'latest',
},
devDependencies: {
next: 'canary',
next: 'v7.0.2-canary.49',
},
scripts: {
'now-build':
@@ -314,12 +314,12 @@ describe('normalizePackageJson', () => {
const result = normalizePackageJson(defaultPackage);
expect(result).toEqual({
dependencies: {
'next-server': 'canary',
'next-server': 'v7.0.2-canary.49',
react: 'latest',
'react-dom': 'latest',
},
devDependencies: {
next: 'canary',
next: 'v7.0.2-canary.49',
},
scripts: {
'now-build':
@@ -403,7 +403,7 @@ describe('normalizePackageJson', () => {
'stylelint-config-recommended': '^2.1.0',
'stylelint-config-styled-components': '^0.1.1',
'stylelint-processor-styled-components': '^1.5.1',
next: 'canary',
next: 'v7.0.2-canary.49',
'next-server': undefined,
xo: '^0.23.0',
consola: '^2.2.6',
@@ -411,7 +411,7 @@ describe('normalizePackageJson', () => {
'styled-components': '^4.1.1',
},
dependencies: {
'next-server': 'canary',
'next-server': 'v7.0.2-canary.49',
react: '^16.6.3',
'react-dom': '^16.6.3',
},

View File

@@ -20,6 +20,7 @@
"./packages/now-next"
],
"exclude": [
"./packages/now-next/launcher.js"
"./packages/now-next/launcher.js",
"./packages/now-next/legacy-launcher.js"
]
}

View File

@@ -2839,6 +2839,11 @@ fast-stream-to-buffer@1.0.0:
dependencies:
end-of-stream "^1.4.1"
fastcgi-client@0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/fastcgi-client/-/fastcgi-client-0.0.1.tgz#1046d42ff2cee2a9ac03fea04695b3ef7311861c"
integrity sha1-EEbUL/LO4qmsA/6gRpWz73MRhhw=
fb-watchman@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.0.tgz#54e9abf7dfa2f26cd9b1636c588c1afc05de5d58"
@@ -5712,7 +5717,7 @@ node-fetch@2.2.0:
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.2.0.tgz#4ee79bde909262f9775f731e3656d0db55ced5b5"
integrity sha512-OayFWziIxiHY8bCUyLX6sTpDH8Jsbp4FfYd1j1f7vZyfgkcOnAyM4oQR16f8a0s7Gl/viMGRey8eScYk4V4EZA==
node-fetch@^2.2.0, node-fetch@^2.2.1, node-fetch@^2.3.0:
node-fetch@2.3.0, node-fetch@^2.2.0, node-fetch@^2.2.1, node-fetch@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.3.0.tgz#1a1d940bbfb916a1d3e0219f037e89e71f8c5fa5"
integrity sha512-MOd8pV3fxENbryESLgVIeaGKrdl+uaYhCSSVkjeOb/31/njTpcis5aWfdqgNlHIrKOLRbMnfPINPOML2CIFeXA==
@@ -8593,7 +8598,7 @@ yargs@^12.0.1:
y18n "^3.2.1 || ^4.0.0"
yargs-parser "^11.1.1"
yauzl@^2.2.1:
yauzl@2.10.0, yauzl@^2.2.1:
version "2.10.0"
resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9"
integrity sha1-x+sXyT4RLLEIb6bY5R+wZnt5pfk=