Skip to content

Commit

Permalink
fix: type error
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaoxiangmoe committed Jul 30, 2023
1 parent dd0cdc1 commit dde3676
Show file tree
Hide file tree
Showing 26 changed files with 212 additions and 63 deletions.
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,6 @@
"tokio",
"ukey",
"Ukey"
]
],
"typescript.tsdk": "node_modules/typescript/lib"
}
53 changes: 30 additions & 23 deletions packages/playground/cases/context/delete-file/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,33 @@
import { test, expect } from "@/fixtures";


test("delete file should work", async ({ page, request, fileAction, rspack }) => {
// asset page status
const statusText = await page.textContent("#root");
expect(statusText).toBe('__PAGE_RENDER__');
// asset script content
const response = await request.get(`http://localhost:${rspack.devServer.options.port}/main.js`);
const bodyResponse = (await response.body()).toString();
expect(bodyResponse).toContain('this is mod1');
expect(bodyResponse).toContain('this is mod2');
// mock file delete action
fileAction.deleteFile("src/mod1.js");
await rspack.waitingForHmr(async () => {
// ensure page status changed
const statusText = await page.textContent("#root");
return statusText === "__HMR_UPDATED__";
});
// asset new script content
const responseAfterDelete = await request.get(`http://localhost:${rspack.devServer.options.port}/main.js`);
const bodyResponseAfterDelete = (await responseAfterDelete.body()).toString();
expect(bodyResponseAfterDelete).not.toContain('this is mod1');
expect(bodyResponseAfterDelete).toContain('this is mod2');
test("delete file should work", async ({
page,
request,
fileAction,
rspack
}) => {
// asset page status
const statusText = await page.textContent("#root");
expect(statusText).toBe("__PAGE_RENDER__");
// asset script content
const response = await request.get(
`http://localhost:${rspack.devServer.options.port}/main.js`
);
const bodyResponse = (await response.body()).toString();
expect(bodyResponse).toContain("this is mod1");
expect(bodyResponse).toContain("this is mod2");
// mock file delete action
fileAction.deleteFile("src/mod1.js");
await rspack.waitingForHmr(async () => {
// ensure page status changed
const statusText = await page.textContent("#root");
return statusText === "__HMR_UPDATED__";
});
// asset new script content
const responseAfterDelete = await request.get(
`http://localhost:${rspack.devServer.options.port}/main.js`
);
const bodyResponseAfterDelete = (await responseAfterDelete.body()).toString();
expect(bodyResponseAfterDelete).not.toContain("this is mod1");
expect(bodyResponseAfterDelete).toContain("this is mod2");
});

12 changes: 10 additions & 2 deletions packages/rspack/src/ErrorHelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const loaderFlag = "LOADER_EXECUTION";

const webpackOptionsFlag = "WEBPACK_OPTIONS";

// @ts-expect-error
exports.cutOffByFlag = (stack, flag) => {
stack = stack.split("\n");
for (let i = 0; i < stack.length; i++) {
Expand All @@ -23,26 +24,31 @@ exports.cutOffByFlag = (stack, flag) => {
}
return stack.join("\n");
};
// @ts-expect-error

exports.cutOffLoaderExecution = stack =>
exports.cutOffByFlag(stack, loaderFlag);

// @ts-expect-error
exports.cutOffWebpackOptions = stack =>
exports.cutOffByFlag(stack, webpackOptionsFlag);

// @ts-expect-error
exports.cutOffMultilineMessage = (stack, message) => {
stack = stack.split("\n");
message = message.split("\n");

// @ts-expect-error
const result = [];

// @ts-expect-error
stack.forEach((line, idx) => {
if (!line.includes(message[idx])) result.push(line);
});

// @ts-expect-error
return result.join("\n");
};

// @ts-expect-error
exports.cutOffMessage = (stack, message) => {
const nextLine = stack.indexOf("\n");
if (nextLine === -1) {
Expand All @@ -53,12 +59,14 @@ exports.cutOffMessage = (stack, message) => {
}
};

// @ts-expect-error
exports.cleanUp = (stack, message) => {
stack = exports.cutOffLoaderExecution(stack);
stack = exports.cutOffMessage(stack, message);
return stack;
};

// @ts-expect-error
exports.cleanUpWebpackOptions = (stack, message) => {
stack = exports.cutOffWebpackOptions(stack);
stack = exports.cutOffMultilineMessage(stack, message);
Expand Down
8 changes: 6 additions & 2 deletions packages/rspack/src/ResolverFactory.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ const {

/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */
/** @typedef {import("enhanced-resolve").Resolver} Resolver */
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */
// /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */
// /** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */
/** @typedef {any} WebpackResolveOptions */
/** @typedef {any} ResolvePluginInstance */

/** @typedef {WebpackResolveOptions & {dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */
/**
Expand All @@ -48,6 +50,7 @@ const convertToResolveOptions = resolveOptionsWithDepType => {
plugins:
plugins &&
/** @type {ResolvePluginInstance[]} */ (
// @ts-expect-error
plugins.filter(item => item !== "...")
)
};
Expand All @@ -63,6 +66,7 @@ const convertToResolveOptions = resolveOptionsWithDepType => {
partialOptions
);

// @ts-expect-error
return removeOperations(
resolveByProperty(options, "byDependency", dependencyType)
);
Expand Down
2 changes: 1 addition & 1 deletion packages/rspack/src/config/browserslistTargetHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const parse = (input, context) => {
/**
* @param {string} input input string
* @param {string} context the context directory
* @returns {string[] | undefined} selected browsers
* @returns {string[] | undefined | null} selected browsers
*/
const load = (input, context) => {
const { configPath, env, query } = parse(input, context);
Expand Down
10 changes: 9 additions & 1 deletion packages/rspack/src/config/target.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const getBrowserslistTargetHandler = memoize(() =>
require("./browserslistTargetHandler")
);

// @ts-expect-error
const getDefaultTarget = context => {
// TODO: align with webpack
// const browsers = getBrowserslistTargetHandler().load(null, context);
Expand Down Expand Up @@ -69,10 +70,12 @@ const getDefaultTarget = context => {
/** @template A @template B @typedef {(A & Never<B>) | (Never<A> & B) | (A & B)} Mix<A,B> */
/** @typedef {Mix<Mix<PlatformTargetProperties, ElectronContextTargetProperties>, Mix<ApiTargetProperties, EcmaTargetProperties>>} TargetProperties */

// @ts-expect-error
const versionDependent = (major, minor) => {
if (!major) return () => /** @type {undefined} */ (undefined);
major = +major;
minor = minor ? +minor : 0;
// @ts-expect-error
return (vMajor, vMinor = 0) => {
return major > vMajor || (major === vMajor && minor >= vMinor);
};
Expand All @@ -87,6 +90,7 @@ const TARGETS = [
(rest, context) => {
const browserslistTargetHandler = getBrowserslistTargetHandler();
const browsers = browserslistTargetHandler.load(
// @ts-expect-error
rest ? rest.trim() : null,
context
);
Expand Down Expand Up @@ -149,6 +153,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
"[async-]node[X[.Y]]",
"Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.",
/^(async-)?node(\d+(?:\.(\d+))?)?$/,
// @ts-expect-error
(asyncFlag, major, minor) => {
const v = versionDependent(major, minor);
// see https://node.green/
Expand Down Expand Up @@ -186,6 +191,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
"electron[X[.Y]]-main/preload/renderer",
"Electron in version X.Y. Script is running in main, preload resp. renderer context.",
/^electron(\d+(?:\.(\d+))?)?-(main|preload|renderer)$/,
// @ts-expect-error
(major, minor, context) => {
const v = versionDependent(major, minor);
// see https://node.green/ + https://github.com/electron/releases
Expand Down Expand Up @@ -227,6 +233,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
"nwjs[X[.Y]] / node-webkit[X[.Y]]",
"NW.js in version X.Y.",
/^(?:nwjs|node-webkit)(\d+(?:\.(\d+))?)?$/,
// @ts-expect-error
(major, minor) => {
const v = versionDependent(major, minor);
// see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md
Expand Down Expand Up @@ -304,7 +311,7 @@ const getTargetProperties = (target, context) => {
).join("\n")}`
);
};

// @ts-expect-error
const mergeTargetProperties = targetProperties => {
const keys = new Set();
for (const tp of targetProperties) {
Expand All @@ -328,6 +335,7 @@ const mergeTargetProperties = targetProperties => {
}
}
if (hasTrue || hasFalse)
// @ts-expect-error
result[key] = hasFalse && hasTrue ? null : hasTrue ? true : false;
}
return /** @type {TargetProperties} */ (result);
Expand Down
17 changes: 13 additions & 4 deletions packages/rspack/src/lib/BannerPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,24 @@ const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const Template = require("./Template");
const createSchemaValidation = require("./util/create-schema-validation");

/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
// /** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */
// /** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */
// /** @typedef {import("./Compiler")} Compiler */
/** @typedef {any} BannerPluginArgument */
/** @typedef {any} BannerPluginOptions */
/** @typedef {any} Compiler */

const validate = createSchemaValidation(
require("../schemas/plugins/BannerPlugin.check.js"),
// @ts-expect-error
() => require("../schemas/plugins/BannerPlugin.json"),
{
name: "Banner Plugin",
baseDataPath: "options"
}
);

// @ts-expect-error
const wrapComment = str => {
if (!str.includes("\n")) {
return Template.toComment(str);
Expand Down Expand Up @@ -56,7 +61,8 @@ class BannerPlugin {
const getBanner = bannerOption;
this.banner = this.options.raw
? getBanner
: data => wrapComment(getBanner(data));
: // @ts-expect-error
data => wrapComment(getBanner(data));
} else {
const banner = this.options.raw
? bannerOption
Expand All @@ -79,10 +85,12 @@ class BannerPlugin {
);
const cache = new WeakMap();

// @ts-expect-error
compiler.hooks.compilation.tap("BannerPlugin", compilation => {
compilation.hooks.processAssets.tap(
{
name: "BannerPlugin",
// @ts-expect-error
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
},
() => {
Expand All @@ -105,6 +113,7 @@ class BannerPlugin {
typeof banner === "function" ? banner({ chunk }) : banner;
const comment = compilation.getPath(normalizedBanner, data);

// @ts-expect-error
compilation.updateAsset(file, old => {
let cached = cache.get(old);
if (!cached || cached.comment !== comment) {
Expand Down
10 changes: 10 additions & 0 deletions packages/rspack/src/lib/Cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ const {
* @returns {void}
*/

// @ts-expect-error
const needCalls = (times, callback) => {
// @ts-expect-error
return err => {
if (--times === 0) {
return callback(err);
Expand Down Expand Up @@ -71,7 +73,9 @@ class Cache {
* @returns {void}
*/
get(identifier, etag, callback) {
// @ts-expect-error
const gotHandlers = [];
// @ts-expect-error
this.hooks.get.callAsync(identifier, etag, gotHandlers, (err, result) => {
if (err) {
callback(makeWebpackError(err, "Cache.hooks.get"));
Expand All @@ -84,10 +88,12 @@ class Cache {
const innerCallback = needCalls(gotHandlers.length, () =>
callback(null, result)
);
// @ts-expect-error
for (const gotHandler of gotHandlers) {
gotHandler(result, innerCallback);
}
} else if (gotHandlers.length === 1) {
// @ts-expect-error
gotHandlers[0](result, () => callback(null, result));
} else {
callback(null, result);
Expand All @@ -108,6 +114,7 @@ class Cache {
identifier,
etag,
data,
// @ts-expect-error
makeWebpackErrorCallback(callback, "Cache.hooks.store")
);
}
Expand All @@ -121,6 +128,7 @@ class Cache {
storeBuildDependencies(dependencies, callback) {
this.hooks.storeBuildDependencies.callAsync(
dependencies,
// @ts-expect-error
makeWebpackErrorCallback(callback, "Cache.hooks.storeBuildDependencies")
);
}
Expand All @@ -138,6 +146,7 @@ class Cache {
*/
endIdle(callback) {
this.hooks.endIdle.callAsync(
// @ts-expect-error
makeWebpackErrorCallback(callback, "Cache.hooks.endIdle")
);
}
Expand All @@ -148,6 +157,7 @@ class Cache {
*/
shutdown(callback) {
this.hooks.shutdown.callAsync(
// @ts-expect-error
makeWebpackErrorCallback(callback, "Cache.hooks.shutdown")
);
}
Expand Down
5 changes: 4 additions & 1 deletion packages/rspack/src/lib/CacheFacade.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ const mergeEtags = require("./cache/mergeEtags.js");
/** @typedef {import("./Cache").Etag} Etag */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */
/** @typedef {typeof import("./util/Hash")} HashConstructor */
// /** @typedef {typeof import("./util/Hash")} HashConstructor */
/** @typedef {any} HashConstructor */

/**
* @template T
Expand Down Expand Up @@ -47,6 +48,7 @@ class MultiItemCache {
* @returns {void}
*/
get(callback) {
// @ts-expect-error
forEachBail(this._items, (item, callback) => item.get(callback), callback);
}

Expand All @@ -55,6 +57,7 @@ class MultiItemCache {
* @returns {Promise<T>} promise with the data
*/
getPromise() {
// @ts-expect-error
const next = i => {
return this._items[i].getPromise().then(result => {
if (result !== undefined) return result;
Expand Down
Loading

0 comments on commit dde3676

Please sign in to comment.