Skip to content

Commit

Permalink
refactor: next
Browse files Browse the repository at this point in the history
BREAKING CHANGE: yes
  • Loading branch information
cap-Bernardito authored Dec 9, 2020
1 parent 6c11e21 commit 4cea28b
Show file tree
Hide file tree
Showing 18 changed files with 1,199 additions and 2,328 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ jobs:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [10.x, 12.x, 14.x]
webpack-version: [4, latest]
webpack-version: [latest]

runs-on: ${{ matrix.os }}

Expand Down
272 changes: 124 additions & 148 deletions README.md

Large diffs are not rendered by default.

1,365 changes: 578 additions & 787 deletions package-lock.json

Large diffs are not rendered by default.

10 changes: 3 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,17 @@
"dist"
],
"peerDependencies": {
"webpack": "^4.37.0 || ^5.0.0"
"webpack": "^5.1.0"
},
"dependencies": {
"cacache": "^15.0.5",
"fast-glob": "^3.2.4",
"find-cache-dir": "^3.3.1",
"glob-parent": "^5.1.1",
"globby": "^11.0.1",
"loader-utils": "^2.0.0",
"normalize-path": "^3.0.0",
"p-limit": "^3.0.2",
"schema-utils": "^3.0.0",
"serialize-javascript": "^5.0.1",
"webpack-sources": "^1.4.3"
"serialize-javascript": "^5.0.1"
},
"devDependencies": {
"@babel/cli": "^7.12.1",
Expand All @@ -62,7 +59,6 @@
"@webpack-contrib/defaults": "^6.3.0",
"@webpack-contrib/eslint-config-webpack": "^3.0.0",
"babel-jest": "^26.6.3",
"chokidar": "^3.4.3",
"cross-env": "^7.0.2",
"del": "^6.0.0",
"del-cli": "^3.0.1",
Expand All @@ -79,7 +75,7 @@
"npm-run-all": "^4.1.5",
"prettier": "^2.1.2",
"standard-version": "^9.0.0",
"webpack": "^5.4.0"
"webpack": "^5.10.0"
},
"keywords": [
"webpack",
Expand Down
148 changes: 32 additions & 116 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import path from "path";
import os from "os";
import crypto from "crypto";

import webpack from "webpack";
import { validate } from "schema-utils";
import pLimit from "p-limit";
import globby from "globby";
import findCacheDir from "find-cache-dir";
import serialize from "serialize-javascript";
import cacache from "cacache";
import loaderUtils from "loader-utils";
import normalizePath from "normalize-path";
import globParent from "glob-parent";
Expand All @@ -19,11 +15,6 @@ import { version } from "../package.json";
import schema from "./options.json";
import { readFile, stat } from "./utils/promisify";

// webpack 5 exposes the sources property to ensure the right version of webpack-sources is used
const { RawSource } =
// eslint-disable-next-line global-require
webpack.sources || require("webpack-sources");

const template = /(\[ext\])|(\[name\])|(\[path\])|(\[folder\])|(\[emoji(?::(\d+))?\])|(\[(?:([^:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\])|(\[\d+\])/;

class CopyPlugin {
Expand All @@ -38,10 +29,6 @@ class CopyPlugin {
}

static async createSnapshot(compilation, startTime, dependency) {
if (!compilation.fileSystemInfo) {
return;
}

// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
compilation.fileSystemInfo.createSnapshot(
Expand All @@ -66,10 +53,6 @@ class CopyPlugin {
}

static async checkSnapshotValid(compilation, snapshot) {
if (!compilation.fileSystemInfo) {
return;
}

// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
compilation.fileSystemInfo.checkSnapshotValid(
Expand All @@ -95,6 +78,7 @@ class CopyPlugin {
inputPattern,
index
) {
const { RawSource } = compiler.webpack.sources;
const pattern =
typeof inputPattern === "string"
? { from: inputPattern }
Expand All @@ -111,6 +95,13 @@ class CopyPlugin {
: pattern.compilerContext
);

pattern.transform =
typeof pattern.transform !== "undefined"
? typeof pattern.transform === "function"
? { transformer: pattern.transform }
: pattern.transform
: {};

logger.log(
`starting to process a pattern from '${pattern.from}' using '${pattern.context}' context`
);
Expand Down Expand Up @@ -152,17 +143,7 @@ class CopyPlugin {
...{ cwd: pattern.context, objectMode: true },
};

// TODO remove after drop webpack@4
if (
inputFileSystem.lstat &&
inputFileSystem.stat &&
inputFileSystem.lstatSync &&
inputFileSystem.statSync &&
inputFileSystem.readdir &&
inputFileSystem.readdirSync
) {
pattern.globOptions.fs = inputFileSystem;
}
pattern.globOptions.fs = inputFileSystem;

switch (pattern.fromType) {
case "dir":
Expand Down Expand Up @@ -327,9 +308,7 @@ class CopyPlugin {
`'to' option '${pattern.to}' determinated as '${pattern.toType}'`
);

const relativeFrom = pattern.flatten
? path.basename(absoluteFilename)
: path.relative(pattern.context, absoluteFilename);
const relativeFrom = path.relative(pattern.context, absoluteFilename);
let filename =
pattern.toType === "dir"
? path.join(pattern.to, relativeFrom)
Expand Down Expand Up @@ -481,67 +460,41 @@ class CopyPlugin {
}
}

if (pattern.transform) {
if (pattern.transform.transformer) {
logger.log(`transforming content for '${absoluteFilename}'...`);

const buffer = result.source.source();

if (pattern.cacheTransform) {
if (pattern.transform.cache) {
const defaultCacheKeys = {
version,
sourceFilename,
transform: pattern.transform,
transform: pattern.transform.transformer,
contentHash: crypto
.createHash("md4")
.update(buffer)
.digest("hex"),
index,
};
const cacheKeys = `transform|${serialize(
typeof pattern.cacheTransform.keys === "function"
? await pattern.cacheTransform.keys(
typeof pattern.transform.cache.keys === "function"
? await pattern.transform.cache.keys(
defaultCacheKeys,
absoluteFilename
)
: { ...defaultCacheKeys, ...pattern.cacheTransform.keys }
: { ...defaultCacheKeys, ...pattern.transform.cache.keys }
)}`;

let cacheItem;
let cacheDirectory;

logger.debug(
`getting transformation cache for '${absoluteFilename}'...`
);

// webpack@5 API
if (cache) {
cacheItem = cache.getItemCache(
cacheKeys,
cache.getLazyHashedEtag(result.source)
);

result.source = await cacheItem.getPromise();
} else {
cacheDirectory = pattern.cacheTransform.directory
? pattern.cacheTransform.directory
: typeof pattern.cacheTransform === "string"
? pattern.cacheTransform
: findCacheDir({ name: "copy-webpack-plugin" }) ||
os.tmpdir();

let cached;
const cacheItem = cache.getItemCache(
cacheKeys,
cache.getLazyHashedEtag(result.source)
);

try {
cached = await cacache.get(cacheDirectory, cacheKeys);
} catch (error) {
logger.debug(
`no transformation cache for '${absoluteFilename}'...`
);
}

// eslint-disable-next-line no-undefined
result.source = cached ? new RawSource(cached.data) : undefined;
}
result.source = await cacheItem.getPromise();

logger.debug(
result.source
Expand All @@ -550,7 +503,7 @@ class CopyPlugin {
);

if (!result.source) {
const transformed = await pattern.transform(
const transformed = await pattern.transform.transformer(
buffer,
absoluteFilename
);
Expand All @@ -561,24 +514,13 @@ class CopyPlugin {
`caching transformation for '${absoluteFilename}'...`
);

// webpack@5 API
if (cache) {
await cacheItem.storePromise(result.source);
} else {
try {
await cacache.put(cacheDirectory, cacheKeys, transformed);
} catch (error) {
compilation.errors.push(error);

return;
}
}
await cacheItem.storePromise(result.source);

logger.debug(`cached transformation for '${absoluteFilename}'`);
}
} else {
result.source = new RawSource(
await pattern.transform(buffer, absoluteFilename)
await pattern.transform.transformer(buffer, absoluteFilename)
);
}
}
Expand Down Expand Up @@ -619,23 +561,6 @@ class CopyPlugin {
);
}

if (pattern.transformPath) {
logger.log(
`transforming '${result.filename}' for '${absoluteFilename}'...`
);

// eslint-disable-next-line no-param-reassign
result.immutable = false;
// eslint-disable-next-line no-param-reassign
result.filename = await pattern.transformPath(
result.filename,
absoluteFilename
);
logger.log(
`transformed new '${result.filename}' for '${absoluteFilename}'...`
);
}

// eslint-disable-next-line no-param-reassign
result.filename = normalizePath(result.filename);

Expand Down Expand Up @@ -663,14 +588,14 @@ class CopyPlugin {

compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
const logger = compilation.getLogger("copy-webpack-plugin");
const cache = compilation.getCache
? compilation.getCache("CopyWebpackPlugin")
: // eslint-disable-next-line no-undefined
undefined;

compilation.hooks.additionalAssets.tapAsync(
"copy-webpack-plugin",
async (callback) => {
const cache = compilation.getCache("CopyWebpackPlugin");

compilation.hooks.processAssets.tapAsync(
{
name: "copy-webpack-plugin",
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
async (unusedAssets, callback) => {
logger.log("starting to add additional assets...");

let assets;
Expand Down Expand Up @@ -712,15 +637,6 @@ class CopyPlugin {
force,
} = asset;

// For old version webpack 4
/* istanbul ignore if */
if (typeof compilation.emitAsset !== "function") {
// eslint-disable-next-line no-param-reassign
compilation.assets[filename] = source;

return;
}

const existingAsset = compilation.getAsset(filename);

if (existingAsset) {
Expand Down
37 changes: 20 additions & 17 deletions src/options.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,36 +43,39 @@
}
]
},
"flatten": {
"type": "boolean"
},
"transform": {
"instanceof": "Function"
},
"cacheTransform": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string"
"instanceof": "Function"
},
{
"type": "object",
"additionalProperties": false,
"properties": {
"directory": {
"type": "string",
"absolutePath": true
"transformer": {
"instanceof": "Function"
},
"keys": {
"cache": {
"anyOf": [
{
"type": "object",
"additionalProperties": true
"type": "boolean"
},
{
"instanceof": "Function"
"type": "object",
"additionalProperties": false,
"properties": {
"keys": {
"anyOf": [
{
"type": "object",
"additionalProperties": true
},
{
"instanceof": "Function"
}
]
}
}
}
]
}
Expand Down
Loading

0 comments on commit 4cea28b

Please sign in to comment.