Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

try our hand at editing some next configs #45

Merged
merged 4 commits into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
311 changes: 310 additions & 1 deletion package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"build:esm": "tsc --module es2020",
"build:cjs": "tsc --module commonjs --outDir dist/cjs",
"postbuild:cjs": "echo '{\"type\": \"commonjs\"}' > ./dist/cjs/package.json",
"prepublish": "npm run build",
"cli": "node --loader tsx --no-warnings ./src/cli",
"test": "glob -c \"node --loader tsx --no-warnings --test\" \"./tests/**/*.test.ts\""
},
Expand Down Expand Up @@ -64,6 +65,7 @@
"@mux/mux-player-react": "1.12.1-canary.0-e90e096",
"chalk": "^4.1.2",
"chokidar": "^3.5.3",
"magicast": "^0.2.10",
"sharp": "^0.32.5",
"symlink-dir": "^5.1.1",
"thumbhash": "^0.1.1",
Expand Down
20 changes: 20 additions & 0 deletions src/cli/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import path from 'node:path';

import log, { Logger } from '../logger.js';
import { checkPackageJsonForNextVideo, updateTSConfigFileContent } from './lib/json-configs.js';
import updateNextConfigFile from './lib/next-config.js';

const GITIGNORE_CONTENTS = `*
!*.json
Expand Down Expand Up @@ -167,6 +168,25 @@ export async function handler(argv: Arguments) {
}
}

try {
const update = await updateNextConfigFile();

if (update) {
changes.push([log.add, `Updated ${update.configPath} to include next-video.`]);
}
} catch (e: any) {
if (e.error === 'not_found') {
changes.push([
log.error,
'No next.config.js or next.config.mjs file found. Please add next-video to your config manually.',
]);
} else if (e.error === 'already_added') {
changes.push([log.info, 'It seems like next-video is already added to your Next Config']);
} else {
changes.push([log.error, 'Failed to update next.config.js, please add next-video to your config manually.']);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When we have the "manual install guide" we should add a link to that here.

}
}

log.success(`${chalk.magenta.bold('next-video')} initialized!`);
changes.forEach(([loggerFn, change]) => loggerFn(change));
}
85 changes: 85 additions & 0 deletions src/cli/lib/next-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { builders, loadFile, generateCode, writeFile } from 'magicast';

import fs from 'node:fs/promises';
import path from 'node:path';

import { PACKAGE_NAME } from '../../constants.js';

const COMMON_TEMPLATE = `

// Everything below here added by the ${PACKAGE_NAME} CLI wizard.
// You should probably clean this up.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is pretty creative. Does your average next.js user actually care, or should this be more like "feel free to clean this up"?


const originalConfig = module.exports;

const withNextVideo = require('${path.join(PACKAGE_NAME, 'process')}');

