Compare commits

..

32 Commits

Author SHA1 Message Date
Connor Davis
dd9017475c Publish
- @now/lambda@0.4.10-canary.1
 - @now/md@0.4.10-canary.1
 - @now/mdx-deck@0.4.19-canary.1
 - @now/next@0.0.85-canary.4
 - @now/node-server@0.4.27-canary.3
 - @now/node@0.4.29-canary.3
 - @now/php@0.4.14-canary.1
 - @now/static-build@0.4.19-canary.1
2019-02-12 21:41:52 -06:00
Connor Davis
031499014f Give tests 4 minutes instead of 2 2019-02-12 21:40:51 -06:00
Connor Davis
2a68d2a2ad Publish
- @now/build-utils@0.4.35-canary.1
 - @now/next@0.0.85-canary.3
 - @now/rust@0.0.3-canary.0
2019-02-12 21:00:19 -06:00
Connor Davis
31299fae6e Force canary bump in @now/next 2019-02-12 20:59:42 -06:00
Connor Davis
4bac0db379 fix @now/build-utils publishing tmp/ 2019-02-12 20:35:12 -06:00
Connor Davis
95e7d459d3 Increase timeout on now-build-utils 2019-02-12 19:39:15 -06:00
Antonio Nuno Monteiro
dd120b8d20 [now-rist] Implement simpler API for *.rs entrypoints (#210) 2019-02-12 13:21:03 -08:00
Mike Engel
b6975676e5 [now-rust] Import Deserialize traits behind de and ser (#203)
See https://github.com/serde-rs/serde/issues/1441
2019-02-12 13:16:14 -08:00
Igor Klopov
a7951dae81 [tests] produce public deployments 2019-02-12 22:07:10 +03:00
Connor Davis
b0c918f7fb Publish
- @now/next@0.0.85-canary.2
2019-02-11 20:28:52 -06:00
Connor Davis
df54dc7dc9 Download Entire Directory when Building now-next (#200) 2019-02-11 20:23:26 -06:00
paulogdm
0dd801ff6c Update now-next-legacy-mode.md (#208)
* Update now-next-legacy-mode.md

From `canary` to `latest`.

* Update now-next-no-serverless-pages-built.md

From `canary` to `latest`

* Apply suggestions from code review

Better words...

Co-Authored-By: paulogdm <paulogdemitri@gmail.com>
2019-02-11 14:41:42 +01:00
Connor Davis
398743ef95 Fix tests not completing 2019-02-08 20:03:32 -06:00
Nathan Rajlich
337c74b81b Publish
- @now/bash@0.1.2
2019-02-08 15:28:30 -08:00
Nathan Rajlich
680bb82ec3 [now-bash] Use mktemp dry run syntax that is compatible with BSD (#204)
For `now dev` running on a MacOS machine, some of our builders will need
to be adjusted to be "platform-aware".

In this case, `mktemp` is provided by BSD instead of GNU, which doesn't
support the long form `--dry-run` flag, however both support the `-u`
flag which does the same thing.
2019-02-08 15:25:51 -08:00
Nathan Rajlich
17ed5411e3 Publish
- @now/rust@0.0.2
2019-02-06 12:58:51 -08:00
Nathan Rajlich
d9bbcb6939 Publish
- @now/rust@0.0.2-canary.2
 - @now/static-build@0.4.19-canary.0
2019-02-05 12:06:03 -08:00
Igor Klopov
800e4de76f [tests] lint fixes 2019-02-05 22:35:18 +03:00
António Nuno Monteiro
864dd468d9 Place generated @now/rust lambdas in the location that matches their entrypoint (#198) 2019-02-05 11:31:41 -08:00
Igor Klopov
ba833871bb [tests] merge build.env from now.json 2019-02-05 22:15:02 +03:00
Arunoda Susiripal
e732bac78e @now/static-build@0.4.18 2019-02-05 02:27:26 +00:00
Arunoda Susiripal
28ea4015b4 Publish
- @now/static-build@0.4.18-canary.3
2019-02-05 02:12:15 +00:00
Arunoda Susiripal
a93d97cabd Use proper test code for now-static-build 2019-02-05 02:10:25 +00:00
Arunoda Susiripal
67f39f7c9b Publish
- @now/static-build@0.4.18-canary.2
2019-02-05 01:58:26 +00:00
Arunoda Susiripal
acd793b9e9 Fix a typo in a message of now-static-build 2019-02-05 01:57:27 +00:00
Arunoda Susiripal
f74d61279d Publish
- @now/static-build@0.4.18-canary.1
2019-02-05 01:50:45 +00:00
Arunoda Susiripala
fcb8eacec0 Check for distDir existence inside now-static-build (#197)
* Throw in case we don't see the distDir

* Add test cases.
2019-02-05 07:18:30 +05:30
Nathan Rajlich
c8fca2ba72 Publish
- @now/build-utils@0.4.35-canary.0
 - @now/rust@0.0.2-canary.1
2019-02-04 14:44:28 -08:00
António Nuno Monteiro
4feffa13eb Fix @now/rust for nested paths (#194)
* Fix `@now/rust` for nested paths

* fix bug

* fs-extra

* no need for mkdirp or rimraf anymore
2019-02-04 14:40:41 -08:00
Igor Klopov
3e330b25f4 Publish 2019-02-04 21:38:37 +03:00
Igor Klopov
9b2cae33af [build-utils] removed in-memory yarn cache 2019-02-04 19:45:46 +03:00
António Nuno Monteiro
4b6371530c Publish initial version to crates.io (#193) 2019-02-01 00:11:45 +01:00
50 changed files with 280 additions and 653 deletions

3
.gitignore vendored
View File

@@ -1,3 +1,4 @@
node_modules
tmp
target/
target/
.next

View File

@@ -34,10 +34,10 @@ Serverless:
In order to create the smallest possible lambdas Next.js has to be configured to build for the `serverless` target.
1. Serverless Next.js requires Next.js 8 or later, currently this version is out on the `canary` release channel:
1. Serverless Next.js requires Next.js 8 or later, to upgrade you can install the `latest` version:
```
npm install next@canary
npm install next --save
```
2. Add the `now-build` script to your `package.json`

View File

@@ -8,10 +8,10 @@ This error occurs when you have your application is not configured for Serverles
In order to create the smallest possible lambdas Next.js has to be configured to build for the `serverless` target.
1. Serverless Next.js requires Next.js 8 or later, currently this version is out on the `canary` release channel:
1. Serverless Next.js requires Next.js 8 or later, to upgrade you can install the `latest` version:
```
npm install next@canary
npm install next --save
```
2. Add the `now-build` script to your `package.json`

View File

@@ -15,7 +15,7 @@
"publish-stable": "lerna version",
"publish-canary": "lerna version prerelease --preid canary",
"lint": "tsc && eslint .",
"test": "jest --runInBand",
"test": "jest --runInBand --verbose",
"lint-staged": "lint-staged"
},
"pre-commit": "lint-staged",

View File

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

View File

@@ -52,7 +52,7 @@ _lambda_runtime_next() {
# Need to use a fifo here instead of bash <() because Lambda
# errors with "/dev/fd/63 not found" for some reason :/
local stdin
stdin="$(mktemp --dry-run)"
stdin="$(mktemp -u)"
mkfifo "$stdin"
_lambda_runtime_body "$event" > "$stdin" &

View File

@@ -1 +1,2 @@
/test
tmp

View File

@@ -1,242 +0,0 @@
/* eslint-disable arrow-body-style,no-multi-assign,no-param-reassign */
const MemoryFileSystem = require('memory-fs');
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const yarnPath = spawnSync('which', ['yarn'])
.stdout.toString()
.trim();
const cachePath = spawnSync(yarnPath, ['cache', 'dir'])
.stdout.toString()
.trim();
spawnSync(yarnPath, ['cache', 'clean']);
const vfs = new MemoryFileSystem();
function isInsideCachePath(filename) {
const relative = path.relative(cachePath, filename);
return !relative.startsWith('..');
}
function replaceFn(name, newFnFactory) {
const prevFn = fs[name];
fs[name] = newFnFactory(prevFn);
}
replaceFn('createWriteStream', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
const stream = vfs.createWriteStream(...args);
stream.on('finish', () => {
setTimeout(() => {
stream.emit('close');
});
});
setTimeout(() => {
stream.emit('open');
});
return stream;
};
});
replaceFn('readFile', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return vfs.readFile(...args.slice(0, -1), (error, result) => {
if (error) {
return prevFn.call(fs, ...args);
}
return callback(error, result);
});
};
});
replaceFn('readdir', (prevFn) => {
return (...args) => {
const dirname = args[0];
if (!isInsideCachePath(dirname)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return prevFn.call(fs, dirname, (error, results) => {
if (error) {
results = [];
}
return vfs.readdir(dirname, (error2, results2) => {
if (error2) {
return callback(error2);
}
// eslint-disable-next-line no-restricted-syntax
for (const result2 of results2) {
if (!results.includes(result2)) {
results.push(result2);
}
}
return callback(error2, results);
});
});
};
});
replaceFn('stat', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return vfs.stat(...args.slice(0, -1), (error, result) => {
if (error) {
return prevFn.call(fs, ...args);
}
result.atime = result.mtime = new Date();
return callback(error, result);
});
};
});
replaceFn('lstat', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return vfs.stat(...args.slice(0, -1), (error, result) => {
if (error) {
return prevFn.call(fs, ...args);
}
result.atime = result.mtime = new Date();
return callback(error, result);
});
};
});
replaceFn('exists', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return vfs.exists(...args.slice(0, -1), (result) => {
if (!result) {
return prevFn.call(fs, ...args);
}
return callback(result);
});
};
});
replaceFn('copyFile', (prevFn) => {
return (...args) => {
const src = args[0];
const dest = args[1];
const callback = args[args.length - 1];
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);
return vfs.writeFile(dest, buffer, callback);
}
return prevFn.call(fs, ...args);
};
});
replaceFn('writeFile', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
return vfs.writeFile(...args);
};
});
replaceFn('mkdir', (prevFn) => {
return (...args) => {
const dirname = args[0];
if (!isInsideCachePath(dirname)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return prevFn.call(fs, dirname, (error) => {
if (error) {
return callback(error);
}
return vfs.mkdirp(dirname, callback);
});
};
});
replaceFn('utimes', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return setTimeout(callback, 0);
};
});
replaceFn('chmod', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return setTimeout(callback, 0);
};
});
replaceFn('chown', (prevFn) => {
return (...args) => {
const filename = args[0];
if (!isInsideCachePath(filename)) {
return prevFn.call(fs, ...args);
}
const callback = args[args.length - 1];
return setTimeout(callback, 0);
};
});
require(yarnPath);