module.exports = withNextVideo(originalConfig);
`;

function extensionToType(filePath: string) {
if (filePath.endsWith('.mjs')) {
return 'module';
}

return 'commonjs';
}

export default async function updateNextConfigFile(parentDir: string = './') {
let type: 'module' | 'commonjs' = 'commonjs';
let configPath: string | undefined = undefined;
let configContents: string = '';

const pathsToCheck = ['next.config.js', 'next.config.mjs'];

for (let i = 0; i < pathsToCheck.length; i++) {
console.log('asdf');
mmcc marked this conversation as resolved.
Show resolved Hide resolved
const filePath = path.join(parentDir, pathsToCheck[i]);
let exists;
try {
exists = await fs.stat(filePath);
} catch (e) {
exists = false;
}

if (exists) {
type = extensionToType(pathsToCheck[i]);
configPath = filePath;
configContents = await fs.readFile(filePath, 'utf-8');

break;
}
}

if (!configPath) {
throw { error: 'not_found' };
}

if (configContents.includes(PACKAGE_NAME)) {
throw { error: 'already_added' };
}

if (type === 'commonjs') {
await fs.appendFile(configPath, COMMON_TEMPLATE);

return { type, configPath };
}

if (type === 'module') {
const mod = await loadFile(configPath);

mod.imports.$add({
from: PACKAGE_NAME,
imported: 'withNextVideo',
local: 'withNextVideo',
});

const expressionToWrap = generateCode(mod.exports.default.$ast).code;
mod.exports.default = builders.raw(`withNextVideo(${expressionToWrap})`);

// @ts-ignore
writeFile(mod, configPath);

return { type, configPath };
}
}
6 changes: 5 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import path from 'node:path';
import fs from 'node:fs/promises';

const packageJsonContents = await fs.readFile(path.join(process.cwd(), 'package.json'), 'utf-8');

Check failure on line 4 in src/constants.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.

Check failure on line 4 in src/constants.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.
const packageJson = JSON.parse(packageJsonContents);

export const VIDEOS_PATH = path.join(process.cwd(), '/videos');
export const PACKAGE_NAME = '@mux/next-video';
export const PACKAGE_NAME = packageJson.name;
8 changes: 8 additions & 0 deletions src/with-next-video.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import fs from 'node:fs/promises';
import { VIDEOS_PATH } from './constants.js';

export default async function withNextVideo(nextConfig: any) {
// We should probably switch to using `phase` here, just a bit concerned about backwards compatibility.
if (process.argv[2] === 'dev') {
const TMP_PUBLIC_VIDEOS_PATH = path.join(process.cwd(), 'public/_videos');

Expand All @@ -16,6 +17,13 @@ export default async function withNextVideo(nextConfig: any) {
});
}

if (typeof nextConfig === 'function') {
return async (...args: any[]) => {
const nextConfigResult = await Promise.resolve(nextConfig(...args));
return withNextVideo(nextConfigResult);
};
}

return Object.assign({}, nextConfig, {
webpack(config: any, options: any) {
if (!options.defaultLoaders) {
Expand Down
6 changes: 3 additions & 3 deletions tests/cli/lib/json-configs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ describe('json-configs', () => {

describe('checkPackageJsonForNextVideo', () => {
it('should return true if next-video is in devDependencies', async () => {
assert.equal(await checkPackageJsonForNextVideo('./tests/cli/factories/package.devDep.json'), true);
assert.equal(await checkPackageJsonForNextVideo('./tests/factories/package.devDep.json'), true);
});

it('should return true if next-video is in dependencies', async () => {
assert.equal(await checkPackageJsonForNextVideo('./tests/cli/factories/package.dep.json'), true);
assert.equal(await checkPackageJsonForNextVideo('./tests/factories/package.dep.json'), true);
});

it('should return false if next-video is in neither', async () => {
assert.equal(await checkPackageJsonForNextVideo('./tests/cli/factories/package.none.json'), false);
assert.equal(await checkPackageJsonForNextVideo('./tests/factories/package.none.json'), false);
});
});
});
55 changes: 55 additions & 0 deletions tests/cli/lib/next-config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import assert from 'node:assert';
import { after, describe, it } from 'node:test';
import fs from 'node:fs/promises';
import path from 'node:path';

import updateNextConfigFile from '../../../src/cli/lib/next-config.js';

function outputConfigName(configName: string) {
if (configName.endsWith('.mjs')) {
return 'next.config.mjs';
}

// We have to return cjs files so we can import them async in a test.
return 'next.config.js';
}

describe('updateNextConfig', () => {
let tmpDirs: string[] = [];

async function createTempDirWithConfig(configName: string): Promise<string> {
const dir = await fs.mkdtemp(path.join('tests', 'tmp-configs-'));
tmpDirs.push(dir);

const outputName = outputConfigName(configName);
await fs.copyFile(path.join('tests', 'factories', configName), path.join(dir, outputName));

return dir;
}

after(() => {
tmpDirs.forEach(async (dir) => {
// await fs.rm(dir, { recursive: true, force: true });
});
});

it('should add next-video to the next.config.js file', async () => {
const dirPath = await createTempDirWithConfig('next.config.js');
await updateNextConfigFile(dirPath);

const updatedContents = await fs.readFile(path.join(dirPath, 'next.config.js'), 'utf-8');

assert(updatedContents.includes('next-video'));
});

it('should add next-video to the next.config.mjs file', async () => {
const dirPath = await createTempDirWithConfig('next.config.mjs');
await updateNextConfigFile(dirPath);

console.log({ dirPath });

const updatedContents = await fs.readFile(path.join(dirPath, 'next.config.mjs'), 'utf-8');

assert(updatedContents.includes('next-video'));
});
});
8 changes: 8 additions & 0 deletions tests/factories/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
};

module.exports = nextConfig;
8 changes: 8 additions & 0 deletions tests/factories/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
};

export default nextConfig;
9 changes: 9 additions & 0 deletions tests/factories/next.function.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
};
return nextConfig;
};
9 changes: 9 additions & 0 deletions tests/factories/next.promise.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = async (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
...defaultConfig,
};
return nextConfig;
};
File renamed without changes.
50 changes: 50 additions & 0 deletions tests/with-next-video.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import assert from 'node:assert';
import { describe, it } from 'node:test';

import withNextVideo from '../src/with-next-video.js';

describe('withNextVideo', () => {
it('should handle nextConfig being a function', async () => {
const nextConfig = (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
...defaultConfig,
};
return nextConfig;
};

const result = await withNextVideo(nextConfig);

const configResult = await result('phase', { defaultConfig: {} });

assert(typeof configResult.webpack === 'function');
});

it('should handle nextConfig being a promise', async () => {
const nextConfig = async (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
...defaultConfig,
};
return nextConfig;
};

const result = await withNextVideo(nextConfig);

const configResult = await result('phase', { defaultConfig: {} });

assert(typeof configResult.webpack === 'function');
});

it('should handle nextConfig being an object', async () => {
const nextConfig = {};

const result = await withNextVideo(nextConfig);

assert(typeof result.webpack === 'function');
});
});
Loading