View File

@@ -3,9 +3,6 @@ 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 });
@@ -66,15 +63,6 @@ async function installDependencies(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 (prod) {
console.log('using memory-fs for yarn cache');
await spawnAsync(
'node',
[path.join(__dirname, 'bootstrap-yarn.js'), '--cwd', destPath].concat(
commandArgs,
),
destPath,
);
} else {
await spawnAsync('yarn', ['--cwd', destPath].concat(commandArgs), destPath);
await spawnAsync('yarn', ['cache', 'clean'], destPath);

View File

@@ -1,6 +1,6 @@
{
"name": "@now/build-utils",
"version": "0.4.33-canary.2",
"version": "0.4.35-canary.1",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -7,7 +7,7 @@ const {
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
jest.setTimeout(4 * 60 * 1000);
const builderUrl = '@canary';
let buildUtilsUrl;

View File

@@ -1,6 +1,6 @@
{
"name": "@now/lambda",
"version": "0.4.10-canary.0",
"version": "0.4.10-canary.1",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -7,7 +7,7 @@ const {
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
jest.setTimeout(4 * 60 * 1000);
const buildUtilsUrl = '@canary';
let builderUrl;

View File

@@ -1,6 +1,6 @@
{
"name": "@now/md",
"version": "0.4.10-canary.0",
"version": "0.4.10-canary.1",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -7,7 +7,7 @@ const {
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
jest.setTimeout(4 * 60 * 1000);
const buildUtilsUrl = '@canary';
let builderUrl;

View File

@@ -1,6 +1,6 @@
{
"name": "@now/mdx-deck",
"version": "0.4.19-canary.0",
"version": "0.4.19-canary.1",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -7,7 +7,7 @@ const {
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
jest.setTimeout(4 * 60 * 1000);
const buildUtilsUrl = '@canary';
let builderUrl;

View File

@@ -15,9 +15,7 @@ const {
excludeFiles,
validateEntrypoint,
includeOnlyEntryDirectory,
moveEntryDirectoryToRoot,
normalizePackageJson,
excludeStaticDirectory,
onlyStaticDirectory,
} = require('./utils');
@@ -33,15 +31,17 @@ const {
/**
* Read package.json from files
* @param {DownloadedFiles} files
* @param {string} entryPath
*/
async function readPackageJson(files) {
if (!files['package.json']) {
async function readPackageJson(entryPath) {
const packagePath = path.join(entryPath, 'package.json');
try {
return JSON.parse(await readFile(packagePath, 'utf8'));
} catch (err) {
console.log('no package.json found in entry');
return {};
}
const packageJsonPath = files['package.json'].fsPath;
return JSON.parse(await readFile(packageJsonPath, 'utf8'));
}
/**
@@ -81,20 +81,10 @@ exports.build = async ({ files, workPath, entrypoint }) => {
console.log('downloading user files...');
const entryDirectory = path.dirname(entrypoint);
const filesOnlyEntryDirectory = includeOnlyEntryDirectory(
files,
entryDirectory,
);
const filesWithEntryDirectoryRoot = moveEntryDirectoryToRoot(
filesOnlyEntryDirectory,
entryDirectory,
);
const filesWithoutStaticDirectory = excludeStaticDirectory(
filesWithEntryDirectoryRoot,
);
const downloadedFiles = await download(filesWithoutStaticDirectory, workPath);
await download(files, workPath);
const entryPath = path.join(workPath, entryDirectory);
const pkg = await readPackageJson(downloadedFiles);
const pkg = await readPackageJson(entryPath);
let nextVersion;
if (pkg.dependencies && pkg.dependencies.next) {
@@ -133,13 +123,13 @@ exports.build = async ({ files, workPath, entrypoint }) => {
if (isLegacy) {
try {
await unlink(path.join(workPath, 'yarn.lock'));
await unlink(path.join(entryPath, 'yarn.lock'));
} catch (err) {
console.log('no yarn.lock removed');
}
try {
await unlink(path.join(workPath, 'package-lock.json'));
await unlink(path.join(entryPath, 'package-lock.json'));
} catch (err) {
console.log('no package-lock.json removed');
}
@@ -151,7 +141,7 @@ exports.build = async ({ files, workPath, entrypoint }) => {
console.log('normalizing package.json');
const packageJson = normalizePackageJson(pkg);
console.log('normalized package.json result: ', packageJson);
await writePackageJson(workPath, packageJson);
await writePackageJson(entryPath, 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',
@@ -161,38 +151,38 @@ exports.build = async ({ files, workPath, entrypoint }) => {
...(pkg.scripts || {}),
};
console.log('normalized package.json result: ', pkg);
await writePackageJson(workPath, pkg);
await writePackageJson(entryPath, 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);
await writeNpmRc(entryPath, process.env.NPM_AUTH_TOKEN);
}
console.log('installing dependencies...');
await runNpmInstall(workPath, ['--prefer-offline']);
await runNpmInstall(entryPath, ['--prefer-offline']);
console.log('running user script...');
await runPackageJsonScript(workPath, 'now-build');
await runPackageJsonScript(entryPath, 'now-build');
if (isLegacy) {
console.log('running npm install --production...');
await runNpmInstall(workPath, ['--prefer-offline', '--production']);
await runNpmInstall(entryPath, ['--prefer-offline', '--production']);
}
if (process.env.NPM_AUTH_TOKEN) {
await unlink(path.join(workPath, '.npmrc'));
await unlink(path.join(entryPath, '.npmrc'));
}
const lambdas = {};
if (isLegacy) {
const filesAfterBuild = await glob('**', workPath);
const filesAfterBuild = await glob('**', entryPath);
console.log('preparing lambda files...');
let buildId;
try {
buildId = await readFile(
path.join(workPath, '.next', 'BUILD_ID'),
path.join(entryPath, '.next', 'BUILD_ID'),
'utf8',
);
} catch (err) {
@@ -201,10 +191,10 @@ exports.build = async ({ files, workPath, entrypoint }) => {
);
throw new Error('Missing BUILD_ID');
}
const dotNextRootFiles = await glob('.next/*', workPath);
const dotNextServerRootFiles = await glob('.next/server/*', workPath);
const dotNextRootFiles = await glob('.next/*', entryPath);
const dotNextServerRootFiles = await glob('.next/server/*', entryPath);
const nodeModules = excludeFiles(
await glob('node_modules/**', workPath),
await glob('node_modules/**', entryPath),
file => file.startsWith('node_modules/.cache'),
);
const launcherFiles = {
@@ -221,7 +211,7 @@ exports.build = async ({ files, workPath, entrypoint }) => {
}
const pages = await glob(
'**/*.js',
path.join(workPath, '.next', 'server', 'static', buildId, 'pages'),
path.join(entryPath, '.next', 'server', 'static', buildId, 'pages'),
);
const launcherPath = path.join(__dirname, 'legacy-launcher.js');
const launcherData = await readFile(launcherPath, 'utf8');
@@ -277,7 +267,7 @@ exports.build = async ({ files, workPath, entrypoint }) => {
};
const pages = await glob(
'**/*.js',
path.join(workPath, '.next', 'serverless', 'pages'),
path.join(entryPath, '.next', 'serverless', 'pages'),
);
const pageKeys = Object.keys(pages);
@@ -313,7 +303,7 @@ exports.build = async ({ files, workPath, entrypoint }) => {
const nextStaticFiles = await glob(
'**',
path.join(workPath, '.next', 'static'),
path.join(entryPath, '.next', 'static'),
);
const staticFiles = Object.keys(nextStaticFiles).reduce(
(mappedFiles, file) => ({
@@ -323,7 +313,9 @@ exports.build = async ({ files, workPath, entrypoint }) => {
{},
);
const nextStaticDirectory = onlyStaticDirectory(filesWithEntryDirectoryRoot);
const nextStaticDirectory = onlyStaticDirectory(
includeOnlyEntryDirectory(files, entryDirectory),
);
const staticDirectoryFiles = Object.keys(nextStaticDirectory).reduce(
(mappedFiles, file) => ({
...mappedFiles,

View File

@@ -1,6 +1,6 @@
{
"name": "@now/next",
"version": "0.0.85-canary.1",
"version": "0.0.85-canary.4",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -1,5 +1,3 @@
const rename = require('@now/build-utils/fs/rename.js'); // eslint-disable-line import/no-extraneous-dependencies
/** @typedef { import('@now/build-utils/file-ref') } FileRef */
/** @typedef { import('@now/build-utils/file-fs-ref') } FileFsRef */
/** @typedef {{[filePath: string]: FileRef|FileFsRef}} Files */
@@ -64,24 +62,6 @@ function includeOnlyEntryDirectory(files, entryDirectory) {
return excludeFiles(files, matcher);
}
/**
* Moves all files under the entry directory to the root directory
* @param {Files} files
* @param {string} entryDirectory
* @returns {Files}
*/
function moveEntryDirectoryToRoot(files, entryDirectory) {
if (entryDirectory === '.') {
return files;
}
function delegate(filePath) {
return filePath.replace(new RegExp(`^${entryDirectory}/`), '');
}
return rename(files, delegate);
}
/**
* Exclude package manager lockfiles from files
* @param {Files} files
@@ -98,19 +78,6 @@ function excludeLockFiles(files) {
return files;
}
/**
* Exclude the static directory from files
* @param {Files} files
* @returns {Files}
*/
function excludeStaticDirectory(files) {
function matcher(filePath) {
return filePath.startsWith('static');
}
return excludeFiles(files, matcher);
}
/**
* Exclude the static directory from files
* @param {Files} files
@@ -173,9 +140,7 @@ module.exports = {
excludeFiles,
validateEntrypoint,
includeOnlyEntryDirectory,
moveEntryDirectoryToRoot,
excludeLockFiles,
normalizePackageJson,
excludeStaticDirectory,
onlyStaticDirectory,
};

View File

@@ -1,6 +1,6 @@
{
"name": "@now/node-server",
"version": "0.4.27-canary.2",
"version": "0.4.27-canary.3",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -7,7 +7,7 @@ const {
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
jest.setTimeout(4 * 60 * 1000);
const buildUtilsUrl = '@canary';
let builderUrl;

View File

@@ -1,6 +1,6 @@
{
"name": "@now/node",
"version": "0.4.29-canary.2",
"version": "0.4.29-canary.3",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -7,7 +7,7 @@ const {
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
jest.setTimeout(4 * 60 * 1000);
const buildUtilsUrl = '@canary';
let builderUrl;

View File

@@ -1,6 +1,6 @@
{
"name": "@now/php",
"version": "0.4.14-canary.0",
"version": "0.4.14-canary.1",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -7,7 +7,7 @@ const {
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
jest.setTimeout(4 * 60 * 1000);
const buildUtilsUrl = '@canary';
let builderUrl;

View File

@@ -448,7 +448,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "now_lambda"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
"http 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)",

View File

@@ -1,8 +1,18 @@
[package]
name = "now_lambda"
version = "0.1.0"
version = "0.1.1"
authors = ["Antonio Nuno Monteiro <anmonteiro@gmail.com>"]
edition = "2018"
description = "Rust bindings for Now.sh Lambdas"
keywords = ["AWS", "Lambda", "Zeit", "Now", "Rust"]
license = "MIT"
homepage = "https://github.com/zeit/now-builders"
repository = "https://github.com/zeit/now-builders"
documentation = "https://docs.rs/now_lambda"
include = [
"src/*.rs",
"Cargo.toml"
]
[dependencies]
serde = "^1"

View File

@@ -1,9 +1,8 @@
const fs = require('fs');
const fs = require('fs-extra');
const path = require('path');
const concat = require('concat-stream');
const execa = require('execa');
const toml = require('toml');
const rimraf = require('rimraf');
const { createLambda } = require('@now/build-utils/lambda.js'); // eslint-disable-line import/no-extraneous-dependencies
const download = require('@now/build-utils/fs/download.js'); // eslint-disable-line import/no-extraneous-dependencies
const glob = require('@now/build-utils/fs/glob.js'); // eslint-disable-line import/no-extraneous-dependencies
@@ -54,13 +53,14 @@ exports.build = async ({ files, entrypoint, workPath }) => {
throw err;
}
const targetPath = path.join(workPath, 'target', 'release');
const targetPath = path.join(entrypointDirname, 'target', 'release');
const binaries = await inferCargoBinaries(
cargoToml,
path.join(workPath, 'src'),
path.join(entrypointDirname, 'src'),
);
const lambdas = {};
const lambdaPath = path.dirname(entrypoint);
await Promise.all(
binaries.map(async (binary) => {
const fsPath = path.join(targetPath, binary);
@@ -72,19 +72,28 @@ exports.build = async ({ files, entrypoint, workPath }) => {
runtime: 'provided',
});
lambdas[binary] = lambda;
lambdas[path.join(lambdaPath, binary)] = lambda;
}),
);
return lambdas;
};
exports.prepareCache = async ({ cachePath, workPath }) => {
exports.prepareCache = async ({ cachePath, entrypoint, workPath }) => {
console.log('preparing cache...');
rimraf.sync(path.join(cachePath, 'target'));
fs.renameSync(path.join(workPath, 'target'), path.join(cachePath, 'target'));
const entrypointDirname = path.dirname(path.join(workPath, entrypoint));
const cacheEntrypointDirname = path.dirname(path.join(cachePath, entrypoint));
// Remove the target folder to avoid 'directory already exists' errors
fs.removeSync(path.join(cacheEntrypointDirname, 'target'));
fs.mkdirpSync(cacheEntrypointDirname);
// Move the target folder to the cache location
fs.renameSync(
path.join(entrypointDirname, 'target'),
path.join(cacheEntrypointDirname, 'target'),
);
return {
...(await glob('target/**', path.join(cachePath))),
...(await glob('**/**', path.join(cachePath))),
};
};

View File

@@ -1,46 +1,10 @@
const fs = require('fs');
const { exists, readdir, stat } = require('fs-extra');
const path = require('path');
function readdir(dir) {
return new Promise((resolve, reject) => {
fs.readdir(dir, (err, files) => {
if (err != null) {
return reject(err);
}
return resolve(files);
});
});
}
function exists(p) {
return new Promise((resolve, reject) => {
fs.exists(p, (err, res) => {
if (err != null) {
return reject(err);
}
return resolve(res);
});
});
}
function stat(p) {
return new Promise((resolve, reject) => {
fs.stat(p, (err, stats) => {
if (err != null) {
return reject(err);
}
return resolve(stats);
});
});
}
async function inferCargoBinaries(cargoToml, srcDir) {
const { package: pkg, bin } = cargoToml;
const binaries = [];
const hasMain = (await readdir(srcDir)).includes('main.rs');
const hasMain = await exists(path.join(srcDir, 'main.rs'));
if (hasMain) {
binaries.push(pkg.name);

View File

@@ -1,6 +1,6 @@
{
"name": "@now/rust",
"version": "0.0.2-canary.0",
"version": "0.0.3-canary.0",
"license": "MIT",
"repository": {
"type": "git",
@@ -15,8 +15,8 @@
"dependencies": {
"concat-stream": "^2.0.0",
"execa": "^1.0.0",
"fs-extra": "^7.0.1",
"node-fetch": "^2.3.0",
"rimraf": "^2.6.3",
"tar": "^4.4.8",
"toml": "^2.3.3"
}

View File

@@ -1,6 +1,6 @@
//! Provides a Now Lambda oriented request and response body entity interface
use std::{borrow::Cow, ops::Deref};
use std::{borrow::Cow, ops::Deref, str};
use base64::display::Base64Display;
use serde::ser::{Error as SerError, Serialize, Serializer};
@@ -76,6 +76,12 @@ impl From<()> for Body {
}
}
impl From<Body> for () {
fn from(_: Body) -> Self {
()
}
}
impl<'a> From<&'a str> for Body {
fn from(s: &'a str) -> Self {
Body::Text(s.into())
@@ -87,6 +93,15 @@ impl From<String> for Body {
Body::Text(b)
}
}
impl From<Body> for String {
fn from(b: Body) -> String {
match b {
Body::Empty => String::from(""),
Body::Text(t) => t,
Body::Binary(b) => str::from_utf8(&b).unwrap().to_owned(),
}
}
}
impl From<Cow<'static, str>> for Body {
#[inline]
@@ -98,6 +113,13 @@ impl From<Cow<'static, str>> for Body {
}
}
impl From<Body> for Cow<'static, str> {
#[inline]
fn from(b: Body) -> Cow<'static, str> {
Cow::Owned(String::from(b))
}
}
impl From<Cow<'static, [u8]>> for Body {
#[inline]
fn from(cow: Cow<'static, [u8]>) -> Body {
@@ -108,12 +130,29 @@ impl From<Cow<'static, [u8]>> for Body {
}
}
impl From<Body> for Cow<'static, [u8]> {
#[inline]
fn from(b: Body) -> Self {
Cow::Owned(b.as_ref().to_owned())
}
}
impl From<Vec<u8>> for Body {
fn from(b: Vec<u8>) -> Self {
Body::Binary(b)
}
}
impl From<Body> for Vec<u8> {
fn from(b: Body) -> Self {
match b {
Body::Empty => "".as_bytes().to_owned(),
Body::Text(t) => t.into_bytes(),
Body::Binary(b) => b.to_owned(),
}
}
}
impl<'a> From<&'a [u8]> for Body {
fn from(b: &'a [u8]) -> Self {
Body::Binary(b.to_vec())

View File

@@ -1,3 +1,4 @@
use http;
use lambda_runtime::error::LambdaErrorExt;
use std::{error::Error, fmt};
@@ -19,13 +20,21 @@ impl fmt::Display for NowError {
write!(f, "{}", self.msg)
}
}
impl Error for NowError {}
impl From<std::num::ParseIntError> for NowError {
fn from(i: std::num::ParseIntError) -> Self {
NowError::new(&format!("{}", i))
}
}
impl From<http::Error> for NowError {
fn from(i: http::Error) -> Self {
NowError::new(&format!("{}", i))
}
}
// the value returned by the error_type function is included as the
// `errorType` in the AWS Lambda response
impl LambdaErrorExt for NowError {

View File

@@ -21,16 +21,16 @@ use crate::{
pub type Request = http::Request<Body>;
/// Functions acting as Now Lambda handlers must conform to this type.
pub trait Handler<R> {
pub trait Handler<R, B, E> {
/// Method to execute the handler function
fn run(&mut self, event: Request) -> Result<R, NowError>;
fn run(&mut self, event: http::Request<B>) -> Result<R, E>;
}
impl<Function, R> Handler<R> for Function
impl<Function, R, B, E> Handler<R, B, E> for Function
where
Function: FnMut(Request) -> Result<R, NowError>,
Function: FnMut(http::Request<B>) -> Result<R, E>,
{
fn run(&mut self, event: Request) -> Result<R, NowError> {
fn run(&mut self, event: http::Request<B>) -> Result<R, E> {
(*self)(event)
}
}
@@ -43,8 +43,10 @@ where
///
/// # Panics
/// The function panics if the Lambda environment variables are not set.
pub fn start<R>(f: impl Handler<R>, runtime: Option<TokioRuntime>)
pub fn start<R, B, E>(f: impl Handler<R, B, E>, runtime: Option<TokioRuntime>)
where
B: From<Body>,
E: Into<NowError>,
R: IntoResponse,
{
// handler requires a mutable ref
@@ -56,8 +58,10 @@ where
match parse_result {
Ok(req) => {
debug!("Deserialized Now proxy request successfully");
func.run(req.into())
let request: http::Request<Body> = req.into();
func.run(request.map(|b| b.into()))
.map(|resp| NowResponse::from(resp.into_response()))
.map_err(|e| e.into())
}
Err(e) => {
error!("Could not deserialize event body to NowRequest {}", e);

View File

@@ -1,13 +1,8 @@
use std::{borrow::Cow, fmt, mem};
use http::{self, header::HeaderValue, HeaderMap, Method, Request as HttpRequest};
use serde::{
de::{Error as DeError, MapAccess, Visitor},
Deserialize, Deserializer,
};
use serde::de::{Deserializer, Error as DeError, MapAccess, Visitor};
use serde_derive::Deserialize;
#[allow(unused_imports)]
use serde_json::Value;
use crate::body::Body;
@@ -92,18 +87,6 @@ where
deserializer.deserialize_map(HeaderVisitor)
}
/// deserializes (json) null values to their default values
// https://github.com/serde-rs/serde/issues/1098
#[allow(dead_code)]
fn nullable_default<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: Default + Deserialize<'de>,
{
let opt = Option::deserialize(deserializer)?;
Ok(opt.unwrap_or_else(T::default))
}
impl<'a> From<NowRequest<'a>> for HttpRequest<Body> {
fn from(value: NowRequest<'_>) -> Self {
let NowRequest {

View File

@@ -4,10 +4,7 @@ use http::{
header::{HeaderMap, HeaderValue},
Response,
};
use serde::{
ser::{Error as SerError, SerializeMap},
Serializer,
};
use serde::ser::{Error as SerError, SerializeMap, Serializer};
use serde_derive::Serialize;
use crate::body::Body;

View File

@@ -4,10 +4,7 @@ use std::{
sync::Arc,
};
use serde::{
de::{MapAccess, Visitor},
Deserialize, Deserializer,
};
use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
/// A read-only view into a map of string data
#[derive(Default, Debug, PartialEq)]

View File

@@ -1,26 +1,21 @@
/* global afterAll, beforeAll, describe, expect, it, jest */
const fs = require('fs');
const inferCargoBinaries = require('../inferCargoBinaries');
/* global beforeEach, describe, expect, it, jest */
const { exists, readdir, stat } = fs;
const isDir = fs.Stats.prototype.isDirectory;
let inferCargoBinaries;
beforeAll(() => {
fs.exists = jest.fn((p, cb) => cb(null, false));
});
afterAll(() => {
fs.readdir = readdir;
fs.stat = stat;
fs.Stats.prototype.isDirectory = isDir;
fs.exists = exists;
beforeEach(() => {
jest.resetAllMocks();
jest.resetModules();
});
// src/
// |- main.rs
describe('one binary, src/main.rs', async () => {
beforeAll(() => {
fs.readdir = jest.fn((p, cb) => cb(null, ['main.rs']));
beforeEach(() => {
jest.mock('fs-extra', () => Object.assign(jest.genMockFromModule('fs-extra'), {
readdir: jest.fn(async () => ['main.rs']),
exists: jest.fn(async p => p.endsWith('main.rs')),
}));
inferCargoBinaries = require('../inferCargoBinaries');
});
it('infers only one binary', async () => {
@@ -29,7 +24,9 @@ describe('one binary, src/main.rs', async () => {
name: 'foo',
},
};
expect(inferCargoBinaries(toml, '/path/to/src')).resolves.toEqual(['foo']);
return expect(inferCargoBinaries(toml, '/path/to/src')).resolves.toEqual([
'foo',
]);
});
});
@@ -40,8 +37,12 @@ describe('one binary, src/main.rs', async () => {
// |- bar.rs
// |- main.rs
describe('two binaries, src/main.rs, src/bar.rs', async () => {
beforeAll(() => {
fs.readdir = jest.fn((p, cb) => cb(null, ['main.rs', 'bar.rs']));
beforeEach(() => {
jest.mock('fs-extra', () => Object.assign(jest.genMockFromModule('fs-extra'), {
readdir: jest.fn(async () => ['main.rs', 'bar.rs']),
exists: jest.fn(async p => p.endsWith('main.rs')),
}));
inferCargoBinaries = require('../inferCargoBinaries');
});
it('infers two binaries', async () => {
@@ -51,10 +52,9 @@ describe('two binaries, src/main.rs, src/bar.rs', async () => {
},
bin: [{ name: 'bar', path: 'src/bar.rs' }],
};
expect((await inferCargoBinaries(toml, '/path/to/src')).sort()).toEqual([
'bar',
'foo',
]);
return expect(
(await inferCargoBinaries(toml, '/path/to/src')).sort(),
).toEqual(['bar', 'foo']);
});
});
@@ -62,8 +62,11 @@ describe('two binaries, src/main.rs, src/bar.rs', async () => {
// src/
// |- foo.rs
describe('one named binary, no main.rs', async () => {
beforeAll(() => {
fs.readdir = jest.fn((p, cb) => cb(null, ['bar.rs']));
beforeEach(() => {
jest.mock('fs-extra', () => Object.assign(jest.genMockFromModule('fs-extra'), {
readdir: jest.fn(async () => ['bar.rs']),
}));
inferCargoBinaries = require('../inferCargoBinaries');
});
it('infers only one binary', async () => {
@@ -73,9 +76,9 @@ describe('one named binary, no main.rs', async () => {
},
bin: [{ name: 'bar', path: 'src/bar.rs' }],
};
expect((await inferCargoBinaries(toml, '/path/to/src')).sort()).toEqual([
'bar',
]);
return expect(
(await inferCargoBinaries(toml, '/path/to/src')).sort(),
).toEqual(['bar']);
});
});
@@ -86,20 +89,24 @@ describe('one named binary, no main.rs', async () => {
// | |- baz.rs
// |- main.rs
describe('multiple binaries in bin/, no [[bin]] section', async () => {
beforeAll(() => {
fs.readdir = jest.fn((p, cb) => {
if (p === '/path/to/src') {
return cb(null, ['bin', 'main.rs']);
}
if (p === '/path/to/src/bin') {
return cb(null, ['bar.rs', 'baz.rs']);
}
beforeEach(() => {
jest.mock('fs-extra', () => Object.assign(jest.genMockFromModule('fs-extra'), {
readdir: jest.fn(async (p) => {
if (p === '/path/to/src') {
return ['bin', 'main.rs'];
}
if (p === '/path/to/src/bin') {
return ['bar.rs', 'baz.rs'];
}
return cb('some error');
});
fs.exists = jest.fn((p, cb) => cb(null, p.endsWith('bin')));
fs.stat = jest.fn((_, cb) => cb(null, new fs.Stats()));
fs.Stats.prototype.isDirectory = jest.fn(() => true);
throw new Error('some error');
}),
exists: jest.fn(async p => p.endsWith('bin') || p.endsWith('main.rs')),
stat: jest.fn(async () => ({
isDirectory: () => true,
})),
}));
inferCargoBinaries = require('../inferCargoBinaries');
});
it('infers three binaries', async () => {
@@ -123,20 +130,24 @@ describe('multiple binaries in bin/, no [[bin]] section', async () => {
// | |- baz.rs
// |- main.rs
describe('src/bin exists but one binary is ignored', async () => {
beforeAll(() => {
fs.readdir = jest.fn((p, cb) => {
if (p === '/path/to/src') {
return cb(null, ['bin', 'main.rs']);
}
if (p === '/path/to/src/bin') {
return cb(null, ['bar.rs', 'baz.rs']);
}
beforeEach(() => {
jest.mock('fs-extra', () => Object.assign(jest.genMockFromModule('fs-extra'), {
readdir: jest.fn(async (p) => {
if (p === '/path/to/src') {
return ['bin', 'main.rs'];
}
if (p === '/path/to/src/bin') {
return ['bar.rs', 'baz.rs'];
}
return cb('some error');
});
fs.exists = jest.fn((p, cb) => cb(null, p.endsWith('bin')));
fs.stat = jest.fn((_, cb) => cb(null, new fs.Stats()));
fs.Stats.prototype.isDirectory = jest.fn(() => true);
throw new Error('some error');
}),
exists: jest.fn(async p => p.endsWith('bin') || p.endsWith('main.rs')),
stat: jest.fn(async () => ({
isDirectory: () => true,
})),
}));
inferCargoBinaries = require('../inferCargoBinaries');
});
it('infers only one binary', async () => {

View File

@@ -1,12 +1,22 @@
const download = require('@now/build-utils/fs/download.js'); // eslint-disable-line import/no-extraneous-dependencies
const glob = require('@now/build-utils/fs/glob.js'); // eslint-disable-line import/no-extraneous-dependencies
const path = require('path');
const { existsSync } = require('fs');
const {
runNpmInstall,
runPackageJsonScript,
runShellScript,
} = require('@now/build-utils/fs/run-user-scripts.js'); // eslint-disable-line import/no-extraneous-dependencies
function validateDistDir(distDir) {
const distDirName = path.basename(distDir);
if (!existsSync(distDir)) {
const message = `Build was unable to create the distDir: ${distDirName}.`
+ '\nMake sure you mentioned the correct dist directory: https://zeit.co/docs/v2/deployments/official-builders/static-build-now-static-build/#configuring-the-dist-directory';
throw new Error(message);
}
}
exports.build = async ({
files, entrypoint, workPath, config,
}) => {
@@ -24,6 +34,7 @@ exports.build = async ({
if (path.basename(entrypoint) === 'package.json') {
await runNpmInstall(entrypointFsDirname, ['--prefer-offline']);
if (await runPackageJsonScript(entrypointFsDirname, 'now-build')) {
validateDistDir(distPath);
return glob('**', distPath, mountpoint);
}
throw new Error(`An error running "now-build" script in "${entrypoint}"`);
@@ -31,6 +42,7 @@ exports.build = async ({
if (path.extname(entrypoint) === '.sh') {
await runShellScript(path.join(workPath, entrypoint));
validateDistDir(distPath);
return glob('**', distPath, mountpoint);
}

View File

@@ -1,6 +1,6 @@
{
"name": "@now/static-build",
"version": "0.4.18-canary.0",
"version": "0.4.19-canary.1",
"license": "MIT",
"repository": {
"type": "git",

View File

@@ -0,0 +1,6 @@
{
"version": 2,
"builds": [
{ "src": "package.json", "use": "@now/static-build", "config": {"distDir": "out"} }
]
}

View File

@@ -0,0 +1,8 @@
{
"dependencies": {
"cowsay": "^1.3.1"
},
"scripts": {
"now-build": "mkdir dist && cowsay cow:RANDOMNESS_PLACEHOLDER > dist/index.txt"
}
}

View File

@@ -0,0 +1,8 @@
{
"dependencies": {
"yodasay": "^1.1.6"
},
"scripts": {
"now-build": "mkdir dist && yodasay yoda:RANDOMNESS_PLACEHOLDER > dist/index.txt"
}
}

View File

@@ -7,7 +7,7 @@ const {
testDeployment,
} = require('../../../test/lib/deployment/test-deployment.js');
jest.setTimeout(2 * 60 * 1000);
jest.setTimeout(4 * 60 * 1000);
const buildUtilsUrl = '@canary';
let builderUrl;
@@ -21,6 +21,21 @@ const fixturesPath = path.resolve(__dirname, 'fixtures');
// eslint-disable-next-line no-restricted-syntax
for (const fixture of fs.readdirSync(fixturesPath)) {
if (fixture === '04-wrong-dist-dir') {
// eslint-disable-next-line no-loop-func
it(`should not build ${fixture}`, async () => {
try {
await testDeployment(
{ builderUrl, buildUtilsUrl },
path.join(fixturesPath, fixture),
);
} catch (err) {
expect(err.message).toMatch(/is ERROR/);
}
});
continue; //eslint-disable-line
}
// eslint-disable-next-line no-loop-func
it(`should build ${fixture}`, async () => {
await expect(

View File

@@ -0,0 +1 @@
module.exports = () => 'Hello!';

View File

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

View File

@@ -1 +1,3 @@
export default () => 'Index page';
import hello from '../../shared/hello';
export default () => `${hello()} Welcome to the index page`;

View File

@@ -18,8 +18,9 @@ async function nowDeploy (bodies, randomness) {
const nowDeployPayload = {
version: 2,
env: Object.assign({}, nowJson.env, { RANDOMNESS_ENV_VAR: randomness }),
build: { env: { RANDOMNESS_BUILD_ENV_VAR: randomness } },
public: true,
env: { ...nowJson.env, RANDOMNESS_ENV_VAR: randomness },
build: { env: { ...(nowJson.build || {}).env, RANDOMNESS_BUILD_ENV_VAR: randomness } },
name: 'test',
files,
builds: nowJson.builds,

View File

@@ -2,11 +2,7 @@ const {
excludeFiles,
validateEntrypoint,
includeOnlyEntryDirectory,
moveEntryDirectoryToRoot,
excludeLockFiles,
normalizePackageJson,
excludeStaticDirectory,
onlyStaticDirectory,
} = require('@now/next/utils');
const FileRef = require('@now/build-utils/file-ref'); // eslint-disable-line import/no-extraneous-dependencies
@@ -46,7 +42,7 @@ describe('validateEntrypoint', () => {
});
describe('includeOnlyEntryDirectory', () => {
it('should exclude files outside entry directory', () => {
it('should include files outside entry directory', () => {
const entryDirectory = 'frontend';
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
@@ -58,149 +54,6 @@ describe('includeOnlyEntryDirectory', () => {
expect(result['package.json']).toBeUndefined();
expect(result['package-lock.json']).toBeUndefined();
});
it('should handle entry directory being dot', () => {
const entryDirectory = '.';
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
'package.json': new FileRef({ digest: 'package' }),
'package-lock.json': new FileRef({ digest: 'package-lock' }),
};
const result = includeOnlyEntryDirectory(files, entryDirectory);
expect(result['frontend/pages/index.js']).toBeDefined();
expect(result['package.json']).toBeDefined();
expect(result['package-lock.json']).toBeDefined();
});
});
describe('moveEntryDirectoryToRoot', () => {
it('should move entrydirectory files to the root', () => {
const entryDirectory = 'frontend';
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
};
const result = moveEntryDirectoryToRoot(files, entryDirectory);
expect(result['pages/index.js']).toBeDefined();
});
it('should work with deep nested subdirectories', () => {
const entryDirectory = 'frontend/my/app';
const files = {
'frontend/my/app/pages/index.js': new FileRef({ digest: 'index' }),
};
const result = moveEntryDirectoryToRoot(files, entryDirectory);
expect(result['pages/index.js']).toBeDefined();
});
it('should do nothing when entry directory is dot', () => {
const entryDirectory = '.';
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
};
const result = moveEntryDirectoryToRoot(files, entryDirectory);
expect(result['frontend/pages/index.js']).toBeDefined();
});
});
describe('excludeLockFiles', () => {
it('should remove package-lock.json', () => {
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
'package.json': new FileRef({ digest: 'package' }),
'package-lock.json': new FileRef({ digest: 'package-lock' }),
};
const result = excludeLockFiles(files);
expect(result['frontend/pages/index.js']).toBeDefined();
expect(result['package-lock.json']).toBeUndefined();
});
it('should remove yarn.lock', () => {
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
'package.json': new FileRef({ digest: 'package' }),
'yarn.lock': new FileRef({ digest: 'yarn-lock' }),
};
const result = excludeLockFiles(files);
expect(result['frontend/pages/index.js']).toBeDefined();
expect(result['yarn.lock']).toBeUndefined();
});
it('should remove both package-lock.json and yarn.lock', () => {
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
'package.json': new FileRef({ digest: 'package' }),
'yarn.lock': new FileRef({ digest: 'yarn-lock' }),
'package-lock.json': new FileRef({ digest: 'package-lock' }),
};
const result = excludeLockFiles(files);
expect(result['frontend/pages/index.js']).toBeDefined();
expect(result['yarn.lock']).toBeUndefined();
expect(result['package-lock.json']).toBeUndefined();
});
});
describe('excludeStaticDirectory', () => {
it('should remove the /static directory files', () => {
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
'package.json': new FileRef({ digest: 'package' }),
'yarn.lock': new FileRef({ digest: 'yarn-lock' }),
'package-lock.json': new FileRef({ digest: 'package-lock' }),
'static/image.png': new FileRef({ digest: 'image' }),
};
const result = excludeStaticDirectory(files);
expect(result['frontend/pages/index.js']).toBeDefined();
expect(result['yarn.lock']).toBeDefined();
expect(result['package-lock.json']).toBeDefined();
expect(result['static/image.png']).toBeUndefined();
});
it('should remove the nested /static directory files', () => {
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
'package.json': new FileRef({ digest: 'package' }),
'yarn.lock': new FileRef({ digest: 'yarn-lock' }),
'package-lock.json': new FileRef({ digest: 'package-lock' }),
'static/images/png/image.png': new FileRef({ digest: 'image' }),
};
const result = excludeStaticDirectory(files);
expect(result['frontend/pages/index.js']).toBeDefined();
expect(result['yarn.lock']).toBeDefined();
expect(result['package-lock.json']).toBeDefined();
expect(result['static/images/png/image.png']).toBeUndefined();
});
});
describe('onlyStaticDirectory', () => {
it('should keep only /static directory files', () => {
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
'package.json': new FileRef({ digest: 'package' }),
'yarn.lock': new FileRef({ digest: 'yarn-lock' }),
'package-lock.json': new FileRef({ digest: 'package-lock' }),
'static/image.png': new FileRef({ digest: 'image' }),
};
const result = onlyStaticDirectory(files);
expect(result['frontend/pages/index.js']).toBeUndefined();
expect(result['yarn.lock']).toBeUndefined();
expect(result['package-lock.json']).toBeUndefined();
expect(result['static/image.png']).toBeDefined();
});
it('should keep nested /static directory files', () => {
const files = {
'frontend/pages/index.js': new FileRef({ digest: 'index' }),
'package.json': new FileRef({ digest: 'package' }),
'yarn.lock': new FileRef({ digest: 'yarn-lock' }),
'package-lock.json': new FileRef({ digest: 'package-lock' }),
'static/images/png/image.png': new FileRef({ digest: 'image' }),
};
const result = onlyStaticDirectory(files);
expect(result['frontend/pages/index.js']).toBeUndefined();
expect(result['yarn.lock']).toBeUndefined();
expect(result['package-lock.json']).toBeUndefined();
expect(result['static/images/png/image.png']).toBeDefined();
});
});
describe('normalizePackageJson', () => {

View File

@@ -7065,13 +7065,6 @@ rimraf@2, rimraf@^2.2.6, rimraf@^2.2.8, rimraf@^2.5.4, rimraf@^2.6.1, rimraf@^2.
dependencies:
glob "^7.0.5"
rimraf@^2.6.3:
version "2.6.3"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab"
integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==
dependencies:
glob "^7.1.3"
rmfr@2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/rmfr/-/rmfr-2.0.0.tgz#8a42e81332550b3f0019b8fb8ab245bea81b6d1c"