diff --git a/.eslintignore b/.eslintignore index 421b2fb729a9..a0149d12f8e9 100644 --- a/.eslintignore +++ b/.eslintignore @@ -6,8 +6,6 @@ crates/rspack_plugin_mf crates/rspack_plugin_extract_css/src/runtime packages/rspack/compiled packages/rspack-dev-server/client -packages/rspack-plugin-react-refresh/client -packages/rspack-plugin-preact-refresh/client packages/playground packages/rspack/src/stats/DefaultStatsPrinterPlugin.ts packages/rspack-test-tools/template diff --git a/.prettierignore b/.prettierignore index a968f49e8af4..f48276101652 100644 --- a/.prettierignore +++ b/.prettierignore @@ -13,7 +13,6 @@ packages/**/etc/**/* packages/rspack-test-tools/template/**/* packages/rspack-test-tools/src/helper/legacy/**/* packages/rspack-test-tools/tests/**/* -packages/rspack-test-preact-refresh/tests/**/* packages/rspack-plugin-mini-css-extract/test/cases/**/* crates/**/* diff --git a/README.md b/README.md index d1a8807aeacf..64bbde6a17e2 100644 --- a/README.md +++ b/README.md @@ -81,8 +81,8 @@ Thanks to: - The [rolldown-legacy](https://github.com/rolldown-rs/rolldown-legacy) project created by old [Rolldown team](https://github.com/rolldown-rs), It's the predecessor of the [rolldown](https://github.com/rolldown) project, which explores the possibility of making a performant bundler in Rust with Rollup-compatible API. It inspires the design principles of Rspack. - The [html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin) project created by [@jantimon](https://github.com/jantimon), `@rspack/html-plugin` is a fork of [html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin) to avoid some webpack API usage not supported in Rspack. - The [Turbopack](https://github.com/vercel/turbo) project which inspired the AST path logic of Rspack. -- The [react-refresh-webpack-plugin](https://github.com/pmmmwh/react-refresh-webpack-plugin) created by [@pmmmwh](https://github.com/pmmmwh), which inspires implement react refresh. -- The [prefresh](https://github.com/preactjs/prefresh) created by [@Jovi De Croock](https://github.com/JoviDeCroock), which inspires implement preact refresh rspack plugin. +- The [react-refresh-webpack-plugin](https://github.com/pmmmwh/react-refresh-webpack-plugin) created by [@pmmmwh](https://github.com/pmmmwh), which inspires implement [react refresh rspack plugin](https://github.com/rspack-contrib/rspack-plugin-react-refresh). +- The [prefresh](https://github.com/preactjs/prefresh) created by [@Jovi De Croock](https://github.com/JoviDeCroock), which inspires implement [preact refresh rspack plugin](https://github.com/rspack-contrib/rspack-plugin-preact-refresh). - The [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin) project created by [@sokra](https://github.com/sokra) which inspired implement css extract plugin. - The [copy-webpack-plugin](https://github.com/webpack-contrib/copy-webpack-plugin) project created by [@kevlened](https://github.com/kevlened) which inspired implement copy rspack plugin. diff --git a/biome.jsonc b/biome.jsonc index bc4194f54894..b201eaf8d51f 100644 --- a/biome.jsonc +++ b/biome.jsonc @@ -16,7 +16,6 @@ "packages/**/etc/**/*", "crates/**/*", "tests/**/*", - "packages/rspack-plugin-preact-refresh/tests/**/*", "packages/rspack-test-tools/template/**/*", "packages/rspack-test-tools/tests/**/*", "packages/rspack-test-tools/src/helper/legacy/**/*", @@ -25,8 +24,6 @@ // --- ignore runtime code in browser "packages/rspack/hot", "packages/rspack-dev-server/client", - "packages/rspack-plugin-react-refresh/client", - "packages/rspack-plugin-preact-refresh/client", "packages/rspack/src/container/default.runtime.js" ] }, @@ -75,8 +72,6 @@ // --- ignore runtime code in browser "packages/rspack/hot", "packages/rspack-dev-server/client", - "packages/rspack-plugin-react-refresh/client", - "packages/rspack-plugin-preact-refresh/client", "packages/rspack/src/container/default.runtime.js" ] }, diff --git a/packages/create-rspack/template-react-ts/package.json b/packages/create-rspack/template-react-ts/package.json index 0d6c57be21e5..7a4f9d0ed6ae 100644 --- a/packages/create-rspack/template-react-ts/package.json +++ b/packages/create-rspack/template-react-ts/package.json @@ -13,7 +13,7 @@ "devDependencies": { "@rspack/cli": "workspace:*", "@rspack/core": "workspace:*", - "@rspack/plugin-react-refresh": "workspace:*", + "@rspack/plugin-react-refresh": "1.0.0-beta.5", "@types/react": "^18.2.48", "@types/react-dom": "^18.2.18", "cross-env": "^7.0.3", @@ -21,4 +21,4 @@ "ts-node": "^10.9.2", "typescript": "^5.3.3" } -} +} \ No newline at end of file diff --git a/packages/create-rspack/template-react/package.json b/packages/create-rspack/template-react/package.json index 6f5a2b587472..62a8ecf922cb 100644 --- a/packages/create-rspack/template-react/package.json +++ b/packages/create-rspack/template-react/package.json @@ -11,7 +11,7 @@ "react-dom": "^18.2.0" }, "devDependencies": { - "@rspack/plugin-react-refresh": "workspace:*", + "@rspack/plugin-react-refresh": "1.0.0-beta.5", "@rspack/cli": "workspace:*", "@rspack/core": "workspace:*", "@types/react": "^18.2.48", @@ -19,4 +19,4 @@ "cross-env": "^7.0.3", "react-refresh": "^0.14.0" } -} +} \ No newline at end of file diff --git a/packages/playground/package.json b/packages/playground/package.json index 3a8b3e812a3e..e4ef38ba4ea9 100644 --- a/packages/playground/package.json +++ b/packages/playground/package.json @@ -18,7 +18,7 @@ "core-js": "3.36.1", "@rspack/core": "workspace:*", "@rspack/dev-server": "workspace:*", - "@rspack/plugin-react-refresh": "workspace:*", + "@rspack/plugin-react-refresh": "1.0.0-beta.5", "@swc/helpers": "0.5.8", "@types/fs-extra": "11.0.4", "babel-loader": "^9.1.3", diff --git a/packages/rspack-cli/tsconfig.json b/packages/rspack-cli/tsconfig.json index 65b39f11a2bd..e13412b8d194 100644 --- a/packages/rspack-cli/tsconfig.json +++ b/packages/rspack-cli/tsconfig.json @@ -1,6 +1,8 @@ { "extends": "../../tsconfig.base.json", - "include": ["src"], + "include": [ + "src" + ], "compilerOptions": { "outDir": "dist", "rootDir": "src" @@ -11,9 +13,6 @@ }, { "path": "../rspack-dev-server" - }, - { - "path": "../rspack-plugin-react-refresh" } ] -} +} \ No newline at end of file diff --git a/packages/rspack-dev-server/package.json b/packages/rspack-dev-server/package.json index f0b215e6a413..86b23e0ed0c6 100644 --- a/packages/rspack-dev-server/package.json +++ b/packages/rspack-dev-server/package.json @@ -40,7 +40,7 @@ "typescript": "5.0.2", "@rspack/core": "workspace:*", "@rspack/dev-server": "workspace:*", - "@rspack/plugin-react-refresh": "workspace:*", + "@rspack/plugin-react-refresh": "1.0.0-beta.5", "@types/connect-history-api-fallback": "1.5.4", "@types/express": "4.17.21", "@types/mime-types": "2.1.4", diff --git a/packages/rspack-dev-server/tests/normalizeOptions.test.ts b/packages/rspack-dev-server/tests/normalizeOptions.test.ts index 9a23935f9c17..412e0e65b782 100644 --- a/packages/rspack-dev-server/tests/normalizeOptions.test.ts +++ b/packages/rspack-dev-server/tests/normalizeOptions.test.ts @@ -35,7 +35,7 @@ describe.skip("normalize options snapshot", () => { it("shouldn't have reactRefreshEntry.js by default when in production mode", async () => { const reactRefreshEntry = - "/rspack-plugin-react-refresh/client/reactRefreshEntry.js"; + "plugin-react-refresh/client/reactRefreshEntry.js"; const entries1 = await getAdditionEntries( {}, { diff --git a/packages/rspack-lite-tapable/LICENSE b/packages/rspack-lite-tapable/LICENSE deleted file mode 100644 index 46310101ad8a..000000000000 --- a/packages/rspack-lite-tapable/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2022-present Bytedance, Inc. and its affiliates. - - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/packages/rspack-lite-tapable/README.md b/packages/rspack-lite-tapable/README.md deleted file mode 100644 index b864cc7c4be1..000000000000 --- a/packages/rspack-lite-tapable/README.md +++ /dev/null @@ -1,16 +0,0 @@ - - - Rspack Banner - - -# @rspack/lite-tapable - -Lite weight tapable for Rspack. - -## Documentation - -See for details. - -## License - -Rspack is [MIT licensed](https://github.com/web-infra-dev/rspack/blob/main/LICENSE). diff --git a/packages/rspack-lite-tapable/api-extractor.json b/packages/rspack-lite-tapable/api-extractor.json deleted file mode 100644 index 1e0238cd9f0a..000000000000 --- a/packages/rspack-lite-tapable/api-extractor.json +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Config file for API Extractor. For more info, please visit: https://api-extractor.com - */ -{ - "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", - "extends": "../../api-extractor.json" -} diff --git a/packages/rspack-lite-tapable/etc/api.md b/packages/rspack-lite-tapable/etc/api.md deleted file mode 100644 index c44819a6b1a0..000000000000 --- a/packages/rspack-lite-tapable/etc/api.md +++ /dev/null @@ -1,353 +0,0 @@ -## API Report File for "@rspack/lite-tapable" - -> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). - -```ts - -// @public (undocumented) -type Append = { - 0: [U]; - 1: [T[0], U]; - 2: [T[0], T[1], U]; - 3: [T[0], T[1], T[2], U]; - 4: [T[0], T[1], T[2], T[3], U]; - 5: [T[0], T[1], T[2], T[3], T[4], U]; - 6: [T[0], T[1], T[2], T[3], T[4], T[5], U]; - 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], U]; - 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], U]; -}[Measure]; - -// @public (undocumented) -type ArgumentNames = FixedSizeArray; - -// @public (undocumented) -export type AsArray = T extends any[] ? T : [T]; - -// @public (undocumented) -export class AsyncParallelHook extends HookBase { - // (undocumented) - callAsyncStageRange(queried: QueriedHook, ...args: Append, Callback>): void; -} - -// @public (undocumented) -export class AsyncSeriesBailHook extends HookBase { - // (undocumented) - callAsyncStageRange(queried: QueriedHook, ...args: Append, Callback>): void; -} - -// @public (undocumented) -export class AsyncSeriesHook extends HookBase { - // (undocumented) - callAsyncStageRange(queried: QueriedHook, ...args: Append, Callback>): void; -} - -// @public (undocumented) -export class AsyncSeriesWaterfallHook extends HookBase[0], AdditionalOptions> { - constructor(args?: FixedSizeArray["length"], string>, name?: string); - // (undocumented) - callAsyncStageRange(queried: QueriedHook[0], AdditionalOptions>, ...args: Append, Callback[0]>>): void; -} - -// @public (undocumented) -export type Callback = (error: E | null, result?: T) => void; - -// @public (undocumented) -type ExtractHookAdditionalOptions = H extends Hook ? A : never; - -// @public (undocumented) -type ExtractHookArgs = H extends Hook ? T : never; - -// @public (undocumented) -type ExtractHookReturn = H extends Hook ? R : never; - -// @public (undocumented) -type FixedSizeArray = T extends 0 ? void[] : ReadonlyArray & { - 0: U; - length: T; -}; - -// @public (undocumented) -export type Fn = (...args: AsArray) => R; - -// @public (undocumented) -export type FnAsync = (...args: Append, InnerCallback>) => void; - -// @public (undocumented) -export type FnPromise = (...args: AsArray) => Promise; - -// @public (undocumented) -type FullTap = Tap & { - type: "sync" | "async" | "promise"; - fn: Function; -}; - -// @public (undocumented) -export interface Hook { - // (undocumented) - intercept(interceptor: HookInterceptor): void; - // (undocumented) - isUsed(): boolean; - // (undocumented) - name?: string; - // (undocumented) - queryStageRange(stageRange: StageRange): QueriedHook; - // (undocumented) - tap(opt: Options, fn: Fn): void; - // (undocumented) - tapAsync(opt: Options, fn: FnAsync): void; - // (undocumented) - tapPromise(opt: Options, fn: FnPromise): void; - // (undocumented) - withOptions(opt: TapOptions & IfSet): Hook; -} - -// @public (undocumented) -export class HookBase implements Hook { - constructor(args?: FixedSizeArray["length"], string>, name?: string); - // (undocumented) - args: ArgumentNames>; - // (undocumented) - callAsync(...args: Append, Callback>): void; - // (undocumented) - callAsyncStageRange(queried: QueriedHook, ...args: Append, Callback>): void; - // (undocumented) - _insert(item: FullTap & IfSet): void; - // (undocumented) - intercept(interceptor: HookInterceptor): void; - // (undocumented) - interceptors: HookInterceptor[]; - // (undocumented) - isUsed(): boolean; - // (undocumented) - name?: string; - // (undocumented) - _prepareArgs(args: AsArray): (T | undefined)[]; - // (undocumented) - promise(...args: AsArray): Promise; - // (undocumented) - promiseStageRange(queried: QueriedHook, ...args: AsArray): Promise; - // (undocumented) - queryStageRange(stageRange: StageRange): QueriedHook; - // (undocumented) - _runCallInterceptors(...args: any[]): void; - // (undocumented) - _runDoneInterceptors(): void; - // (undocumented) - _runErrorInterceptors(e: Error): void; - // (undocumented) - _runRegisterInterceptors(options: FullTap & IfSet): FullTap & IfSet; - // (undocumented) - _runResultInterceptors(r: R): void; - // (undocumented) - _runTapInterceptors(tap: FullTap & IfSet): void; - // (undocumented) - tap(options: Options, fn: Fn): void; - // (undocumented) - _tap(type: "sync" | "async" | "promise", options: Options, fn: Function): void; - // (undocumented) - tapAsync(options: Options, fn: FnAsync): void; - // (undocumented) - tapPromise(options: Options, fn: FnPromise): void; - // (undocumented) - taps: (FullTap & IfSet)[]; - // (undocumented) - withOptions(options: TapOptions & IfSet): Hook; -} - -// @public (undocumented) -export type HookFactory = (key: HookMapKey, hook?: H) => H; - -// @public (undocumented) -export interface HookInterceptor { - // (undocumented) - call?: (...args: any[]) => void; - // (undocumented) - done?: () => void; - // (undocumented) - error?: (err: Error) => void; - // (undocumented) - loop?: (...args: any[]) => void; - // (undocumented) - name?: string; - // (undocumented) - register?: (tap: FullTap & IfSet) => FullTap & IfSet; - // (undocumented) - result?: (result: R) => void; - // (undocumented) - tap?: (tap: FullTap & IfSet) => void; -} - -// @public (undocumented) -export class HookMap { - constructor(factory: HookFactory, name?: string); - // (undocumented) - _factory: HookFactory; - // (undocumented) - for(key: HookMapKey): H; - // (undocumented) - get(key: HookMapKey): H | undefined; - // (undocumented) - intercept(interceptor: HookMapInterceptor): void; - // (undocumented) - _interceptors: HookMapInterceptor[]; - // (undocumented) - isUsed(): boolean; - // (undocumented) - _map: Map; - // (undocumented) - name?: string; - // (undocumented) - queryStageRange(stageRange: StageRange): QueriedHookMap; -} - -// @public (undocumented) -export interface HookMapInterceptor { - // (undocumented) - factory?: HookFactory; -} - -// @public (undocumented) -export type HookMapKey = any; - -// @public (undocumented) -type IfSet = X extends UnsetAdditionalOptions ? {} : X; - -// @public (undocumented) -type InnerCallback = (error?: E | null | false, result?: T) => void; - -// @public (undocumented) -export const maxStage: number; - -// @public (undocumented) -type Measure = T extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 ? T : never; - -// @public (undocumented) -export const minStage: number; - -// @public (undocumented) -export class MultiHook { - constructor(hooks: H[], name?: string); - // (undocumented) - hooks: H[]; - // (undocumented) - intercept(interceptor: HookInterceptor, ExtractHookReturn, ExtractHookAdditionalOptions>): void; - // (undocumented) - isUsed(): boolean; - // (undocumented) - name?: string; - // (undocumented) - tap(options: Options>, fn: Fn, ExtractHookReturn>): void; - // (undocumented) - tapAsync(options: Options>, fn: FnAsync, ExtractHookReturn>): void; - // (undocumented) - tapPromise(options: Options>, fn: FnPromise, ExtractHookReturn>): void; - // (undocumented) - withOptions(options: TapOptions & IfSet>): MultiHook>; -} - -// @public (undocumented) -export type Options = string | (Tap & IfSet); - -// @public (undocumented) -export class QueriedHook { - constructor(stageRange: StageRange, hook: HookBase); - // (undocumented) - call(...args: AsArray): R; - // (undocumented) - callAsync(...args: Append, Callback>): void; - // (undocumented) - hook: HookBase; - // (undocumented) - isUsed(): boolean; - // (undocumented) - promise(...args: AsArray): Promise; - // (undocumented) - stageRange: StageRange; - // (undocumented) - tapsInRange: (FullTap & IfSet)[]; -} - -// @public (undocumented) -export class QueriedHookMap { - constructor(stageRange: StageRange, hookMap: HookMap); - // (undocumented) - for(key: HookMapKey): QueriedHook; - // (undocumented) - get(key: HookMapKey): QueriedHook | undefined; - // (undocumented) - hookMap: HookMap; - // (undocumented) - isUsed(): boolean; - // (undocumented) - stageRange: StageRange; -} - -// @public (undocumented) -export const safeStage: (stage: number) => number; - -// @public (undocumented) -export type StageRange = readonly [number, number]; - -// @public (undocumented) -export class SyncBailHook extends HookBase { - // (undocumented) - call(...args: AsArray): R; - // (undocumented) - callAsyncStageRange(queried: QueriedHook, ...args: Append, Callback>): void; - // (undocumented) - callStageRange(queried: QueriedHook, ...args: AsArray): R; - // (undocumented) - tapAsync(): never; - // (undocumented) - tapPromise(): never; -} - -// @public (undocumented) -export class SyncHook extends HookBase { - // (undocumented) - call(...args: AsArray): R; - // (undocumented) - callAsyncStageRange(queried: QueriedHook, ...args: Append, Callback>): void; - // (undocumented) - callStageRange(queried: QueriedHook, ...args: AsArray): R; - // (undocumented) - tapAsync(): never; - // (undocumented) - tapPromise(): never; -} - -// @public (undocumented) -export class SyncWaterfallHook extends HookBase[0], AdditionalOptions> { - constructor(args?: FixedSizeArray["length"], string>, name?: string); - // (undocumented) - call(...args: AsArray): AsArray[0]; - // (undocumented) - callAsyncStageRange(queried: QueriedHook[0], AdditionalOptions>, ...args: Append, Callback[0]>>): void; - // (undocumented) - callStageRange(queried: QueriedHook[0], AdditionalOptions>, ...args: AsArray): AsArray[0]; - // (undocumented) - tapAsync(): never; - // (undocumented) - tapPromise(): never; -} - -// @public (undocumented) -type Tap = TapOptions & { - name: string; -}; - -// @public (undocumented) -type TapOptions = { - before?: string; - stage?: number; -}; - -// @public (undocumented) -class UnsetAdditionalOptions { - // (undocumented) - _UnsetAdditionalOptions: true; -} - -// (No @packageDocumentation comment for this package) - -``` diff --git a/packages/rspack-lite-tapable/jest.config.js b/packages/rspack-lite-tapable/jest.config.js deleted file mode 100644 index d0d5e171f9e8..000000000000 --- a/packages/rspack-lite-tapable/jest.config.js +++ /dev/null @@ -1,11 +0,0 @@ -/** @type {import('ts-jest/dist/types').JestConfigWithTsJest} */ -const config = { - preset: "ts-jest", - testEnvironment: "../../scripts/test/patch-node-env.cjs", - testTimeout: process.env.CI ? 200000 : 30000, - testMatch: ["/tests/**/*.test.ts", "/tests/**/*.test.js"], - watchPathIgnorePatterns: ["/tests/.*/dist"], - extensionsToTreatAsEsm: [".mts"] -}; - -module.exports = config; diff --git a/packages/rspack-lite-tapable/package.json b/packages/rspack-lite-tapable/package.json deleted file mode 100644 index a6442c15df03..000000000000 --- a/packages/rspack-lite-tapable/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@rspack/lite-tapable", - "version": "1.0.0-beta.3", - "license": "MIT", - "description": "Lite weight tapable for Rspack", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", - "publishConfig": { - "access": "public", - "provenance": true - }, - "exports": { - ".": { - "default": "./dist/index.js" - } - }, - "devDependencies": { - "typescript": "5.0.2" - }, - "scripts": { - "build": "tsc -b ./tsconfig.build.json", - "build:force": "tsc -b ./tsconfig.build.json --force", - "test": "jest --colors", - "api-extractor": "api-extractor run --verbose", - "api-extractor:ci": "api-extractor run --verbose || diff temp/api.md etc/api.md" - }, - "files": [ - "dist" - ], - "engines": { - "node": ">=16.0.0" - }, - "homepage": "https://rspack.dev", - "bugs": "https://github.com/web-infra-dev/rspack/issues", - "repository": { - "type": "git", - "url": "https://github.com/web-infra-dev/rspack", - "directory": "packages/lite-tapable" - } -} \ No newline at end of file diff --git a/packages/rspack-lite-tapable/src/index.ts b/packages/rspack-lite-tapable/src/index.ts deleted file mode 100644 index 4374ed641fbe..000000000000 --- a/packages/rspack-lite-tapable/src/index.ts +++ /dev/null @@ -1,1158 +0,0 @@ -type FixedSizeArray = T extends 0 - ? void[] - : ReadonlyArray & { - 0: U; - length: T; - }; -type Measure = T extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 - ? T - : never; -type Append = { - 0: [U]; - 1: [T[0], U]; - 2: [T[0], T[1], U]; - 3: [T[0], T[1], T[2], U]; - 4: [T[0], T[1], T[2], T[3], U]; - 5: [T[0], T[1], T[2], T[3], T[4], U]; - 6: [T[0], T[1], T[2], T[3], T[4], T[5], U]; - 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], U]; - 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], U]; -}[Measure]; -export type AsArray = T extends any[] ? T : [T]; - -export type Fn = (...args: AsArray) => R; -export type FnAsync = ( - ...args: Append, InnerCallback> -) => void; -export type FnPromise = (...args: AsArray) => Promise; - -declare class UnsetAdditionalOptions { - _UnsetAdditionalOptions: true; -} -type IfSet = X extends UnsetAdditionalOptions ? {} : X; - -export type Callback = (error: E | null, result?: T) => void; -type InnerCallback = (error?: E | null | false, result?: T) => void; - -type FullTap = Tap & { - type: "sync" | "async" | "promise"; - fn: Function; -}; - -type Tap = TapOptions & { - name: string; -}; - -type TapOptions = { - before?: string; - stage?: number; -}; - -export type Options = - | string - | (Tap & IfSet); - -export interface HookInterceptor< - T, - R, - AdditionalOptions = UnsetAdditionalOptions -> { - name?: string; - tap?: (tap: FullTap & IfSet) => void; - call?: (...args: any[]) => void; - loop?: (...args: any[]) => void; - error?: (err: Error) => void; - result?: (result: R) => void; - done?: () => void; - register?: ( - tap: FullTap & IfSet - ) => FullTap & IfSet; -} - -type ArgumentNames = FixedSizeArray; -type ExtractHookArgs = H extends Hook ? T : never; -type ExtractHookReturn = H extends Hook ? R : never; -type ExtractHookAdditionalOptions = - H extends Hook ? A : never; - -export interface Hook< - T = any, - R = any, - AdditionalOptions = UnsetAdditionalOptions -> { - name?: string; - tap(opt: Options, fn: Fn): void; - tapAsync(opt: Options, fn: FnAsync): void; - tapPromise(opt: Options, fn: FnPromise): void; - intercept(interceptor: HookInterceptor): void; - isUsed(): boolean; - withOptions( - opt: TapOptions & IfSet - ): Hook; - queryStageRange(stageRange: StageRange): QueriedHook; -} - -export class HookBase - implements Hook -{ - args: ArgumentNames>; - name?: string; - taps: (FullTap & IfSet)[]; - interceptors: HookInterceptor[]; - - constructor( - args = [] as unknown as ArgumentNames>, - name?: string - ) { - this.args = args; - this.name = name; - this.taps = []; - this.interceptors = []; - } - - intercept(interceptor: HookInterceptor) { - this.interceptors.push(Object.assign({}, interceptor)); - if (interceptor.register) { - for (let i = 0; i < this.taps.length; i++) { - this.taps[i] = interceptor.register(this.taps[i]); - } - } - } - - _runRegisterInterceptors( - options: FullTap & IfSet - ): FullTap & IfSet { - return this.interceptors.reduce((options, interceptor) => { - return interceptor.register?.(options) ?? options; - }, options); - } - - _runCallInterceptors(...args: any[]) { - for (const interceptor of this.interceptors) { - if (interceptor.call) { - interceptor.call(...args); - } - } - } - - _runErrorInterceptors(e: Error) { - for (const interceptor of this.interceptors) { - if (interceptor.error) { - interceptor.error(e); - } - } - } - - _runTapInterceptors(tap: FullTap & IfSet) { - for (const interceptor of this.interceptors) { - if (interceptor.tap) { - interceptor.tap(tap); - } - } - } - - _runDoneInterceptors() { - for (const interceptor of this.interceptors) { - if (interceptor.done) { - interceptor.done(); - } - } - } - - _runResultInterceptors(r: R) { - for (const interceptor of this.interceptors) { - if (interceptor.result) { - interceptor.result(r); - } - } - } - - withOptions( - options: TapOptions & IfSet - ): Hook { - const mergeOptions = (opt: any) => - Object.assign({}, options, typeof opt === "string" ? { name: opt } : opt); - - return { - name: this.name, - tap: (opt: Options, fn: Fn) => - this.tap(mergeOptions(opt), fn), - tapAsync: (opt: Options, fn: FnAsync) => - this.tapAsync(mergeOptions(opt), fn), - tapPromise: (opt: Options, fn: FnPromise) => - this.tapPromise(mergeOptions(opt), fn), - intercept: (interceptor: HookInterceptor) => - this.intercept(interceptor), - isUsed: () => this.isUsed(), - withOptions: (opt: TapOptions & IfSet) => - this.withOptions(mergeOptions(opt)), - queryStageRange: (stageRange: StageRange) => - this.queryStageRange(stageRange) - }; - } - - isUsed() { - return this.taps.length > 0 || this.interceptors.length > 0; - } - - queryStageRange( - stageRange: StageRange - ): QueriedHook { - return new QueriedHook(stageRange, this); - } - - callAsyncStageRange( - queried: QueriedHook, - ...args: Append, Callback> - ) { - throw new Error("Hook should implement there own _callAsyncStageRange"); - } - - callAsync(...args: Append, Callback>): void { - return this.callAsyncStageRange( - this.queryStageRange(allStageRange), - ...args - ); - } - - promiseStageRange( - queried: QueriedHook, - ...args: AsArray - ): Promise { - return new Promise((resolve, reject) => { - this.callAsyncStageRange( - queried, - // @ts-expect-error - ...args, - (e: Error, r: R) => { - if (e) return reject(e); - return resolve(r); - } - ); - }); - } - - promise(...args: AsArray): Promise { - return this.promiseStageRange(this.queryStageRange(allStageRange), ...args); - } - - tap(options: Options, fn: Fn) { - this._tap("sync", options, fn); - } - - tapAsync(options: Options, fn: FnAsync) { - this._tap("async", options, fn); - } - - tapPromise(options: Options, fn: FnPromise) { - this._tap("promise", options, fn); - } - - _tap( - type: "sync" | "async" | "promise", - options: Options, - fn: Function - ) { - let normalizedOptions = options as Tap & IfSet; - - if (typeof options === "string") { - normalizedOptions = { - name: options.trim() - } as Tap & IfSet; - } else if (typeof options !== "object" || options === null) { - throw new Error("Invalid tap options"); - } - - if ( - typeof normalizedOptions.name !== "string" || - normalizedOptions.name === "" - ) { - throw new Error("Missing name for tap"); - } - - this._insert( - this._runRegisterInterceptors( - Object.assign({ type, fn }, normalizedOptions) - ) - ); - } - - _insert(item: FullTap & IfSet) { - let before; - if (typeof item.before === "string") { - before = new Set([item.before]); - } else if (Array.isArray(item.before)) { - before = new Set(item.before); - } - let stage = 0; - if (typeof item.stage === "number") { - stage = item.stage; - } - let i = this.taps.length; - while (i > 0) { - i--; - const x = this.taps[i]; - this.taps[i + 1] = x; - const xStage = x.stage || 0; - if (before) { - if (before.has(x.name)) { - before.delete(x.name); - continue; - } - if (before.size > 0) { - continue; - } - } - if (xStage > stage) { - continue; - } - i++; - break; - } - this.taps[i] = item; - } - - _prepareArgs(args: AsArray): (T | undefined)[] { - const len = this.args.length; - if (args.length < len) { - args.length = len; - return (args as (T | undefined)[]).fill(undefined, args.length, len); - } - if (args.length > len) { - args.length = len; - return args; - } - return args; - } -} - -export type StageRange = readonly [number, number]; -export const minStage = Number.NEGATIVE_INFINITY; -export const maxStage = Number.POSITIVE_INFINITY; -const allStageRange = [minStage, maxStage] as const; -const i32MIN = -(2 ** 31); -const i32MAX = 2 ** 31 - 1; -export const safeStage = (stage: number) => { - if (stage < i32MIN) return i32MIN; - if (stage > i32MAX) return i32MAX; - return stage; -}; - -export class QueriedHook { - stageRange: StageRange; - hook: HookBase; - tapsInRange: (FullTap & IfSet)[]; - - constructor(stageRange: StageRange, hook: HookBase) { - const tapsInRange: typeof hook.taps = []; - const [from, to] = stageRange; - for (const tap of hook.taps) { - const stage = tap.stage ?? 0; - if (from <= stage && stage < to) { - tapsInRange.push(tap); - } else if (to === maxStage && stage === maxStage) { - tapsInRange.push(tap); - } - } - this.stageRange = stageRange; - this.hook = hook; - this.tapsInRange = tapsInRange; - } - - isUsed(): boolean { - if (this.tapsInRange.length > 0) return true; - if ( - this.stageRange[0] === minStage && - this.hook.interceptors.some(i => i.call) - ) - return true; - if ( - this.stageRange[1] === maxStage && - this.hook.interceptors.some(i => i.done) - ) - return true; - return false; - } - - call(...args: AsArray): R { - if ( - typeof (this.hook as SyncHook).callStageRange !== - "function" - ) { - throw new Error( - "hook is not a SyncHook, call methods only exists on SyncHook" - ); - } - return (this.hook as SyncHook).callStageRange( - this, - ...args - ); - } - - callAsync(...args: Append, Callback>): void { - return this.hook.callAsyncStageRange(this, ...args); - } - - promise(...args: AsArray): Promise { - return this.hook.promiseStageRange(this, ...args); - } -} - -export class SyncHook< - T, - R = void, - AdditionalOptions = UnsetAdditionalOptions -> extends HookBase { - callAsyncStageRange( - queried: QueriedHook, - ...args: Append, Callback> - ) { - const { - stageRange: [from, to], - tapsInRange - } = queried; - const argsWithoutCb = args.slice(0, args.length - 1) as AsArray; - const cb = args[args.length - 1] as Callback; - const args2 = this._prepareArgs(argsWithoutCb); - if (from === minStage) { - this._runCallInterceptors(...args2); - } - for (const tap of tapsInRange) { - this._runTapInterceptors(tap); - try { - tap.fn(...args2); - } catch (e) { - const err = e as Error; - this._runErrorInterceptors(err); - return cb(err); - } - } - if (to === maxStage) { - this._runDoneInterceptors(); - cb(null); - } - } - - call(...args: AsArray): R { - return this.callStageRange(this.queryStageRange(allStageRange), ...args); - } - - callStageRange( - queried: QueriedHook, - ...args: AsArray - ): R { - let result; - let error; - this.callAsyncStageRange( - queried, - // @ts-expect-error - ...args, - (e: Error, r: R): void => { - error = e; - result = r; - } - ); - if (error) { - throw error; - } - return result as R; - } - - tapAsync(): never { - throw new Error("tapAsync is not supported on a SyncHook"); - } - - tapPromise(): never { - throw new Error("tapPromise is not supported on a SyncHook"); - } -} - -export class SyncBailHook< - T, - R, - AdditionalOptions = UnsetAdditionalOptions -> extends HookBase { - callAsyncStageRange( - queried: QueriedHook, - ...args: Append, Callback> - ) { - const { - stageRange: [from, to], - tapsInRange - } = queried; - const argsWithoutCb = args.slice(0, args.length - 1) as AsArray; - const cb = args[args.length - 1] as Callback; - const args2 = this._prepareArgs(argsWithoutCb); - if (from === minStage) { - this._runCallInterceptors(...args2); - } - for (const tap of tapsInRange) { - this._runTapInterceptors(tap); - let r = undefined; - try { - r = tap.fn(...args2); - } catch (e) { - const err = e as Error; - this._runErrorInterceptors(err); - return cb(err); - } - if (r !== undefined) { - this._runResultInterceptors(r); - return cb(null, r); - } - } - if (to === maxStage) { - this._runDoneInterceptors(); - cb(null); - } - } - - call(...args: AsArray): R { - return this.callStageRange(this.queryStageRange(allStageRange), ...args); - } - - callStageRange( - queried: QueriedHook, - ...args: AsArray - ): R { - let result; - let error; - this.callAsyncStageRange( - queried, - // @ts-expect-error - ...args, - (e: Error, r: R): void => { - error = e; - result = r; - } - ); - if (error) { - throw error; - } - return result as R; - } - - tapAsync(): never { - throw new Error("tapAsync is not supported on a SyncBailHook"); - } - - tapPromise(): never { - throw new Error("tapPromise is not supported on a SyncBailHook"); - } -} - -export class SyncWaterfallHook< - T, - AdditionalOptions = UnsetAdditionalOptions -> extends HookBase[0], AdditionalOptions> { - constructor( - args = [] as unknown as ArgumentNames>, - name?: string - ) { - if (args.length < 1) - throw new Error("Waterfall hooks must have at least one argument"); - super(args, name); - } - - callAsyncStageRange( - queried: QueriedHook[0], AdditionalOptions>, - ...args: Append, Callback[0]>> - ) { - const { - stageRange: [from, to], - tapsInRange - } = queried; - const argsWithoutCb = args.slice(0, args.length - 1) as AsArray; - const cb = args[args.length - 1] as Callback[0]>; - const args2 = this._prepareArgs(argsWithoutCb); - if (from === minStage) { - this._runCallInterceptors(...args2); - } - for (const tap of tapsInRange) { - this._runTapInterceptors(tap); - try { - const r = tap.fn(...args2); - if (r !== undefined) { - args2[0] = r; - } - } catch (e) { - const err = e as Error; - this._runErrorInterceptors(err); - return cb(err); - } - } - if (to === maxStage) { - this._runDoneInterceptors(); - cb(null, args2[0]); - } - } - - call(...args: AsArray): AsArray[0] { - return this.callStageRange(this.queryStageRange(allStageRange), ...args); - } - - callStageRange( - queried: QueriedHook[0], AdditionalOptions>, - ...args: AsArray - ): AsArray[0] { - let result; - let error; - this.callAsyncStageRange( - queried, - // @ts-expect-error - ...args, - (e: Error, r: AsArray[0]): void => { - error = e; - result = r; - } - ); - if (error) { - throw error; - } - return result as AsArray[0]; - } - - tapAsync(): never { - throw new Error("tapAsync is not supported on a SyncWaterfallHook"); - } - - tapPromise(): never { - throw new Error("tapPromise is not supported on a SyncWaterfallHook"); - } -} - -export class AsyncParallelHook< - T, - AdditionalOptions = UnsetAdditionalOptions -> extends HookBase { - callAsyncStageRange( - queried: QueriedHook, - ...args: Append, Callback> - ) { - const { - stageRange: [from], - tapsInRange - } = queried; - const argsWithoutCb = args.slice(0, args.length - 1) as AsArray; - const cb = args[args.length - 1] as Callback; - const args2 = this._prepareArgs(argsWithoutCb); - if (from === minStage) { - this._runCallInterceptors(...args2); - } - const done = () => { - this._runDoneInterceptors(); - cb(null); - }; - const error = (e: Error) => { - this._runErrorInterceptors(e); - cb(e); - }; - if (tapsInRange.length === 0) return done(); - let counter = tapsInRange.length; - for (const tap of tapsInRange) { - this._runTapInterceptors(tap); - if (tap.type === "promise") { - const promise = tap.fn(...args2); - if (!promise || !promise.then) { - throw new Error( - `Tap function (tapPromise) did not return promise (returned ${promise})` - ); - } - promise.then( - () => { - counter -= 1; - if (counter === 0) { - done(); - } - }, - (e: Error) => { - counter = 0; - error(e); - } - ); - } else if (tap.type === "async") { - tap.fn(...args2, (e: Error) => { - if (e) { - counter = 0; - error(e); - } else { - counter -= 1; - if (counter === 0) { - done(); - } - } - }); - } else { - let hasError = false; - try { - tap.fn(...args2); - } catch (e) { - hasError = true; - counter = 0; - error(e as Error); - } - if (!hasError && --counter === 0) { - done(); - } - } - if (counter <= 0) return; - } - } -} - -export class AsyncSeriesHook< - T, - AdditionalOptions = UnsetAdditionalOptions -> extends HookBase { - callAsyncStageRange( - queried: QueriedHook, - ...args: Append, Callback> - ) { - const { - stageRange: [from], - tapsInRange - } = queried; - const argsWithoutCb = args.slice(0, args.length - 1) as AsArray; - const cb = args[args.length - 1] as Callback; - const args2 = this._prepareArgs(argsWithoutCb); - if (from === minStage) { - this._runCallInterceptors(...args2); - } - const done = () => { - this._runDoneInterceptors(); - cb(null); - }; - const error = (e: Error) => { - this._runErrorInterceptors(e); - cb(e); - }; - if (tapsInRange.length === 0) return done(); - let index = 0; - const next = () => { - const tap = tapsInRange[index]; - this._runTapInterceptors(tap); - if (tap.type === "promise") { - const promise = tap.fn(...args2); - if (!promise || !promise.then) { - throw new Error( - `Tap function (tapPromise) did not return promise (returned ${promise})` - ); - } - promise.then( - () => { - index += 1; - if (index === tapsInRange.length) { - done(); - } else { - next(); - } - }, - (e: Error) => { - index = tapsInRange.length; - error(e); - } - ); - } else if (tap.type === "async") { - tap.fn(...args2, (e: Error) => { - if (e) { - index = tapsInRange.length; - error(e); - } else { - index += 1; - if (index === tapsInRange.length) { - done(); - } else { - next(); - } - } - }); - } else { - let hasError = false; - try { - tap.fn(...args2); - } catch (e) { - hasError = true; - index = tapsInRange.length; - error(e as Error); - } - if (!hasError) { - index += 1; - if (index === tapsInRange.length) { - done(); - } else { - next(); - } - } - } - if (index === tapsInRange.length) return; - }; - next(); - } -} - -export class AsyncSeriesBailHook< - T, - R, - AdditionalOptions = UnsetAdditionalOptions -> extends HookBase { - callAsyncStageRange( - queried: QueriedHook, - ...args: Append, Callback> - ) { - const { - stageRange: [from], - tapsInRange - } = queried; - const argsWithoutCb = args.slice(0, args.length - 1) as AsArray; - const cb = args[args.length - 1] as Callback; - const args2 = this._prepareArgs(argsWithoutCb); - if (from === minStage) { - this._runCallInterceptors(...args2); - } - const done = () => { - this._runDoneInterceptors(); - cb(null); - }; - const error = (e: Error) => { - this._runErrorInterceptors(e); - cb(e); - }; - const result = (r: R) => { - this._runResultInterceptors(r); - cb(null, r); - }; - if (tapsInRange.length === 0) return done(); - let index = 0; - const next = () => { - const tap = tapsInRange[index]; - this._runTapInterceptors(tap); - if (tap.type === "promise") { - const promise = tap.fn(...args2); - if (!promise || !promise.then) { - throw new Error( - `Tap function (tapPromise) did not return promise (returned ${promise})` - ); - } - promise.then( - (r: R) => { - index += 1; - if (r !== undefined) { - result(r); - } else if (index === tapsInRange.length) { - done(); - } else { - next(); - } - }, - (e: Error) => { - index = tapsInRange.length; - error(e); - } - ); - } else if (tap.type === "async") { - tap.fn(...args2, (e: Error, r: R) => { - if (e) { - index = tapsInRange.length; - error(e); - } else { - index += 1; - if (r !== undefined) { - result(r); - } else if (index === tapsInRange.length) { - done(); - } else { - next(); - } - } - }); - } else { - let hasError = false; - let r = undefined; - try { - r = tap.fn(...args2); - } catch (e) { - hasError = true; - index = tapsInRange.length; - error(e as Error); - } - if (!hasError) { - index += 1; - if (r !== undefined) { - result(r); - } else if (index === tapsInRange.length) { - done(); - } else { - next(); - } - } - } - if (index === tapsInRange.length) return; - }; - next(); - } -} - -export class AsyncSeriesWaterfallHook< - T, - AdditionalOptions = UnsetAdditionalOptions -> extends HookBase[0], AdditionalOptions> { - constructor( - args = [] as unknown as ArgumentNames>, - name?: string - ) { - if (args.length < 1) - throw new Error("Waterfall hooks must have at least one argument"); - super(args, name); - } - - callAsyncStageRange( - queried: QueriedHook[0], AdditionalOptions>, - ...args: Append, Callback[0]>> - ) { - const { - stageRange: [from], - tapsInRange - } = queried; - const argsWithoutCb = args.slice(0, args.length - 1) as AsArray; - const cb = args[args.length - 1] as Callback[0]>; - const args2 = this._prepareArgs(argsWithoutCb); - if (from === minStage) { - this._runCallInterceptors(...args2); - } - const result = (r: AsArray[0]) => { - this._runResultInterceptors(r); - cb(null, r); - }; - const error = (e: Error) => { - this._runErrorInterceptors(e); - cb(e); - }; - if (tapsInRange.length === 0) return result(args2[0]); - let index = 0; - const next = () => { - const tap = tapsInRange[index]; - this._runTapInterceptors(tap); - if (tap.type === "promise") { - const promise = tap.fn(...args2); - if (!promise || !promise.then) { - throw new Error( - `Tap function (tapPromise) did not return promise (returned ${promise})` - ); - } - promise.then( - (r: AsArray[0]) => { - index += 1; - if (r !== undefined) { - args2[0] = r; - } - if (index === tapsInRange.length) { - result(args2[0]); - } else { - next(); - } - }, - (e: Error) => { - index = tapsInRange.length; - error(e); - } - ); - } else if (tap.type === "async") { - tap.fn(...args2, (e: Error, r: AsArray[0]) => { - if (e) { - index = tapsInRange.length; - error(e); - } else { - index += 1; - if (r !== undefined) { - args2[0] = r; - } - if (index === tapsInRange.length) { - result(args2[0]); - } else { - next(); - } - } - }); - } else { - let hasError = false; - try { - const r = tap.fn(...args2); - if (r !== undefined) { - args2[0] = r; - } - } catch (e) { - hasError = true; - index = tapsInRange.length; - error(e as Error); - } - if (!hasError) { - index += 1; - if (index === tapsInRange.length) { - result(args2[0]); - } else { - next(); - } - } - } - if (index === tapsInRange.length) return; - }; - next(); - } -} - -const defaultFactory = (key: HookMapKey, hook: unknown) => hook; - -export type HookMapKey = any; -export type HookFactory = (key: HookMapKey, hook?: H) => H; -export interface HookMapInterceptor { - factory?: HookFactory; -} - -export class HookMap { - _map: Map = new Map(); - _factory: HookFactory; - name?: string; - _interceptors: HookMapInterceptor[]; - - constructor(factory: HookFactory, name?: string) { - this.name = name; - this._factory = factory; - this._interceptors = []; - } - - get(key: HookMapKey) { - return this._map.get(key); - } - - for(key: HookMapKey) { - const hook = this.get(key); - if (hook !== undefined) { - return hook; - } - let newHook = this._factory(key); - const interceptors = this._interceptors; - for (let i = 0; i < interceptors.length; i++) { - const factory = interceptors[i].factory; - if (factory) { - newHook = factory(key, newHook); - } - } - this._map.set(key, newHook); - return newHook; - } - - intercept(interceptor: HookMapInterceptor) { - this._interceptors.push( - Object.assign( - { - factory: defaultFactory - }, - interceptor - ) - ); - } - - isUsed(): boolean { - for (const key of this._map.keys()) { - const hook = this.get(key); - if (hook?.isUsed()) { - return true; - } - } - return false; - } - - queryStageRange(stageRange: StageRange): QueriedHookMap { - return new QueriedHookMap(stageRange, this); - } -} - -export class QueriedHookMap { - stageRange: StageRange; - hookMap: HookMap; - - constructor(stageRange: StageRange, hookMap: HookMap) { - this.stageRange = stageRange; - this.hookMap = hookMap; - } - - get(key: HookMapKey) { - return this.hookMap.get(key)?.queryStageRange(this.stageRange); - } - - for(key: HookMapKey) { - return this.hookMap.for(key).queryStageRange(this.stageRange); - } - - isUsed(): boolean { - for (const key in this.hookMap._map.keys()) { - if (this.get(key)?.isUsed()) { - return true; - } - } - return false; - } -} - -export class MultiHook { - hooks: H[]; - name?: string; - - constructor(hooks: H[], name?: string) { - this.hooks = hooks; - this.name = name; - } - - tap( - options: Options>, - fn: Fn, ExtractHookReturn> - ) { - for (const hook of this.hooks) { - hook.tap(options, fn); - } - } - - tapAsync( - options: Options>, - fn: FnAsync, ExtractHookReturn> - ) { - for (const hook of this.hooks) { - hook.tapAsync(options, fn); - } - } - - tapPromise( - options: Options>, - fn: FnPromise, ExtractHookReturn> - ) { - for (const hook of this.hooks) { - hook.tapPromise(options, fn); - } - } - - isUsed() { - for (const hook of this.hooks) { - if (hook.isUsed()) return true; - } - return false; - } - - intercept( - interceptor: HookInterceptor< - ExtractHookArgs, - ExtractHookReturn, - ExtractHookAdditionalOptions - > - ) { - for (const hook of this.hooks) { - hook.intercept(interceptor); - } - } - - withOptions(options: TapOptions & IfSet>) { - return new MultiHook( - this.hooks.map(h => h.withOptions(options)), - this.name - ); - } -} diff --git a/packages/rspack-lite-tapable/tests/AsyncParallelHooks.test.js b/packages/rspack-lite-tapable/tests/AsyncParallelHooks.test.js deleted file mode 100644 index 2155cd1ef587..000000000000 --- a/packages/rspack-lite-tapable/tests/AsyncParallelHooks.test.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/AsyncParallelHooks.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -const HookTester = require("./HookTester"); -const { AsyncParallelHook } = require("../"); - -describe("AsyncParallelHook", () => { - it("should have to correct behavior", async () => { - const tester = new HookTester(args => new AsyncParallelHook(args)); - - const result = await tester.run(); - - expect(result).toMatchSnapshot(); - }, 15000); -}); - -// describe("AsyncParallelBailHook", () => { -// it("should have to correct behavior", async () => { -// const tester = new HookTester(args => new AsyncParallelBailHook(args)); - -// const result = await tester.run(); - -// expect(result).toMatchSnapshot(); -// }, 15000); -// }); diff --git a/packages/rspack-lite-tapable/tests/AsyncSeriesHooks.test.js b/packages/rspack-lite-tapable/tests/AsyncSeriesHooks.test.js deleted file mode 100644 index 3ec2284ef4c0..000000000000 --- a/packages/rspack-lite-tapable/tests/AsyncSeriesHooks.test.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/AsyncSeriesHooks.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -const HookTester = require("./HookTester"); -const { - AsyncSeriesHook, - AsyncSeriesBailHook, - AsyncSeriesWaterfallHook -} = require("../"); - -describe("AsyncSeriesHook", () => { - it("should not have call method", () => { - const hook = new AsyncSeriesHook([]); - expect(hook.call).toEqual(undefined); - expect(typeof hook.callAsync).toEqual("function"); - expect(typeof hook.promise).toEqual("function"); - }); - - it("should have tap method", done => { - const hook = new AsyncSeriesHook([]); - const mockTap = jest.fn(); - hook.tap("somePlugin", mockTap); - hook.callAsync(() => done()); - expect(mockTap).toHaveBeenCalledTimes(1); - }); - - it("should have promise method", done => { - const hook = new AsyncSeriesHook([]); - const mockTap = jest.fn(); - hook.tap("somePlugin", mockTap); - hook.promise().then(() => done()); - expect(mockTap).toHaveBeenCalledTimes(1); - }); - - it("should have to correct behavior", async () => { - const tester = new HookTester(args => new AsyncSeriesHook(args)); - - const result = await tester.run(); - - expect(result).toMatchSnapshot(); - }); -}); - -describe("AsyncSeriesBailHook", () => { - it("should have to correct behavior", async () => { - const tester = new HookTester(args => new AsyncSeriesBailHook(args)); - - const result = await tester.run(); - - expect(result).toMatchSnapshot(); - }); - - it("should not crash with many plugins", () => { - const hook = new AsyncSeriesBailHook(["x"]); - for (let i = 0; i < 1000; i++) { - hook.tap("Test", () => 42); - } - hook.tapAsync("Test", (x, callback) => callback(null, 42)); - hook.tapPromise("Test", x => Promise.resolve(42)); - return expect(hook.promise()).resolves.toBe(42); - }); -}); - -describe("AsyncSeriesWaterfallHook", () => { - it("should have to correct behavior", async () => { - const tester = new HookTester(args => new AsyncSeriesWaterfallHook(args)); - - const result = await tester.run(); - - expect(result).toMatchSnapshot(); - }); -}); - -// describe("AsyncSeriesLoopHook", () => { -// it("should have to correct behavior", async () => { -// const tester = new HookTester(args => new AsyncSeriesLoopHook(args)); - -// const result = await tester.runForLoop(); - -// expect(result).toMatchSnapshot(); -// }); -// }); diff --git a/packages/rspack-lite-tapable/tests/Hook.test.js b/packages/rspack-lite-tapable/tests/Hook.test.js deleted file mode 100644 index 7cb2cc7bf821..000000000000 --- a/packages/rspack-lite-tapable/tests/Hook.test.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/Hook.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -const { SyncHook } = require("../"); - -describe("Hook", () => { - it("should allow to insert hooks before others and in stages", () => { - const hook = new SyncHook(); - - const calls = []; - hook.tap("A", () => calls.push("A")); - hook.tap( - { - name: "B", - before: "A" - }, - () => calls.push("B") - ); - - calls.length = 0; - hook.call(); - expect(calls).toEqual(["B", "A"]); - - hook.tap( - { - name: "C", - before: ["A", "B"] - }, - () => calls.push("C") - ); - - calls.length = 0; - hook.call(); - expect(calls).toEqual(["C", "B", "A"]); - - hook.tap( - { - name: "D", - before: "B" - }, - () => calls.push("D") - ); - - calls.length = 0; - hook.call(); - expect(calls).toEqual(["C", "D", "B", "A"]); - - hook.tap( - { - name: "E", - stage: -5 - }, - () => calls.push("E") - ); - hook.tap( - { - name: "F", - stage: -3 - }, - () => calls.push("F") - ); - - calls.length = 0; - hook.call(); - expect(calls).toEqual(["E", "F", "C", "D", "B", "A"]); - }); - it("should throw without a valid name", () => { - const hook = new SyncHook(); - expect(() => hook.tap("", () => {})).toThrow( - new Error("Missing name for tap") - ); - expect(() => hook.tap(" ", () => {})).toThrow( - new Error("Missing name for tap") - ); - }); -}); diff --git a/packages/rspack-lite-tapable/tests/HookTester.js b/packages/rspack-lite-tapable/tests/HookTester.js deleted file mode 100644 index ea45e2e8e77f..000000000000 --- a/packages/rspack-lite-tapable/tests/HookTester.js +++ /dev/null @@ -1,1231 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/HookTester.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -describe("HookTester", () => { - it("should run", () => {}); -}); - -process.on("unhandledRejection", err => console.error(err.stack)); - -class HookTester { - constructor(hookCreator, sync) { - this.hookCreator = hookCreator; - this.sync = sync; - } - - async run(syncOnly) { - const result = { - sync: {}, - async: {}, - intercept: {} - }; - - if (syncOnly) { - await this.runSync(result.sync, "call"); - } else { - await this.runAsync(result.async, "callAsync"); - await this.runAsync(result.async, "promise"); - - await this.runIntercept(result.intercept, "callAsync"); - await this.runIntercept(result.intercept, "promise"); - } - - await this.runSync(result.sync, "callAsync"); - await this.runSync(result.sync, "promise"); - - return result; - } - - async runForLoop(syncOnly) { - const result = { - sync: {}, - async: {} - }; - - if (syncOnly) { - await this.runForLoopSync(result.sync, "call"); - } else { - await this.runForLoopAsync(result.async, "callAsync"); - await this.runForLoopAsync(result.async, "promise"); - } - - await this.runForLoopSync(result.sync, "callAsync"); - await this.runForLoopSync(result.sync, "promise"); - - return result; - } - - async runForLoopAsync(result, method) { - { - const hook = this.createHook([], `${method}BrokenPromise`); - hook.tapPromise("promise", () => "this is not a promise"); - result[`${method}BrokenPromise`] = await this.gainResult(cb => - hook[method](cb) - ); - } - { - const hook = this.createHook([], `${method}SinglePromise`); - hook.tapPromise("promise", () => { - result[`${method}SinglePromiseCalled`] = - (result[`${method}SinglePromiseCalled`] || 0) + 1; - if (result[`${method}SinglePromiseCalled`] < 42) - return Promise.resolve().then(() => true); - return Promise.resolve().then(() => {}); - }); - result[`${method}SinglePromise`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook([], `${method}MultiplePromise`); - hook.tapPromise("promise1", () => { - result[`${method}MultiplePromiseCalled1`] = - (result[`${method}MultiplePromiseCalled1`] || 0) + 1; - if (result[`${method}MultiplePromiseCalled1`] < 42) - return Promise.resolve().then(() => true); - return Promise.resolve().then(() => {}); - }); - hook.tapPromise("promise2", () => { - result[`${method}MultiplePromiseCalled2`] = - (result[`${method}MultiplePromiseCalled2`] || 0) + 1; - if (result[`${method}MultiplePromiseCalled2`] < 42) - return Promise.resolve().then(() => true); - return Promise.resolve().then(() => {}); - }); - result[`${method}MultiplePromise`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook([], `${method}SingleAsync`); - hook.tapAsync("async", callback => { - result[`${method}SingleAsyncCalled`] = - (result[`${method}SingleAsyncCalled`] || 0) + 1; - if (result[`${method}SingleAsyncCalled`] < 42) - return Promise.resolve().then(() => callback(null, true)); - return Promise.resolve().then(() => callback()); - }); - result[`${method}SingleAsync`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook([], `${method}MultipleAsync`); - hook.tapAsync("async1", callback => { - result[`${method}MultipleAsyncCalled1`] = - (result[`${method}MultipleAsyncCalled1`] || 0) + 1; - if (result[`${method}MultipleAsyncCalled1`] < 42) - return Promise.resolve().then(() => callback(null, true)); - return Promise.resolve().then(() => callback()); - }); - hook.tapAsync("async2", callback => { - result[`${method}MultipleAsyncCalled2`] = - (result[`${method}MultipleAsyncCalled2`] || 0) + 1; - if (result[`${method}MultipleAsyncCalled2`] < 42) - return Promise.resolve().then(() => callback(null, true)); - return Promise.resolve().then(() => callback()); - }); - result[`${method}MultipleAsync`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook([], `${method}Mixed`); - hook.tapAsync("async1", callback => { - result[`${method}MixedCalled1`] = - (result[`${method}MixedCalled1`] || 0) + 1; - if (result[`${method}MixedCalled1`] < 42) - return Promise.resolve().then(() => callback(null, true)); - return Promise.resolve().then(() => callback()); - }); - hook.tap("sync2", () => { - result[`${method}MixedCalled2`] = - (result[`${method}MixedCalled2`] || 0) + 1; - if (result[`${method}MixedCalled2`] < 42) return true; - }); - hook.tapPromise("promise3", () => { - result[`${method}MixedCalled3`] = - (result[`${method}MixedCalled3`] || 0) + 1; - if (result[`${method}MixedCalled3`] < 42) - return Promise.resolve().then(() => true); - return Promise.resolve().then(() => {}); - }); - result[`${method}Mixed`] = await this.gainResult(cb => hook[method](cb)); - } - } - - async runForLoopSync(result, method) { - { - const hook = this.createHook([], `${method}None`); - result[`${method}None`] = await this.gainResult(cb => hook[method](cb)); - } - - { - const hook = this.createHook(["arg"], `${method}NoneWithArg`); - result[`${method}NoneWithArg`] = await this.gainResult(cb => - hook[method](42, cb) - ); - } - - { - const hook = this.createHook([], `${method}SingleSync`); - hook.tap("sync", () => { - result[`${method}SingleSyncCalled`] = - (result[`${method}SingleSyncCalled`] || 0) + 1; - if (result[`${method}SingleSyncCalled`] < 42) return true; - }); - result[`${method}SingleSync`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook([], `${method}MultipleSync`); - hook.tap("sync1", () => { - result[`${method}MultipleSyncCalled1`] = - (result[`${method}MultipleSyncCalled1`] || 0) + 1; - if (result[`${method}MultipleSyncCalled1`] < 42) return true; - }); - hook.tap("sync2", () => { - result[`${method}MultipleSyncCalled2`] = - (result[`${method}MultipleSyncCalled2`] || 0) + 1; - if (result[`${method}MultipleSyncCalled2`] < 42) return true; - }); - result[`${method}MultipleSync`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook([], `${method}InterceptedSync`); - hook.tap("sync1", () => { - result[`${method}InterceptedSyncCalled1`] = - (result[`${method}InterceptedSyncCalled1`] || 0) + 1; - if (result[`${method}InterceptedSyncCalled1`] < 42) return true; - }); - hook.tap("sync2", () => { - result[`${method}InterceptedSyncCalled2`] = - (result[`${method}InterceptedSyncCalled2`] || 0) + 1; - if (result[`${method}InterceptedSyncCalled2`] < 42) return true; - }); - hook.intercept({ - call: a => - (result[`${method}InterceptedSyncCalledCall`] = - (result[`${method}InterceptedSyncCalledCall`] || 0) + 1), - loop: a => - (result[`${method}InterceptedSyncCalledLoop`] = - (result[`${method}InterceptedSyncCalledLoop`] || 0) + 1), - tap: tap => { - result[`${method}InterceptedSyncCalledTap`] = - (result[`${method}InterceptedSyncCalledTap`] || 0) + 1; - } - }); - result[`${method}InterceptedSync`] = await this.gainResult(cb => - hook[method](cb) - ); - } - } - - async runSync(result, method) { - { - const hook = this.createHook([], `${method}None`); - result[`${method}None`] = await this.gainResult(cb => hook[method](cb)); - } - - { - const hook = this.createHook(["arg"], `${method}NoneWithArg`); - result[`${method}NoneWithArg`] = await this.gainResult(cb => - hook[method](42, cb) - ); - } - - { - const hook = this.createHook([], `${method}SingleSync`); - hook.tap("sync", () => { - result[`${method}SingleSyncCalled`] = true; - return 42; - }); - result[`${method}SingleSync`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook(["myArg"], `${method}SingleSyncWithArg`); - hook.tap("sync", nr => { - result[`${method}SingleSyncWithArgCalled`] = nr; - return nr; - }); - result[`${method}SingleSyncWithArg`] = await this.gainResult(cb => - hook[method](42, cb) - ); - } - - { - const hook = this.createHook([], `${method}MultipleSync`); - hook.tap("sync1", () => { - result[`${method}MultipleSyncCalled1`] = true; - return 42; - }); - hook.tap("sync2", () => { - result[`${method}MultipleSyncCalled2`] = true; - return 43; - }); - result[`${method}MultipleSync`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook(["a"], `${method}MultipleSyncWithArg`); - hook.tap("sync1", a => { - result[`${method}MultipleSyncWithArgCalled1`] = a; - return 42 + a; - }); - hook.tap("sync2", a => { - result[`${method}MultipleSyncWithArgCalled2`] = a; - return 43 + a; - }); - result[`${method}MultipleSyncWithArg`] = await this.gainResult(cb => - hook[method](42, cb) - ); - } - - { - const hook = this.createHook( - ["a"], - `${method}MultipleSyncWithArgNoReturn` - ); - hook.tap("sync1", a => { - result[`${method}MultipleSyncWithArgNoReturnCalled1`] = a; - }); - hook.tap("sync2", a => { - result[`${method}MultipleSyncWithArgNoReturnCalled2`] = a; - }); - result[`${method}MultipleSyncWithArgNoReturn`] = await this.gainResult( - cb => hook[method](42, cb) - ); - } - - { - const hook = this.createHook( - ["a"], - `${method}MultipleSyncWithArgFirstReturn` - ); - hook.tap("sync1", a => { - result[`${method}MultipleSyncWithArgFirstReturnCalled1`] = a; - return 42 + a; - }); - hook.tap("sync2", a => { - result[`${method}MultipleSyncWithArgFirstReturnCalled2`] = a; - }); - result[`${method}MultipleSyncWithArgFirstReturn`] = await this.gainResult( - cb => hook[method](42, cb) - ); - } - - { - const hook = this.createHook( - ["a"], - `${method}MultipleSyncWithArgLastReturn` - ); - hook.tap("sync1", a => { - result[`${method}MultipleSyncWithArgLastReturnCalled1`] = a; - }); - hook.tap("sync2", a => { - result[`${method}MultipleSyncWithArgLastReturnCalled2`] = a; - return 43 + a; - }); - result[`${method}MultipleSyncWithArgLastReturn`] = await this.gainResult( - cb => hook[method](42, cb) - ); - } - - { - const hook = this.createHook( - ["a", "b", "c"], - `${method}MultipleSyncWithArgs` - ); - hook.tap("sync1", (a, b, c) => { - result[`${method}MultipleSyncWithArgsCalled1`] = [a, b, c]; - return a + b + c; - }); - hook.tap("sync2", (a, b, c) => { - result[`${method}MultipleSyncWithArgsCalled2`] = [a, b, c]; - return a + b + c + 1; - }); - result[`${method}MultipleSyncWithArgs`] = await this.gainResult(cb => - hook[method](42, 43, 44, cb) - ); - } - - { - const hook = this.createHook([], `${method}MultipleSyncError`); - hook.tap("sync1", () => { - result[`${method}MultipleSyncErrorCalled1`] = true; - }); - hook.tap("sync2", () => { - result[`${method}MultipleSyncErrorCalled2`] = true; - throw new Error("Error in sync2"); - }); - hook.tap("sync3", () => { - result[`${method}MultipleSyncErrorCalled3`] = true; - }); - result[`${method}MultipleSyncError`] = await this.gainResult(cb => - hook[method](cb) - ); - } - - { - const hook = this.createHook(["a", "b", "c"], `${method}Intercepted`); - hook.intercept({ - call: (a, b, c) => { - result[`${method}InterceptedCall1`] = [a, b, c]; - }, - tap: tap => { - result[`${method}InterceptedTap1`] = Object.assign({}, tap, { - fn: tap.fn.length - }); - } - }); - hook.intercept({ - call: (a, b, c) => { - result[`${method}InterceptedCall2`] = [a, b, c]; - }, - tap: tap => { - if (!result[`${method}InterceptedTap2`]) - result[`${method}InterceptedTap2`] = Object.assign({}, tap, { - fn: tap.fn.length - }); - } - }); - hook.tap("sync1", (a, b, c) => a + b + c); - hook.tap("sync2", (a, b) => a + b + 1); - result[`${method}Intercepted`] = await this.gainResult(cb => - hook[method](1, 2, 3, cb) - ); - } - } - - async runAsync(result, type) { - { - const hook = this.createHook([], `${type}None`); - result[`${type}None`] = await this.gainResult(cb => hook[type](cb)); - } - - { - const hook = this.createHook(["arg"], `${type}NoneWithArg`); - result[`${type}NoneWithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook([], `${type}SingleSync`); - hook.tap("sync", () => { - result[`${type}SingleSyncCalled1`] = true; - return 42; - }); - result[`${type}SingleSync`] = await this.gainResult(cb => hook[type](cb)); - } - - { - const hook = this.createHook(["x"], `${type}SingleSyncWithArg`); - hook.tap("sync", arg => { - result[`${type}SingleSyncWithArgCalled1`] = arg; - return arg + 1; - }); - result[`${type}SingleSyncWithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}SingleSyncWithArgNoReturn`); - hook.tap("sync", arg => { - result[`${type}SingleSyncWithArgNoReturnCalled1`] = arg; - }); - result[`${type}SingleSyncWithArgNoReturn`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook([], `${type}MultipleSync`); - hook.tap("sync1", () => { - result[`${type}MultipleSyncCalled1`] = true; - return 42; - }); - hook.tap("sync2", () => { - result[`${type}MultipleSyncCalled2`] = true; - return 43; - }); - result[`${type}MultipleSync`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook([], `${type}MultipleSyncLastReturn`); - hook.tap("sync1", () => { - result[`${type}MultipleSyncLastReturnCalled1`] = true; - }); - hook.tap("sync2", () => { - result[`${type}MultipleSyncLastReturnCalled2`] = true; - return 43; - }); - result[`${type}MultipleSyncLastReturn`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook([], `${type}MultipleSyncNoReturn`); - hook.tap("sync1", () => { - result[`${type}MultipleSyncNoReturnCalled1`] = true; - }); - hook.tap("sync2", () => { - result[`${type}MultipleSyncNoReturnCalled2`] = true; - }); - result[`${type}MultipleSyncNoReturn`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook(["arg"], `${type}MultipleSyncWithArg`); - hook.tap("sync1", arg => { - result[`${type}MultipleSyncWithArgCalled1`] = arg; - return arg + 1; - }); - hook.tap("sync2", arg => { - result[`${type}MultipleSyncWithArgCalled2`] = arg; - return arg + 2; - }); - result[`${type}MultipleSyncWithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook( - ["arg"], - `${type}MultipleSyncWithArgNoReturn` - ); - hook.tap("sync1", arg => { - result[`${type}MultipleSyncWithArgNoReturnCalled1`] = arg; - }); - hook.tap("sync2", arg => { - result[`${type}MultipleSyncWithArgNoReturnCalled2`] = arg; - }); - result[`${type}MultipleSyncWithArgNoReturn`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook( - ["arg"], - `${type}MultipleSyncWithArgLastReturn` - ); - hook.tap("sync1", arg => { - result[`${type}MultipleSyncWithArgLastReturnCalled1`] = arg; - }); - hook.tap("sync2", arg => { - result[`${type}MultipleSyncWithArgLastReturnCalled2`] = arg; - return arg + 2; - }); - result[`${type}MultipleSyncWithArgLastReturn`] = await this.gainResult( - cb => hook[type](42, cb) - ); - } - - { - const hook = this.createHook( - ["arg"], - `${type}MultipleSyncWithArgFirstReturn` - ); - hook.tap("sync1", arg => { - result[`${type}MultipleSyncWithArgFirstReturnCalled1`] = arg; - return arg + 1; - }); - hook.tap("sync2", arg => { - result[`${type}MultipleSyncWithArgFirstReturnCalled2`] = arg; - }); - result[`${type}MultipleSyncWithArgFirstReturn`] = await this.gainResult( - cb => hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}SingleAsyncWithArg`); - hook.tapAsync("async", (arg, callback) => { - result[`${type}SingleAsyncWithArgCalled1`] = arg; - callback(null, arg); - }); - result[`${type}SingleAsyncWithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}MultipleAsyncWithArg`); - hook.tapAsync("async1", (arg, callback) => { - result[`${type}MultipleAsyncWithArgCalled1`] = arg; - callback(null, arg + 1); - }); - hook.tapAsync("async2", (arg, callback) => { - result[`${type}MultipleAsyncWithArgCalled2`] = arg; - callback(null, arg + 2); - }); - result[`${type}MultipleAsyncWithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook( - ["x"], - `${type}MultipleAsyncWithArgNoReturn` - ); - hook.tapAsync("async1", (arg, callback) => { - result[`${type}MultipleAsyncWithArgNoReturnCalled1`] = arg; - callback(); - }); - hook.tapAsync("async2", (arg, callback) => { - result[`${type}MultipleAsyncWithArgNoReturnCalled2`] = arg; - callback(); - }); - result[`${type}MultipleAsyncWithArgNoReturn`] = await this.gainResult( - cb => hook[type](42, cb) - ); - } - - { - const hook = this.createHook( - ["x"], - `${type}MultipleAsyncWithArgFirstReturn` - ); - hook.tapAsync("async1", (arg, callback) => { - result[`${type}MultipleAsyncWithArgFirstReturnCalled1`] = arg; - callback(null, arg + 1); - }); - hook.tapAsync("async2", (arg, callback) => { - result[`${type}MultipleAsyncWithArgFirstReturnCalled2`] = arg; - callback(); - }); - result[`${type}MultipleAsyncWithArgFirstReturn`] = await this.gainResult( - cb => hook[type](42, cb) - ); - } - - { - const hook = this.createHook( - ["x"], - `${type}MultipleAsyncWithArgLastReturn` - ); - hook.tapAsync("async1", (arg, callback) => { - result[`${type}MultipleAsyncWithArgLastReturnCalled1`] = arg; - callback(); - }); - hook.tapAsync("async2", (arg, callback) => { - result[`${type}MultipleAsyncWithArgLastReturnCalled2`] = arg; - callback(null, arg + 2); - }); - result[`${type}MultipleAsyncWithArgLastReturn`] = await this.gainResult( - cb => hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}SinglePromiseWithArg`); - hook.tapPromise("promise", arg => { - result[`${type}SinglePromiseWithArgCalled1`] = arg; - return Promise.resolve(arg + 1); - }); - result[`${type}SinglePromiseWithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}MultiplePromiseWithArg`); - hook.tapPromise("promise1", arg => { - result[`${type}MultiplePromiseWithArgCalled1`] = arg; - return Promise.resolve(arg + 1); - }); - hook.tapPromise("promise2", arg => { - result[`${type}MultiplePromiseWithArgCalled2`] = arg; - return Promise.resolve(arg + 2); - }); - result[`${type}MultiplePromiseWithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook( - ["x"], - `${type}MultiplePromiseWithArgNoReturn` - ); - hook.tapPromise("promise1", arg => { - result[`${type}MultiplePromiseWithArgNoReturnCalled1`] = arg; - return Promise.resolve(); - }); - hook.tapPromise("promise2", arg => { - result[`${type}MultiplePromiseWithArgNoReturnCalled2`] = arg; - return Promise.resolve(); - }); - result[`${type}MultiplePromiseWithArgNoReturn`] = await this.gainResult( - cb => hook[type](42, cb) - ); - } - - { - const hook = this.createHook( - ["x"], - `${type}MultiplePromiseWithArgFirstReturn` - ); - hook.tapPromise("promise1", arg => { - result[`${type}MultiplePromiseWithArgFirstReturnCalled1`] = arg; - return Promise.resolve(arg + 1); - }); - hook.tapPromise("promise2", arg => { - result[`${type}MultiplePromiseWithArgFirstReturnCalled2`] = arg; - return Promise.resolve(); - }); - result[`${type}MultiplePromiseWithArgFirstReturn`] = - await this.gainResult(cb => hook[type](42, cb)); - } - - { - const hook = this.createHook( - ["x"], - `${type}MultiplePromiseWithArgLastReturn` - ); - hook.tapPromise("promise1", arg => { - result[`${type}MultiplePromiseWithArgLastReturnCalled1`] = arg; - return Promise.resolve(); - }); - hook.tapPromise("promise2", arg => { - result[`${type}MultiplePromiseWithArgLastReturnCalled2`] = arg; - return Promise.resolve(arg + 2); - }); - result[`${type}MultiplePromiseWithArgLastReturn`] = await this.gainResult( - cb => hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}MultipleMixed1WithArg`); - hook.tapAsync("async", (arg, callback) => { - result[`${type}MultipleMixed1WithArgCalled1`] = arg; - callback(null, arg + 1); - }); - hook.tapPromise("promise", arg => { - result[`${type}MultipleMixed1WithArgCalled2`] = arg; - return Promise.resolve(arg + 2); - }); - hook.tap("sync", arg => { - result[`${type}MultipleMixed1WithArgCalled3`] = arg; - return arg + 3; - }); - result[`${type}MultipleMixed1WithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}MultipleMixed2WithArg`); - hook.tapAsync("async", (arg, callback) => { - result[`${type}MultipleMixed2WithArgCalled1`] = arg; - setTimeout(() => callback(null, arg + 1), 100); - }); - hook.tapPromise("promise", arg => { - result[`${type}MultipleMixed2WithArgCalled2`] = arg; - return Promise.resolve(arg + 2); - }); - result[`${type}MultipleMixed2WithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}MultipleMixed3WithArg`); - hook.tapAsync("async1", (arg, callback) => { - result[`${type}MultipleMixed3WithArgCalled1`] = arg; - callback(null, arg + 1); - }); - hook.tapPromise("promise", arg => { - result[`${type}MultipleMixed3WithArgCalled2`] = arg; - return Promise.resolve(arg + 2); - }); - hook.tapAsync("async2", (arg, callback) => { - result[`${type}MultipleMixed3WithArgCalled3`] = arg; - setTimeout(() => callback(null, arg + 3), 100); - }); - result[`${type}MultipleMixed3WithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook([], `${type}MultipleSyncError`); - hook.tap("sync1", () => { - result[`${type}MultipleSyncErrorCalled1`] = true; - }); - hook.tap("sync2", () => { - throw new Error("Error in sync2"); - }); - hook.tap("sync3", () => { - result[`${type}MultipleSyncErrorCalled3`] = true; - }); - result[`${type}MultipleSyncError`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook([], `${type}MultipleAsyncError`); - hook.tapAsync("async1", callback => { - result[`${type}MultipleAsyncErrorCalled1`] = true; - callback(); - }); - hook.tapAsync("async2", callback => { - callback(new Error("Error in async2")); - }); - hook.tapAsync("async3", callback => { - result[`${type}MultipleAsyncErrorCalled3`] = true; - callback(); - }); - result[`${type}MultipleAsyncError`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook([], `${type}MultipleAsyncLateError`); - hook.tapAsync("async1", callback => { - result[`${type}MultipleAsyncLateErrorCalled1`] = true; - callback(); - }); - hook.tapAsync("async2", callback => { - setTimeout(() => callback(new Error("Error in async2")), 100); - }); - hook.tapAsync("async3", callback => { - result[`${type}MultipleAsyncLateErrorCalled3`] = true; - callback(); - }); - result[`${type}MultipleAsyncLateError`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook( - [], - `${type}MultipleAsyncLateErrorEarlyResult1` - ); - hook.tapAsync("async1", callback => { - result[`${type}MultipleAsyncLateErrorEarlyResult1Called1`] = true; - callback(); - }); - hook.tapAsync("async2", callback => { - setTimeout(() => callback(new Error("Error in async2")), 100); - }); - hook.tapAsync("async3", callback => { - result[`${type}MultipleAsyncLateErrorEarlyResult1Called3`] = true; - callback(null, 7); - }); - result[`${type}MultipleAsyncLateErrorEarlyResult1`] = - await this.gainResult(cb => hook[type](cb)); - } - - { - const hook = this.createHook( - [], - `${type}MultipleAsyncLateErrorEarlyResult2` - ); - hook.tapAsync("async1", callback => { - result[`${type}MultipleAsyncLateErrorEarlyResult2Called1`] = true; - setTimeout(() => callback(null, 42), 200); - }); - hook.tapAsync("async2", callback => { - setTimeout(() => callback(new Error("Error in async2")), 100); - }); - hook.tapAsync("async3", callback => { - result[`${type}MultipleAsyncLateErrorEarlyResult2Called3`] = true; - callback(null, 7); - }); - result[`${type}MultipleAsyncLateErrorEarlyResult2`] = - await this.gainResult(cb => hook[type](cb)); - } - - { - const hook = this.createHook([], `${type}MultipleAsyncEarlyError`); - hook.tapAsync("async1", callback => { - result[`${type}MultipleAsyncEarlyErrorCalled1`] = true; - setTimeout(() => callback(), 100); - }); - hook.tapAsync("async2", callback => { - callback(new Error("Error in async2")); - }); - hook.tapAsync("async3", callback => { - result[`${type}MultipleAsyncEarlyErrorCalled3`] = true; - setTimeout(() => callback(), 100); - }); - result[`${type}MultipleAsyncEarlyError`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook([], `${type}MultiplePromiseError`); - hook.tapPromise("promise1", () => { - result[`${type}MultiplePromiseErrorCalled1`] = true; - return Promise.resolve(); - }); - hook.tapPromise("promise2", () => { - return Promise.resolve().then(() => { - throw new Error("Error in async2"); - }); - }); - hook.tapPromise("promise3", () => { - result[`${type}MultiplePromiseErrorCalled3`] = true; - return Promise.resolve(); - }); - result[`${type}MultiplePromiseError`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook([], `${type}MultiplePromiseLateError`); - hook.tapPromise("promise1", () => { - result[`${type}MultiplePromiseLateErrorCalled1`] = true; - return Promise.resolve(); - }); - hook.tapPromise("promise2", () => { - return new Promise((resolve, reject) => { - setTimeout(() => reject(new Error("Error in async2")), 100); - }); - }); - hook.tapPromise("promise3", () => { - result[`${type}MultiplePromiseLateErrorCalled3`] = true; - return Promise.resolve(); - }); - result[`${type}MultiplePromiseLateError`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook([], `${type}MultiplePromiseEarlyError`); - hook.tapPromise("promise1", () => { - result[`${type}MultiplePromiseEarlyErrorCalled1`] = true; - return new Promise(resolve => setTimeout(() => resolve(), 100)); - }); - hook.tapPromise("promise2", () => { - return Promise.resolve().then(() => { - throw new Error("Error in async2"); - }); - }); - hook.tapPromise("promise3", () => { - result[`${type}MultiplePromiseEarlyErrorCalled3`] = true; - return new Promise(resolve => setTimeout(() => resolve(), 100)); - }); - result[`${type}MultiplePromiseEarlyError`] = await this.gainResult(cb => - hook[type](cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}MultipleMixedError1WithArg`); - hook.tapAsync("async", (arg, callback) => { - result[`${type}MultipleMixedError1WithArgCalled1`] = arg; - callback(null, arg); - }); - hook.tapPromise("promise", arg => { - result[`${type}MultipleMixedError1WithArgCalled2`] = arg; - return Promise.resolve(arg + 1); - }); - hook.tap("sync", arg => { - result[`${type}MultipleMixedError1WithArgCalled3`] = arg; - throw new Error("Error in sync"); - }); - result[`${type}MultipleMixedError1WithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}MultipleMixedError2WithArg`); - hook.tapAsync("async", (arg, callback) => { - result[`${type}MultipleMixedError2WithArgCalled1`] = arg; - callback(null, arg); - }); - hook.tapPromise("promise", arg => { - result[`${type}MultipleMixedError2WithArgCalled2`] = arg; - return Promise.resolve().then(() => { - throw new Error("Error in promise"); - }); - }); - hook.tap("sync", arg => { - result[`${type}MultipleMixedError2WithArgCalled3`] = arg; - return arg + 2; - }); - result[`${type}MultipleMixedError2WithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook(["x"], `${type}MultipleMixedError3WithArg`); - hook.tapAsync("async", (arg, callback) => { - result[`${type}MultipleMixedError3WithArgCalled1`] = arg; - callback(new Error("Error in async")); - }); - hook.tapPromise("promise", arg => { - result[`${type}MultipleMixedError3WithArgCalled2`] = arg; - return Promise.resolve(arg + 1); - }); - hook.tap("sync", arg => { - result[`${type}MultipleMixedError3WithArgCalled3`] = arg; - return arg + 2; - }); - result[`${type}MultipleMixedError3WithArg`] = await this.gainResult(cb => - hook[type](42, cb) - ); - } - - { - const hook = this.createHook([], `${type}MultipleMixedLateError`); - hook.tapAsync("async", callback => { - result[`${type}MultipleMixedLateErrorCalled1`] = true; - setTimeout(() => callback(new Error("Error in async")), 100); - }); - hook.tapPromise("promise", () => { - result[`${type}MultipleMixedLateErrorCalled2`] = true; - return Promise.resolve(42); - }); - hook.tap("sync", () => { - result[`${type}MultipleMixedLateErrorCalled3`] = true; - return 43; - }); - result[`${type}MultipleMixedLateError`] = await this.gainResult(cb => - hook[type](cb) - ); - } - } - - async runIntercept(result, type) { - { - const hook = this.createHook(["a", "b", "c"], `${type}Intercepted`); - hook.intercept({ - call: (a, b, c) => { - result[`${type}InterceptedCall1`] = [a, b, c]; - }, - - done: () => { - result[`${type}InterceptedDone1`] = true; - }, - - result: r => { - result[`${type}InterceptedResult1`] = r; - }, - - error: err => { - result[`${type}InterceptedError1`] = err; - }, - - tap: tap => { - result[`${type}InterceptedTap1`] = Object.assign({}, tap, { - fn: tap.fn.length - }); - } - }); - hook.intercept({ - call: (a, b, c) => { - result[`${type}InterceptedCall2`] = [a, b, c]; - }, - - done: () => { - result[`${type}InterceptedDone2`] = true; - }, - - result: r => { - result[`${type}InterceptedResult2`] = r; - }, - - error: err => { - result[`${type}InterceptedError2`] = err; - }, - - tap: tap => { - if (!result[`${type}InterceptedTap2`]) - result[`${type}InterceptedTap2`] = Object.assign({}, tap, { - fn: tap.fn.length - }); - } - }); - hook.tap("sync", (a, b, c) => a + b + c); - hook.tapPromise("promise", (a, b) => Promise.resolve(a + b + 1)); - result[`${type}Intercepted`] = await this.gainResult(cb => - hook[type](1, 2, 3, cb) - ); - } - - // We don't support context, it's deprecated in tapable - // { - // const hook = this.createHook( - // ["a", "b", "c"], - // `${type}ContextIntercepted` - // ); - // hook.intercept({ - // call: (context, a, b, c) => { - // context.number = 42; - // result[`${type}ContextInterceptedCall1`] = [context, a, b, c]; - // }, - // loop: (context, a, b, c) => { - // context.number2 = 88; - // result[`${type}ContextInterceptedLoop1`] = [context, a, b, c]; - // }, - // tap: (context, tap) => { - // result[`${type}ContextInterceptedTap1`] = context; - // }, - // context: true - // }); - // hook.intercept({ - // call: (a, b, c) => { - // result[`${type}ContextInterceptedCall2`] = [a, b, c]; - // } - // }); - // hook.tap( - // { - // name: "sync", - // context: true - // }, - // (context, a, b, c) => context.number + a + b + c - // ); - // result[`${type}ContextIntercepted`] = await this.gainResult(cb => - // hook[type](1, 2, 3, cb) - // ); - // } - - // { - // const hook = this.createHook( - // ["a", "b", "c"], - // `${type}UnusedContextIntercepted` - // ); - // hook.intercept({ - // call: (context, a, b, c) => { - // result[`${type}UnusedContextInterceptedCall1`] = [context, a, b, c]; - // }, - // tap: (context, tap) => { - // result[`${type}UnusedContextInterceptedTap1`] = context; - // }, - // context: true - // }); - // hook.intercept({ - // call: (a, b, c) => { - // result[`${type}UnusedContextInterceptedCall2`] = [a, b, c]; - // } - // }); - // hook.tap("sync", (a, b, c) => a + b + c); - // result[`${type}UnusedContextIntercepted`] = await this.gainResult(cb => - // hook[type](1, 2, 3, cb) - // ); - // } - } - - gainResult(fn) { - return Promise.race([ - new Promise(resolve => { - try { - const ret = fn((err, result) => { - if (err) { - resolve({ - type: "async", - error: err.message - }); - } else { - resolve({ - type: "async", - value: result - }); - } - }); - if (ret instanceof Promise) { - resolve( - ret.then( - res => ({ - type: "promise", - value: res - }), - err => ({ - type: "promise", - error: err.message - }) - ) - ); - } else if (ret !== undefined) { - resolve({ - type: "return", - value: ret - }); - } - } catch (e) { - resolve({ - error: e.message - }); - } - }), - new Promise(resolve => { - setTimeout( - () => - resolve({ - type: "no result" - }), - 1000 - ); - }) - ]); - } - - createHook(args, name) { - try { - return this.hookCreator(args, name); - } catch (err) { - return { - tap: () => {}, - tapPromise: () => {}, - tapAsync: () => {}, - intercept: () => {}, - call: () => { - throw err; - }, - callAsync: () => { - throw err; - }, - promise: () => { - throw err; - } - }; - } - } -} - -module.exports = HookTester; diff --git a/packages/rspack-lite-tapable/tests/MultiHook.test.js b/packages/rspack-lite-tapable/tests/MultiHook.test.js deleted file mode 100644 index f050410ddc10..000000000000 --- a/packages/rspack-lite-tapable/tests/MultiHook.test.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/MultiHook.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -const { MultiHook } = require("../"); - -describe("MultiHook", () => { - const redirectedMethods = ["tap", "tapAsync", "tapPromise"]; - for (const name of redirectedMethods) { - it(`should redirect ${name}`, () => { - const calls = []; - const fakeHook = { - [name]: (options, fn) => { - calls.push({ options, fn }); - } - }; - new MultiHook([fakeHook, fakeHook])[name]("options", "fn"); - expect(calls).toEqual([ - { options: "options", fn: "fn" }, - { options: "options", fn: "fn" } - ]); - }); - } - it("should redirect intercept", () => { - const calls = []; - const fakeHook = { - intercept: interceptor => { - calls.push(interceptor); - } - }; - new MultiHook([fakeHook, fakeHook]).intercept("interceptor"); - expect(calls).toEqual(["interceptor", "interceptor"]); - }); - // it("should redirect withOptions", () => { - // const calls = []; - // const fakeHook = { - // withOptions: options => { - // calls.push(options); - // return { - // tap: (options, fn) => { - // calls.push({ options, fn }); - // } - // }; - // } - // }; - // const newHook = new MultiHook([fakeHook, fakeHook]).withOptions("options"); - // newHook.tap("options", "fn"); - // expect(calls).toEqual([ - // "options", - // "options", - // { options: "options", fn: "fn" }, - // { options: "options", fn: "fn" } - // ]); - // }); - it("should redirect isUsed", () => { - const calls = []; - const fakeHook1 = { - isUsed: () => { - return true; - } - }; - const fakeHook2 = { - isUsed: () => { - return false; - } - }; - expect(new MultiHook([fakeHook1, fakeHook1]).isUsed()).toEqual(true); - expect(new MultiHook([fakeHook1, fakeHook2]).isUsed()).toEqual(true); - expect(new MultiHook([fakeHook2, fakeHook1]).isUsed()).toEqual(true); - expect(new MultiHook([fakeHook2, fakeHook2]).isUsed()).toEqual(false); - }); -}); diff --git a/packages/rspack-lite-tapable/tests/SyncBailHook.test.js b/packages/rspack-lite-tapable/tests/SyncBailHook.test.js deleted file mode 100644 index 6ac42730977b..000000000000 --- a/packages/rspack-lite-tapable/tests/SyncBailHook.test.js +++ /dev/null @@ -1,108 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/SyncBailHook.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -const { SyncBailHook } = require("../"); - -describe("SyncBailHook", () => { - it("should allow to create sync bail hooks", async () => { - const h1 = new SyncBailHook(["a"]); - const h2 = new SyncBailHook(["a", "b"]); - - let r = h1.call(1); - expect(r).toEqual(undefined); - - h1.tap("A", a => undefined); - h2.tap("A", (a, b) => [a, b]); - - expect(h1.call(1)).toEqual(undefined); - expect(await h1.promise(1)).toEqual(undefined); - expect(await pify(cb => h1.callAsync(1, cb))).toEqual(undefined); - expect(h2.call(1, 2)).toEqual([1, 2]); - expect(await h2.promise(1, 2)).toEqual([1, 2]); - expect(await pify(cb => h2.callAsync(1, 2, cb))).toEqual([1, 2]); - - h1.tap("B", a => "ok" + a); - h2.tap("B", (a, b) => "wrong"); - - expect(h1.call(10)).toEqual("ok10"); - expect(await h1.promise(10)).toEqual("ok10"); - expect(await pify(cb => h1.callAsync(10, cb))).toEqual("ok10"); - expect(h2.call(10, 20)).toEqual([10, 20]); - expect(await h2.promise(10, 20)).toEqual([10, 20]); - expect(await pify(cb => h2.callAsync(10, 20, cb))).toEqual([10, 20]); - }); - - it("should bail on non-null return", async () => { - const h1 = new SyncBailHook(["a"]); - const mockCall1 = jest.fn(); - const mockCall2 = jest.fn(() => "B"); - const mockCall3 = jest.fn(() => "C"); - h1.tap("A", mockCall1); - h1.tap("B", mockCall2); - h1.tap("C", mockCall3); - expect(h1.call()).toEqual("B"); - expect(mockCall1).toHaveBeenCalledTimes(1); - expect(mockCall2).toHaveBeenCalledTimes(1); - expect(mockCall3).toHaveBeenCalledTimes(0); - }); - - it("should allow to intercept calls", () => { - const hook = new SyncBailHook(["x"]); - - const mockCall = jest.fn(); - const mockTap = jest.fn(x => x); - - hook.intercept({ - call: mockCall, - tap: mockTap - }); - - hook.call(5); - - expect(mockCall).toHaveBeenLastCalledWith(5); - expect(mockTap).not.toHaveBeenCalled(); - - hook.tap("test", () => 10); - - hook.call(7); - - expect(mockCall).toHaveBeenLastCalledWith(7); - expect(mockTap).toHaveBeenCalled(); - }); - - it("should throw on tapAsync", () => { - const hook = new SyncBailHook(["x"]); - expect(() => hook.tapAsync()).toThrow(/tapAsync/); - }); - - it("should throw on tapPromise", () => { - const hook = new SyncBailHook(["x"]); - expect(() => hook.tapPromise()).toThrow(/tapPromise/); - }); - - it("should not crash with many plugins", () => { - const hook = new SyncBailHook(["x"]); - for (let i = 0; i < 1000; i++) { - hook.tap("Test", () => 42); - } - expect(hook.call()).toBe(42); - }); -}); - -function pify(fn) { - return new Promise((resolve, reject) => { - fn((err, result) => { - if (err) reject(err); - else resolve(result); - }); - }); -} diff --git a/packages/rspack-lite-tapable/tests/SyncHook.test.js b/packages/rspack-lite-tapable/tests/SyncHook.test.js deleted file mode 100644 index 26435e81c46a..000000000000 --- a/packages/rspack-lite-tapable/tests/SyncHook.test.js +++ /dev/null @@ -1,132 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/SyncHook.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -const { SyncHook } = require("../"); - -describe("SyncHook", () => { - it("should allow to create sync hooks", async () => { - const h0 = new SyncHook(); - const h1 = new SyncHook(["test"]); - const h2 = new SyncHook(["test", "arg2"]); - const h3 = new SyncHook(["test", "arg2", "arg3"]); - - h0.call(); - await h0.promise(); - await new Promise(resolve => h0.callAsync(resolve)); - - const mock0 = jest.fn(); - h0.tap("A", mock0); - - h0.call(); - - expect(mock0).toHaveBeenLastCalledWith(); - - const mock1 = jest.fn(); - h0.tap("B", mock1); - - h0.call(); - - expect(mock1).toHaveBeenLastCalledWith(); - - const mock2 = jest.fn(); - const mock3 = jest.fn(); - const mock4 = jest.fn(); - const mock5 = jest.fn(); - - h1.tap("C", mock2); - h2.tap("D", mock3); - h3.tap("E", mock4); - h3.tap("F", mock5); - - h1.call("1"); - h2.call("1", 2); - h3.call("1", 2, 3); - - expect(mock2).toHaveBeenLastCalledWith("1"); - expect(mock3).toHaveBeenLastCalledWith("1", 2); - expect(mock4).toHaveBeenLastCalledWith("1", 2, 3); - expect(mock5).toHaveBeenLastCalledWith("1", 2, 3); - - await new Promise(resolve => h1.callAsync("a", resolve)); - await h2.promise("a", "b"); - await new Promise(resolve => h3.callAsync("a", "b", "c", resolve)); - - expect(mock2).toHaveBeenLastCalledWith("a"); - expect(mock3).toHaveBeenLastCalledWith("a", "b"); - expect(mock4).toHaveBeenLastCalledWith("a", "b", "c"); - expect(mock5).toHaveBeenLastCalledWith("a", "b", "c"); - - await h3.promise("x", "y"); - - expect(mock4).toHaveBeenLastCalledWith("x", "y", undefined); - expect(mock5).toHaveBeenLastCalledWith("x", "y", undefined); - }); - - it("should sync execute hooks", () => { - const h1 = new SyncHook(["a"]); - const mockCall1 = jest.fn(); - const mockCall2 = jest.fn(() => "B"); - const mockCall3 = jest.fn(() => "C"); - h1.tap("A", mockCall1); - h1.tap("B", mockCall2); - h1.tap("C", mockCall3); - expect(h1.call()).toEqual(undefined); - expect(mockCall1).toHaveBeenCalledTimes(1); - expect(mockCall2).toHaveBeenCalledTimes(1); - expect(mockCall3).toHaveBeenCalledTimes(1); - }); - - it("should allow to intercept calls", () => { - const hook = new SyncHook(["arg1", "arg2"]); - - const mockCall = jest.fn(); - const mock0 = jest.fn(); - const mockRegister = jest.fn(x => ({ - name: "huh", - type: "sync", - fn: mock0 - })); - - const mock1 = jest.fn(); - hook.tap("Test1", mock1); - - hook.intercept({ - call: mockCall, - register: mockRegister - }); - - const mock2 = jest.fn(); - hook.tap("Test2", mock2); - - hook.call(1, 2); - - expect(mockCall).toHaveBeenLastCalledWith(1, 2); - expect(mockRegister).toHaveBeenLastCalledWith({ - type: "sync", - name: "Test2", - fn: mock2 - }); - expect(mock1).not.toHaveBeenLastCalledWith(1, 2); - expect(mock2).not.toHaveBeenLastCalledWith(1, 2); - expect(mock0).toHaveBeenLastCalledWith(1, 2); - }); - - it("should throw error on tapAsync", () => { - const hook = new SyncHook(["arg1", "arg2"]); - expect(() => hook.tapAsync()).toThrow(/tapAsync/); - }); - - it("should throw error on tapPromise", () => { - const hook = new SyncHook(["arg1", "arg2"]); - expect(() => hook.tapPromise()).toThrow(/tapPromise/); - }); -}); diff --git a/packages/rspack-lite-tapable/tests/SyncHooks.test.js b/packages/rspack-lite-tapable/tests/SyncHooks.test.js deleted file mode 100644 index 8abe74305641..000000000000 --- a/packages/rspack-lite-tapable/tests/SyncHooks.test.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/SyncHooks.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -const HookTester = require("./HookTester"); -const { SyncHook, SyncBailHook, SyncWaterfallHook } = require("../"); - -describe("SyncHook", () => { - it("should have to correct behavior", async () => { - const tester = new HookTester(args => new SyncHook(args)); - - const result = await tester.run(true); - - expect(result).toMatchSnapshot(); - }, 15000); -}); - -describe("SyncBailHook", () => { - it("should have to correct behavior", async () => { - const tester = new HookTester(args => new SyncBailHook(args)); - - const result = await tester.run(true); - - expect(result).toMatchSnapshot(); - }, 15000); -}); - -describe("SyncWaterfallHook", () => { - it("should have to correct behavior", async () => { - const tester = new HookTester(args => new SyncWaterfallHook(args)); - - const result = await tester.run(true); - - expect(result).toMatchSnapshot(); - }, 15000); -}); - -// describe("SyncLoopHook", () => { -// it("should have to correct behavior", async () => { -// const tester = new HookTester(args => new SyncLoopHook(args)); - -// const result = await tester.runForLoop(true); - -// expect(result).toMatchSnapshot(); -// }, 15000); -// }); diff --git a/packages/rspack-lite-tapable/tests/SyncWaterfallHook.test.js b/packages/rspack-lite-tapable/tests/SyncWaterfallHook.test.js deleted file mode 100644 index 3fc279f47d57..000000000000 --- a/packages/rspack-lite-tapable/tests/SyncWaterfallHook.test.js +++ /dev/null @@ -1,164 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/webpack/tapable/blob/a0a7b26/lib/__tests__/SyncWaterfallHook.js - * - * MIT Licensed - * Author Tobias Koppers @sokra - * Copyright (c) JS Foundation and other contributors - * https://github.com/webpack/webpack/blob/main/LICENSE - */ - -"use strict"; - -const { SyncWaterfallHook } = require("../"); - -describe("SyncWaterfallHook", () => { - it("should throw an error when hook has no argument", () => { - expect(() => new SyncWaterfallHook()).toThrow( - "Waterfall hooks must have at least one argument" - ); - }); - - it("should allow to create sync hooks", async () => { - const hook = new SyncWaterfallHook(["arg1", "arg2"]); - - const mock0 = jest.fn(arg => arg + ",0"); - const mock1 = jest.fn(arg => arg + ",1"); - const mock2 = jest.fn(arg => arg + ",2"); - hook.tap("A", mock0); - hook.tap("B", mock1); - hook.tap("C", mock2); - - const returnValue0 = hook.call("sync", "a2"); - expect(returnValue0).toBe("sync,0,1,2"); - expect(mock0).toHaveBeenLastCalledWith("sync", "a2"); - expect(mock1).toHaveBeenLastCalledWith("sync,0", "a2"); - expect(mock2).toHaveBeenLastCalledWith("sync,0,1", "a2"); - - const returnValue1 = await new Promise(resolve => - hook.callAsync("async", "a2", (...args) => resolve(args)) - ); - - expect(returnValue1).toEqual([null, "async,0,1,2"]); - expect(mock0).toHaveBeenLastCalledWith("async", "a2"); - expect(mock1).toHaveBeenLastCalledWith("async,0", "a2"); - expect(mock2).toHaveBeenLastCalledWith("async,0,1", "a2"); - - const returnValue2 = await hook.promise("promise", "a2"); - - expect(returnValue2).toBe("promise,0,1,2"); - expect(mock0).toHaveBeenLastCalledWith("promise", "a2"); - expect(mock1).toHaveBeenLastCalledWith("promise,0", "a2"); - expect(mock2).toHaveBeenLastCalledWith("promise,0,1", "a2"); - }); - - it("should allow to intercept calls", () => { - const hook = new SyncWaterfallHook(["arg1", "arg2"]); - - const mockCall = jest.fn(); - const mock0 = jest.fn(() => "mock0"); - const mockRegister = jest.fn(x => ({ - name: "huh", - type: "sync", - fn: mock0 - })); - - const mock1 = jest.fn(() => "mock1"); - hook.tap("Test1", mock1); - - hook.intercept({ - call: mockCall, - register: mockRegister - }); - - const mock2 = jest.fn(() => "mock2"); - hook.tap("Test2", mock2); - - const returnValue = hook.call(1, 2); - - expect(returnValue).toBe("mock0"); - expect(mockCall).toHaveBeenLastCalledWith(1, 2); - expect(mockRegister).toHaveBeenLastCalledWith({ - type: "sync", - name: "Test2", - fn: mock2 - }); - expect(mock1).not.toHaveBeenLastCalledWith(1, 2); - expect(mock2).not.toHaveBeenLastCalledWith(1, 2); - expect(mock0.mock.calls).toEqual([ - [1, 2], - ["mock0", 2] - ]); - }); - it("should allow to create waterfall hooks", async () => { - const h1 = new SyncWaterfallHook(["a"]); - const h2 = new SyncWaterfallHook(["a", "b"]); - - expect(h1.call(1)).toEqual(1); - - h1.tap("A", a => undefined); - h2.tap("A", (a, b) => [a, b]); - - expect(h1.call(1)).toEqual(1); - expect(await h1.promise(1)).toEqual(1); - expect(await pify(cb => h1.callAsync(1, cb))).toEqual(1); - expect(h2.call(1, 2)).toEqual([1, 2]); - expect(await h2.promise(1, 2)).toEqual([1, 2]); - expect(await pify(cb => h2.callAsync(1, 2, cb))).toEqual([1, 2]); - - let count = 1; - count = h1.call(count + ++count); // 1 + 2 => 3 - count = h1.call(count + ++count); // 3 + 4 => 7 - count = h1.call(count + ++count); // 7 + 8 => 15 - expect(count).toEqual(15); - }); - - it("should throw when args have length less than 1", () => { - expect(() => { - new SyncWaterfallHook([]); - }).toThrow(/Waterfall/); - }); - - it("should allow to intercept calls", () => { - const hook = new SyncWaterfallHook(["x"]); - - const mockCall = jest.fn(); - const mockTap = jest.fn(x => x); - - hook.intercept({ - call: mockCall, - tap: mockTap - }); - - hook.call(5); - - expect(mockCall).toHaveBeenLastCalledWith(5); - expect(mockTap).not.toHaveBeenCalled(); - - hook.tap("test", () => 10); - - hook.call(7); - - expect(mockCall).toHaveBeenLastCalledWith(7); - expect(mockTap).toHaveBeenCalled(); - }); - - it("should throw on tapAsync", () => { - const hook = new SyncWaterfallHook(["x"]); - expect(() => hook.tapAsync()).toThrow(/tapAsync/); - }); - - it("should throw on tapPromise", () => { - const hook = new SyncWaterfallHook(["x"]); - expect(() => hook.tapPromise()).toThrow(/tapPromise/); - }); -}); - -function pify(fn) { - return new Promise((resolve, reject) => { - fn((err, result) => { - if (err) reject(err); - else resolve(result); - }); - }); -} diff --git a/packages/rspack-lite-tapable/tests/__snapshots__/AsyncParallelHooks.test.js.snap b/packages/rspack-lite-tapable/tests/__snapshots__/AsyncParallelHooks.test.js.snap deleted file mode 100644 index ea31b4f2a9a7..000000000000 --- a/packages/rspack-lite-tapable/tests/__snapshots__/AsyncParallelHooks.test.js.snap +++ /dev/null @@ -1,688 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`AsyncParallelHook should have to correct behavior 1`] = ` -{ - "async": { - "callAsyncMultipleAsyncEarlyError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncEarlyErrorCalled1": true, - "callAsyncMultipleAsyncError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncErrorCalled1": true, - "callAsyncMultipleAsyncLateError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncLateErrorCalled1": true, - "callAsyncMultipleAsyncLateErrorCalled3": true, - "callAsyncMultipleAsyncLateErrorEarlyResult1": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncLateErrorEarlyResult1Called1": true, - "callAsyncMultipleAsyncLateErrorEarlyResult1Called3": true, - "callAsyncMultipleAsyncLateErrorEarlyResult2": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncLateErrorEarlyResult2Called1": true, - "callAsyncMultipleAsyncLateErrorEarlyResult2Called3": true, - "callAsyncMultipleAsyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgCalled1": 42, - "callAsyncMultipleAsyncWithArgCalled2": 42, - "callAsyncMultipleAsyncWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgFirstReturnCalled2": 42, - "callAsyncMultipleAsyncWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleAsyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleMixed1WithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleMixed1WithArgCalled1": 42, - "callAsyncMultipleMixed1WithArgCalled2": 42, - "callAsyncMultipleMixed1WithArgCalled3": 42, - "callAsyncMultipleMixed2WithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleMixed2WithArgCalled1": 42, - "callAsyncMultipleMixed2WithArgCalled2": 42, - "callAsyncMultipleMixed3WithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleMixed3WithArgCalled1": 42, - "callAsyncMultipleMixed3WithArgCalled2": 42, - "callAsyncMultipleMixed3WithArgCalled3": 42, - "callAsyncMultipleMixedError1WithArg": { - "error": "Error in sync", - "type": "async", - }, - "callAsyncMultipleMixedError1WithArgCalled1": 42, - "callAsyncMultipleMixedError1WithArgCalled2": 42, - "callAsyncMultipleMixedError1WithArgCalled3": 42, - "callAsyncMultipleMixedError2WithArg": { - "error": "Error in promise", - "type": "async", - }, - "callAsyncMultipleMixedError2WithArgCalled1": 42, - "callAsyncMultipleMixedError2WithArgCalled2": 42, - "callAsyncMultipleMixedError2WithArgCalled3": 42, - "callAsyncMultipleMixedError3WithArg": { - "error": "Error in async", - "type": "async", - }, - "callAsyncMultipleMixedError3WithArgCalled1": 42, - "callAsyncMultipleMixedLateError": { - "error": "Error in async", - "type": "async", - }, - "callAsyncMultipleMixedLateErrorCalled1": true, - "callAsyncMultipleMixedLateErrorCalled2": true, - "callAsyncMultipleMixedLateErrorCalled3": true, - "callAsyncMultiplePromiseEarlyError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseEarlyErrorCalled1": true, - "callAsyncMultiplePromiseEarlyErrorCalled3": true, - "callAsyncMultiplePromiseError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseErrorCalled1": true, - "callAsyncMultiplePromiseErrorCalled3": true, - "callAsyncMultiplePromiseLateError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseLateErrorCalled1": true, - "callAsyncMultiplePromiseLateErrorCalled3": true, - "callAsyncMultiplePromiseWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgCalled1": 42, - "callAsyncMultiplePromiseWithArgCalled2": 42, - "callAsyncMultiplePromiseWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgFirstReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgFirstReturnCalled2": 42, - "callAsyncMultiplePromiseWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgLastReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgLastReturnCalled2": 42, - "callAsyncMultiplePromiseWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgNoReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgNoReturnCalled2": 42, - "callAsyncMultipleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncCalled1": true, - "callAsyncMultipleSyncCalled2": true, - "callAsyncMultipleSyncError": { - "error": "Error in sync2", - "type": "async", - }, - "callAsyncMultipleSyncErrorCalled1": true, - "callAsyncMultipleSyncLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncLastReturnCalled1": true, - "callAsyncMultipleSyncLastReturnCalled2": true, - "callAsyncMultipleSyncNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncNoReturnCalled1": true, - "callAsyncMultipleSyncNoReturnCalled2": true, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgCalled2": 42, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturnCalled2": 42, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncNone": { - "type": "async", - "value": undefined, - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleAsyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleAsyncWithArgCalled1": 42, - "callAsyncSinglePromiseWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSinglePromiseWithArgCalled1": 42, - "callAsyncSingleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncCalled1": true, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncWithArgCalled1": 42, - "callAsyncSingleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleAsyncEarlyError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncEarlyErrorCalled1": true, - "promiseMultipleAsyncError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncErrorCalled1": true, - "promiseMultipleAsyncLateError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncLateErrorCalled1": true, - "promiseMultipleAsyncLateErrorCalled3": true, - "promiseMultipleAsyncLateErrorEarlyResult1": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncLateErrorEarlyResult1Called1": true, - "promiseMultipleAsyncLateErrorEarlyResult1Called3": true, - "promiseMultipleAsyncLateErrorEarlyResult2": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncLateErrorEarlyResult2Called1": true, - "promiseMultipleAsyncLateErrorEarlyResult2Called3": true, - "promiseMultipleAsyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgCalled1": 42, - "promiseMultipleAsyncWithArgCalled2": 42, - "promiseMultipleAsyncWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgFirstReturnCalled1": 42, - "promiseMultipleAsyncWithArgFirstReturnCalled2": 42, - "promiseMultipleAsyncWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgLastReturnCalled1": 42, - "promiseMultipleAsyncWithArgLastReturnCalled2": 42, - "promiseMultipleAsyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgNoReturnCalled1": 42, - "promiseMultipleAsyncWithArgNoReturnCalled2": 42, - "promiseMultipleMixed1WithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleMixed1WithArgCalled1": 42, - "promiseMultipleMixed1WithArgCalled2": 42, - "promiseMultipleMixed1WithArgCalled3": 42, - "promiseMultipleMixed2WithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleMixed2WithArgCalled1": 42, - "promiseMultipleMixed2WithArgCalled2": 42, - "promiseMultipleMixed3WithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleMixed3WithArgCalled1": 42, - "promiseMultipleMixed3WithArgCalled2": 42, - "promiseMultipleMixed3WithArgCalled3": 42, - "promiseMultipleMixedError1WithArg": { - "error": "Error in sync", - "type": "promise", - }, - "promiseMultipleMixedError1WithArgCalled1": 42, - "promiseMultipleMixedError1WithArgCalled2": 42, - "promiseMultipleMixedError1WithArgCalled3": 42, - "promiseMultipleMixedError2WithArg": { - "error": "Error in promise", - "type": "promise", - }, - "promiseMultipleMixedError2WithArgCalled1": 42, - "promiseMultipleMixedError2WithArgCalled2": 42, - "promiseMultipleMixedError2WithArgCalled3": 42, - "promiseMultipleMixedError3WithArg": { - "error": "Error in async", - "type": "promise", - }, - "promiseMultipleMixedError3WithArgCalled1": 42, - "promiseMultipleMixedLateError": { - "error": "Error in async", - "type": "promise", - }, - "promiseMultipleMixedLateErrorCalled1": true, - "promiseMultipleMixedLateErrorCalled2": true, - "promiseMultipleMixedLateErrorCalled3": true, - "promiseMultiplePromiseEarlyError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseEarlyErrorCalled1": true, - "promiseMultiplePromiseEarlyErrorCalled3": true, - "promiseMultiplePromiseError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseErrorCalled1": true, - "promiseMultiplePromiseErrorCalled3": true, - "promiseMultiplePromiseLateError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseLateErrorCalled1": true, - "promiseMultiplePromiseLateErrorCalled3": true, - "promiseMultiplePromiseWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgCalled1": 42, - "promiseMultiplePromiseWithArgCalled2": 42, - "promiseMultiplePromiseWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgFirstReturnCalled1": 42, - "promiseMultiplePromiseWithArgFirstReturnCalled2": 42, - "promiseMultiplePromiseWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgLastReturnCalled1": 42, - "promiseMultiplePromiseWithArgLastReturnCalled2": 42, - "promiseMultiplePromiseWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgNoReturnCalled1": 42, - "promiseMultiplePromiseWithArgNoReturnCalled2": 42, - "promiseMultipleSync": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncCalled1": true, - "promiseMultipleSyncCalled2": true, - "promiseMultipleSyncError": { - "error": "Error in sync2", - "type": "promise", - }, - "promiseMultipleSyncErrorCalled1": true, - "promiseMultipleSyncLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncLastReturnCalled1": true, - "promiseMultipleSyncLastReturnCalled2": true, - "promiseMultipleSyncNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncNoReturnCalled1": true, - "promiseMultipleSyncNoReturnCalled2": true, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgCalled2": 42, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgFirstReturnCalled2": 42, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseNone": { - "type": "promise", - "value": undefined, - }, - "promiseNoneWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleAsyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleAsyncWithArgCalled1": 42, - "promiseSinglePromiseWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSinglePromiseWithArgCalled1": 42, - "promiseSingleSync": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncCalled1": true, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncWithArgCalled1": 42, - "promiseSingleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncWithArgNoReturnCalled1": 42, - }, - "intercept": { - "callAsyncIntercepted": { - "type": "async", - "value": undefined, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedDone1": true, - "callAsyncInterceptedDone2": true, - "callAsyncInterceptedTap1": { - "fn": 2, - "name": "promise", - "type": "promise", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - "promiseIntercepted": { - "type": "promise", - "value": undefined, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedDone1": true, - "promiseInterceptedDone2": true, - "promiseInterceptedTap1": { - "fn": 2, - "name": "promise", - "type": "promise", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - }, - "sync": { - "callAsyncIntercepted": { - "type": "async", - "value": undefined, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncMultipleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncCalled1": true, - "callAsyncMultipleSyncCalled2": true, - "callAsyncMultipleSyncError": { - "error": "Error in sync2", - "type": "async", - }, - "callAsyncMultipleSyncErrorCalled1": true, - "callAsyncMultipleSyncErrorCalled2": true, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgCalled2": 42, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturnCalled2": 42, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleSyncWithArgs": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callAsyncMultipleSyncWithArgsCalled2": [ - 42, - 43, - 44, - ], - "callAsyncNone": { - "type": "async", - "value": undefined, - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncCalled": true, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncWithArgCalled": 42, - "promiseIntercepted": { - "type": "promise", - "value": undefined, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseMultipleSync": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncCalled1": true, - "promiseMultipleSyncCalled2": true, - "promiseMultipleSyncError": { - "error": "Error in sync2", - "type": "promise", - }, - "promiseMultipleSyncErrorCalled1": true, - "promiseMultipleSyncErrorCalled2": true, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgCalled2": 42, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgFirstReturnCalled2": 42, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseMultipleSyncWithArgs": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "promiseMultipleSyncWithArgsCalled2": [ - 42, - 43, - 44, - ], - "promiseNone": { - "type": "promise", - "value": undefined, - }, - "promiseNoneWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSync": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncCalled": true, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncWithArgCalled": 42, - }, -} -`; diff --git a/packages/rspack-lite-tapable/tests/__snapshots__/AsyncSeriesHooks.test.js.snap b/packages/rspack-lite-tapable/tests/__snapshots__/AsyncSeriesHooks.test.js.snap deleted file mode 100644 index 6fe1c25093d6..000000000000 --- a/packages/rspack-lite-tapable/tests/__snapshots__/AsyncSeriesHooks.test.js.snap +++ /dev/null @@ -1,1880 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`AsyncSeriesBailHook should have to correct behavior 1`] = ` -{ - "async": { - "callAsyncMultipleAsyncEarlyError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncEarlyErrorCalled1": true, - "callAsyncMultipleAsyncError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncErrorCalled1": true, - "callAsyncMultipleAsyncLateError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncLateErrorCalled1": true, - "callAsyncMultipleAsyncLateErrorEarlyResult1": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncLateErrorEarlyResult1Called1": true, - "callAsyncMultipleAsyncLateErrorEarlyResult2": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleAsyncLateErrorEarlyResult2Called1": true, - "callAsyncMultipleAsyncWithArg": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleAsyncWithArgCalled1": 42, - "callAsyncMultipleAsyncWithArgFirstReturn": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleAsyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgLastReturn": { - "type": "async", - "value": 44, - }, - "callAsyncMultipleAsyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleAsyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleMixed1WithArg": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleMixed1WithArgCalled1": 42, - "callAsyncMultipleMixed2WithArg": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleMixed2WithArgCalled1": 42, - "callAsyncMultipleMixed3WithArg": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleMixed3WithArgCalled1": 42, - "callAsyncMultipleMixedError1WithArg": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleMixedError1WithArgCalled1": 42, - "callAsyncMultipleMixedError2WithArg": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleMixedError2WithArgCalled1": 42, - "callAsyncMultipleMixedError3WithArg": { - "error": "Error in async", - "type": "async", - }, - "callAsyncMultipleMixedError3WithArgCalled1": 42, - "callAsyncMultipleMixedLateError": { - "error": "Error in async", - "type": "async", - }, - "callAsyncMultipleMixedLateErrorCalled1": true, - "callAsyncMultiplePromiseEarlyError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseEarlyErrorCalled1": true, - "callAsyncMultiplePromiseError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseErrorCalled1": true, - "callAsyncMultiplePromiseLateError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseLateErrorCalled1": true, - "callAsyncMultiplePromiseWithArg": { - "type": "async", - "value": 43, - }, - "callAsyncMultiplePromiseWithArgCalled1": 42, - "callAsyncMultiplePromiseWithArgFirstReturn": { - "type": "async", - "value": 43, - }, - "callAsyncMultiplePromiseWithArgFirstReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgLastReturn": { - "type": "async", - "value": 44, - }, - "callAsyncMultiplePromiseWithArgLastReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgLastReturnCalled2": 42, - "callAsyncMultiplePromiseWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgNoReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgNoReturnCalled2": 42, - "callAsyncMultipleSync": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleSyncCalled1": true, - "callAsyncMultipleSyncError": { - "error": "Error in sync2", - "type": "async", - }, - "callAsyncMultipleSyncErrorCalled1": true, - "callAsyncMultipleSyncLastReturn": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleSyncLastReturnCalled1": true, - "callAsyncMultipleSyncLastReturnCalled2": true, - "callAsyncMultipleSyncNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncNoReturnCalled1": true, - "callAsyncMultipleSyncNoReturnCalled2": true, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": 44, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncNone": { - "type": "async", - "value": undefined, - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleAsyncWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleAsyncWithArgCalled1": 42, - "callAsyncSinglePromiseWithArg": { - "type": "async", - "value": 43, - }, - "callAsyncSinglePromiseWithArgCalled1": 42, - "callAsyncSingleSync": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSyncCalled1": true, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": 43, - }, - "callAsyncSingleSyncWithArgCalled1": 42, - "callAsyncSingleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleAsyncEarlyError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncEarlyErrorCalled1": true, - "promiseMultipleAsyncError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncErrorCalled1": true, - "promiseMultipleAsyncLateError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncLateErrorCalled1": true, - "promiseMultipleAsyncLateErrorEarlyResult1": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncLateErrorEarlyResult1Called1": true, - "promiseMultipleAsyncLateErrorEarlyResult2": { - "type": "promise", - "value": 42, - }, - "promiseMultipleAsyncLateErrorEarlyResult2Called1": true, - "promiseMultipleAsyncWithArg": { - "type": "promise", - "value": 43, - }, - "promiseMultipleAsyncWithArgCalled1": 42, - "promiseMultipleAsyncWithArgFirstReturn": { - "type": "promise", - "value": 43, - }, - "promiseMultipleAsyncWithArgFirstReturnCalled1": 42, - "promiseMultipleAsyncWithArgLastReturn": { - "type": "promise", - "value": 44, - }, - "promiseMultipleAsyncWithArgLastReturnCalled1": 42, - "promiseMultipleAsyncWithArgLastReturnCalled2": 42, - "promiseMultipleAsyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgNoReturnCalled1": 42, - "promiseMultipleAsyncWithArgNoReturnCalled2": 42, - "promiseMultipleMixed1WithArg": { - "type": "promise", - "value": 43, - }, - "promiseMultipleMixed1WithArgCalled1": 42, - "promiseMultipleMixed2WithArg": { - "type": "promise", - "value": 43, - }, - "promiseMultipleMixed2WithArgCalled1": 42, - "promiseMultipleMixed3WithArg": { - "type": "promise", - "value": 43, - }, - "promiseMultipleMixed3WithArgCalled1": 42, - "promiseMultipleMixedError1WithArg": { - "type": "promise", - "value": 42, - }, - "promiseMultipleMixedError1WithArgCalled1": 42, - "promiseMultipleMixedError2WithArg": { - "type": "promise", - "value": 42, - }, - "promiseMultipleMixedError2WithArgCalled1": 42, - "promiseMultipleMixedError3WithArg": { - "error": "Error in async", - "type": "promise", - }, - "promiseMultipleMixedError3WithArgCalled1": 42, - "promiseMultipleMixedLateError": { - "error": "Error in async", - "type": "promise", - }, - "promiseMultipleMixedLateErrorCalled1": true, - "promiseMultiplePromiseEarlyError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseEarlyErrorCalled1": true, - "promiseMultiplePromiseError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseErrorCalled1": true, - "promiseMultiplePromiseLateError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseLateErrorCalled1": true, - "promiseMultiplePromiseWithArg": { - "type": "promise", - "value": 43, - }, - "promiseMultiplePromiseWithArgCalled1": 42, - "promiseMultiplePromiseWithArgFirstReturn": { - "type": "promise", - "value": 43, - }, - "promiseMultiplePromiseWithArgFirstReturnCalled1": 42, - "promiseMultiplePromiseWithArgLastReturn": { - "type": "promise", - "value": 44, - }, - "promiseMultiplePromiseWithArgLastReturnCalled1": 42, - "promiseMultiplePromiseWithArgLastReturnCalled2": 42, - "promiseMultiplePromiseWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgNoReturnCalled1": 42, - "promiseMultiplePromiseWithArgNoReturnCalled2": 42, - "promiseMultipleSync": { - "type": "promise", - "value": 42, - }, - "promiseMultipleSyncCalled1": true, - "promiseMultipleSyncError": { - "error": "Error in sync2", - "type": "promise", - }, - "promiseMultipleSyncErrorCalled1": true, - "promiseMultipleSyncLastReturn": { - "type": "promise", - "value": 43, - }, - "promiseMultipleSyncLastReturnCalled1": true, - "promiseMultipleSyncLastReturnCalled2": true, - "promiseMultipleSyncNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncNoReturnCalled1": true, - "promiseMultipleSyncNoReturnCalled2": true, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": 43, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": 43, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": 44, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseNone": { - "type": "promise", - "value": undefined, - }, - "promiseNoneWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleAsyncWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleAsyncWithArgCalled1": 42, - "promiseSinglePromiseWithArg": { - "type": "promise", - "value": 43, - }, - "promiseSinglePromiseWithArgCalled1": 42, - "promiseSingleSync": { - "type": "promise", - "value": 42, - }, - "promiseSingleSyncCalled1": true, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": 43, - }, - "promiseSingleSyncWithArgCalled1": 42, - "promiseSingleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncWithArgNoReturnCalled1": 42, - }, - "intercept": { - "callAsyncIntercepted": { - "type": "async", - "value": 6, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedResult1": 6, - "callAsyncInterceptedResult2": 6, - "callAsyncInterceptedTap1": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - "promiseIntercepted": { - "type": "promise", - "value": 6, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedResult1": 6, - "promiseInterceptedResult2": 6, - "promiseInterceptedTap1": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - }, - "sync": { - "callAsyncIntercepted": { - "type": "async", - "value": 6, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedTap1": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncMultipleSync": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleSyncCalled1": true, - "callAsyncMultipleSyncError": { - "error": "Error in sync2", - "type": "async", - }, - "callAsyncMultipleSyncErrorCalled1": true, - "callAsyncMultipleSyncErrorCalled2": true, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": 84, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": 84, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": 85, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleSyncWithArgs": { - "type": "async", - "value": 129, - }, - "callAsyncMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callAsyncNone": { - "type": "async", - "value": undefined, - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSync": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSyncCalled": true, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSyncWithArgCalled": 42, - "promiseIntercepted": { - "type": "promise", - "value": 6, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedTap1": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseMultipleSync": { - "type": "promise", - "value": 42, - }, - "promiseMultipleSyncCalled1": true, - "promiseMultipleSyncError": { - "error": "Error in sync2", - "type": "promise", - }, - "promiseMultipleSyncErrorCalled1": true, - "promiseMultipleSyncErrorCalled2": true, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": 84, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": 84, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": 85, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseMultipleSyncWithArgs": { - "type": "promise", - "value": 129, - }, - "promiseMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "promiseNone": { - "type": "promise", - "value": undefined, - }, - "promiseNoneWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSync": { - "type": "promise", - "value": 42, - }, - "promiseSingleSyncCalled": true, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleSyncWithArgCalled": 42, - }, -} -`; - -exports[`AsyncSeriesHook should have to correct behavior 1`] = ` -{ - "async": { - "callAsyncMultipleAsyncEarlyError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncEarlyErrorCalled1": true, - "callAsyncMultipleAsyncError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncErrorCalled1": true, - "callAsyncMultipleAsyncLateError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncLateErrorCalled1": true, - "callAsyncMultipleAsyncLateErrorEarlyResult1": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncLateErrorEarlyResult1Called1": true, - "callAsyncMultipleAsyncLateErrorEarlyResult2": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultipleAsyncLateErrorEarlyResult2Called1": true, - "callAsyncMultipleAsyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgCalled1": 42, - "callAsyncMultipleAsyncWithArgCalled2": 42, - "callAsyncMultipleAsyncWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgFirstReturnCalled2": 42, - "callAsyncMultipleAsyncWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleAsyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleAsyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleMixed1WithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleMixed1WithArgCalled1": 42, - "callAsyncMultipleMixed1WithArgCalled2": 42, - "callAsyncMultipleMixed1WithArgCalled3": 42, - "callAsyncMultipleMixed2WithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleMixed2WithArgCalled1": 42, - "callAsyncMultipleMixed2WithArgCalled2": 42, - "callAsyncMultipleMixed3WithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleMixed3WithArgCalled1": 42, - "callAsyncMultipleMixed3WithArgCalled2": 42, - "callAsyncMultipleMixed3WithArgCalled3": 42, - "callAsyncMultipleMixedError1WithArg": { - "error": "Error in sync", - "type": "async", - }, - "callAsyncMultipleMixedError1WithArgCalled1": 42, - "callAsyncMultipleMixedError1WithArgCalled2": 42, - "callAsyncMultipleMixedError1WithArgCalled3": 42, - "callAsyncMultipleMixedError2WithArg": { - "error": "Error in promise", - "type": "async", - }, - "callAsyncMultipleMixedError2WithArgCalled1": 42, - "callAsyncMultipleMixedError2WithArgCalled2": 42, - "callAsyncMultipleMixedError3WithArg": { - "error": "Error in async", - "type": "async", - }, - "callAsyncMultipleMixedError3WithArgCalled1": 42, - "callAsyncMultipleMixedLateError": { - "error": "Error in async", - "type": "async", - }, - "callAsyncMultipleMixedLateErrorCalled1": true, - "callAsyncMultiplePromiseEarlyError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseEarlyErrorCalled1": true, - "callAsyncMultiplePromiseError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseErrorCalled1": true, - "callAsyncMultiplePromiseLateError": { - "error": "Error in async2", - "type": "async", - }, - "callAsyncMultiplePromiseLateErrorCalled1": true, - "callAsyncMultiplePromiseWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgCalled1": 42, - "callAsyncMultiplePromiseWithArgCalled2": 42, - "callAsyncMultiplePromiseWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgFirstReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgFirstReturnCalled2": 42, - "callAsyncMultiplePromiseWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgLastReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgLastReturnCalled2": 42, - "callAsyncMultiplePromiseWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultiplePromiseWithArgNoReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgNoReturnCalled2": 42, - "callAsyncMultipleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncCalled1": true, - "callAsyncMultipleSyncCalled2": true, - "callAsyncMultipleSyncError": { - "error": "Error in sync2", - "type": "async", - }, - "callAsyncMultipleSyncErrorCalled1": true, - "callAsyncMultipleSyncLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncLastReturnCalled1": true, - "callAsyncMultipleSyncLastReturnCalled2": true, - "callAsyncMultipleSyncNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncNoReturnCalled1": true, - "callAsyncMultipleSyncNoReturnCalled2": true, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgCalled2": 42, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturnCalled2": 42, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncNone": { - "type": "async", - "value": undefined, - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleAsyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleAsyncWithArgCalled1": 42, - "callAsyncSinglePromiseWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSinglePromiseWithArgCalled1": 42, - "callAsyncSingleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncCalled1": true, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncWithArgCalled1": 42, - "callAsyncSingleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleAsyncEarlyError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncEarlyErrorCalled1": true, - "promiseMultipleAsyncError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncErrorCalled1": true, - "promiseMultipleAsyncLateError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncLateErrorCalled1": true, - "promiseMultipleAsyncLateErrorEarlyResult1": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncLateErrorEarlyResult1Called1": true, - "promiseMultipleAsyncLateErrorEarlyResult2": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultipleAsyncLateErrorEarlyResult2Called1": true, - "promiseMultipleAsyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgCalled1": 42, - "promiseMultipleAsyncWithArgCalled2": 42, - "promiseMultipleAsyncWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgFirstReturnCalled1": 42, - "promiseMultipleAsyncWithArgFirstReturnCalled2": 42, - "promiseMultipleAsyncWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgLastReturnCalled1": 42, - "promiseMultipleAsyncWithArgLastReturnCalled2": 42, - "promiseMultipleAsyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleAsyncWithArgNoReturnCalled1": 42, - "promiseMultipleAsyncWithArgNoReturnCalled2": 42, - "promiseMultipleMixed1WithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleMixed1WithArgCalled1": 42, - "promiseMultipleMixed1WithArgCalled2": 42, - "promiseMultipleMixed1WithArgCalled3": 42, - "promiseMultipleMixed2WithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleMixed2WithArgCalled1": 42, - "promiseMultipleMixed2WithArgCalled2": 42, - "promiseMultipleMixed3WithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleMixed3WithArgCalled1": 42, - "promiseMultipleMixed3WithArgCalled2": 42, - "promiseMultipleMixed3WithArgCalled3": 42, - "promiseMultipleMixedError1WithArg": { - "error": "Error in sync", - "type": "promise", - }, - "promiseMultipleMixedError1WithArgCalled1": 42, - "promiseMultipleMixedError1WithArgCalled2": 42, - "promiseMultipleMixedError1WithArgCalled3": 42, - "promiseMultipleMixedError2WithArg": { - "error": "Error in promise", - "type": "promise", - }, - "promiseMultipleMixedError2WithArgCalled1": 42, - "promiseMultipleMixedError2WithArgCalled2": 42, - "promiseMultipleMixedError3WithArg": { - "error": "Error in async", - "type": "promise", - }, - "promiseMultipleMixedError3WithArgCalled1": 42, - "promiseMultipleMixedLateError": { - "error": "Error in async", - "type": "promise", - }, - "promiseMultipleMixedLateErrorCalled1": true, - "promiseMultiplePromiseEarlyError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseEarlyErrorCalled1": true, - "promiseMultiplePromiseError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseErrorCalled1": true, - "promiseMultiplePromiseLateError": { - "error": "Error in async2", - "type": "promise", - }, - "promiseMultiplePromiseLateErrorCalled1": true, - "promiseMultiplePromiseWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgCalled1": 42, - "promiseMultiplePromiseWithArgCalled2": 42, - "promiseMultiplePromiseWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgFirstReturnCalled1": 42, - "promiseMultiplePromiseWithArgFirstReturnCalled2": 42, - "promiseMultiplePromiseWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgLastReturnCalled1": 42, - "promiseMultiplePromiseWithArgLastReturnCalled2": 42, - "promiseMultiplePromiseWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultiplePromiseWithArgNoReturnCalled1": 42, - "promiseMultiplePromiseWithArgNoReturnCalled2": 42, - "promiseMultipleSync": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncCalled1": true, - "promiseMultipleSyncCalled2": true, - "promiseMultipleSyncError": { - "error": "Error in sync2", - "type": "promise", - }, - "promiseMultipleSyncErrorCalled1": true, - "promiseMultipleSyncLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncLastReturnCalled1": true, - "promiseMultipleSyncLastReturnCalled2": true, - "promiseMultipleSyncNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncNoReturnCalled1": true, - "promiseMultipleSyncNoReturnCalled2": true, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgCalled2": 42, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgFirstReturnCalled2": 42, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseNone": { - "type": "promise", - "value": undefined, - }, - "promiseNoneWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleAsyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleAsyncWithArgCalled1": 42, - "promiseSinglePromiseWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSinglePromiseWithArgCalled1": 42, - "promiseSingleSync": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncCalled1": true, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncWithArgCalled1": 42, - "promiseSingleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncWithArgNoReturnCalled1": 42, - }, - "intercept": { - "callAsyncIntercepted": { - "type": "async", - "value": undefined, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedDone1": true, - "callAsyncInterceptedDone2": true, - "callAsyncInterceptedTap1": { - "fn": 2, - "name": "promise", - "type": "promise", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - "promiseIntercepted": { - "type": "promise", - "value": undefined, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedDone1": true, - "promiseInterceptedDone2": true, - "promiseInterceptedTap1": { - "fn": 2, - "name": "promise", - "type": "promise", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - }, - "sync": { - "callAsyncIntercepted": { - "type": "async", - "value": undefined, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncMultipleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncCalled1": true, - "callAsyncMultipleSyncCalled2": true, - "callAsyncMultipleSyncError": { - "error": "Error in sync2", - "type": "async", - }, - "callAsyncMultipleSyncErrorCalled1": true, - "callAsyncMultipleSyncErrorCalled2": true, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgCalled2": 42, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturnCalled2": 42, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleSyncWithArgs": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callAsyncMultipleSyncWithArgsCalled2": [ - 42, - 43, - 44, - ], - "callAsyncNone": { - "type": "async", - "value": undefined, - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncCalled": true, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncWithArgCalled": 42, - "promiseIntercepted": { - "type": "promise", - "value": undefined, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseMultipleSync": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncCalled1": true, - "promiseMultipleSyncCalled2": true, - "promiseMultipleSyncError": { - "error": "Error in sync2", - "type": "promise", - }, - "promiseMultipleSyncErrorCalled1": true, - "promiseMultipleSyncErrorCalled2": true, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgCalled2": 42, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgFirstReturnCalled2": 42, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseMultipleSyncWithArgs": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "promiseMultipleSyncWithArgsCalled2": [ - 42, - 43, - 44, - ], - "promiseNone": { - "type": "promise", - "value": undefined, - }, - "promiseNoneWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSync": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncCalled": true, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncWithArgCalled": 42, - }, -} -`; - -exports[`AsyncSeriesWaterfallHook should have to correct behavior 1`] = ` -{ - "async": { - "callAsyncMultipleAsyncEarlyError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleAsyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleAsyncLateError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleAsyncLateErrorEarlyResult1": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleAsyncLateErrorEarlyResult2": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleAsyncWithArg": { - "type": "async", - "value": 45, - }, - "callAsyncMultipleAsyncWithArgCalled1": 42, - "callAsyncMultipleAsyncWithArgCalled2": 43, - "callAsyncMultipleAsyncWithArgFirstReturn": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleAsyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgFirstReturnCalled2": 43, - "callAsyncMultipleAsyncWithArgLastReturn": { - "type": "async", - "value": 44, - }, - "callAsyncMultipleAsyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleAsyncWithArgNoReturn": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleAsyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleAsyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleMixed1WithArg": { - "type": "async", - "value": 48, - }, - "callAsyncMultipleMixed1WithArgCalled1": 42, - "callAsyncMultipleMixed1WithArgCalled2": 43, - "callAsyncMultipleMixed1WithArgCalled3": 45, - "callAsyncMultipleMixed2WithArg": { - "type": "async", - "value": 45, - }, - "callAsyncMultipleMixed2WithArgCalled1": 42, - "callAsyncMultipleMixed2WithArgCalled2": 43, - "callAsyncMultipleMixed3WithArg": { - "type": "async", - "value": 48, - }, - "callAsyncMultipleMixed3WithArgCalled1": 42, - "callAsyncMultipleMixed3WithArgCalled2": 43, - "callAsyncMultipleMixed3WithArgCalled3": 45, - "callAsyncMultipleMixedError1WithArg": { - "error": "Error in sync", - "type": "async", - }, - "callAsyncMultipleMixedError1WithArgCalled1": 42, - "callAsyncMultipleMixedError1WithArgCalled2": 42, - "callAsyncMultipleMixedError1WithArgCalled3": 43, - "callAsyncMultipleMixedError2WithArg": { - "error": "Error in promise", - "type": "async", - }, - "callAsyncMultipleMixedError2WithArgCalled1": 42, - "callAsyncMultipleMixedError2WithArgCalled2": 42, - "callAsyncMultipleMixedError3WithArg": { - "error": "Error in async", - "type": "async", - }, - "callAsyncMultipleMixedError3WithArgCalled1": 42, - "callAsyncMultipleMixedLateError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultiplePromiseEarlyError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultiplePromiseError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultiplePromiseLateError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultiplePromiseWithArg": { - "type": "async", - "value": 45, - }, - "callAsyncMultiplePromiseWithArgCalled1": 42, - "callAsyncMultiplePromiseWithArgCalled2": 43, - "callAsyncMultiplePromiseWithArgFirstReturn": { - "type": "async", - "value": 43, - }, - "callAsyncMultiplePromiseWithArgFirstReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgFirstReturnCalled2": 43, - "callAsyncMultiplePromiseWithArgLastReturn": { - "type": "async", - "value": 44, - }, - "callAsyncMultiplePromiseWithArgLastReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgLastReturnCalled2": 42, - "callAsyncMultiplePromiseWithArgNoReturn": { - "type": "async", - "value": 42, - }, - "callAsyncMultiplePromiseWithArgNoReturnCalled1": 42, - "callAsyncMultiplePromiseWithArgNoReturnCalled2": 42, - "callAsyncMultipleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleSyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleSyncLastReturn": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleSyncNoReturn": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": 45, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgCalled2": 43, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": 43, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturnCalled2": 43, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": 44, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncNone": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleAsyncWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleAsyncWithArgCalled1": 42, - "callAsyncSinglePromiseWithArg": { - "type": "async", - "value": 43, - }, - "callAsyncSinglePromiseWithArgCalled1": 42, - "callAsyncSingleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": 43, - }, - "callAsyncSingleSyncWithArgCalled1": 42, - "callAsyncSingleSyncWithArgNoReturn": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleAsyncEarlyError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleAsyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleAsyncLateError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleAsyncLateErrorEarlyResult1": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleAsyncLateErrorEarlyResult2": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleAsyncWithArg": { - "type": "promise", - "value": 45, - }, - "promiseMultipleAsyncWithArgCalled1": 42, - "promiseMultipleAsyncWithArgCalled2": 43, - "promiseMultipleAsyncWithArgFirstReturn": { - "type": "promise", - "value": 43, - }, - "promiseMultipleAsyncWithArgFirstReturnCalled1": 42, - "promiseMultipleAsyncWithArgFirstReturnCalled2": 43, - "promiseMultipleAsyncWithArgLastReturn": { - "type": "promise", - "value": 44, - }, - "promiseMultipleAsyncWithArgLastReturnCalled1": 42, - "promiseMultipleAsyncWithArgLastReturnCalled2": 42, - "promiseMultipleAsyncWithArgNoReturn": { - "type": "promise", - "value": 42, - }, - "promiseMultipleAsyncWithArgNoReturnCalled1": 42, - "promiseMultipleAsyncWithArgNoReturnCalled2": 42, - "promiseMultipleMixed1WithArg": { - "type": "promise", - "value": 48, - }, - "promiseMultipleMixed1WithArgCalled1": 42, - "promiseMultipleMixed1WithArgCalled2": 43, - "promiseMultipleMixed1WithArgCalled3": 45, - "promiseMultipleMixed2WithArg": { - "type": "promise", - "value": 45, - }, - "promiseMultipleMixed2WithArgCalled1": 42, - "promiseMultipleMixed2WithArgCalled2": 43, - "promiseMultipleMixed3WithArg": { - "type": "promise", - "value": 48, - }, - "promiseMultipleMixed3WithArgCalled1": 42, - "promiseMultipleMixed3WithArgCalled2": 43, - "promiseMultipleMixed3WithArgCalled3": 45, - "promiseMultipleMixedError1WithArg": { - "error": "Error in sync", - "type": "promise", - }, - "promiseMultipleMixedError1WithArgCalled1": 42, - "promiseMultipleMixedError1WithArgCalled2": 42, - "promiseMultipleMixedError1WithArgCalled3": 43, - "promiseMultipleMixedError2WithArg": { - "error": "Error in promise", - "type": "promise", - }, - "promiseMultipleMixedError2WithArgCalled1": 42, - "promiseMultipleMixedError2WithArgCalled2": 42, - "promiseMultipleMixedError3WithArg": { - "error": "Error in async", - "type": "promise", - }, - "promiseMultipleMixedError3WithArgCalled1": 42, - "promiseMultipleMixedLateError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultiplePromiseEarlyError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultiplePromiseError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultiplePromiseLateError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultiplePromiseWithArg": { - "type": "promise", - "value": 45, - }, - "promiseMultiplePromiseWithArgCalled1": 42, - "promiseMultiplePromiseWithArgCalled2": 43, - "promiseMultiplePromiseWithArgFirstReturn": { - "type": "promise", - "value": 43, - }, - "promiseMultiplePromiseWithArgFirstReturnCalled1": 42, - "promiseMultiplePromiseWithArgFirstReturnCalled2": 43, - "promiseMultiplePromiseWithArgLastReturn": { - "type": "promise", - "value": 44, - }, - "promiseMultiplePromiseWithArgLastReturnCalled1": 42, - "promiseMultiplePromiseWithArgLastReturnCalled2": 42, - "promiseMultiplePromiseWithArgNoReturn": { - "type": "promise", - "value": 42, - }, - "promiseMultiplePromiseWithArgNoReturnCalled1": 42, - "promiseMultiplePromiseWithArgNoReturnCalled2": 42, - "promiseMultipleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleSyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleSyncLastReturn": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleSyncNoReturn": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": 45, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgCalled2": 43, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": 43, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgFirstReturnCalled2": 43, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": 44, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": 42, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseNone": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseNoneWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleAsyncWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleAsyncWithArgCalled1": 42, - "promiseSinglePromiseWithArg": { - "type": "promise", - "value": 43, - }, - "promiseSinglePromiseWithArgCalled1": 42, - "promiseSingleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": 43, - }, - "promiseSingleSyncWithArgCalled1": 42, - "promiseSingleSyncWithArgNoReturn": { - "type": "promise", - "value": 42, - }, - "promiseSingleSyncWithArgNoReturnCalled1": 42, - }, - "intercept": { - "callAsyncIntercepted": { - "type": "async", - "value": 9, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedResult1": 9, - "callAsyncInterceptedResult2": 9, - "callAsyncInterceptedTap1": { - "fn": 2, - "name": "promise", - "type": "promise", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - "promiseIntercepted": { - "type": "promise", - "value": 9, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedResult1": 9, - "promiseInterceptedResult2": 9, - "promiseInterceptedTap1": { - "fn": 2, - "name": "promise", - "type": "promise", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync", - "type": "sync", - }, - }, - "sync": { - "callAsyncIntercepted": { - "type": "async", - "value": 9, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncMultipleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleSyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": 127, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgCalled2": 84, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": 84, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturnCalled2": 84, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": 85, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleSyncWithArgs": { - "type": "async", - "value": 217, - }, - "callAsyncMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callAsyncMultipleSyncWithArgsCalled2": [ - 129, - 43, - 44, - ], - "callAsyncNone": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSyncWithArgCalled": 42, - "promiseIntercepted": { - "type": "promise", - "value": 9, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseMultipleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleSyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": 127, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgCalled2": 84, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": 84, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgFirstReturnCalled2": 84, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": 85, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": 42, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseMultipleSyncWithArgs": { - "type": "promise", - "value": 217, - }, - "promiseMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "promiseMultipleSyncWithArgsCalled2": [ - 129, - 43, - 44, - ], - "promiseNone": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseNoneWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleSyncWithArgCalled": 42, - }, -} -`; diff --git a/packages/rspack-lite-tapable/tests/__snapshots__/SyncHooks.test.js.snap b/packages/rspack-lite-tapable/tests/__snapshots__/SyncHooks.test.js.snap deleted file mode 100644 index 085b8c1aa030..000000000000 --- a/packages/rspack-lite-tapable/tests/__snapshots__/SyncHooks.test.js.snap +++ /dev/null @@ -1,789 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`SyncBailHook should have to correct behavior 1`] = ` -{ - "async": {}, - "intercept": {}, - "sync": { - "callAsyncIntercepted": { - "type": "async", - "value": 6, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedTap1": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncMultipleSync": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleSyncCalled1": true, - "callAsyncMultipleSyncError": { - "error": "Error in sync2", - "type": "async", - }, - "callAsyncMultipleSyncErrorCalled1": true, - "callAsyncMultipleSyncErrorCalled2": true, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": 84, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": 84, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": 85, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleSyncWithArgs": { - "type": "async", - "value": 129, - }, - "callAsyncMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callAsyncNone": { - "type": "async", - "value": undefined, - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSync": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSyncCalled": true, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSyncWithArgCalled": 42, - "callIntercepted": { - "type": "return", - "value": 6, - }, - "callInterceptedCall1": [ - 1, - 2, - 3, - ], - "callInterceptedCall2": [ - 1, - 2, - 3, - ], - "callInterceptedTap1": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callMultipleSync": { - "type": "return", - "value": 42, - }, - "callMultipleSyncCalled1": true, - "callMultipleSyncError": { - "error": "Error in sync2", - }, - "callMultipleSyncErrorCalled1": true, - "callMultipleSyncErrorCalled2": true, - "callMultipleSyncWithArg": { - "type": "return", - "value": 84, - }, - "callMultipleSyncWithArgCalled1": 42, - "callMultipleSyncWithArgFirstReturn": { - "type": "return", - "value": 84, - }, - "callMultipleSyncWithArgFirstReturnCalled1": 42, - "callMultipleSyncWithArgLastReturn": { - "type": "return", - "value": 85, - }, - "callMultipleSyncWithArgLastReturnCalled1": 42, - "callMultipleSyncWithArgLastReturnCalled2": 42, - "callMultipleSyncWithArgNoReturn": { - "type": "no result", - }, - "callMultipleSyncWithArgNoReturnCalled1": 42, - "callMultipleSyncWithArgNoReturnCalled2": 42, - "callMultipleSyncWithArgs": { - "type": "return", - "value": 129, - }, - "callMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callNone": { - "type": "no result", - }, - "callNoneWithArg": { - "type": "no result", - }, - "callSingleSync": { - "type": "return", - "value": 42, - }, - "callSingleSyncCalled": true, - "callSingleSyncWithArg": { - "type": "return", - "value": 42, - }, - "callSingleSyncWithArgCalled": 42, - "promiseIntercepted": { - "type": "promise", - "value": 6, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedTap1": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseMultipleSync": { - "type": "promise", - "value": 42, - }, - "promiseMultipleSyncCalled1": true, - "promiseMultipleSyncError": { - "error": "Error in sync2", - "type": "promise", - }, - "promiseMultipleSyncErrorCalled1": true, - "promiseMultipleSyncErrorCalled2": true, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": 84, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": 84, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": 85, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseMultipleSyncWithArgs": { - "type": "promise", - "value": 129, - }, - "promiseMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "promiseNone": { - "type": "promise", - "value": undefined, - }, - "promiseNoneWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSync": { - "type": "promise", - "value": 42, - }, - "promiseSingleSyncCalled": true, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleSyncWithArgCalled": 42, - }, -} -`; - -exports[`SyncHook should have to correct behavior 1`] = ` -{ - "async": {}, - "intercept": {}, - "sync": { - "callAsyncIntercepted": { - "type": "async", - "value": undefined, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncMultipleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncCalled1": true, - "callAsyncMultipleSyncCalled2": true, - "callAsyncMultipleSyncError": { - "error": "Error in sync2", - "type": "async", - }, - "callAsyncMultipleSyncErrorCalled1": true, - "callAsyncMultipleSyncErrorCalled2": true, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgCalled2": 42, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturnCalled2": 42, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleSyncWithArgs": { - "type": "async", - "value": undefined, - }, - "callAsyncMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callAsyncMultipleSyncWithArgsCalled2": [ - 42, - 43, - 44, - ], - "callAsyncNone": { - "type": "async", - "value": undefined, - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSync": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncCalled": true, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": undefined, - }, - "callAsyncSingleSyncWithArgCalled": 42, - "callIntercepted": { - "type": "no result", - }, - "callInterceptedCall1": [ - 1, - 2, - 3, - ], - "callInterceptedCall2": [ - 1, - 2, - 3, - ], - "callInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "callInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callMultipleSync": { - "type": "no result", - }, - "callMultipleSyncCalled1": true, - "callMultipleSyncCalled2": true, - "callMultipleSyncError": { - "error": "Error in sync2", - }, - "callMultipleSyncErrorCalled1": true, - "callMultipleSyncErrorCalled2": true, - "callMultipleSyncWithArg": { - "type": "no result", - }, - "callMultipleSyncWithArgCalled1": 42, - "callMultipleSyncWithArgCalled2": 42, - "callMultipleSyncWithArgFirstReturn": { - "type": "no result", - }, - "callMultipleSyncWithArgFirstReturnCalled1": 42, - "callMultipleSyncWithArgFirstReturnCalled2": 42, - "callMultipleSyncWithArgLastReturn": { - "type": "no result", - }, - "callMultipleSyncWithArgLastReturnCalled1": 42, - "callMultipleSyncWithArgLastReturnCalled2": 42, - "callMultipleSyncWithArgNoReturn": { - "type": "no result", - }, - "callMultipleSyncWithArgNoReturnCalled1": 42, - "callMultipleSyncWithArgNoReturnCalled2": 42, - "callMultipleSyncWithArgs": { - "type": "no result", - }, - "callMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callMultipleSyncWithArgsCalled2": [ - 42, - 43, - 44, - ], - "callNone": { - "type": "no result", - }, - "callNoneWithArg": { - "type": "no result", - }, - "callSingleSync": { - "type": "no result", - }, - "callSingleSyncCalled": true, - "callSingleSyncWithArg": { - "type": "no result", - }, - "callSingleSyncWithArgCalled": 42, - "promiseIntercepted": { - "type": "promise", - "value": undefined, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseMultipleSync": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncCalled1": true, - "promiseMultipleSyncCalled2": true, - "promiseMultipleSyncError": { - "error": "Error in sync2", - "type": "promise", - }, - "promiseMultipleSyncErrorCalled1": true, - "promiseMultipleSyncErrorCalled2": true, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgCalled2": 42, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgFirstReturnCalled2": 42, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseMultipleSyncWithArgs": { - "type": "promise", - "value": undefined, - }, - "promiseMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "promiseMultipleSyncWithArgsCalled2": [ - 42, - 43, - 44, - ], - "promiseNone": { - "type": "promise", - "value": undefined, - }, - "promiseNoneWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSync": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncCalled": true, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": undefined, - }, - "promiseSingleSyncWithArgCalled": 42, - }, -} -`; - -exports[`SyncWaterfallHook should have to correct behavior 1`] = ` -{ - "async": {}, - "intercept": {}, - "sync": { - "callAsyncIntercepted": { - "type": "async", - "value": 9, - }, - "callAsyncInterceptedCall1": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedCall2": [ - 1, - 2, - 3, - ], - "callAsyncInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "callAsyncInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callAsyncMultipleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleSyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncMultipleSyncWithArg": { - "type": "async", - "value": 127, - }, - "callAsyncMultipleSyncWithArgCalled1": 42, - "callAsyncMultipleSyncWithArgCalled2": 84, - "callAsyncMultipleSyncWithArgFirstReturn": { - "type": "async", - "value": 84, - }, - "callAsyncMultipleSyncWithArgFirstReturnCalled1": 42, - "callAsyncMultipleSyncWithArgFirstReturnCalled2": 84, - "callAsyncMultipleSyncWithArgLastReturn": { - "type": "async", - "value": 85, - }, - "callAsyncMultipleSyncWithArgLastReturnCalled1": 42, - "callAsyncMultipleSyncWithArgLastReturnCalled2": 42, - "callAsyncMultipleSyncWithArgNoReturn": { - "type": "async", - "value": 42, - }, - "callAsyncMultipleSyncWithArgNoReturnCalled1": 42, - "callAsyncMultipleSyncWithArgNoReturnCalled2": 42, - "callAsyncMultipleSyncWithArgs": { - "type": "async", - "value": 217, - }, - "callAsyncMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callAsyncMultipleSyncWithArgsCalled2": [ - 129, - 43, - 44, - ], - "callAsyncNone": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncNoneWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "callAsyncSingleSyncWithArg": { - "type": "async", - "value": 42, - }, - "callAsyncSingleSyncWithArgCalled": 42, - "callIntercepted": { - "type": "return", - "value": 9, - }, - "callInterceptedCall1": [ - 1, - 2, - 3, - ], - "callInterceptedCall2": [ - 1, - 2, - 3, - ], - "callInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "callInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "callMultipleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "callMultipleSyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "callMultipleSyncWithArg": { - "type": "return", - "value": 127, - }, - "callMultipleSyncWithArgCalled1": 42, - "callMultipleSyncWithArgCalled2": 84, - "callMultipleSyncWithArgFirstReturn": { - "type": "return", - "value": 84, - }, - "callMultipleSyncWithArgFirstReturnCalled1": 42, - "callMultipleSyncWithArgFirstReturnCalled2": 84, - "callMultipleSyncWithArgLastReturn": { - "type": "return", - "value": 85, - }, - "callMultipleSyncWithArgLastReturnCalled1": 42, - "callMultipleSyncWithArgLastReturnCalled2": 42, - "callMultipleSyncWithArgNoReturn": { - "type": "return", - "value": 42, - }, - "callMultipleSyncWithArgNoReturnCalled1": 42, - "callMultipleSyncWithArgNoReturnCalled2": 42, - "callMultipleSyncWithArgs": { - "type": "return", - "value": 217, - }, - "callMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "callMultipleSyncWithArgsCalled2": [ - 129, - 43, - 44, - ], - "callNone": { - "error": "Waterfall hooks must have at least one argument", - }, - "callNoneWithArg": { - "type": "return", - "value": 42, - }, - "callSingleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "callSingleSyncWithArg": { - "type": "return", - "value": 42, - }, - "callSingleSyncWithArgCalled": 42, - "promiseIntercepted": { - "type": "promise", - "value": 9, - }, - "promiseInterceptedCall1": [ - 1, - 2, - 3, - ], - "promiseInterceptedCall2": [ - 1, - 2, - 3, - ], - "promiseInterceptedTap1": { - "fn": 2, - "name": "sync2", - "type": "sync", - }, - "promiseInterceptedTap2": { - "fn": 3, - "name": "sync1", - "type": "sync", - }, - "promiseMultipleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleSyncError": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseMultipleSyncWithArg": { - "type": "promise", - "value": 127, - }, - "promiseMultipleSyncWithArgCalled1": 42, - "promiseMultipleSyncWithArgCalled2": 84, - "promiseMultipleSyncWithArgFirstReturn": { - "type": "promise", - "value": 84, - }, - "promiseMultipleSyncWithArgFirstReturnCalled1": 42, - "promiseMultipleSyncWithArgFirstReturnCalled2": 84, - "promiseMultipleSyncWithArgLastReturn": { - "type": "promise", - "value": 85, - }, - "promiseMultipleSyncWithArgLastReturnCalled1": 42, - "promiseMultipleSyncWithArgLastReturnCalled2": 42, - "promiseMultipleSyncWithArgNoReturn": { - "type": "promise", - "value": 42, - }, - "promiseMultipleSyncWithArgNoReturnCalled1": 42, - "promiseMultipleSyncWithArgNoReturnCalled2": 42, - "promiseMultipleSyncWithArgs": { - "type": "promise", - "value": 217, - }, - "promiseMultipleSyncWithArgsCalled1": [ - 42, - 43, - 44, - ], - "promiseMultipleSyncWithArgsCalled2": [ - 129, - 43, - 44, - ], - "promiseNone": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseNoneWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleSync": { - "error": "Waterfall hooks must have at least one argument", - }, - "promiseSingleSyncWithArg": { - "type": "promise", - "value": 42, - }, - "promiseSingleSyncWithArgCalled": 42, - }, -} -`; diff --git a/packages/rspack-lite-tapable/tsconfig.build.json b/packages/rspack-lite-tapable/tsconfig.build.json deleted file mode 100644 index 04066aad27dc..000000000000 --- a/packages/rspack-lite-tapable/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "sourceMap": false, - "declarationMap": false, - } -} diff --git a/packages/rspack-lite-tapable/tsconfig.json b/packages/rspack-lite-tapable/tsconfig.json deleted file mode 100644 index dc248090cdf6..000000000000 --- a/packages/rspack-lite-tapable/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "dist", - "rootDir": "src" - }, - "include": ["src"], - "ts-node": { - "transpileOnly": true - } -} diff --git a/packages/rspack-plugin-preact-refresh/CHANGELOG.md b/packages/rspack-plugin-preact-refresh/CHANGELOG.md deleted file mode 100644 index f2c1f404aa66..000000000000 --- a/packages/rspack-plugin-preact-refresh/CHANGELOG.md +++ /dev/null @@ -1 +0,0 @@ -# @rspack/plugin-preact-refresh diff --git a/packages/rspack-plugin-preact-refresh/LICENSE b/packages/rspack-plugin-preact-refresh/LICENSE deleted file mode 100644 index 46310101ad8a..000000000000 --- a/packages/rspack-plugin-preact-refresh/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2022-present Bytedance, Inc. and its affiliates. - - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/packages/rspack-plugin-preact-refresh/README.md b/packages/rspack-plugin-preact-refresh/README.md deleted file mode 100644 index 9b6c91e43345..000000000000 --- a/packages/rspack-plugin-preact-refresh/README.md +++ /dev/null @@ -1,16 +0,0 @@ - - - Rspack Banner - - -# @rspack/plugin-preact-refresh - -Preact refresh plugin for rspack. - -## Documentation - -See [https://rspack.dev](https://rspack.dev) for details. - -## License - -Rspack is [MIT licensed](https://github.com/web-infra-dev/rspack/blob/main/LICENSE). diff --git a/packages/rspack-plugin-preact-refresh/api-extractor.json b/packages/rspack-plugin-preact-refresh/api-extractor.json deleted file mode 100644 index 1e0238cd9f0a..000000000000 --- a/packages/rspack-plugin-preact-refresh/api-extractor.json +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Config file for API Extractor. For more info, please visit: https://api-extractor.com - */ -{ - "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", - "extends": "../../api-extractor.json" -} diff --git a/packages/rspack-plugin-preact-refresh/client/intercept.cjs b/packages/rspack-plugin-preact-refresh/client/intercept.cjs deleted file mode 100644 index 3a6caf52f9eb..000000000000 --- a/packages/rspack-plugin-preact-refresh/client/intercept.cjs +++ /dev/null @@ -1,45 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/utils/Runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -__webpack_require__.i.push(function (options) { - var originalFactory = options.factory; - options.factory = function (moduleObject, moduleExports, webpackRequire) { - var prevRefreshReg = self.$RefreshReg$; - var prevRefreshSig = self.$RefreshSig$; - self.$RefreshSig$ = function () { - var status = "begin"; - var savedType; - - return function (type, key, forceReset, getCustomHooks) { - if (!savedType) savedType = type; - status = self.__PREFRESH__.sign( - type || savedType, - key, - forceReset, - getCustomHooks, - status - ); - return type; - }; - }; - var reg = function (currentModuleId) { - self.$RefreshReg$ = function (type, id) { - self.__PREFRESH__.register(type, currentModuleId + " " + id); - }; - }; - reg(); - try { - originalFactory.call(this, moduleObject, moduleExports, webpackRequire); - } finally { - self.$RefreshReg$ = prevRefreshReg; - self.$RefreshSig$ = prevRefreshSig; - } - }; -}); diff --git a/packages/rspack-plugin-preact-refresh/client/prefresh.cjs b/packages/rspack-plugin-preact-refresh/client/prefresh.cjs deleted file mode 100644 index 26f9a0994277..000000000000 --- a/packages/rspack-plugin-preact-refresh/client/prefresh.cjs +++ /dev/null @@ -1,70 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/utils/prefresh.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const { isComponent, flush } = require("@prefresh/utils"); - -// eslint-disable-next-line -const getExports = m => m.exports || m.__proto__.exports; - -function isSafeExport(key) { - return ( - key === "__esModule" || - key === "__N_SSG" || - key === "__N_SSP" || - key === "config" - ); -} - -function registerExports(moduleExports, moduleId) { - self["__PREFRESH__"].register(moduleExports, moduleId + " %exports%"); - if (moduleExports == null || typeof moduleExports !== "object") return; - - for (const key in moduleExports) { - if (isSafeExport(key)) continue; - const exportValue = moduleExports[key]; - const typeID = moduleId + " %exports% " + key; - self["__PREFRESH__"].register(exportValue, typeID); - } -} - -const shouldBind = m => { - let isCitizen = false; - const moduleExports = getExports(m); - - if (isComponent(moduleExports)) { - isCitizen = true; - } - - if ( - moduleExports === undefined || - moduleExports === null || - typeof moduleExports !== "object" - ) { - isCitizen = isCitizen || false; - } else { - for (const key in moduleExports) { - if (key === "__esModule") continue; - - const exportValue = moduleExports[key]; - if (isComponent(exportValue)) { - isCitizen = isCitizen || true; - } - } - } - - return isCitizen; -}; - -module.exports = Object.freeze({ - getExports, - shouldBind, - flush, - registerExports -}); diff --git a/packages/rspack-plugin-preact-refresh/etc/api.md b/packages/rspack-plugin-preact-refresh/etc/api.md deleted file mode 100644 index 6710e5393996..000000000000 --- a/packages/rspack-plugin-preact-refresh/etc/api.md +++ /dev/null @@ -1,17 +0,0 @@ -## API Report File for "@rspack/plugin-preact-refresh" - -> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). - -```ts - -// @public (undocumented) -export interface IPreactRefreshRspackPluginOptions { - // (undocumented) - overlay?: { - module: string; - }; -} - -// (No @packageDocumentation comment for this package) - -``` diff --git a/packages/rspack-plugin-preact-refresh/jest.config.js b/packages/rspack-plugin-preact-refresh/jest.config.js deleted file mode 100644 index ea7b0bcff82a..000000000000 --- a/packages/rspack-plugin-preact-refresh/jest.config.js +++ /dev/null @@ -1,28 +0,0 @@ -const path = require("node:path"); - -const root = path.resolve(__dirname, "../../"); -/** @type {import('jest').Config} */ -const config = { - testEnvironment: "../../scripts/test/patch-node-env.cjs", - setupFilesAfterEnv: ["@rspack/test-tools/setup-expect"], - testTimeout: process.env.CI ? 60000 : 30000, - testMatch: ["/tests/*.test.js"], - moduleNameMapper: { - // Fixed jest-serialize-path not working when non-ascii code contains. - slash: path.join(__dirname, "../../scripts/test/slash.cjs"), - // disable sourcmap remapping for ts file - "source-map-support/register": "identity-obj-proxy" - }, - cache: false, - transformIgnorePatterns: [root], - snapshotFormat: { - escapeString: true, - printBasicPrototype: true - }, - globals: { - updateSnapshot: - process.argv.includes("-u") || process.argv.includes("--updateSnapshot") - } -}; - -module.exports = config; diff --git a/packages/rspack-plugin-preact-refresh/package.json b/packages/rspack-plugin-preact-refresh/package.json deleted file mode 100644 index 36496dd75e50..000000000000 --- a/packages/rspack-plugin-preact-refresh/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "@rspack/plugin-preact-refresh", - "version": "1.0.0-beta.3", - "license": "MIT", - "description": "Preact refresh plugin for rspack", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "exports": { - ".": { - "default": "./dist/index.js" - }, - "./intercept": "./client/reactRefresh.js", - "./prefresh": "./client/prefresh.js", - "./package.json": "./package.json" - }, - "scripts": { - "build": "tsc -b ./tsconfig.build.json", - "dev": "tsc -b -w", - "test": "cross-env RSPACK_HOT_TEST=true jest --colors", - "api-extractor": "api-extractor run --verbose", - "api-extractor:ci": "api-extractor run --verbose || diff temp/api.md etc/api.md" - }, - "files": [ - "client", - "dist" - ], - "publishConfig": { - "access": "public", - "provenance": true - }, - "homepage": "https://rspack.dev", - "bugs": "https://github.com/web-infra-dev/rspack/issues", - "repository": { - "type": "git", - "url": "https://github.com/web-infra-dev/rspack", - "directory": "packages/rspack-plugin-preact-refresh" - }, - "devDependencies": { - "@prefresh/core": "^1.5.0", - "@prefresh/utils": "^1.2.0", - "@rspack/core": "workspace:*", - "@rspack/test-tools": "workspace:*", - "@swc/plugin-prefresh": "^2.0.8", - "@swc/helpers": "0.5.8", - "preact": "^10.15.1", - "typescript": "5.0.2" - }, - "peerDependencies": { - "@prefresh/core": "^1.5.0", - "@prefresh/utils": "^1.2.0" - } -} \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/src/index.ts b/packages/rspack-plugin-preact-refresh/src/index.ts deleted file mode 100644 index 74b51fe6cd44..000000000000 --- a/packages/rspack-plugin-preact-refresh/src/index.ts +++ /dev/null @@ -1,121 +0,0 @@ -import fs from "node:fs"; -import type { Compiler, RspackPluginInstance } from "@rspack/core"; - -export interface IPreactRefreshRspackPluginOptions { - overlay?: { - module: string; - }; -} - -const PREACT_PATHS = [ - "preact", - "preact/compat", - "preact/debug", - "preact/devtools", - "preact/hooks", - "preact/test-utils", - "preact/jsx-runtime", - "preact/jsx-dev-runtime", - "preact/compat/client", - "preact/compat/server", - "preact/compat/jsx-runtime", - "preact/compat/jsx-dev-runtime", - "preact/compat/scheduler", - "preact/package.json", - "preact/compat/package.json", - "preact/debug/package.json", - "preact/devtools/package.json", - "preact/hooks/package.json", - "preact/test-utils/package.json", - "preact/jsx-runtime/package.json" -].reduce( - (obj, i) => { - obj[i] = require.resolve(i); - return obj; - }, - {} as Record -); -const PREFRESH_CORE_PATH = require.resolve("@prefresh/core"); -const PREFRESH_UTILS_PATH = require.resolve("@prefresh/utils"); -const RUNTIME_UTIL_PATH = require.resolve("../client/prefresh.cjs"); -const RUNTIME_INTERCEPT_PATH = require.resolve("../client/intercept.cjs"); - -const INTERNAL_PATHS = [ - ...Object.values(PREACT_PATHS), - PREFRESH_UTILS_PATH, - PREFRESH_CORE_PATH, - RUNTIME_UTIL_PATH, - RUNTIME_INTERCEPT_PATH -]; - -const runtimeSource = fs.readFileSync(RUNTIME_INTERCEPT_PATH, "utf-8"); - -const NAME = "PreactRefreshRspackPlugin"; - -class PreactRefreshRspackPlugin implements RspackPluginInstance { - name = NAME; - - constructor(private options: IPreactRefreshRspackPluginOptions) { - this.options = { - overlay: options?.overlay - }; - } - - apply(compiler: Compiler) { - if ( - process.env.NODE_ENV === "production" || - compiler.options.mode === "production" - ) - return; - - new compiler.webpack.ProvidePlugin({ - __prefresh_utils__: RUNTIME_UTIL_PATH, - ...(this.options.overlay - ? { - __prefresh_errors__: require.resolve(this.options.overlay.module) - } - : {}) - }).apply(compiler); - new compiler.webpack.EntryPlugin(compiler.context, "@prefresh/core", { - name: undefined - }).apply(compiler); - // new compiler.webpack.DefinePlugin({ __refresh_library__ }).apply(compiler); - compiler.options.resolve.alias = { - "@prefresh/core": PREFRESH_CORE_PATH, - "@prefresh/utils": PREFRESH_UTILS_PATH, - ...PREACT_PATHS, - ...compiler.options.resolve.alias - }; - compiler.options.module.rules.unshift({ - include: /\.([jt]sx?)$/, - exclude: { - or: [/node_modules/, ...INTERNAL_PATHS].filter(Boolean) - }, - use: "builtin:preact-refresh-loader" - }); - - compiler.hooks.thisCompilation.tap(NAME, compilation => { - compilation.hooks.runtimeModule.tap(NAME, (runtimeModule, chunk) => { - // rspack does not have addRuntimeModule and runtimeRequirements on js side - if ( - runtimeModule.constructorName === "HotModuleReplacementRuntimeModule" - ) { - if (!runtimeModule.source) { - throw new Error( - "Can not get the original source of HotModuleReplacementRuntimeModule" - ); - } - const originalSource = - runtimeModule.source.source.toString("utf-8") || ""; - runtimeModule.source.source = Buffer.from( - `${originalSource}\n${runtimeSource}`, - "utf-8" - ); - } - }); - }); - } -} - -// @ts-expect-error output module.exports -export = PreactRefreshRspackPlugin; diff --git a/packages/rspack-plugin-preact-refresh/temp/api.md b/packages/rspack-plugin-preact-refresh/temp/api.md deleted file mode 100644 index 6710e5393996..000000000000 --- a/packages/rspack-plugin-preact-refresh/temp/api.md +++ /dev/null @@ -1,17 +0,0 @@ -## API Report File for "@rspack/plugin-preact-refresh" - -> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). - -```ts - -// @public (undocumented) -export interface IPreactRefreshRspackPluginOptions { - // (undocumented) - overlay?: { - module: string; - }; -} - -// (No @packageDocumentation comment for this package) - -``` diff --git a/packages/rspack-plugin-preact-refresh/tests/Hot.test.js b/packages/rspack-plugin-preact-refresh/tests/Hot.test.js deleted file mode 100644 index 9c000f9a6902..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/Hot.test.js +++ /dev/null @@ -1,5 +0,0 @@ -const { describeByWalk, createHotCase } = require("@rspack/test-tools"); - -describeByWalk(__filename, (name, src, dist) => { - createHotCase(name, src, dist, "web"); -}); diff --git a/packages/rspack-plugin-preact-refresh/tests/HotSnapshot.test.js b/packages/rspack-plugin-preact-refresh/tests/HotSnapshot.test.js deleted file mode 100644 index 0758c9cc7a6d..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/HotSnapshot.test.js +++ /dev/null @@ -1,13 +0,0 @@ -const { describeByWalk, createHotStepCase } = require("@rspack/test-tools"); -const path = require("path"); - -describeByWalk( - __filename, - (name, src, dist) => { - createHotStepCase(name, src, dist, "web"); - }, - { - source: path.resolve(__dirname, "./hotCases"), - dist: path.resolve(__dirname, `./js/hot-snapshot`) - } -); diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/__snapshots__/web/0.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/__snapshots__/web/0.snap.txt deleted file mode 100644 index 628eddf1a5be..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/__snapshots__/web/0.snap.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Case useContext#initial: Step 0 - -## Changed Files - - -## Asset Files -- Bundle: bundle.js - -## Manifest - - -## Update \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/__snapshots__/web/1.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/__snapshots__/web/1.snap.txt deleted file mode 100644 index 98336cc49a75..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/__snapshots__/web/1.snap.txt +++ /dev/null @@ -1,174 +0,0 @@ -# Case useContext#initial: Step 1 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 5303 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ../useContext​#initial/app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"../useContext​#initial/app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* harmony import */var preact_compat__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! preact/compat */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/dist/compat.js"); -/* harmony import */var preact_compat__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(preact_compat__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */var preact_hooks__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! preact/hooks */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/hooks/dist/hooks.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -var _s = $RefreshSig$(); - - -var Theme = Object.assign(preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext["9a7f9b58505c7bd5cea11ed614d1c628$Theme1"] || (preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext["9a7f9b58505c7bd5cea11ed614d1c628$Theme1"] = (0,preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext)('blue')), { - __: 'blue' -}); -function Inner() { - _s(); - var theme = (0,preact_hooks__WEBPACK_IMPORTED_MODULE_2__.useContext)(Theme); - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: [ - "after: ", - theme - ] - }, void 0, true, { - fileName: "/tests/hotCases/hook/useContext#initial/app.jsx", - lineNumber: 8, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/hook/useContext#initial/app.jsx", - lineNumber: 8, - columnNumber: 11 - }, this); -} -_s(Inner, "+C1P7ukOg/azcV4AZ819oyezFOE="); -_c = Inner; -function App() { - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Inner, {}, void 0, false, { - fileName: "/tests/hotCases/hook/useContext#initial/app.jsx", - lineNumber: 13, - columnNumber: 5 - }, this); -} -_c1 = App; -var _c, _c1; -$RefreshReg$(_c, "Inner"); -$RefreshReg$(_c1, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/app.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/app.jsx deleted file mode 100644 index dee840eaabfc..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/app.jsx +++ /dev/null @@ -1,33 +0,0 @@ -import { createContext } from 'preact/compat' -import { useContext } from 'preact/hooks' - -const Theme = createContext('light') - -function Inner() { - const theme = useContext(Theme) - return (
before: {theme}
) -} - -export function App() { - return ( - - ) -} - ---- -import { createContext } from 'preact/compat' -import { useContext } from 'preact/hooks' - -const Theme = createContext('blue') - -function Inner() { - const theme = useContext(Theme) - return (
after: {theme}
) -} - -export function App() { - return ( - - ) -} - diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/index.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/index.jsx deleted file mode 100644 index 94b691d781d9..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/index.jsx +++ /dev/null @@ -1,29 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { App } from './app'; -import update from '../../update'; - -const container = document.createElement('div'); -container.id = "root"; -document.body.appendChild(container); -const root = ReactDOM.createRoot(container); -root.render( -
- -
, -); - -it("should keep state", (done) => { - expect(container.querySelector('span').textContent).toBe("before: light"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("after: blue"); - done(); - }), - ) -}); - - -if (module.hot) { - module.hot.accept('./app'); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/rspack.config.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/rspack.config.js deleted file mode 100644 index acb4cfadcd1a..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#initial/rspack.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const ReactRefreshRspackPlugin = require("../../../.."); - -/** @type {import('@rspack/core').Configuration} */ -module.exports = { - context: __dirname, - entry: "./index.jsx", - resolve: { - extensions: ["...", ".ts", ".tsx", ".jsx"], - alias: { - react: "preact/compat", - "react-dom/test-utils": "preact/test-utils", - "react-dom": "preact/compat", // Must be below test-utils - "react/jsx-runtime": "preact/jsx-runtime" - } - }, - module: { - rules: [ - { - test: /\.jsx?$/, - exclude: [/node_modules/], - use: { - loader: "builtin:swc-loader", - options: { - jsc: { - experimental: { - plugins: [ - [ - "@swc/plugin-prefresh", // enable prefresh specific transformation - {} - ] - ] - }, - parser: { - syntax: "ecmascript", - jsx: true - }, - externalHelpers: true, - preserveAllComments: false, - transform: { - react: { - runtime: "automatic", - pragma: "h", - pragmaFrag: "Fragment", - throwIfNamespace: true, - useBuiltins: false, - development: true, - refresh: true // enable react hooks hmr compatiblity - } - } - } - } - }, - type: "javascript/auto" - } - ] - }, - plugins: [new ReactRefreshRspackPlugin()] -}; diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/__snapshots__/web/0.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/__snapshots__/web/0.snap.txt deleted file mode 100644 index 4511e21c69b0..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/__snapshots__/web/0.snap.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Case useContext#keep: Step 0 - -## Changed Files - - -## Asset Files -- Bundle: bundle.js - -## Manifest - - -## Update \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/__snapshots__/web/1.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/__snapshots__/web/1.snap.txt deleted file mode 100644 index 66038622fd71..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/__snapshots__/web/1.snap.txt +++ /dev/null @@ -1,181 +0,0 @@ -# Case useContext#keep: Step 1 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 5609 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ../useContext​#keep/app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"../useContext​#keep/app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* harmony import */var preact_compat__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! preact/compat */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/dist/compat.js"); -/* harmony import */var preact_compat__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(preact_compat__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */var preact_hooks__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! preact/hooks */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/hooks/dist/hooks.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -var _s = $RefreshSig$(); - - -var Theme = Object.assign(preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext["91a36a55649ecf40cb43fd8678b78391$Theme1"] || (preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext["91a36a55649ecf40cb43fd8678b78391$Theme1"] = (0,preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext)('light')), { - __: 'light' -}); -function Inner() { - _s(); - var theme = (0,preact_hooks__WEBPACK_IMPORTED_MODULE_2__.useContext)(Theme); - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: [ - "after: ", - theme - ] - }, void 0, true, { - fileName: "/tests/hotCases/hook/useContext#keep/app.jsx", - lineNumber: 8, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/hook/useContext#keep/app.jsx", - lineNumber: 8, - columnNumber: 11 - }, this); -} -_s(Inner, "+C1P7ukOg/azcV4AZ819oyezFOE="); -_c = Inner; -function App() { - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Theme.Provider, { - value: "dark", - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Inner, {}, void 0, false, { - fileName: "/tests/hotCases/hook/useContext#keep/app.jsx", - lineNumber: 14, - columnNumber: 7 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/hook/useContext#keep/app.jsx", - lineNumber: 13, - columnNumber: 5 - }, this); -} -_c1 = App; -var _c, _c1; -$RefreshReg$(_c, "Inner"); -$RefreshReg$(_c1, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/app.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/app.jsx deleted file mode 100644 index e63129b682fd..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/app.jsx +++ /dev/null @@ -1,37 +0,0 @@ -import { createContext } from 'preact/compat' -import { useContext } from 'preact/hooks' - -const Theme = createContext('light') - -function Inner() { - const theme = useContext(Theme) - return (
before: {theme}
) -} - -export function App() { - return ( - - - - ) -} - ---- -import { createContext } from 'preact/compat' -import { useContext } from 'preact/hooks' - -const Theme = createContext('light') - -function Inner() { - const theme = useContext(Theme) - return (
after: {theme}
) -} - -export function App() { - return ( - - - - ) -} - diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/index.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/index.jsx deleted file mode 100644 index d740c0c655ee..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/index.jsx +++ /dev/null @@ -1,29 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { App } from './app'; -import update from '../../update'; - -const container = document.createElement('div'); -container.id = "root"; -document.body.appendChild(container); -const root = ReactDOM.createRoot(container); -root.render( -
- -
, -); - -it("should keep state", (done) => { - expect(container.querySelector('span').textContent).toBe("before: dark"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("after: dark"); - done(); - }), - ) -}); - - -if (module.hot) { - module.hot.accept('./app'); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/rspack.config.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/rspack.config.js deleted file mode 100644 index acb4cfadcd1a..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#keep/rspack.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const ReactRefreshRspackPlugin = require("../../../.."); - -/** @type {import('@rspack/core').Configuration} */ -module.exports = { - context: __dirname, - entry: "./index.jsx", - resolve: { - extensions: ["...", ".ts", ".tsx", ".jsx"], - alias: { - react: "preact/compat", - "react-dom/test-utils": "preact/test-utils", - "react-dom": "preact/compat", // Must be below test-utils - "react/jsx-runtime": "preact/jsx-runtime" - } - }, - module: { - rules: [ - { - test: /\.jsx?$/, - exclude: [/node_modules/], - use: { - loader: "builtin:swc-loader", - options: { - jsc: { - experimental: { - plugins: [ - [ - "@swc/plugin-prefresh", // enable prefresh specific transformation - {} - ] - ] - }, - parser: { - syntax: "ecmascript", - jsx: true - }, - externalHelpers: true, - preserveAllComments: false, - transform: { - react: { - runtime: "automatic", - pragma: "h", - pragmaFrag: "Fragment", - throwIfNamespace: true, - useBuiltins: false, - development: true, - refresh: true // enable react hooks hmr compatiblity - } - } - } - } - }, - type: "javascript/auto" - } - ] - }, - plugins: [new ReactRefreshRspackPlugin()] -}; diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/__snapshots__/web/0.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/__snapshots__/web/0.snap.txt deleted file mode 100644 index 0e24b3e36cf8..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/__snapshots__/web/0.snap.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Case useContext#provide: Step 0 - -## Changed Files - - -## Asset Files -- Bundle: bundle.js - -## Manifest - - -## Update \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/__snapshots__/web/1.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/__snapshots__/web/1.snap.txt deleted file mode 100644 index b9d4f743134b..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/__snapshots__/web/1.snap.txt +++ /dev/null @@ -1,181 +0,0 @@ -# Case useContext#provide: Step 1 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 5625 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ../useContext​#provide/app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"../useContext​#provide/app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* harmony import */var preact_compat__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! preact/compat */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/dist/compat.js"); -/* harmony import */var preact_compat__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(preact_compat__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */var preact_hooks__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! preact/hooks */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/hooks/dist/hooks.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -var _s = $RefreshSig$(); - - -var Theme = Object.assign(preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext["49e76449f8402aca4293f15c90ad5b2e$Theme1"] || (preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext["49e76449f8402aca4293f15c90ad5b2e$Theme1"] = (0,preact_compat__WEBPACK_IMPORTED_MODULE_1__.createContext)('light')), { - __: 'light' -}); -function Inner() { - _s(); - var theme = (0,preact_hooks__WEBPACK_IMPORTED_MODULE_2__.useContext)(Theme); - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: [ - "after: ", - theme - ] - }, void 0, true, { - fileName: "/tests/hotCases/hook/useContext#provide/app.jsx", - lineNumber: 8, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/hook/useContext#provide/app.jsx", - lineNumber: 8, - columnNumber: 11 - }, this); -} -_s(Inner, "+C1P7ukOg/azcV4AZ819oyezFOE="); -_c = Inner; -function App() { - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Theme.Provider, { - value: "light", - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Inner, {}, void 0, false, { - fileName: "/tests/hotCases/hook/useContext#provide/app.jsx", - lineNumber: 14, - columnNumber: 7 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/hook/useContext#provide/app.jsx", - lineNumber: 13, - columnNumber: 5 - }, this); -} -_c1 = App; -var _c, _c1; -$RefreshReg$(_c, "Inner"); -$RefreshReg$(_c1, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/app.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/app.jsx deleted file mode 100644 index 34c5914b3dbf..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/app.jsx +++ /dev/null @@ -1,37 +0,0 @@ -import { createContext } from 'preact/compat' -import { useContext } from 'preact/hooks' - -const Theme = createContext('light') - -function Inner() { - const theme = useContext(Theme) - return (
before: {theme}
) -} - -export function App() { - return ( - - - - ) -} - ---- -import { createContext } from 'preact/compat' -import { useContext } from 'preact/hooks' - -const Theme = createContext('light') - -function Inner() { - const theme = useContext(Theme) - return (
after: {theme}
) -} - -export function App() { - return ( - - - - ) -} - diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/index.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/index.jsx deleted file mode 100644 index 708e6bee4377..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/index.jsx +++ /dev/null @@ -1,29 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { App } from './app'; -import update from '../../update'; - -const container = document.createElement('div'); -container.id = "root"; -document.body.appendChild(container); -const root = ReactDOM.createRoot(container); -root.render( -
- -
, -); - -it("should keep state", (done) => { - expect(container.querySelector('span').textContent).toBe("before: dark"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("after: light"); - done(); - }), - ) -}); - - -if (module.hot) { - module.hot.accept('./app'); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/rspack.config.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/rspack.config.js deleted file mode 100644 index acb4cfadcd1a..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useContext#provide/rspack.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const ReactRefreshRspackPlugin = require("../../../.."); - -/** @type {import('@rspack/core').Configuration} */ -module.exports = { - context: __dirname, - entry: "./index.jsx", - resolve: { - extensions: ["...", ".ts", ".tsx", ".jsx"], - alias: { - react: "preact/compat", - "react-dom/test-utils": "preact/test-utils", - "react-dom": "preact/compat", // Must be below test-utils - "react/jsx-runtime": "preact/jsx-runtime" - } - }, - module: { - rules: [ - { - test: /\.jsx?$/, - exclude: [/node_modules/], - use: { - loader: "builtin:swc-loader", - options: { - jsc: { - experimental: { - plugins: [ - [ - "@swc/plugin-prefresh", // enable prefresh specific transformation - {} - ] - ] - }, - parser: { - syntax: "ecmascript", - jsx: true - }, - externalHelpers: true, - preserveAllComments: false, - transform: { - react: { - runtime: "automatic", - pragma: "h", - pragmaFrag: "Fragment", - throwIfNamespace: true, - useBuiltins: false, - development: true, - refresh: true // enable react hooks hmr compatiblity - } - } - } - } - }, - type: "javascript/auto" - } - ] - }, - plugins: [new ReactRefreshRspackPlugin()] -}; diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/__snapshots__/web/0.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/__snapshots__/web/0.snap.txt deleted file mode 100644 index cff3e8678b17..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/__snapshots__/web/0.snap.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Case useState#keep: Step 0 - -## Changed Files - - -## Asset Files -- Bundle: bundle.js - -## Manifest - - -## Update \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/__snapshots__/web/1.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/__snapshots__/web/1.snap.txt deleted file mode 100644 index d062eaabec78..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/__snapshots__/web/1.snap.txt +++ /dev/null @@ -1,162 +0,0 @@ -# Case useState#keep: Step 1 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 4728 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ../useState​#keep/app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"../useState​#keep/app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var _swc_helpers_sliced_to_array__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @swc/helpers/_/_sliced_to_array */ "../../../../../../node_modules/.pnpm/@swc+helpers@0.5.8/node_modules/@swc/helpers/esm/_sliced_to_array.js"); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* harmony import */var preact_hooks__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! preact/hooks */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/hooks/dist/hooks.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - - -var _s = $RefreshSig$(); - -function App() { - _s(); - var _useState = (0,_swc_helpers_sliced_to_array__WEBPACK_IMPORTED_MODULE_2__._)((0,preact_hooks__WEBPACK_IMPORTED_MODULE_1__.useState)('light'), 2), theme = _useState[0], setTheme = _useState[1]; - (0,preact_hooks__WEBPACK_IMPORTED_MODULE_1__.useLayoutEffect)(function() {}, []); - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: [ - "after: ", - theme - ] - }, void 0, true, { - fileName: "/tests/hotCases/hook/useState#keep/app.jsx", - lineNumber: 6, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/hook/useState#keep/app.jsx", - lineNumber: 6, - columnNumber: 11 - }, this); -} -_s(App, "HKUtO7qo1dBz/EOqzI5a9yW85oU="); -_c = App; -var _c; -$RefreshReg$(_c, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/app.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/app.jsx deleted file mode 100644 index 2f31baace907..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/app.jsx +++ /dev/null @@ -1,21 +0,0 @@ -import { useState, useLayoutEffect } from 'preact/hooks' - -export function App() { - const [theme, setTheme] = useState('light'); - useLayoutEffect(() => { - setTimeout(() => { - setTheme('dark'); - }, 100); - }, []); - return (
before: {theme}
); -} - ---- -import { useState, useLayoutEffect } from 'preact/hooks' - -export function App() { - const [theme, setTheme] = useState('light'); - useLayoutEffect(() => { }, []); - return (
after: {theme}
); -} - diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/index.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/index.jsx deleted file mode 100644 index 7695ca1b33cf..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/index.jsx +++ /dev/null @@ -1,33 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { App } from './app'; -import update from '../../update'; - -const container = document.createElement('div'); -container.id = "root"; -document.body.appendChild(container); -const root = ReactDOM.createRoot(container); -root.render( -
- -
, -); - -it("should keep state", (done) => { - expect(container.querySelector('span').textContent).toBe("before: light"); - setTimeout(() => { - expect(container.querySelector('span').textContent).toBe("before: dark"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("after: dark"); - done(); - }), - ) - }, 200); - -}); - - -if (module.hot) { - module.hot.accept('./app'); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/rspack.config.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/rspack.config.js deleted file mode 100644 index acb4cfadcd1a..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#keep/rspack.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const ReactRefreshRspackPlugin = require("../../../.."); - -/** @type {import('@rspack/core').Configuration} */ -module.exports = { - context: __dirname, - entry: "./index.jsx", - resolve: { - extensions: ["...", ".ts", ".tsx", ".jsx"], - alias: { - react: "preact/compat", - "react-dom/test-utils": "preact/test-utils", - "react-dom": "preact/compat", // Must be below test-utils - "react/jsx-runtime": "preact/jsx-runtime" - } - }, - module: { - rules: [ - { - test: /\.jsx?$/, - exclude: [/node_modules/], - use: { - loader: "builtin:swc-loader", - options: { - jsc: { - experimental: { - plugins: [ - [ - "@swc/plugin-prefresh", // enable prefresh specific transformation - {} - ] - ] - }, - parser: { - syntax: "ecmascript", - jsx: true - }, - externalHelpers: true, - preserveAllComments: false, - transform: { - react: { - runtime: "automatic", - pragma: "h", - pragmaFrag: "Fragment", - throwIfNamespace: true, - useBuiltins: false, - development: true, - refresh: true // enable react hooks hmr compatiblity - } - } - } - } - }, - type: "javascript/auto" - } - ] - }, - plugins: [new ReactRefreshRspackPlugin()] -}; diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/__snapshots__/web/0.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/__snapshots__/web/0.snap.txt deleted file mode 100644 index 919f8c5ce286..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/__snapshots__/web/0.snap.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Case useState#reset: Step 0 - -## Changed Files - - -## Asset Files -- Bundle: bundle.js - -## Manifest - - -## Update \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/__snapshots__/web/1.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/__snapshots__/web/1.snap.txt deleted file mode 100644 index a73608512c7e..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/__snapshots__/web/1.snap.txt +++ /dev/null @@ -1,161 +0,0 @@ -# Case useState#reset: Step 1 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 4620 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ../useState​#reset/app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"../useState​#reset/app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var _swc_helpers_sliced_to_array__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @swc/helpers/_/_sliced_to_array */ "../../../../../../node_modules/.pnpm/@swc+helpers@0.5.8/node_modules/@swc/helpers/esm/_sliced_to_array.js"); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* harmony import */var preact_hooks__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! preact/hooks */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/hooks/dist/hooks.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - - -var _s = $RefreshSig$(); - -function App() { - _s(); - var _useState = (0,_swc_helpers_sliced_to_array__WEBPACK_IMPORTED_MODULE_2__._)((0,preact_hooks__WEBPACK_IMPORTED_MODULE_1__.useState)('light'), 1), theme = _useState[0]; - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: [ - "after: ", - theme - ] - }, void 0, true, { - fileName: "/tests/hotCases/hook/useState#reset/app.jsx", - lineNumber: 5, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/hook/useState#reset/app.jsx", - lineNumber: 5, - columnNumber: 11 - }, this); -} -_s(App, "iRFZ/jNSewRB4O1lKD63OsK7w6w="); -_c = App; -var _c; -$RefreshReg$(_c, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/app.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/app.jsx deleted file mode 100644 index e81020cbf474..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/app.jsx +++ /dev/null @@ -1,20 +0,0 @@ -import { useState, useLayoutEffect } from 'preact/hooks' - -export function App() { - const [theme, setTheme] = useState('light'); - useLayoutEffect(() => { - setTimeout(() => { - setTheme('dark'); - }, 100); - }, []); - return (
before: {theme}
); -} - ---- -import { useState, useLayoutEffect } from 'preact/hooks' - -export function App() { - const [theme] = useState('light'); - return (
after: {theme}
); -} - diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/index.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/index.jsx deleted file mode 100644 index 8829a4449ef6..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/index.jsx +++ /dev/null @@ -1,33 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { App } from './app'; -import update from '../../update'; - -const container = document.createElement('div'); -container.id = "root"; -document.body.appendChild(container); -const root = ReactDOM.createRoot(container); -root.render( -
- -
, -); - -it("should keep state", (done) => { - expect(container.querySelector('span').textContent).toBe("before: light"); - setTimeout(() => { - expect(container.querySelector('span').textContent).toBe("before: dark"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("after: light"); - done(); - }), - ) - }, 200); - -}); - - -if (module.hot) { - module.hot.accept('./app'); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/rspack.config.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/rspack.config.js deleted file mode 100644 index acb4cfadcd1a..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/hook/useState#reset/rspack.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const ReactRefreshRspackPlugin = require("../../../.."); - -/** @type {import('@rspack/core').Configuration} */ -module.exports = { - context: __dirname, - entry: "./index.jsx", - resolve: { - extensions: ["...", ".ts", ".tsx", ".jsx"], - alias: { - react: "preact/compat", - "react-dom/test-utils": "preact/test-utils", - "react-dom": "preact/compat", // Must be below test-utils - "react/jsx-runtime": "preact/jsx-runtime" - } - }, - module: { - rules: [ - { - test: /\.jsx?$/, - exclude: [/node_modules/], - use: { - loader: "builtin:swc-loader", - options: { - jsc: { - experimental: { - plugins: [ - [ - "@swc/plugin-prefresh", // enable prefresh specific transformation - {} - ] - ] - }, - parser: { - syntax: "ecmascript", - jsx: true - }, - externalHelpers: true, - preserveAllComments: false, - transform: { - react: { - runtime: "automatic", - pragma: "h", - pragmaFrag: "Fragment", - throwIfNamespace: true, - useBuiltins: false, - development: true, - refresh: true // enable react hooks hmr compatiblity - } - } - } - } - }, - type: "javascript/auto" - } - ] - }, - plugins: [new ReactRefreshRspackPlugin()] -}; diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/0.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/0.snap.txt deleted file mode 100644 index 705e9459d369..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/0.snap.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Case basic: Step 0 - -## Changed Files - - -## Asset Files -- Bundle: bundle.js - -## Manifest - - -## Update \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/1.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/1.snap.txt deleted file mode 100644 index 9e7910d7944c..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/1.snap.txt +++ /dev/null @@ -1,150 +0,0 @@ -# Case basic: Step 1 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 3821 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ./app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"./app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -function App() { - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: "content 2" - }, void 0, false, { - fileName: "/tests/hotCases/jsx/basic/app.jsx", - lineNumber: 2, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/jsx/basic/app.jsx", - lineNumber: 2, - columnNumber: 11 - }, this); -} -_c = App; -var _c; -$RefreshReg$(_c, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/2.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/2.snap.txt deleted file mode 100644 index 151ed1957511..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/__snapshots__/web/2.snap.txt +++ /dev/null @@ -1,192 +0,0 @@ -# Case basic: Step 2 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 3821 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ./app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"./app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -function App() { - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: "content 3" - }, void 0, false, { - fileName: "/tests/hotCases/jsx/basic/app.jsx", - lineNumber: 2, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/jsx/basic/app.jsx", - lineNumber: 2, - columnNumber: 11 - }, this); -} -_c = App; -var _c; -$RefreshReg$(_c, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` - - - - -## Runtime -### Status - -```txt -check => prepare => dispose => apply => idle -``` - - - -### JavaScript - -#### Outdated - -Outdated Modules: -- ./app.jsx - - -Outdated Dependencies: -```json -{} -``` - -#### Updated - -Updated Modules: -- ./app.jsx - -Updated Runtime: -- `__webpack_require__.h` - - -#### Callback - -Accepted Callback: - - -Disposed Callback: -- ./app.jsx \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/app.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/app.jsx deleted file mode 100644 index 553a1ad88cd5..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/app.jsx +++ /dev/null @@ -1,11 +0,0 @@ -export function App() { - return (
content 1
); -} ---- -export function App() { - return (
content 2
); -} ---- -export function App() { - return (
content 3
); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/index.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/index.jsx deleted file mode 100644 index b4d4cef443eb..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/index.jsx +++ /dev/null @@ -1,34 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { App } from './app'; -import update from '../../update'; - -const container = document.createElement('div'); -container.id = "root"; -document.body.appendChild(container); -const root = ReactDOM.createRoot(container); -root.render( -
- -
, -); - -it("should rerender jsx", (done) => { - expect(container.querySelector('span').textContent).toBe("content 1"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("content 2"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("content 3"); - done() - }), - ) - }), - ) -}); - - -if (module.hot) { - module.hot.accept('./app'); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/rspack.config.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/rspack.config.js deleted file mode 100644 index ddc40b2d3ba9..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/basic/rspack.config.js +++ /dev/null @@ -1,57 +0,0 @@ -const ReactRefreshRspackPlugin = require("../../../.."); - -/** @type {import('@rspack/core').Configuration} */ -module.exports = { - context: __dirname, - entry: "./index.jsx", - resolve: { - extensions: ["...", ".ts", ".tsx", ".jsx"], - alias: { - react: "preact/compat", - "react-dom/test-utils": "preact/test-utils", - "react-dom": "preact/compat", // Must be below test-utils - "react/jsx-runtime": "preact/jsx-runtime" - } - }, - module: { - rules: [ - { - test: /\.jsx?$/, - exclude: [/node_modules/], - use: { - loader: "builtin:swc-loader", - options: { - jsc: { - experimental: { - plugins: [ - [ - "@swc/plugin-prefresh", // enable prefresh specific transformation - {} - ] - ] - }, - parser: { - syntax: "ecmascript", - jsx: true - }, - externalHelpers: true, - preserveAllComments: false, - transform: { - react: { - runtime: "automatic", - pragma: "h", - pragmaFrag: "Fragment", - throwIfNamespace: true, - useBuiltins: false, - refresh: true // enable react hooks hmr compatiblity - } - } - } - } - }, - type: "javascript/auto" - } - ] - }, - plugins: [new ReactRefreshRspackPlugin()] -}; diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/0.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/0.snap.txt deleted file mode 100644 index 9e91e61d754d..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/0.snap.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Case child: Step 0 - -## Changed Files - - -## Asset Files -- Bundle: bundle.js - -## Manifest - - -## Update \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/1.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/1.snap.txt deleted file mode 100644 index 59e7c61ac53c..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/1.snap.txt +++ /dev/null @@ -1,249 +0,0 @@ -# Case child: Step 1 - -## Changed Files -- app.jsx -- child.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 7278 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ./app.jsx -- ./child.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"./app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* harmony import */var _child__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./child */ "./child.jsx"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - - -function App() { - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(_child__WEBPACK_IMPORTED_MODULE_1__.Child, {}, void 0, false, { - fileName: "/tests/hotCases/jsx/child/app.jsx", - lineNumber: 4, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/jsx/child/app.jsx", - lineNumber: 4, - columnNumber: 11 - }, this); -} -_c = App; -var _c; -$RefreshReg$(_c, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), -"./child.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - Child: function() { return Child; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -function Child() { - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: "has child" - }, void 0, false, { - fileName: "/tests/hotCases/jsx/child/child.jsx", - lineNumber: 2, - columnNumber: 11 - }, this); -} -_c = Child; -var _c; -$RefreshReg$(_c, "Child"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/2.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/2.snap.txt deleted file mode 100644 index 62c434c810cd..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/__snapshots__/web/2.snap.txt +++ /dev/null @@ -1,188 +0,0 @@ -# Case child: Step 2 - -## Changed Files -- child.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 3557 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ./child.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"./child.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - Child: function() { return Child; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -function Child() { - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: "child change" - }, void 0, false, { - fileName: "/tests/hotCases/jsx/child/child.jsx", - lineNumber: 2, - columnNumber: 11 - }, this); -} -_c = Child; -var _c; -$RefreshReg$(_c, "Child"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` - - - - -## Runtime -### Status - -```txt -check => prepare => dispose => apply => idle -``` - - - -### JavaScript - -#### Outdated - -Outdated Modules: -- ./app.jsx -- ./child.jsx - - -Outdated Dependencies: -```json -{} -``` - -#### Updated - -Updated Modules: -- ./app.jsx -- ./child.jsx - -Updated Runtime: -- `__webpack_require__.h` - - -#### Callback - -Accepted Callback: - - -Disposed Callback: -- ./app.jsx \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/app.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/app.jsx deleted file mode 100644 index 7512d52ec261..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/app.jsx +++ /dev/null @@ -1,10 +0,0 @@ -export function App() { - return (
no child
); -} - ---- -import { Child } from './child' - -export function App() { - return (
); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/child.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/child.jsx deleted file mode 100644 index dd27e090a6ef..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/child.jsx +++ /dev/null @@ -1,9 +0,0 @@ -throw new Error("should not been imported"); ---- -export function Child() { - return (has child); -} ---- -export function Child() { - return (child change); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/index.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/index.jsx deleted file mode 100644 index c14611256934..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/index.jsx +++ /dev/null @@ -1,34 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { App } from './app'; -import update from '../../update'; - -const container = document.createElement('div'); -container.id = "root"; -document.body.appendChild(container); -const root = ReactDOM.createRoot(container); -root.render( -
- -
, -); - -it("should rerender when children change", (done) => { - expect(container.querySelector('span').textContent).toBe("no child"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("has child"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("child change"); - done() - }), - ) - }), - ) -}); - - -if (module.hot) { - module.hot.accept('./app'); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/rspack.config.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/rspack.config.js deleted file mode 100644 index ddc40b2d3ba9..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/child/rspack.config.js +++ /dev/null @@ -1,57 +0,0 @@ -const ReactRefreshRspackPlugin = require("../../../.."); - -/** @type {import('@rspack/core').Configuration} */ -module.exports = { - context: __dirname, - entry: "./index.jsx", - resolve: { - extensions: ["...", ".ts", ".tsx", ".jsx"], - alias: { - react: "preact/compat", - "react-dom/test-utils": "preact/test-utils", - "react-dom": "preact/compat", // Must be below test-utils - "react/jsx-runtime": "preact/jsx-runtime" - } - }, - module: { - rules: [ - { - test: /\.jsx?$/, - exclude: [/node_modules/], - use: { - loader: "builtin:swc-loader", - options: { - jsc: { - experimental: { - plugins: [ - [ - "@swc/plugin-prefresh", // enable prefresh specific transformation - {} - ] - ] - }, - parser: { - syntax: "ecmascript", - jsx: true - }, - externalHelpers: true, - preserveAllComments: false, - transform: { - react: { - runtime: "automatic", - pragma: "h", - pragmaFrag: "Fragment", - throwIfNamespace: true, - useBuiltins: false, - refresh: true // enable react hooks hmr compatiblity - } - } - } - } - }, - type: "javascript/auto" - } - ] - }, - plugins: [new ReactRefreshRspackPlugin()] -}; diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/0.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/0.snap.txt deleted file mode 100644 index 2dba1cf5d40f..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/0.snap.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Case value: Step 0 - -## Changed Files - - -## Asset Files -- Bundle: bundle.js - -## Manifest - - -## Update \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/1.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/1.snap.txt deleted file mode 100644 index 17fea6acc638..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/1.snap.txt +++ /dev/null @@ -1,151 +0,0 @@ -# Case value: Step 1 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 3844 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ./app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"./app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -function App() { - var value = "content 2"; - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: value - }, void 0, false, { - fileName: "/tests/hotCases/jsx/value/app.jsx", - lineNumber: 3, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/jsx/value/app.jsx", - lineNumber: 3, - columnNumber: 11 - }, this); -} -_c = App; -var _c; -$RefreshReg$(_c, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/2.snap.txt b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/2.snap.txt deleted file mode 100644 index d0f11897ee76..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/__snapshots__/web/2.snap.txt +++ /dev/null @@ -1,193 +0,0 @@ -# Case value: Step 2 - -## Changed Files -- app.jsx - -## Asset Files -- Bundle: bundle.js -- Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.LAST_HASH.hot-update.js, size: 3844 - -## Manifest - -### main.LAST_HASH.hot-update.json - -```json -{"c":["main"],"r":[],"m":[]} -``` - - -## Update - - -### main.LAST_HASH.hot-update.js - -#### Changed Modules -- ./app.jsx - -#### Changed Runtime Modules -- webpack/runtime/get_full_hash - -#### Changed Content -```js -"use strict"; -self["webpackHotUpdate"]('main', { -"./app.jsx": (function (module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - App: function() { return App; } -}); -/* harmony import */var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ "../../../../../../node_modules/.pnpm/preact@10.22.0/node_modules/preact/compat/jsx-dev-runtime.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/* provided dependency */ var __prefresh_utils__ = __webpack_require__(/*! ../../../../client/prefresh.cjs */ "../../../../client/prefresh.cjs"); - -function App() { - var value = "content 3"; - return /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", { - children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("span", { - children: value - }, void 0, false, { - fileName: "/tests/hotCases/jsx/value/app.jsx", - lineNumber: 3, - columnNumber: 16 - }, this) - }, void 0, false, { - fileName: "/tests/hotCases/jsx/value/app.jsx", - lineNumber: 3, - columnNumber: 11 - }, this); -} -_c = App; -var _c; -$RefreshReg$(_c, "App"); - -/** - * The following code is modified based on - * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js - * - * MIT Licensed - * Author JoviDeCroock - * Copyright (c) 2021-Present Preact Team - * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE - */ - -const isPrefreshComponent = __prefresh_utils__.shouldBind(module); - -// `@vanilla-extract/webpack` does some custom preprocessing where -// `module.hot` is partially replaced. This leads to our injected -// code being executed although it shouldn't be: -// -// Intermediate result: -// -// if (true) { // <- inlined by intermediate compile step -// const previousHotModuleExports = module.hot.data && ... -// // Crash happens here ---^ -// -// It crashes at that line because some intermediate compiler isn't -// running in hot mode, but the overall guard condition was compiled -// down to being truthy. By moving `module.hot` outside of the -// condition of the if-statement, it will be left as is. -const moduleHot = module.hot; - -if (moduleHot) { - const currentExports = __prefresh_utils__.getExports(module); - const previousHotModuleExports = - moduleHot.data && moduleHot.data.moduleExports; - - __prefresh_utils__.registerExports(currentExports, module.id); - - if (isPrefreshComponent) { - if (previousHotModuleExports) { - try { - __prefresh_utils__.flush(); - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.clearRuntimeErrors - ) { - __prefresh_errors__.clearRuntimeErrors(); - } - } catch (e) { - // Only available in newer webpack versions. - if (moduleHot.invalidate) { - moduleHot.invalidate(); - } else { - self.location.reload(); - } - } - } - - moduleHot.dispose(data => { - data.moduleExports = __prefresh_utils__.getExports(module); - }); - - moduleHot.accept(function errorRecovery() { - if ( - typeof __prefresh_errors__ !== 'undefined' && - __prefresh_errors__ && - __prefresh_errors__.handleRuntimeError - ) { - __prefresh_errors__.handleRuntimeError(error); - } - - __webpack_require__.c[module.id].hot.accept(errorRecovery); - }); - } -} - -}), - -},function(__webpack_require__) { -// webpack/runtime/get_full_hash -(() => { -__webpack_require__.h = function () { - return "CURRENT_HASH"; -}; - -})(); - -} -); -``` - - - - -## Runtime -### Status - -```txt -check => prepare => dispose => apply => idle -``` - - - -### JavaScript - -#### Outdated - -Outdated Modules: -- ./app.jsx - - -Outdated Dependencies: -```json -{} -``` - -#### Updated - -Updated Modules: -- ./app.jsx - -Updated Runtime: -- `__webpack_require__.h` - - -#### Callback - -Accepted Callback: - - -Disposed Callback: -- ./app.jsx \ No newline at end of file diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/app.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/app.jsx deleted file mode 100644 index d796f4ca8802..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/app.jsx +++ /dev/null @@ -1,14 +0,0 @@ -export function App() { - const value = "content 1"; - return (
{value}
) -} ---- -export function App() { - const value = "content 2"; - return (
{value}
) -} ---- -export function App() { - const value = "content 3"; - return (
{value}
) -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/index.jsx b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/index.jsx deleted file mode 100644 index e45e5326a50a..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/index.jsx +++ /dev/null @@ -1,34 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { App } from './app'; -import update from '../../update'; - -const container = document.createElement('div'); -container.id = "root"; -document.body.appendChild(container); -const root = ReactDOM.createRoot(container); -root.render( -
- -
, -); - -it("should rerender value", (done) => { - expect(container.querySelector('span').textContent).toBe("content 1"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("content 2"); - NEXT( - update(done, true, () => { - expect(container.querySelector('span').textContent).toBe("content 3"); - done() - }), - ) - }), - ) -}); - - -if (module.hot) { - module.hot.accept('./app'); -} diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/rspack.config.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/rspack.config.js deleted file mode 100644 index ddc40b2d3ba9..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/jsx/value/rspack.config.js +++ /dev/null @@ -1,57 +0,0 @@ -const ReactRefreshRspackPlugin = require("../../../.."); - -/** @type {import('@rspack/core').Configuration} */ -module.exports = { - context: __dirname, - entry: "./index.jsx", - resolve: { - extensions: ["...", ".ts", ".tsx", ".jsx"], - alias: { - react: "preact/compat", - "react-dom/test-utils": "preact/test-utils", - "react-dom": "preact/compat", // Must be below test-utils - "react/jsx-runtime": "preact/jsx-runtime" - } - }, - module: { - rules: [ - { - test: /\.jsx?$/, - exclude: [/node_modules/], - use: { - loader: "builtin:swc-loader", - options: { - jsc: { - experimental: { - plugins: [ - [ - "@swc/plugin-prefresh", // enable prefresh specific transformation - {} - ] - ] - }, - parser: { - syntax: "ecmascript", - jsx: true - }, - externalHelpers: true, - preserveAllComments: false, - transform: { - react: { - runtime: "automatic", - pragma: "h", - pragmaFrag: "Fragment", - throwIfNamespace: true, - useBuiltins: false, - refresh: true // enable react hooks hmr compatiblity - } - } - } - } - }, - type: "javascript/auto" - } - ] - }, - plugins: [new ReactRefreshRspackPlugin()] -}; diff --git a/packages/rspack-plugin-preact-refresh/tests/hotCases/update.js b/packages/rspack-plugin-preact-refresh/tests/hotCases/update.js deleted file mode 100644 index 8e21026f2ddd..000000000000 --- a/packages/rspack-plugin-preact-refresh/tests/hotCases/update.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = function (done, options, callback) { - return function (err, stats) { - if (err) return done(err); - module.hot - .check(options || true) - .then(updatedModules => { - if (!updatedModules) return done(new Error("No update available")); - if (callback) callback(stats); - }) - .catch(err => { - done(err); - }); - }; -}; diff --git a/packages/rspack-plugin-preact-refresh/tsconfig.build.json b/packages/rspack-plugin-preact-refresh/tsconfig.build.json deleted file mode 100644 index bd25c52bf66a..000000000000 --- a/packages/rspack-plugin-preact-refresh/tsconfig.build.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "sourceMap": false, - "declarationMap": false - }, - "references": [ - { - "path": "../rspack/tsconfig.build.json" - } - ] -} diff --git a/packages/rspack-plugin-preact-refresh/tsconfig.json b/packages/rspack-plugin-preact-refresh/tsconfig.json deleted file mode 100644 index fe06cc39adc6..000000000000 --- a/packages/rspack-plugin-preact-refresh/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "dist", - "rootDir": "src" - }, - "include": ["src"], - "references": [ - { - "path": "../rspack" - } - ] -} diff --git a/packages/rspack-plugin-react-refresh/LICENSE b/packages/rspack-plugin-react-refresh/LICENSE deleted file mode 100644 index 46310101ad8a..000000000000 --- a/packages/rspack-plugin-react-refresh/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2022-present Bytedance, Inc. and its affiliates. - - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/packages/rspack-plugin-react-refresh/README.md b/packages/rspack-plugin-react-refresh/README.md deleted file mode 100644 index 3b5a6ec2501b..000000000000 --- a/packages/rspack-plugin-react-refresh/README.md +++ /dev/null @@ -1,16 +0,0 @@ - - - Rspack Banner - - -# @rspack/plugin-react-refresh - -React refresh plugin for rspack. - -## Documentation - -See [https://rspack.dev](https://rspack.dev) for details. - -## License - -Rspack is [MIT licensed](https://github.com/web-infra-dev/rspack/blob/main/LICENSE). diff --git a/packages/rspack-plugin-react-refresh/api-extractor.json b/packages/rspack-plugin-react-refresh/api-extractor.json deleted file mode 100644 index 8e7ead9695ce..000000000000 --- a/packages/rspack-plugin-react-refresh/api-extractor.json +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Config file for API Extractor. For more info, please visit: https://api-extractor.com - */ -{ - "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", - "extends": "../../api-extractor.json" -} \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/client/errorOverlayEntry.js b/packages/rspack-plugin-react-refresh/client/errorOverlayEntry.js deleted file mode 100644 index f0a97d7b2d8a..000000000000 --- a/packages/rspack-plugin-react-refresh/client/errorOverlayEntry.js +++ /dev/null @@ -1,108 +0,0 @@ -/* global __react_refresh_error_overlay__, __react_refresh_socket__, __resourceQuery */ -/** - * The following code is modified based on - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/f1c8b9a44198449093ca95f85af5df97925e1cfc/client/ErrorOverlayEntry.js - * - * MIT Licensed - * Author Michael Mok - * Copyright (c) 2019 Michael Mok - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/0b960573797bf38926937994c481e4fec9ed8aa6/LICENSE - */ -const events = require('./utils/errorEventHandlers.js'); -const formatWebpackErrors = require('./utils/formatWebpackErrors.js'); -const runWithRetry = require('./utils/retry.js'); - -// Setup error states -let isHotReload = false; -let hasRuntimeErrors = false; - -/** - * Try dismissing the compile error overlay. - * This will also reset runtime error records (if any), - * because we have new source to evaluate. - * @returns {void} - */ -function tryDismissErrorOverlay() { - __react_refresh_error_overlay__.clearCompileError(); - __react_refresh_error_overlay__.clearRuntimeErrors(!hasRuntimeErrors); - hasRuntimeErrors = false; -} - -/** - * A function called after a compile success signal is received from Webpack. - * @returns {void} - */ -function handleCompileSuccess() { - isHotReload = true; - - if (isHotReload) { - tryDismissErrorOverlay(); - } -} - -/** - * A function called after a compile errored signal is received from Webpack. - * @param {string[]} errors - * @returns {void} - */ -function handleCompileErrors(errors) { - isHotReload = true; - - const formattedErrors = formatWebpackErrors(errors); - - // Only show the first error - __react_refresh_error_overlay__.showCompileError(formattedErrors[0]); -} - -/** - * Handles compilation messages from Webpack. - * Integrates with a compile error overlay. - * @param {*} message A Webpack HMR message sent via WebSockets. - * @returns {void} - */ -function compileMessageHandler(message) { - switch (message.type) { - case 'ok': - case 'still-ok': - case 'warnings': { - // TODO: Implement handling for warnings - handleCompileSuccess(); - break; - } - case 'errors': { - handleCompileErrors(message.data); - break; - } - default: { - // Do nothing. - } - } -} - -if (process.env.NODE_ENV !== 'production') { - if (typeof window !== 'undefined') { - function setupOverlay() { - // Only register if no other overlay have been registered - if (!window.__reactRefreshOverlayInjected && __react_refresh_socket__) { - // Registers handlers for compile errors with retry - - // This is to prevent mismatching injection order causing errors to be thrown - runWithRetry(function initSocket() { - __react_refresh_socket__.init(compileMessageHandler, __resourceQuery); - }, 3); - // Registers handlers for runtime errors - events.handleError(function handleError(error) { - hasRuntimeErrors = true; - __react_refresh_error_overlay__.handleRuntimeError(error); - }); - events.handleUnhandledRejection(function handleUnhandledPromiseRejection(error) { - hasRuntimeErrors = true; - __react_refresh_error_overlay__.handleRuntimeError(error); - }); - - // Mark overlay as injected to prevent double-injection - window.__reactRefreshOverlayInjected = true; - } - }; - setupOverlay() - } -} \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/client/overlay/components/CompileErrorTrace.js b/packages/rspack-plugin-react-refresh/client/overlay/components/CompileErrorTrace.js deleted file mode 100644 index 3e812a61b94e..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/components/CompileErrorTrace.js +++ /dev/null @@ -1,58 +0,0 @@ -const ansiHTML = require('../../utils/ansi-html.js'); -const entities = require('html-entities'); -const theme = require('../theme.js'); -const utils = require('../utils.js'); - -ansiHTML.setColors(theme); - -/** - * @typedef {Object} CompileErrorTraceProps - * @property {string} errorMessage - */ - -/** - * A formatter that turns Webpack compile error messages into highlighted HTML source traces. - * @param {Document} document - * @param {HTMLElement} root - * @param {CompileErrorTraceProps} props - * @returns {void} - */ -function CompileErrorTrace(document, root, props) { - const errorParts = props.errorMessage.split('\n'); - if (errorParts.length) { - if (errorParts[0]) { - errorParts[0] = utils.formatFilename(errorParts[0]); - } - - const errorMessage = errorParts.splice(1, 1)[0]; - if (errorMessage) { - // Strip filename from the error message - errorParts.unshift(errorMessage.replace(/^(.*:)\s.*:(\s.*)$/, '$1$2')); - } - } - - const stackContainer = document.createElement('pre'); - stackContainer.innerHTML = entities.decode( - ansiHTML(entities.encode(errorParts.join('\n'), { level: 'html5', mode: 'nonAscii' })), - { level: 'html5' } - ); - stackContainer.style.fontFamily = [ - '"Operator Mono SSm"', - '"Operator Mono"', - '"Fira Code Retina"', - '"Fira Code"', - '"FiraCode-Retina"', - '"Andale Mono"', - '"Lucida Console"', - 'Menlo', - 'Consolas', - 'Monaco', - 'monospace', - ].join(', '); - stackContainer.style.margin = '0'; - stackContainer.style.whiteSpace = 'pre-wrap'; - - root.appendChild(stackContainer); -} - -module.exports = CompileErrorTrace; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/components/PageHeader.js b/packages/rspack-plugin-react-refresh/client/overlay/components/PageHeader.js deleted file mode 100644 index 898d21a89327..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/components/PageHeader.js +++ /dev/null @@ -1,58 +0,0 @@ -const Spacer = require('./Spacer.js'); -const theme = require('../theme.js'); - -/** - * @typedef {Object} PageHeaderProps - * @property {string} [message] - * @property {string} title - * @property {string} [topOffset] - */ - -/** - * The header of the overlay. - * @param {Document} document - * @param {HTMLElement} root - * @param {PageHeaderProps} props - * @returns {void} - */ -function PageHeader(document, root, props) { - const pageHeaderContainer = document.createElement('div'); - pageHeaderContainer.style.background = '#' + theme.dimgrey; - pageHeaderContainer.style.boxShadow = '0 1px 4px rgba(0, 0, 0, 0.3)'; - pageHeaderContainer.style.color = '#' + theme.white; - pageHeaderContainer.style.left = '0'; - pageHeaderContainer.style.right = '0'; - pageHeaderContainer.style.padding = '1rem 1.5rem'; - pageHeaderContainer.style.paddingLeft = 'max(1.5rem, env(safe-area-inset-left))'; - pageHeaderContainer.style.paddingRight = 'max(1.5rem, env(safe-area-inset-right))'; - pageHeaderContainer.style.position = 'fixed'; - pageHeaderContainer.style.top = props.topOffset || '0'; - - const title = document.createElement('h3'); - title.innerText = props.title; - title.style.color = '#' + theme.red; - title.style.fontSize = '1.125rem'; - title.style.lineHeight = '1.3'; - title.style.margin = '0'; - pageHeaderContainer.appendChild(title); - - if (props.message) { - title.style.margin = '0 0 0.5rem'; - - const message = document.createElement('span'); - message.innerText = props.message; - message.style.color = '#' + theme.white; - message.style.wordBreak = 'break-word'; - pageHeaderContainer.appendChild(message); - } - - root.appendChild(pageHeaderContainer); - - // This has to run after appending elements to root - // because we need to actual mounted height. - Spacer(document, root, { - space: pageHeaderContainer.offsetHeight.toString(10), - }); -} - -module.exports = PageHeader; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorFooter.js b/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorFooter.js deleted file mode 100644 index ab3201b6e00b..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorFooter.js +++ /dev/null @@ -1,93 +0,0 @@ -const Spacer = require('./Spacer.js'); -const theme = require('../theme.js'); - -/** - * @typedef {Object} RuntimeErrorFooterProps - * @property {string} [initialFocus] - * @property {boolean} multiple - * @property {function(MouseEvent): void} onClickCloseButton - * @property {function(MouseEvent): void} onClickNextButton - * @property {function(MouseEvent): void} onClickPrevButton - */ - -/** - * A fixed footer that handles pagination of runtime errors. - * @param {Document} document - * @param {HTMLElement} root - * @param {RuntimeErrorFooterProps} props - * @returns {void} - */ -function RuntimeErrorFooter(document, root, props) { - const footer = document.createElement('div'); - footer.style.backgroundColor = '#' + theme.dimgrey; - footer.style.bottom = '0'; - footer.style.boxShadow = '0 -1px 4px rgba(0, 0, 0, 0.3)'; - footer.style.height = '2.5rem'; - footer.style.left = '0'; - footer.style.right = '0'; - footer.style.lineHeight = '2.5rem'; - footer.style.paddingBottom = '0'; - footer.style.paddingBottom = 'env(safe-area-inset-bottom)'; - footer.style.position = 'fixed'; - footer.style.textAlign = 'center'; - footer.style.zIndex = '2'; - - const BUTTON_CONFIGS = { - prev: { - id: 'prev', - label: '◀ Prev', - onClick: props.onClickPrevButton, - }, - close: { - id: 'close', - label: '× Close', - onClick: props.onClickCloseButton, - }, - next: { - id: 'next', - label: 'Next ▶', - onClick: props.onClickNextButton, - }, - }; - - let buttons = [BUTTON_CONFIGS.close]; - if (props.multiple) { - buttons = [BUTTON_CONFIGS.prev, BUTTON_CONFIGS.close, BUTTON_CONFIGS.next]; - } - - /** @type {HTMLButtonElement | undefined} */ - let initialFocusButton; - for (let i = 0; i < buttons.length; i += 1) { - const buttonConfig = buttons[i]; - - const button = document.createElement('button'); - button.id = buttonConfig.id; - button.innerHTML = buttonConfig.label; - button.tabIndex = 1; - button.style.backgroundColor = '#' + theme.dimgrey; - button.style.border = 'none'; - button.style.color = '#' + theme.white; - button.style.cursor = 'pointer'; - button.style.fontSize = 'inherit'; - button.style.height = '100%'; - button.style.padding = '0.5rem 0.75rem'; - button.style.width = (100 / buttons.length).toString(10) + '%'; - button.addEventListener('click', buttonConfig.onClick); - - if (buttonConfig.id === props.initialFocus) { - initialFocusButton = button; - } - - footer.appendChild(button); - } - - root.appendChild(footer); - - Spacer(document, root, { space: '2.5rem' }); - - if (initialFocusButton) { - initialFocusButton.focus(); - } -} - -module.exports = RuntimeErrorFooter; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorHeader.js b/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorHeader.js deleted file mode 100644 index 0b07b0a1cf70..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorHeader.js +++ /dev/null @@ -1,37 +0,0 @@ -const Spacer = require('./Spacer.js'); -const theme = require('../theme.js'); - -/** - * @typedef {Object} RuntimeErrorHeaderProps - * @property {number} currentErrorIndex - * @property {number} totalErrors - */ - -/** - * A fixed header that shows the total runtime error count. - * @param {Document} document - * @param {HTMLElement} root - * @param {RuntimeErrorHeaderProps} props - * @returns {void} - */ -function RuntimeErrorHeader(document, root, props) { - const header = document.createElement('div'); - header.innerText = 'Error ' + (props.currentErrorIndex + 1) + ' of ' + props.totalErrors; - header.style.backgroundColor = '#' + theme.red; - header.style.color = '#' + theme.white; - header.style.fontWeight = '500'; - header.style.height = '2.5rem'; - header.style.left = '0'; - header.style.lineHeight = '2.5rem'; - header.style.position = 'fixed'; - header.style.textAlign = 'center'; - header.style.top = '0'; - header.style.width = '100vw'; - header.style.zIndex = '2'; - - root.appendChild(header); - - Spacer(document, root, { space: '2.5rem' }); -} - -module.exports = RuntimeErrorHeader; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorStack.js b/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorStack.js deleted file mode 100644 index 4a8d00886887..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/components/RuntimeErrorStack.js +++ /dev/null @@ -1,79 +0,0 @@ -const ErrorStackParser = require('error-stack-parser'); -const theme = require('../theme.js'); -const utils = require('../utils.js'); - -/** - * @typedef {Object} RuntimeErrorStackProps - * @property {Error} error - */ - -/** - * A formatter that turns runtime error stacks into highlighted HTML stacks. - * @param {Document} document - * @param {HTMLElement} root - * @param {RuntimeErrorStackProps} props - * @returns {void} - */ -function RuntimeErrorStack(document, root, props) { - const stackTitle = document.createElement('h4'); - stackTitle.innerText = 'Call Stack'; - stackTitle.style.color = '#' + theme.white; - stackTitle.style.fontSize = '1.0625rem'; - stackTitle.style.fontWeight = '500'; - stackTitle.style.lineHeight = '1.3'; - stackTitle.style.margin = '0 0 0.5rem'; - - const stackContainer = document.createElement('div'); - stackContainer.style.fontSize = '0.8125rem'; - stackContainer.style.lineHeight = '1.3'; - stackContainer.style.whiteSpace = 'pre-wrap'; - - let errorStacks; - try { - errorStacks = ErrorStackParser.parse(props.error); - } catch (e) { - errorStacks = []; - stackContainer.innerHTML = 'No stack trace is available for this error!'; - } - - for (let i = 0; i < Math.min(errorStacks.length, 10); i += 1) { - const currentStack = errorStacks[i]; - - const functionName = document.createElement('code'); - functionName.innerHTML = ' ' + currentStack.functionName || '(anonymous function)'; - functionName.style.color = '#' + theme.yellow; - functionName.style.fontFamily = [ - '"Operator Mono SSm"', - '"Operator Mono"', - '"Fira Code Retina"', - '"Fira Code"', - '"FiraCode-Retina"', - '"Andale Mono"', - '"Lucida Console"', - 'Menlo', - 'Consolas', - 'Monaco', - 'monospace', - ].join(', '); - - const fileName = document.createElement('div'); - fileName.innerHTML = - '  ' + - utils.formatFilename(currentStack.fileName) + - ':' + - currentStack.lineNumber + - ':' + - currentStack.columnNumber; - fileName.style.color = '#' + theme.white; - fileName.style.fontSize = '0.6875rem'; - fileName.style.marginBottom = '0.25rem'; - - stackContainer.appendChild(functionName); - stackContainer.appendChild(fileName); - } - - root.appendChild(stackTitle); - root.appendChild(stackContainer); -} - -module.exports = RuntimeErrorStack; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/components/Spacer.js b/packages/rspack-plugin-react-refresh/client/overlay/components/Spacer.js deleted file mode 100644 index 6bb029966654..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/components/Spacer.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * @typedef {Object} SpacerProps - * @property {string} space - */ - -/** - * An empty element to add spacing manually. - * @param {Document} document - * @param {HTMLElement} root - * @param {SpacerProps} props - * @returns {void} - */ -function Spacer(document, root, props) { - const spacer = document.createElement('div'); - spacer.style.paddingBottom = props.space; - root.appendChild(spacer); -} - -module.exports = Spacer; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/containers/CompileErrorContainer.js b/packages/rspack-plugin-react-refresh/client/overlay/containers/CompileErrorContainer.js deleted file mode 100644 index 7f68e7e93923..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/containers/CompileErrorContainer.js +++ /dev/null @@ -1,25 +0,0 @@ -const CompileErrorTrace = require('../components/CompileErrorTrace.js'); -const PageHeader = require('../components/PageHeader.js'); -const Spacer = require('../components/Spacer.js'); - -/** - * @typedef {Object} CompileErrorContainerProps - * @property {string} errorMessage - */ - -/** - * A container to render Webpack compilation error messages with source trace. - * @param {Document} document - * @param {HTMLElement} root - * @param {CompileErrorContainerProps} props - * @returns {void} - */ -function CompileErrorContainer(document, root, props) { - PageHeader(document, root, { - title: 'Failed to compile.', - }); - CompileErrorTrace(document, root, { errorMessage: props.errorMessage }); - Spacer(document, root, { space: '1rem' }); -} - -module.exports = CompileErrorContainer; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/containers/RuntimeErrorContainer.js b/packages/rspack-plugin-react-refresh/client/overlay/containers/RuntimeErrorContainer.js deleted file mode 100644 index 11a6f9dcacf3..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/containers/RuntimeErrorContainer.js +++ /dev/null @@ -1,29 +0,0 @@ -const PageHeader = require('../components/PageHeader.js'); -const RuntimeErrorStack = require('../components/RuntimeErrorStack.js'); -const Spacer = require('../components/Spacer.js'); - -/** - * @typedef {Object} RuntimeErrorContainerProps - * @property {Error} currentError - */ - -/** - * A container to render runtime error messages with stack trace. - * @param {Document} document - * @param {HTMLElement} root - * @param {RuntimeErrorContainerProps} props - * @returns {void} - */ -function RuntimeErrorContainer(document, root, props) { - PageHeader(document, root, { - message: props.currentError.message, - title: props.currentError.name, - topOffset: '2.5rem', - }); - RuntimeErrorStack(document, root, { - error: props.currentError, - }); - Spacer(document, root, { space: '1rem' }); -} - -module.exports = RuntimeErrorContainer; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/index.js b/packages/rspack-plugin-react-refresh/client/overlay/index.js deleted file mode 100644 index 5ad42d1bfc52..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/index.js +++ /dev/null @@ -1,348 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/f1c8b9a44198449093ca95f85af5df97925e1cfc/overlay/index.js - * - * MIT Licensed - * Author Michael Mok - * Copyright (c) 2019 Michael Mok - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/0b960573797bf38926937994c481e4fec9ed8aa6/LICENSE - */ -const RuntimeErrorFooter = require('./components/RuntimeErrorFooter.js'); -const RuntimeErrorHeader = require('./components/RuntimeErrorHeader.js'); -const CompileErrorContainer = require('./containers/CompileErrorContainer.js'); -const RuntimeErrorContainer = require('./containers/RuntimeErrorContainer.js'); -const theme = require('./theme.js'); -const utils = require('./utils.js'); - -/** - * @callback RenderFn - * @returns {void} - */ - -/* ===== Cached elements for DOM manipulations ===== */ -/** - * The iframe that contains the overlay. - * @type {HTMLIFrameElement} - */ -let iframeRoot = null; -/** - * The document object from the iframe root, used to create and render elements. - * @type {Document} - */ -let rootDocument = null; -/** - * The root div elements will attach to. - * @type {HTMLDivElement} - */ -let root = null; -/** - * A Cached function to allow deferred render. - * @type {RenderFn | null} - */ -let scheduledRenderFn = null; - -/* ===== Overlay State ===== */ -/** - * The latest error message from Webpack compilation. - * @type {string} - */ -let currentCompileErrorMessage = ''; -/** - * Index of the error currently shown by the overlay. - * @type {number} - */ -let currentRuntimeErrorIndex = 0; -/** - * The latest runtime error objects. - * @type {Error[]} - */ -let currentRuntimeErrors = []; -/** - * The render mode the overlay is currently in. - * @type {'compileError' | 'runtimeError' | null} - */ -let currentMode = null; - -/** - * @typedef {Object} IframeProps - * @property {function(): void} onIframeLoad - */ - -/** - * Creates the main `iframe` the overlay will attach to. - * Accepts a callback to be ran after iframe is initialized. - * @param {Document} document - * @param {HTMLElement} root - * @param {IframeProps} props - * @returns {HTMLIFrameElement} - */ -function IframeRoot(document, root, props) { - const iframe = document.createElement('iframe'); - iframe.id = 'react-refresh-overlay'; - iframe.src = 'about:blank'; - - iframe.style.border = 'none'; - iframe.style.height = '100%'; - iframe.style.left = '0'; - iframe.style.minHeight = '100vh'; - iframe.style.minHeight = '-webkit-fill-available'; - iframe.style.position = 'fixed'; - iframe.style.top = '0'; - iframe.style.width = '100vw'; - iframe.style.zIndex = '2147483647'; - iframe.addEventListener('load', function onLoad() { - // Reset margin of iframe body - iframe.contentDocument.body.style.margin = '0'; - props.onIframeLoad(); - }); - - // We skip mounting and returns as we need to ensure - // the load event is fired after we setup the global variable - return iframe; -} - -/** - * Creates the main `div` element for the overlay to render. - * @param {Document} document - * @param {HTMLElement} root - * @returns {HTMLDivElement} - */ -function OverlayRoot(document, root) { - const div = document.createElement('div'); - div.id = 'react-refresh-overlay-error'; - - // Style the contents container - div.style.backgroundColor = '#' + theme.grey; - div.style.boxSizing = 'border-box'; - div.style.color = '#' + theme.white; - div.style.fontFamily = [ - '-apple-system', - 'BlinkMacSystemFont', - '"Segoe UI"', - '"Helvetica Neue"', - 'Helvetica', - 'Arial', - 'sans-serif', - '"Apple Color Emoji"', - '"Segoe UI Emoji"', - 'Segoe UI Symbol', - ].join(', '); - div.style.fontSize = '0.875rem'; - div.style.height = '100%'; - div.style.lineHeight = '1.3'; - div.style.overflow = 'auto'; - div.style.padding = '1rem 1.5rem 0'; - div.style.paddingTop = 'max(1rem, env(safe-area-inset-top))'; - div.style.paddingRight = 'max(1.5rem, env(safe-area-inset-right))'; - div.style.paddingBottom = 'env(safe-area-inset-bottom)'; - div.style.paddingLeft = 'max(1.5rem, env(safe-area-inset-left))'; - div.style.width = '100vw'; - - root.appendChild(div); - return div; -} - -/** - * Ensures the iframe root and the overlay root are both initialized before render. - * If check fails, render will be deferred until both roots are initialized. - * @param {RenderFn} renderFn A function that triggers a DOM render. - * @returns {void} - */ -function ensureRootExists(renderFn) { - if (root) { - // Overlay root is ready, we can render right away. - renderFn(); - return; - } - - // Creating an iframe may be asynchronous so we'll defer render. - // In case of multiple calls, function from the last call will be used. - scheduledRenderFn = renderFn; - - if (iframeRoot) { - // Iframe is already ready, it will fire the load event. - return; - } - - // Create the iframe root, and, the overlay root inside it when it is ready. - iframeRoot = IframeRoot(document, document.body, { - onIframeLoad: function onIframeLoad() { - rootDocument = iframeRoot.contentDocument; - root = OverlayRoot(rootDocument, rootDocument.body); - scheduledRenderFn(); - }, - }); - - // We have to mount here to ensure `iframeRoot` is set when `onIframeLoad` fires. - // This is because onIframeLoad() will be called synchronously - // or asynchronously depending on the browser. - document.body.appendChild(iframeRoot); -} - -/** - * Creates the main `div` element for the overlay to render. - * @returns {void} - */ -function render() { - ensureRootExists(function () { - const currentFocus = rootDocument.activeElement; - let currentFocusId; - if (currentFocus.localName === 'button' && currentFocus.id) { - currentFocusId = currentFocus.id; - } - - utils.removeAllChildren(root); - - if (currentCompileErrorMessage) { - currentMode = 'compileError'; - - CompileErrorContainer(rootDocument, root, { - errorMessage: currentCompileErrorMessage, - }); - } else if (currentRuntimeErrors.length) { - currentMode = 'runtimeError'; - - RuntimeErrorHeader(rootDocument, root, { - currentErrorIndex: currentRuntimeErrorIndex, - totalErrors: currentRuntimeErrors.length, - }); - RuntimeErrorContainer(rootDocument, root, { - currentError: currentRuntimeErrors[currentRuntimeErrorIndex], - }); - RuntimeErrorFooter(rootDocument, root, { - initialFocus: currentFocusId, - multiple: currentRuntimeErrors.length > 1, - onClickCloseButton: function onClose() { - clearRuntimeErrors(); - }, - onClickNextButton: function onNext() { - if (currentRuntimeErrorIndex === currentRuntimeErrors.length - 1) { - return; - } - currentRuntimeErrorIndex += 1; - ensureRootExists(render); - }, - onClickPrevButton: function onPrev() { - if (currentRuntimeErrorIndex === 0) { - return; - } - currentRuntimeErrorIndex -= 1; - ensureRootExists(render); - }, - }); - } - }); -} - -/** - * Destroys the state of the overlay. - * @returns {void} - */ -function cleanup() { - // Clean up and reset all internal state. - document.body.removeChild(iframeRoot); - scheduledRenderFn = null; - root = null; - iframeRoot = null; -} - -/** - * Clears Webpack compilation errors and dismisses the compile error overlay. - * @returns {void} - */ -function clearCompileError() { - if (!root || currentMode !== 'compileError') { - return; - } - - currentCompileErrorMessage = ''; - currentMode = null; - cleanup(); -} - -/** - * Clears runtime error records and dismisses the runtime error overlay. - * @param {boolean} [dismissOverlay] Whether to dismiss the overlay or not. - * @returns {void} - */ -function clearRuntimeErrors(dismissOverlay) { - if (!root || currentMode !== 'runtimeError') { - return; - } - - currentRuntimeErrorIndex = 0; - currentRuntimeErrors = []; - - if (typeof dismissOverlay === 'undefined' || dismissOverlay) { - currentMode = null; - cleanup(); - } -} - -/** - * Shows the compile error overlay with the specific Webpack error message. - * @param {string} message - * @returns {void} - */ -function showCompileError(message) { - if (!message) { - return; - } - - currentCompileErrorMessage = message; - - render(); -} - -/** - * Shows the runtime error overlay with the specific error records. - * @param {Error[]} errors - * @returns {void} - */ -function showRuntimeErrors(errors) { - if (!errors || !errors.length) { - return; - } - - currentRuntimeErrors = errors; - - render(); -} - -/** - * The debounced version of `showRuntimeErrors` to prevent frequent renders - * due to rapid firing listeners. - * @param {Error[]} errors - * @returns {void} - */ -const debouncedShowRuntimeErrors = utils.debounce(showRuntimeErrors, 30); - -/** - * Detects if an error is a Webpack compilation error. - * @param {Error} error The error of interest. - * @returns {boolean} If the error is a Webpack compilation error. - */ -function isWebpackCompileError(error) { - return /Module [A-z ]+\(from/.test(error.message) || /Cannot find module/.test(error.message); -} - -/** - * Handles runtime error contexts captured with EventListeners. - * Integrates with a runtime error overlay. - * @param {Error} error A valid error object. - * @returns {void} - */ -function handleRuntimeError(error) { - if (error && !isWebpackCompileError(error) && currentRuntimeErrors.indexOf(error) === -1) { - currentRuntimeErrors = currentRuntimeErrors.concat(error); - } - debouncedShowRuntimeErrors(currentRuntimeErrors); -} - -module.exports = Object.freeze({ - clearCompileError: clearCompileError, - clearRuntimeErrors: clearRuntimeErrors, - handleRuntimeError: handleRuntimeError, - showCompileError: showCompileError, - showRuntimeErrors: showRuntimeErrors, -}); \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/client/overlay/theme.js b/packages/rspack-plugin-react-refresh/client/overlay/theme.js deleted file mode 100644 index a1d32f01af1f..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/theme.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @typedef {Object} Theme - * @property {string[]} reset - * @property {string} black - * @property {string} red - * @property {string} green - * @property {string} yellow - * @property {string} blue - * @property {string} magenta - * @property {string} cyan - * @property {string} white - * @property {string} lightgrey - * @property {string} darkgrey - * @property {string} grey - * @property {string} dimgrey - */ - -/** - * @type {Theme} theme - * A collection of colors to be used by the overlay. - * Partially adopted from Tomorrow Night Bright. - */ -const theme = { - reset: ['transparent', 'transparent'], - black: '000000', - red: 'D34F56', - green: 'B9C954', - yellow: 'E6C452', - blue: '7CA7D8', - magenta: 'C299D6', - cyan: '73BFB1', - white: 'FFFFFF', - lightgrey: 'C7C7C7', - darkgrey: 'A9A9A9', - grey: '474747', - dimgrey: '343434', -}; - -module.exports = theme; diff --git a/packages/rspack-plugin-react-refresh/client/overlay/utils.js b/packages/rspack-plugin-react-refresh/client/overlay/utils.js deleted file mode 100644 index fed4dea6daf4..000000000000 --- a/packages/rspack-plugin-react-refresh/client/overlay/utils.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Debounce a function to delay invoking until wait (ms) have elapsed since the last invocation. - * @param {function(...*): *} fn The function to be debounced. - * @param {number} wait Milliseconds to wait before invoking again. - * @return {function(...*): void} The debounced function. - */ -function debounce(fn, wait) { - /** - * A cached setTimeout handler. - * @type {number | undefined} - */ - let timer; - - /** - * @returns {void} - */ - function debounced() { - const context = this; - const args = arguments; - - clearTimeout(timer); - timer = setTimeout(function () { - return fn.apply(context, args); - }, wait); - } - - return debounced; -} - -/** - * Prettify a filename from error stacks into the desired format. - * @param {string} filename The filename to be formatted. - * @returns {string} The formatted filename. - */ -function formatFilename(filename) { - // Strip away protocol and domain for compiled files - const htmlMatch = /^https?:\/\/(.*)\/(.*)/.exec(filename); - if (htmlMatch && htmlMatch[1] && htmlMatch[2]) { - return htmlMatch[2]; - } - - // Strip everything before the first directory for source files - const sourceMatch = /\/.*?([^./]+[/|\\].*)$/.exec(filename); - if (sourceMatch && sourceMatch[1]) { - return sourceMatch[1].replace(/\?$/, ''); - } - - // Unknown filename type, use it as is - return filename; -} - -/** - * Remove all children of an element. - * @param {HTMLElement} element A valid HTML element. - * @param {number} [skip] Number of elements to skip removing. - * @returns {void} - */ -function removeAllChildren(element, skip) { - /** @type {Node[]} */ - const childList = Array.prototype.slice.call( - element.childNodes, - typeof skip !== 'undefined' ? skip : 0 - ); - - for (let i = 0; i < childList.length; i += 1) { - element.removeChild(childList[i]); - } -} - -module.exports = { - debounce: debounce, - formatFilename: formatFilename, - removeAllChildren: removeAllChildren, -}; diff --git a/packages/rspack-plugin-react-refresh/client/reactRefresh.js b/packages/rspack-plugin-react-refresh/client/reactRefresh.js deleted file mode 100644 index 0decd89e7fcb..000000000000 --- a/packages/rspack-plugin-react-refresh/client/reactRefresh.js +++ /dev/null @@ -1,23 +0,0 @@ -// Thanks https://github.com/pmmmwh/react-refresh-webpack-plugin -const RefreshUtils = require("./refreshUtils"); -const RefreshRuntime = require("react-refresh/runtime"); - -// Port from https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/loader/utils/getRefreshModuleRuntime.js#L29 -function refresh(moduleId, webpackHot) { - const currentExports = RefreshUtils.getModuleExports(moduleId); - const fn = exports => { - RefreshUtils.executeRuntime(exports, moduleId, webpackHot); - }; - if (typeof Promise !== "undefined" && currentExports instanceof Promise) { - currentExports.then(fn); - } else { - fn(currentExports); - } -} - -module.exports = { - refresh, - register: RefreshRuntime.register, - createSignatureFunctionForTransform: - RefreshRuntime.createSignatureFunctionForTransform -}; diff --git a/packages/rspack-plugin-react-refresh/client/reactRefreshEntry.js b/packages/rspack-plugin-react-refresh/client/reactRefreshEntry.js deleted file mode 100644 index f60184768d26..000000000000 --- a/packages/rspack-plugin-react-refresh/client/reactRefreshEntry.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/0b960573797bf38926937994c481e4fec9ed8aa6/client/ReactRefreshEntry.js - * - * MIT Licensed - * Author Michael Mok - * Copyright (c) 2019 Michael Mok - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/0b960573797bf38926937994c481e4fec9ed8aa6/LICENSE - */ - -var RefreshRuntime = require("react-refresh/runtime"); -var safeThis = (function () { - // copied from core-js-pure/features/global-this - "use strict"; - - var check = function (it) { - return it && it.Math == Math && it; - }; - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - // eslint-disable-next-line es/no-global-this -- safe - return ( - check(typeof globalThis == "object" && globalThis) || - check(typeof window == "object" && window) || - // eslint-disable-next-line no-restricted-globals -- safe - check(typeof self == "object" && self) || - check(typeof __webpack_require__.g == "object" && __webpack_require__.g) || - // eslint-disable-next-line no-new-func -- fallback - (function () { - return this; - })() || - this || - Function("return this")() - ); -})(); - -if (process.env.NODE_ENV !== "production") { - if (typeof safeThis !== "undefined") { - var $RefreshInjected$ = "__reactRefreshInjected"; - // Namespace the injected flag (if necessary) for monorepo compatibility - if ( - typeof __react_refresh_library__ !== "undefined" && - __react_refresh_library__ - ) { - $RefreshInjected$ += "_" + __react_refresh_library__; - } - - // Only inject the runtime if it hasn't been injected - if (!safeThis[$RefreshInjected$]) { - RefreshRuntime.injectIntoGlobalHook(safeThis); - - // Empty implementation to avoid "ReferenceError: variable is not defined" in module which didn't pass builtin:react-refresh-loader - safeThis.$RefreshSig$ = () => type => type; - safeThis.$RefreshReg$ = () => {}; - - // Mark the runtime as injected to prevent double-injection - safeThis[$RefreshInjected$] = true; - } - } -} diff --git a/packages/rspack-plugin-react-refresh/client/refreshUtils.js b/packages/rspack-plugin-react-refresh/client/refreshUtils.js deleted file mode 100644 index 693fc508e235..000000000000 --- a/packages/rspack-plugin-react-refresh/client/refreshUtils.js +++ /dev/null @@ -1,297 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/0b960573797bf38926937994c481e4fec9ed8aa6/lib/runtime/RefreshUtils.js - * - * MIT Licensed - * Author Michael Mok - * Copyright (c) 2019 Michael Mok - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/0b960573797bf38926937994c481e4fec9ed8aa6/LICENSE - */ - -/* global __webpack_require__ */ -var Refresh = require("react-refresh/runtime"); - -/** - * Extracts exports from a webpack module object. - * @param {string} moduleId A Webpack module ID. - * @returns {*} An exports object from the module. - */ -function getModuleExports(moduleId) { - if (typeof moduleId === "undefined") { - // `moduleId` is unavailable, which indicates that this module is not in the cache, - // which means we won't be able to capture any exports, - // and thus they cannot be refreshed safely. - // These are likely runtime or dynamically generated modules. - return {}; - } - - var maybeModule = __webpack_require__.c[moduleId]; - if (typeof maybeModule === "undefined") { - // `moduleId` is available but the module in cache is unavailable, - // which indicates the module is somehow corrupted (e.g. broken Webpacak `module` globals). - // We will warn the user (as this is likely a mistake) and assume they cannot be refreshed. - console.warn( - "[React Refresh] Failed to get exports for module: " + moduleId + "." - ); - return {}; - } - - var exportsOrPromise = maybeModule.exports; - if (typeof Promise !== "undefined" && exportsOrPromise instanceof Promise) { - return exportsOrPromise.then(function (exports) { - return exports; - }); - } - return exportsOrPromise; -} - -/** - * Calculates the signature of a React refresh boundary. - * If this signature changes, it's unsafe to accept the boundary. - * - * This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/907d6af22ac6ebe58572be418e9253a90665ecbd/packages/metro/src/lib/polyfills/require.js#L795-L816). - * @param {*} moduleExports A Webpack module exports object. - * @returns {string[]} A React refresh boundary signature array. - */ -function getReactRefreshBoundarySignature(moduleExports) { - var signature = []; - signature.push(Refresh.getFamilyByType(moduleExports)); - - if (moduleExports == null || typeof moduleExports !== "object") { - // Exit if we can't iterate over exports. - return signature; - } - - for (var key in moduleExports) { - if (key === "__esModule") { - continue; - } - - signature.push(key); - signature.push(Refresh.getFamilyByType(moduleExports[key])); - } - - return signature; -} - -/** - * Creates a helper that performs a delayed React refresh. - * @returns {function(function(): void): void} A debounced React refresh function. - */ -function createDebounceUpdate() { - /** - * A cached setTimeout handler. - * @type {number | undefined} - */ - var refreshTimeout; - - /** - * Performs react refresh on a delay and clears the error overlay. - * @param {function(): void} callback - * @returns {void} - */ - function enqueueUpdate(callback) { - if (typeof refreshTimeout === "undefined") { - refreshTimeout = setTimeout(function () { - refreshTimeout = undefined; - Refresh.performReactRefresh(); - callback(); - }, 30); - } - } - - return enqueueUpdate; -} - -/** - * Checks if all exports are likely a React component. - * - * This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/febdba2383113c88296c61e28e4ef6a7f4939fda/packages/metro/src/lib/polyfills/require.js#L748-L774). - * @param {*} moduleExports A Webpack module exports object. - * @returns {boolean} Whether the exports are React component like. - */ -function isReactRefreshBoundary(moduleExports) { - if (Refresh.isLikelyComponentType(moduleExports)) { - return true; - } - if ( - moduleExports === undefined || - moduleExports === null || - typeof moduleExports !== "object" - ) { - // Exit if we can't iterate over exports. - return false; - } - - var hasExports = false; - var areAllExportsComponents = true; - for (var key in moduleExports) { - hasExports = true; - - // This is the ES Module indicator flag - if (key === "__esModule") { - continue; - } - - // We can (and have to) safely execute getters here, - // as Webpack manually assigns harmony exports to getters, - // without any side-effects attached. - // Ref: https://github.com/webpack/webpack/blob/b93048643fe74de2a6931755911da1212df55897/lib/MainTemplate.js#L281 - var exportValue = moduleExports[key]; - if (!Refresh.isLikelyComponentType(exportValue)) { - areAllExportsComponents = false; - } - } - - return hasExports && areAllExportsComponents; -} - -/** - * Checks if exports are likely a React component and registers them. - * - * This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/febdba2383113c88296c61e28e4ef6a7f4939fda/packages/metro/src/lib/polyfills/require.js#L818-L835). - * @param {*} moduleExports A Webpack module exports object. - * @param {string} moduleId A Webpack module ID. - * @returns {void} - */ -function registerExportsForReactRefresh(moduleExports, moduleId) { - if (Refresh.isLikelyComponentType(moduleExports)) { - // Register module.exports if it is likely a component - Refresh.register(moduleExports, moduleId + " %exports%"); - } - - if ( - moduleExports === undefined || - moduleExports === null || - typeof moduleExports !== "object" - ) { - // Exit if we can't iterate over the exports. - return; - } - - for (var key in moduleExports) { - // Skip registering the ES Module indicator - if (key === "__esModule") { - continue; - } - - var exportValue = moduleExports[key]; - if (Refresh.isLikelyComponentType(exportValue)) { - var typeID = moduleId + " %exports% " + key; - Refresh.register(exportValue, typeID); - } - } -} - -/** - * Compares previous and next module objects to check for mutated boundaries. - * - * This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/907d6af22ac6ebe58572be418e9253a90665ecbd/packages/metro/src/lib/polyfills/require.js#L776-L792). - * @param {*} prevExports The current Webpack module exports object. - * @param {*} nextExports The next Webpack module exports object. - * @returns {boolean} Whether the React refresh boundary should be invalidated. - */ -function shouldInvalidateReactRefreshBoundary(prevExports, nextExports) { - var prevSignature = getReactRefreshBoundarySignature(prevExports); - var nextSignature = getReactRefreshBoundarySignature(nextExports); - - if (prevSignature.length !== nextSignature.length) { - return true; - } - - for (var i = 0; i < nextSignature.length; i += 1) { - if (prevSignature[i] !== nextSignature[i]) { - return true; - } - } - - return false; -} - -var enqueueUpdate = createDebounceUpdate(); -function executeRuntime( - moduleExports, - moduleId, - webpackHot, - refreshOverlay, - isTest -) { - registerExportsForReactRefresh(moduleExports, moduleId); - - if (webpackHot) { - var isHotUpdate = !!webpackHot.data; - var prevExports; - if (isHotUpdate) { - prevExports = webpackHot.data.prevExports; - } - - if (isReactRefreshBoundary(moduleExports)) { - webpackHot.dispose( - /** - * A callback to performs a full refresh if React has unrecoverable errors, - * and also caches the to-be-disposed module. - * @param {*} data A hot module data object from Webpack HMR. - * @returns {void} - */ - function hotDisposeCallback(data) { - // We have to mutate the data object to get data registered and cached - data.prevExports = moduleExports; - } - ); - webpackHot.accept( - /** - * An error handler to allow self-recovering behaviours. - * @param {Error} error An error occurred during evaluation of a module. - * @returns {void} - */ - function hotErrorHandler(error) { - if (typeof refreshOverlay !== "undefined" && refreshOverlay) { - refreshOverlay.handleRuntimeError(error); - } - - if (typeof isTest !== "undefined" && isTest) { - if (window.onHotAcceptError) { - window.onHotAcceptError(error.message); - } - } - - __webpack_require__.c[moduleId].hot.accept(hotErrorHandler); - } - ); - - if (isHotUpdate) { - if ( - isReactRefreshBoundary(prevExports) && - shouldInvalidateReactRefreshBoundary(prevExports, moduleExports) - ) { - webpackHot.invalidate(); - } else { - enqueueUpdate( - /** - * A function to dismiss the error overlay after performing React refresh. - * @returns {void} - */ - function updateCallback() { - if (typeof refreshOverlay !== "undefined" && refreshOverlay) { - refreshOverlay.clearRuntimeErrors(); - } - } - ); - } - } - } else { - if (isHotUpdate && typeof prevExports !== "undefined") { - webpackHot.invalidate(); - } - } - } -} - -module.exports = Object.freeze({ - enqueueUpdate: enqueueUpdate, - executeRuntime: executeRuntime, - getModuleExports: getModuleExports, - isReactRefreshBoundary: isReactRefreshBoundary, - shouldInvalidateReactRefreshBoundary: shouldInvalidateReactRefreshBoundary, - registerExportsForReactRefresh: registerExportsForReactRefresh -}); diff --git a/packages/rspack-plugin-react-refresh/client/utils/ansi-html.js b/packages/rspack-plugin-react-refresh/client/utils/ansi-html.js deleted file mode 100644 index 56f911530e9f..000000000000 --- a/packages/rspack-plugin-react-refresh/client/utils/ansi-html.js +++ /dev/null @@ -1,305 +0,0 @@ -/* eslint-disable */ -// @ts-nocheck -/** - * The following code is modified based on - * https://github.com/mahdyar/ansi-html-community/blob/b86cc3f1fa1d118477877352f0eafe1a70fd20ab/index.js - * - * Supported: - * - added support for 24-bit RGB colors. - * - * Apache 2.0 Licensed - * Author @Tjatse - * https://github.com/mahdyar/ansi-html-community/blob/master/LICENSE - */ -"use strict"; - -module.exports = ansiHTML; - -// Reference to https://github.com/sindresorhus/ansi-regex -var _regANSI = - /(?:(?:\u001b\[)|\u009b)(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\u001b[A-M]/; - -var _defColors = { - reset: ["fff", "000"], // [FOREGROUND_COLOR, BACKGROUND_COLOR] - black: "000", - red: "ff0000", - green: "209805", - yellow: "e8bf03", - blue: "0000ff", - magenta: "ff00ff", - cyan: "00ffee", - lightgrey: "f0f0f0", - darkgrey: "888" -}; -var _styles = { - 30: "black", - 31: "red", - 32: "green", - 33: "yellow", - 34: "blue", - 35: "magenta", - 36: "cyan", - 37: "lightgrey" -}; - -var _colorMode = { - 2: "rgb" -}; - -var _openTags = { - 1: "font-weight:bold", // bold - 2: "opacity:0.5", // dim - 3: "", // italic - 4: "", // underscore - 8: "display:none", // hidden - 9: "", // delete - 38: function (match) { - // color - var mode = _colorMode[match[0]]; - if (mode === "rgb") { - var r, g, b; - r = match[1]; - g = match[2]; - b = match[3]; - match.advance(4); - return "color: rgb(" + r + "," + g + "," + b + ")"; - } - }, - 48: function (match) { - // background color - var mode = _colorMode[match[0]]; - if (mode === "rgb") { - var r, g, b; - r = match[1]; - g = match[2]; - b = match[3]; - match.advance(4); - return "background-color: rgb(" + r + "," + g + "," + b + ")"; - } - } -}; - -var _openTagToCloseTag = { - 3: "23", - 4: "24", - 9: "29" -}; - -var _closeTags = { - 0: function (ansiCodes) { - if (!ansiCodes) return ""; - if (!ansiCodes.length) return ""; - var code, - ret = ""; - while ((code = ansiCodes.pop())) { - var closeTag = _openTagToCloseTag[code]; - if (closeTag) { - ret += _closeTags[closeTag]; - continue; - } - ret += ""; - } - return ret; - }, - 23: "", // reset italic - 24: "", // reset underscore - 29: "" // reset delete -}; - -[21, 22, 27, 28, 39, 49].forEach(function (n) { - _closeTags[n] = ""; -}); - -/** - * Normalize ';' | '' -> '' - * @param {string | null} seq - * @returns {null | string} - */ -function normalizeSeq(seq) { - if (seq === null || seq === undefined) return null; - if (seq.startsWith(";")) { - return seq.slice(1); - } - return seq; -} - -/** - * Converts text with ANSI color codes to HTML markup. - * @param {String} text - * @returns {*} - */ -function ansiHTML(text) { - // Returns the text if the string has no ANSI escape code. - if (!_regANSI.test(text)) { - return text; - } - - // Cache opened sequence. - var ansiCodes = []; - // Replace with markup. - var ret = text.replace( - /\033\[(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?m/g, - function (m) { - var match = m.match(/(;?\d+)/g).map(normalizeSeq); - Object.defineProperty(match, "advance", { - value: function (count) { - this.splice(0, count); - } - }); - var seq, - rep = ""; - while ((seq = match[0])) { - match.advance(1); - rep += applySeq(seq); - } - return rep; - - function applySeq(seq) { - var other = _openTags[seq]; - if ( - other && - (other = typeof other === "function" ? other(match) : other) - ) { - // If reset signal is encountered, we have to reset everything. - var ret = ""; - if (seq === "0") { - ret += _closeTags[seq](ansiCodes); - } - // If current sequence has been opened, close it. - if (!!~ansiCodes.indexOf(seq)) { - // eslint-disable-line no-extra-boolean-cast - ansiCodes.pop(); - return ""; - } - // Open tag. - ansiCodes.push(seq); - return ( - ret + (other[0] === "<" ? other : '') - ); - } - - var ct = _closeTags[seq]; - if (typeof ct === "function") { - return ct(ansiCodes); - } else if (ct) { - // Pop sequence - ansiCodes.pop(); - return ct; - } - return ""; - } - } - ); - - // Make sure tags are closed. - var l = ansiCodes.length; - l > 0 && (ret += Array(l + 1).join("")); - - return ret; -} - -/** - * Customize colors. - * @param {Object} colors reference to _defColors - */ -ansiHTML.setColors = function (colors) { - if (typeof colors !== "object") { - throw new Error("`colors` parameter must be an Object."); - } - - var _finalColors = {}; - for (var key in _defColors) { - var hex = colors.hasOwnProperty(key) ? colors[key] : null; - if (!hex) { - _finalColors[key] = _defColors[key]; - continue; - } - if ("reset" === key) { - if (typeof hex === "string") { - hex = [hex]; - } - if ( - !Array.isArray(hex) || - hex.length === 0 || - hex.some(function (h) { - return typeof h !== "string"; - }) - ) { - throw new Error( - "The value of `" + - key + - "` property must be an Array and each item could only be a hex string, e.g.: FF0000" - ); - } - var defHexColor = _defColors[key]; - if (!hex[0]) { - hex[0] = defHexColor[0]; - } - if (hex.length === 1 || !hex[1]) { - hex = [hex[0]]; - hex.push(defHexColor[1]); - } - - hex = hex.slice(0, 2); - } else if (typeof hex !== "string") { - throw new Error( - "The value of `" + key + "` property must be a hex string, e.g.: FF0000" - ); - } - _finalColors[key] = hex; - } - _setTags(_finalColors); -}; - -/** - * Reset colors. - */ -ansiHTML.reset = function () { - _setTags(_defColors); -}; - -/** - * Expose tags, including open and close. - * @type {Object} - */ -ansiHTML.tags = {}; - -if (Object.defineProperty) { - Object.defineProperty(ansiHTML.tags, "open", { - get: function () { - return _openTags; - } - }); - Object.defineProperty(ansiHTML.tags, "close", { - get: function () { - return _closeTags; - } - }); -} else { - ansiHTML.tags.open = _openTags; - ansiHTML.tags.close = _closeTags; -} - -function _setTags(colors) { - // reset all - _openTags["0"] = - "font-weight:normal;opacity:1;color:#" + - colors.reset[0] + - ";background:#" + - colors.reset[1]; - // inverse - _openTags["7"] = - "color:#" + colors.reset[1] + ";background:#" + colors.reset[0]; - // dark grey - _openTags["90"] = "color:#" + colors.darkgrey; - - for (var code in _styles) { - var color = _styles[code]; - var oriColor = colors[color] || "000"; - _openTags[code] = "color:#" + oriColor; - code = parseInt(code); - _openTags[(code + 10).toString()] = "background:#" + oriColor; - } -} - -ansiHTML.reset(); diff --git a/packages/rspack-plugin-react-refresh/client/utils/errorEventHandlers.js b/packages/rspack-plugin-react-refresh/client/utils/errorEventHandlers.js deleted file mode 100644 index 49bb5d98f8ef..000000000000 --- a/packages/rspack-plugin-react-refresh/client/utils/errorEventHandlers.js +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @callback EventCallback - * @param {string | Error | null} context - * @returns {void} - */ -/** - * @callback EventHandler - * @param {Event} event - * @returns {void} - */ - -/** - * A function that creates an event handler for the `error` event. - * @param {EventCallback} callback A function called to handle the error context. - * @returns {EventHandler} A handler for the `error` event. - */ -function createErrorHandler(callback) { - return function errorHandler(event) { - if (!event || !event.error) { - return callback(null); - } - if (event.error instanceof Error) { - return callback(event.error); - } - // A non-error was thrown, we don't have a trace. :( - // Look in your browser's devtools for more information - return callback(new Error(event.error)); - }; -} - -/** - * A function that creates an event handler for the `unhandledrejection` event. - * @param {EventCallback} callback A function called to handle the error context. - * @returns {EventHandler} A handler for the `unhandledrejection` event. - */ -function createRejectionHandler(callback) { - return function rejectionHandler(event) { - if (!event || !event.reason) { - return callback(new Error('Unknown')); - } - if (event.reason instanceof Error) { - return callback(event.reason); - } - // A non-error was rejected, we don't have a trace :( - // Look in your browser's devtools for more information - return callback(new Error(event.reason)); - }; -} - -/** - * Creates a handler that registers an EventListener on window for a valid type - * and calls a callback when the event fires. - * @param {string} eventType A valid DOM event type. - * @param {function(EventCallback): EventHandler} createHandler A function that creates an event handler. - * @returns {register} A function that registers the EventListener given a callback. - */ -function createWindowEventHandler(eventType, createHandler) { - /** - * @type {EventHandler | null} A cached event handler function. - */ - let eventHandler = null; - - /** - * Unregisters an EventListener if it has been registered. - * @returns {void} - */ - function unregister() { - if (eventHandler === null) { - return; - } - window.removeEventListener(eventType, eventHandler); - eventHandler = null; - } - - /** - * Registers an EventListener if it hasn't been registered. - * @param {EventCallback} callback A function called after the event handler to handle its context. - * @returns {unregister | void} A function to unregister the registered EventListener if registration is performed. - */ - function register(callback) { - if (eventHandler !== null) { - return; - } - eventHandler = createHandler(callback); - window.addEventListener(eventType, eventHandler); - - return unregister; - } - - return register; -} - -const handleError = createWindowEventHandler('error', createErrorHandler); -const handleUnhandledRejection = createWindowEventHandler( - 'unhandledrejection', - createRejectionHandler -); - -module.exports = { - handleError: handleError, - handleUnhandledRejection: handleUnhandledRejection, -}; \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/client/utils/formatWebpackErrors.js b/packages/rspack-plugin-react-refresh/client/utils/formatWebpackErrors.js deleted file mode 100644 index 5bd9ed9af116..000000000000 --- a/packages/rspack-plugin-react-refresh/client/utils/formatWebpackErrors.js +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @typedef {Object} WebpackErrorObj - * @property {string} moduleIdentifier - * @property {string} moduleName - * @property {string} message - */ - -const friendlySyntaxErrorLabel = 'Syntax error:'; - -/** - * Checks if the error message is for a syntax error. - * @param {string} message The raw Webpack error message. - * @returns {boolean} Whether the error message is for a syntax error. - */ -function isLikelyASyntaxError(message) { - return message.indexOf(friendlySyntaxErrorLabel) !== -1; -} - -/** - * Cleans up Webpack error messages. - * - * This implementation is based on the one from [create-react-app](https://github.com/facebook/create-react-app/blob/edc671eeea6b7d26ac3f1eb2050e50f75cf9ad5d/packages/react-dev-utils/formatWebpackMessages.js). - * @param {string} message The raw Webpack error message. - * @returns {string} The formatted Webpack error message. - */ -function formatMessage(message) { - let lines = message.split('\n'); - - // Strip Webpack-added headers off errors/warnings - // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js - lines = lines.filter(function (line) { - return !/Module [A-z ]+\(from/.test(line); - }); - - // Remove leading newline - if (lines.length > 2 && lines[1].trim() === '') { - lines.splice(1, 1); - } - - // Remove duplicated newlines - lines = lines.filter(function (line, index, arr) { - return index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim(); - }); - - // Clean up the file name - lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1'); - - // Cleans up verbose "module not found" messages for files and packages. - if (lines[1] && lines[1].indexOf('Module not found: ') === 0) { - lines = [ - lines[0], - lines[1] - .replace('Error: ', '') - .replace('Module not found: Cannot find file:', 'Cannot find file:'), - ]; - } - - message = lines.join('\n'); - - // Clean up syntax errors - message = message.replace('SyntaxError:', friendlySyntaxErrorLabel); - - // Internal stacks are generally useless, so we strip them - - // except the stacks containing `webpack:`, - // because they're normally from user code generated by webpack. - message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ''); // at ... ...:x:y - message = message.replace(/^\s*at\s((?!webpack:).)*[\s)]*(\n|$)/gm, ''); // at ... - message = message.replace(/^\s*at\s(\n|$)/gm, ''); // at - - return message.trim(); -} - -/** - * Formats Webpack error messages into a more readable format. - * @param {Array} errors An array of Webpack error messages. - * @returns {string[]} The formatted Webpack error messages. - */ -function formatWebpackErrors(errors) { - let formattedErrors = errors.map(function (errorObjOrMessage) { - // Webpack 5 compilation errors are in the form of descriptor objects, - // so we have to join pieces to get the format we want. - if (typeof errorObjOrMessage === 'object') { - return formatMessage([errorObjOrMessage.moduleName, errorObjOrMessage.message].join('\n')); - } - // Webpack 4 compilation errors are strings - return formatMessage(errorObjOrMessage); - }); - - if (formattedErrors.some(isLikelyASyntaxError)) { - // If there are any syntax errors, show just them. - formattedErrors = formattedErrors.filter(isLikelyASyntaxError); - } - return formattedErrors; -} - -module.exports = formatWebpackErrors; \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/client/utils/retry.js b/packages/rspack-plugin-react-refresh/client/utils/retry.js deleted file mode 100644 index cc2f1c81d476..000000000000 --- a/packages/rspack-plugin-react-refresh/client/utils/retry.js +++ /dev/null @@ -1,23 +0,0 @@ -function runWithRetry(callback, maxRetries) { - function executeWithRetryAndTimeout(currentCount) { - try { - if (currentCount > maxRetries - 1) { - console.warn('[React Refresh] Failed to set up the socket connection.'); - return; - } - - callback(); - } catch (err) { - setTimeout( - function () { - executeWithRetryAndTimeout(currentCount + 1); - }, - Math.pow(10, currentCount) - ); - } - } - - executeWithRetryAndTimeout(0); -} - -module.exports = runWithRetry; \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/etc/api.md b/packages/rspack-plugin-react-refresh/etc/api.md deleted file mode 100644 index bef3592afdeb..000000000000 --- a/packages/rspack-plugin-react-refresh/etc/api.md +++ /dev/null @@ -1,39 +0,0 @@ -## API Report File for "@rspack/plugin-react-refresh" - -> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). - -```ts - -// @public (undocumented) -type IntegrationType = "wds"; - -// @public (undocumented) -interface OverlayOptions { - // (undocumented) - entry: string; - // (undocumented) - module: string; - // (undocumented) - sockHost?: string; - // (undocumented) - sockIntegration: IntegrationType; - // (undocumented) - sockPath?: string; - // (undocumented) - sockPort?: string; - // (undocumented) - sockProtocol?: string; -} - -// @public (undocumented) -export type PluginOptions = { - include?: string | RegExp | (string | RegExp)[] | null; - exclude?: string | RegExp | (string | RegExp)[] | null; - library?: string; - forceEnable?: boolean; - overlay?: boolean | OverlayOptions; -}; - -// (No @packageDocumentation comment for this package) - -``` diff --git a/packages/rspack-plugin-react-refresh/package.json b/packages/rspack-plugin-react-refresh/package.json deleted file mode 100644 index dd9429c5d786..000000000000 --- a/packages/rspack-plugin-react-refresh/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "name": "@rspack/plugin-react-refresh", - "version": "1.0.0-beta.3", - "license": "MIT", - "description": "React refresh plugin for rspack", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "exports": { - ".": { - "default": "./dist/index.js" - }, - "./react-refresh": "./client/reactRefresh.js", - "./react-refresh-entry": "./client/reactRefreshEntry.js", - "./package.json": "./package.json" - }, - "scripts": { - "build": "tsc -b ./tsconfig.build.json", - "dev": "tsc -b -w", - "test": "jest --colors", - "api-extractor": "api-extractor run --verbose", - "api-extractor:ci": "api-extractor run --verbose || diff temp/api.md etc/api.md" - }, - "files": [ - "client", - "dist" - ], - "publishConfig": { - "access": "public", - "provenance": true - }, - "homepage": "https://rspack.dev", - "bugs": "https://github.com/web-infra-dev/rspack/issues", - "repository": { - "type": "git", - "url": "https://github.com/web-infra-dev/rspack", - "directory": "packages/rspack-plugin-react-refresh" - }, - "devDependencies": { - "@rspack/core": "workspace:*", - "@rspack/plugin-react-refresh": "workspace:*", - "react-refresh": "^0.14.0", - "typescript": "5.0.2" - }, - "dependencies": { - "error-stack-parser": "^2.0.6", - "html-entities": "^2.1.0" - }, - "peerDependencies": { - "react-refresh": ">=0.10.0 <1.0.0" - }, - "peerDependenciesMeta": { - "react-refresh": { - "optional": true - } - }, - "jest": { - "watchPathIgnorePatterns": [ - "/dist", - "/tests/dist" - ], - "testEnvironment": "../../scripts/test/patch-node-env.cjs" - } -} \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/src/index.ts b/packages/rspack-plugin-react-refresh/src/index.ts deleted file mode 100644 index da2aa275519d..000000000000 --- a/packages/rspack-plugin-react-refresh/src/index.ts +++ /dev/null @@ -1,122 +0,0 @@ -import path from "node:path"; -import { normalizeOptions } from "./options"; -import { getAdditionalEntries } from "./utils/getAdditionalEntries"; -import { getSocketIntegration } from "./utils/getSocketIntegration"; - -import type { Compiler } from "@rspack/core"; -import type { NormalizedPluginOptions, PluginOptions } from "./options"; - -export type { PluginOptions }; - -const reactRefreshPath = require.resolve("../client/reactRefresh.js"); -const reactRefreshEntryPath = require.resolve("../client/reactRefreshEntry.js"); - -const refreshUtilsPath = require.resolve("../client/refreshUtils.js"); -const refreshRuntimeDirPath = path.dirname( - require.resolve("react-refresh", { - paths: [reactRefreshPath] - }) -); - -const runtimePaths = [ - reactRefreshEntryPath, - reactRefreshPath, - refreshUtilsPath, - refreshRuntimeDirPath -]; - -class ReactRefreshRspackPlugin { - options: NormalizedPluginOptions; - - static deprecated_runtimePaths: string[]; - - constructor(options: PluginOptions = {}) { - this.options = normalizeOptions(options); - } - - apply(compiler: Compiler) { - if ( - // Webpack do not set process.env.NODE_ENV, so we need to check for mode. - // Ref: https://github.com/webpack/webpack/issues/7074 - (compiler.options.mode !== "development" || - // We also check for production process.env.NODE_ENV, - // in case it was set and mode is non-development (e.g. 'none') - (process.env.NODE_ENV && process.env.NODE_ENV === "production")) && - !this.options.forceEnable - ) { - return; - } - const addEntries = getAdditionalEntries({ - devServer: compiler.options.devServer, - options: this.options - }); - - for (const entry of addEntries.prependEntries) { - new compiler.webpack.EntryPlugin(compiler.context, entry, { - name: undefined - }).apply(compiler); - } - - for (const entry of addEntries.overlayEntries) { - new compiler.webpack.EntryPlugin(compiler.context, entry, { - name: undefined - }).apply(compiler); - } - - new compiler.webpack.ProvidePlugin({ - $ReactRefreshRuntime$: reactRefreshPath - }).apply(compiler); - - compiler.options.module.rules.unshift({ - include: this.options.include!, - exclude: { - or: [this.options.exclude!, [...runtimePaths]].filter(Boolean) - }, - use: "builtin:react-refresh-loader" - }); - - const definedModules: any = { - // For Multiple Instance Mode - __react_refresh_library__: JSON.stringify( - compiler.webpack.Template.toIdentifier( - this.options.library || - compiler.options.output.uniqueName || - compiler.options.output.library - ) - ) - }; - const providedModules: any = { - __react_refresh_utils__: refreshUtilsPath - }; - if (this.options.overlay === false) { - // Stub errorOverlay module so their calls can be erased - definedModules.__react_refresh_error_overlay__ = false; - definedModules.__react_refresh_socket__ = false; - } else { - if (this.options.overlay.module) { - providedModules.__react_refresh_error_overlay__ = require.resolve( - this.options.overlay.module - ); - } - - if (this.options.overlay.sockIntegration) { - providedModules.__react_refresh_socket__ = getSocketIntegration( - this.options.overlay.sockIntegration - ); - } - } - new compiler.webpack.DefinePlugin(definedModules).apply(compiler); - new compiler.webpack.ProvidePlugin(providedModules).apply(compiler); - - const refreshPath = path.dirname(require.resolve("react-refresh")); - compiler.options.resolve.alias = { - "react-refresh": refreshPath, - ...compiler.options.resolve.alias - }; - } -} - -ReactRefreshRspackPlugin.deprecated_runtimePaths = runtimePaths; - -// @ts-expect-error output module.exports -export = ReactRefreshRspackPlugin; diff --git a/packages/rspack-plugin-react-refresh/src/options.ts b/packages/rspack-plugin-react-refresh/src/options.ts deleted file mode 100644 index 7273d7f841b7..000000000000 --- a/packages/rspack-plugin-react-refresh/src/options.ts +++ /dev/null @@ -1,68 +0,0 @@ -import type { IntegrationType } from "./utils/getSocketIntegration"; - -interface OverlayOptions { - entry: string; - module: string; - sockIntegration: IntegrationType; - sockHost?: string; - sockPath?: string; - sockPort?: string; - sockProtocol?: string; -} - -export type PluginOptions = { - include?: string | RegExp | (string | RegExp)[] | null; - exclude?: string | RegExp | (string | RegExp)[] | null; - library?: string; - forceEnable?: boolean; - overlay?: boolean | OverlayOptions; -}; - -export interface NormalizedPluginOptions extends Required { - overlay: false | OverlayOptions; -} - -const d = ( - object: PluginOptions, - property: K, - defaultValue?: PluginOptions[K] -) => { - // TODO: should we also add default for null? - if ( - typeof object[property] === "undefined" && - typeof defaultValue !== "undefined" - ) { - object[property] = defaultValue; - } - return object[property]; -}; - -const normalizeOverlay = (options: PluginOptions["overlay"]) => { - const defaultOverlay: OverlayOptions = { - entry: require.resolve("../client/errorOverlayEntry.js"), - module: require.resolve("../client/overlay/index.js"), - sockIntegration: "wds" - }; - if (!options) { - return false; - } - if (typeof options === "undefined" || options === true) { - return defaultOverlay; - } - options.entry = options.entry ?? defaultOverlay.entry; - options.module = options.module ?? defaultOverlay.module; - options.sockIntegration = - options.sockIntegration ?? defaultOverlay.sockIntegration; - return options; -}; - -export function normalizeOptions( - options: PluginOptions -): NormalizedPluginOptions { - d(options, "exclude", /node_modules/i); - d(options, "include", /\.([cm]js|[jt]sx?|flow)$/i); - d(options, "library"); - d(options, "forceEnable", false); - options.overlay = normalizeOverlay(options.overlay); - return options as NormalizedPluginOptions; -} diff --git a/packages/rspack-plugin-react-refresh/src/sockets/WDSSocket.ts b/packages/rspack-plugin-react-refresh/src/sockets/WDSSocket.ts deleted file mode 100644 index d79cd7f880ab..000000000000 --- a/packages/rspack-plugin-react-refresh/src/sockets/WDSSocket.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** - * The following code is modified based on - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/f1c8b9a44198449093ca95f85af5df97925e1cfc/sockets/WDSSocket.js - * - * MIT Licensed - * Author Michael Mok - * Copyright (c) 2019 Michael Mok - * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/0b960573797bf38926937994c481e4fec9ed8aa6/LICENSE - */ -import getSocketUrlParts from "./utils/getSocketUrlParts"; -import getUrlFromParts from "./utils/getUrlFromParts"; -import getWDSMetadata from "./utils/getWDSMetadata"; -import type { SocketClient } from "./utils/getWDSMetadata"; - -declare global { - var __webpack_dev_server_client__: SocketClient | { default: SocketClient }; -} - -/** - * Initializes a socket server for HMR for webpack-dev-server. - * @param messageHandler A handler to consume Webpack compilation messages. - * @param resourceQuery Webpack's `__resourceQuery` string. - * @returns - */ -export function init( - messageHandler: (...args: any[]) => void, - resourceQuery: string -) { - if (typeof __webpack_dev_server_client__ !== "undefined") { - let SocketClient: SocketClient; - - if ("default" in __webpack_dev_server_client__) { - SocketClient = __webpack_dev_server_client__.default; - } else { - SocketClient = __webpack_dev_server_client__; - } - - const wdsMeta = getWDSMetadata(SocketClient); - const urlParts = getSocketUrlParts(resourceQuery, wdsMeta); - - const connection = new SocketClient(getUrlFromParts(urlParts, wdsMeta)); - - connection.onMessage(function onSocketMessage(data) { - const message = JSON.parse(data); - messageHandler(message); - }); - } -} diff --git a/packages/rspack-plugin-react-refresh/src/sockets/utils/getCurrentScriptSource.ts b/packages/rspack-plugin-react-refresh/src/sockets/utils/getCurrentScriptSource.ts deleted file mode 100644 index 0e7232e9d3b9..000000000000 --- a/packages/rspack-plugin-react-refresh/src/sockets/utils/getCurrentScriptSource.ts +++ /dev/null @@ -1,20 +0,0 @@ -export default function getCurrentScriptSource() { - // `document.currentScript` is the most accurate way to get the current running script, - // but is not supported in all browsers (most notably, IE). - if ("currentScript" in document) { - // In some cases, `document.currentScript` would be `null` even if the browser supports it: - // e.g. asynchronous chunks on Firefox. - // We should not fallback to the list-approach as it would not be safe. - if (document.currentScript == null) return; - return document.currentScript.getAttribute("src"); - } - // Fallback to getting all scripts running in the document, - // and finding the last one injected. - const scriptElementsWithSrc: HTMLOrSVGScriptElement[] = - Array.prototype.filter.call((document as Document).scripts || [], elem => - elem.getAttribute("src") - ); - if (!scriptElementsWithSrc.length) return; - const currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1]; - return currentScript.getAttribute("src"); -} diff --git a/packages/rspack-plugin-react-refresh/src/sockets/utils/getSocketUrlParts.ts b/packages/rspack-plugin-react-refresh/src/sockets/utils/getSocketUrlParts.ts deleted file mode 100644 index fb2fefdb6ff3..000000000000 --- a/packages/rspack-plugin-react-refresh/src/sockets/utils/getSocketUrlParts.ts +++ /dev/null @@ -1,137 +0,0 @@ -import getCurrentScriptSource from "./getCurrentScriptSource"; -import type { WDSMetaObj } from "./getWDSMetadata"; -export interface SocketUrlParts { - auth?: string; - hostname: string; - protocol?: string; - pathname: string; - port?: string; -} - -interface ParsedQuery { - sockHost: string; - sockPath: string; - sockPort: string; - sockProtocol?: string; -} - -export default function getSocketUrlParts( - resourceQuery?: string, - metadata: WDSMetaObj = {} -): SocketUrlParts { - const urlParts: SocketUrlParts = {} as SocketUrlParts; - - // If the resource query is available, - // parse it and ignore everything we received from the script host. - if (resourceQuery) { - const parsedQuery: ParsedQuery = {} as ParsedQuery; - const searchParams = new URLSearchParams(resourceQuery.slice(1)); - searchParams.forEach((value, key) => { - parsedQuery[key as keyof ParsedQuery] = value; - }); - - urlParts.hostname = parsedQuery.sockHost; - urlParts.pathname = parsedQuery.sockPath; - urlParts.port = parsedQuery.sockPort; - - // Make sure the protocol from resource query has a trailing colon - if (parsedQuery.sockProtocol) { - urlParts.protocol = `${parsedQuery.sockProtocol}:`; - } - } else { - const scriptSource = getCurrentScriptSource(); - - let url: URL = {} as URL; - try { - // The placeholder `baseURL` with `window.location.href`, - // is to allow parsing of path-relative or protocol-relative URLs, - // and will have no effect if `scriptSource` is a fully valid URL. - url = new URL(scriptSource!, window.location.href); - } catch (e) { - // URL parsing failed, do nothing. - // We will still proceed to see if we can recover using `resourceQuery` - } - - // Parse authentication credentials in case we need them - if (url.username) { - // Since HTTP basic authentication does not allow empty username, - // we only include password if the username is not empty. - // Result: or : - urlParts.auth = url.username; - if (url.password) { - urlParts.auth += `:${url.password}`; - } - } - - // `file://` URLs has `'null'` origin - if (url.origin !== "null") { - urlParts.hostname = url.hostname; - } - - urlParts.protocol = url.protocol; - urlParts.port = url.port; - } - - if (!urlParts.pathname) { - if (metadata.version === 4) { - // This is hard-coded in WDS v4 - urlParts.pathname = "/ws"; - } else { - // This is hard-coded in WDS v3 - urlParts.pathname = "/sockjs-node"; - } - } - - // Check for IPv4 and IPv6 host addresses that correspond to any/empty. - // This is important because `hostname` can be empty for some hosts, - // such as 'about:blank' or 'file://' URLs. - const isEmptyHostname = - urlParts.hostname === "0.0.0.0" || - urlParts.hostname === "[::]" || - !urlParts.hostname; - // We only re-assign the hostname if it is empty, - // and if we are using HTTP/HTTPS protocols. - if ( - isEmptyHostname && - window.location.hostname && - window.location.protocol.indexOf("http") === 0 - ) { - urlParts.hostname = window.location.hostname; - } - - // We only re-assign `protocol` when `protocol` is unavailable, - // or if `hostname` is available and is empty, - // since otherwise we risk creating an invalid URL. - // We also do this when 'https' is used as it mandates the use of secure sockets. - if ( - !urlParts.protocol || - (urlParts.hostname && - (isEmptyHostname || window.location.protocol === "https:")) - ) { - urlParts.protocol = window.location.protocol; - } - - // We only re-assign port when it is not available - if (!urlParts.port) { - urlParts.port = window.location.port; - } - - if (!urlParts.hostname || !urlParts.pathname) { - throw new Error( - [ - "[React Refresh] Failed to get an URL for the socket connection.", - "This usually means that the current executed script doesn't have a `src` attribute set.", - "You should either specify the socket path parameters under the `devServer` key in your Rspack config, or use the `overlay` option.", - "https://www.rspack.dev/guide/tech/react#fast-refresh" - ].join("\n") - ); - } - - return { - auth: urlParts.auth, - hostname: urlParts.hostname, - pathname: urlParts.pathname, - protocol: urlParts.protocol, - port: urlParts.port || undefined - }; -} diff --git a/packages/rspack-plugin-react-refresh/src/sockets/utils/getUrlFromParts.ts b/packages/rspack-plugin-react-refresh/src/sockets/utils/getUrlFromParts.ts deleted file mode 100644 index 8b0f7bc8c04e..000000000000 --- a/packages/rspack-plugin-react-refresh/src/sockets/utils/getUrlFromParts.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { SocketUrlParts } from "./getSocketUrlParts"; -import type { WDSMetaObj } from "./getWDSMetadata"; - -/** - * Create a valid URL from parsed URL parts. - * @param urlParts The parsed URL parts. - * @param metadata The parsed WDS metadata object. - * @returns The generated URL. - */ -export default function urlFromParts( - urlParts: SocketUrlParts, - metadata: WDSMetaObj = {} -): string { - let fullProtocol = "http:"; - if (urlParts.protocol) { - fullProtocol = urlParts.protocol; - } - if (metadata.enforceWs) { - fullProtocol = fullProtocol.replace(/^(?:http|.+-extension|file)/i, "ws"); - } - - fullProtocol = `${fullProtocol}//`; - - let fullHost = urlParts.hostname; - if (urlParts.auth) { - const fullAuth = `${urlParts.auth.split(":").map(encodeURIComponent).join(":")}@`; - fullHost = fullAuth + fullHost; - } - if (urlParts.port) { - fullHost = `${fullHost}:${urlParts.port}`; - } - - const url = new URL(urlParts.pathname, fullProtocol + fullHost); - return url.href; -} diff --git a/packages/rspack-plugin-react-refresh/src/sockets/utils/getWDSMetadata.ts b/packages/rspack-plugin-react-refresh/src/sockets/utils/getWDSMetadata.ts deleted file mode 100644 index b7cd6cfd593a..000000000000 --- a/packages/rspack-plugin-react-refresh/src/sockets/utils/getWDSMetadata.ts +++ /dev/null @@ -1,52 +0,0 @@ -export interface WDSMetaObj { - enforceWs?: boolean; - version?: number; -} - -declare class WebSocketClient { - public client: WebSocket; - - constructor(url: string); - - onOpen(f: (...args: any[]) => void): void; - - onClose(f: (...args: any[]) => void): void; - - onMessage(f: (...args: any[]) => void): void; -} - -export interface SocketClient { - new (url: string): WebSocketClient; -} - -export default function getWDSMetadata(SocketClient: SocketClient): WDSMetaObj { - let enforceWs = false; - if ( - typeof SocketClient.name !== "undefined" && - SocketClient.name !== null && - SocketClient.name.toLowerCase().includes("websocket") - ) { - enforceWs = true; - } - - let version; - // WDS versions <=3.5.0 - if (!("onMessage" in SocketClient.prototype)) { - version = 3; - } else { - // WDS versions >=3.5.0 <4 - if ( - "getClientPath" in SocketClient || - Object.getPrototypeOf(SocketClient).name === "BaseClient" - ) { - version = 3; - } else { - version = 4; - } - } - - return { - enforceWs: enforceWs, - version: version - }; -} diff --git a/packages/rspack-plugin-react-refresh/src/utils/getAdditionalEntries.ts b/packages/rspack-plugin-react-refresh/src/utils/getAdditionalEntries.ts deleted file mode 100644 index 15ccb3271326..000000000000 --- a/packages/rspack-plugin-react-refresh/src/utils/getAdditionalEntries.ts +++ /dev/null @@ -1,99 +0,0 @@ -import querystring from "node:querystring"; -import type { NormalizedPluginOptions } from "../options"; - -export interface AdditionalEntries { - prependEntries: string[]; - overlayEntries: string[]; -} - -export function getAdditionalEntries({ - devServer, - options -}: { - devServer: any; - options: NormalizedPluginOptions; -}): AdditionalEntries { - const resourceQuery: Record = {}; - - if (devServer) { - const { client, https, http2, sockHost, sockPath, sockPort } = devServer; - let { host, path, port } = devServer; - - let protocol = https || http2 ? "https" : "http"; - if (sockHost) host = sockHost; - if (sockPath) path = sockPath; - if (sockPort) port = sockPort; - - if (client && client.webSocketURL != null) { - let parsedUrl = client.webSocketURL; - if (typeof parsedUrl === "string") parsedUrl = new URL(parsedUrl); - - let auth; - if (parsedUrl.username) { - auth = parsedUrl.username; - if (parsedUrl.password) { - auth += `:${parsedUrl.password}`; - } - } - - if (parsedUrl.hostname != null) { - host = [auth != null && auth, parsedUrl.hostname] - .filter(Boolean) - .join("@"); - } - if (parsedUrl.pathname != null) { - path = parsedUrl.pathname; - } - if (parsedUrl.port != null) { - port = !["0", "auto"].includes(String(parsedUrl.port)) - ? parsedUrl.port - : undefined; - } - if (parsedUrl.protocol != null) { - protocol = - parsedUrl.protocol !== "auto" - ? parsedUrl.protocol.replace(":", "") - : "ws"; - } - } - - if (host) resourceQuery.sockHost = host; - if (path) resourceQuery.sockPath = path; - if (port) resourceQuery.sockPort = port; - resourceQuery.sockProtocol = protocol; - } - - if (options.overlay) { - const { sockHost, sockPath, sockPort, sockProtocol } = options.overlay; - if (sockHost) resourceQuery.sockHost = sockHost; - if (sockPath) resourceQuery.sockPath = sockPath; - if (sockPort) resourceQuery.sockPort = sockPort; - if (sockProtocol) resourceQuery.sockProtocol = sockProtocol; - } - - // We don't need to URI encode the resourceQuery as it will be parsed by Webpack - const queryString = querystring.stringify( - resourceQuery, - undefined, - undefined, - { - encodeURIComponent(str: string): string { - return str; - } - } - ); - - const prependEntries = [ - // React-refresh runtime - require.resolve("../../client/reactRefreshEntry") - ]; - - const overlayEntries = [ - // Error overlay runtime - options.overlay !== false && - options.overlay?.entry && - `${require.resolve(options.overlay.entry)}${queryString ? `?${queryString}` : ""}` - ].filter(Boolean) as string[]; - - return { prependEntries, overlayEntries }; -} diff --git a/packages/rspack-plugin-react-refresh/src/utils/getSocketIntegration.ts b/packages/rspack-plugin-react-refresh/src/utils/getSocketIntegration.ts deleted file mode 100644 index a596e5663ea7..000000000000 --- a/packages/rspack-plugin-react-refresh/src/utils/getSocketIntegration.ts +++ /dev/null @@ -1,17 +0,0 @@ -export type IntegrationType = "wds"; - -export function getSocketIntegration(integrationType: IntegrationType) { - let resolvedSocketIntegration; - switch (integrationType) { - case "wds": { - resolvedSocketIntegration = require.resolve("../sockets/WDSSocket"); - break; - } - default: { - resolvedSocketIntegration = require.resolve(integrationType); - break; - } - } - - return resolvedSocketIntegration; -} diff --git a/packages/rspack-plugin-react-refresh/tests/fixtures/.gitignore b/packages/rspack-plugin-react-refresh/tests/fixtures/.gitignore deleted file mode 100644 index 736e8ae58ad8..000000000000 --- a/packages/rspack-plugin-react-refresh/tests/fixtures/.gitignore +++ /dev/null @@ -1 +0,0 @@ -!node_modules \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/tests/fixtures/custom/index.js b/packages/rspack-plugin-react-refresh/tests/fixtures/custom/index.js deleted file mode 100644 index 347e2083214b..000000000000 --- a/packages/rspack-plugin-react-refresh/tests/fixtures/custom/index.js +++ /dev/null @@ -1 +0,0 @@ -require("foo"); diff --git a/packages/rspack-plugin-react-refresh/tests/fixtures/default/index.js b/packages/rspack-plugin-react-refresh/tests/fixtures/default/index.js deleted file mode 100644 index 5882cb5bbc55..000000000000 --- a/packages/rspack-plugin-react-refresh/tests/fixtures/default/index.js +++ /dev/null @@ -1,2 +0,0 @@ -require("foo"); -module.exports = "default"; diff --git a/packages/rspack-plugin-react-refresh/tests/fixtures/node_modules/foo/index.js b/packages/rspack-plugin-react-refresh/tests/fixtures/node_modules/foo/index.js deleted file mode 100644 index 539eee6809ae..000000000000 --- a/packages/rspack-plugin-react-refresh/tests/fixtures/node_modules/foo/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = "foo" diff --git a/packages/rspack-plugin-react-refresh/tests/fixtures/node_modules/foo/package.json b/packages/rspack-plugin-react-refresh/tests/fixtures/node_modules/foo/package.json deleted file mode 100644 index 9035eef7f7ad..000000000000 --- a/packages/rspack-plugin-react-refresh/tests/fixtures/node_modules/foo/package.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "foo", - "main": "./index.js" -} \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/tests/test.spec.ts b/packages/rspack-plugin-react-refresh/tests/test.spec.ts deleted file mode 100644 index fe06e8c06af2..000000000000 --- a/packages/rspack-plugin-react-refresh/tests/test.spec.ts +++ /dev/null @@ -1,144 +0,0 @@ -const fs = require("fs"); -const path = require("path"); -const { rspack } = require("@rspack/core"); -const ReactRefreshPlugin = require("@rspack/plugin-react-refresh"); - -const uniqueName = "ReactRefreshLibrary"; -const compileWithReactRefresh = (fixturePath, refreshOptions, callback) => { - let dist = path.join(fixturePath, "dist"); - rspack( - { - mode: "development", - context: fixturePath, - entry: { - fixture: path.join(fixturePath, "index.js") - }, - output: { - path: dist, - uniqueName - }, - plugins: [new ReactRefreshPlugin(refreshOptions)], - optimization: { - runtimeChunk: { - name: "runtime" - }, - splitChunks: { - cacheGroups: { - reactRefresh: { - test: /[\\/](react-refresh|rspack-plugin-react-refresh\/client|react-refresh-webpack-plugin)[\\/]/, - name: "react-refresh", - chunks: "all", - priority: -1000 - }, - foo: { - test: /[\\/]node_modules[\\/]foo/, - name: "vendor", - chunks: "all", - priority: -500, - enforce: true - } - } - } - } - }, - (error, stats) => { - expect(error).toBeFalsy(); - const statsJson = stats.toJson({ all: true }); - expect(statsJson.errors).toHaveLength(0); - expect(statsJson.warnings).toHaveLength(0); - callback(error, stats, { - reactRefresh: fs.readFileSync( - path.join(fixturePath, "dist", "react-refresh.js"), - "utf-8" - ), - fixture: fs.readFileSync( - path.join(fixturePath, "dist", "fixture.js"), - "utf-8" - ), - runtime: fs.readFileSync( - path.join(fixturePath, "dist", "runtime.js"), - "utf-8" - ), - vendor: fs.readFileSync( - path.join(fixturePath, "dist", "vendor.js"), - "utf-8" - ) - }); - } - ); -}; - -describe("react-refresh-rspack-plugin", () => { - it("should exclude node_modules when compiling with default options", done => { - compileWithReactRefresh( - path.join(__dirname, "fixtures/default"), - {}, - (_, __, { reactRefresh, fixture, runtime, vendor }) => { - expect(vendor).not.toContain("function $RefreshReg$"); - done(); - } - ); - }); - - it("should include non node_modules when compiling with default options", done => { - compileWithReactRefresh( - path.join(__dirname, "fixtures/default"), - {}, - (_, __, { reactRefresh, fixture, runtime, vendor }) => { - expect(fixture).toContain("function $RefreshReg$"); - done(); - } - ); - }); - - it("should add library to make sure work in Micro-Frontend", done => { - compileWithReactRefresh( - path.join(__dirname, "fixtures/default"), - {}, - (_, __, { reactRefresh, fixture, runtime, vendor }) => { - expect(reactRefresh).toContain(uniqueName); - done(); - } - ); - }); - - it("should include selected file when compiling", done => { - compileWithReactRefresh( - path.join(__dirname, "fixtures/custom"), - { - exclude: null, - include: path.join(__dirname, "fixtures/node_modules/foo") - }, - (_, __, { reactRefresh, fixture, runtime, vendor }) => { - expect(vendor).toContain("function $RefreshReg$"); - done(); - } - ); - }); - - it("should exclude selected file when compiling", done => { - compileWithReactRefresh( - path.join(__dirname, "fixtures/custom"), - { - exclude: path.join(__dirname, "fixtures/custom/index.js") - }, - (_, __, { reactRefresh, fixture, runtime, vendor }) => { - expect(fixture).not.toContain("function $RefreshReg$"); - done(); - } - ); - }); - - it("should always exclude react-refresh related modules", done => { - compileWithReactRefresh( - path.join(__dirname, "fixtures/custom"), - { - exclude: null - }, - (_, __, { reactRefresh, fixture, runtime, vendor }) => { - expect(reactRefresh).not.toContain("function $RefreshReg$"); - done(); - } - ); - }); -}); diff --git a/packages/rspack-plugin-react-refresh/tsconfig.build.json b/packages/rspack-plugin-react-refresh/tsconfig.build.json deleted file mode 100644 index 418e82591500..000000000000 --- a/packages/rspack-plugin-react-refresh/tsconfig.build.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "sourceMap": false, - "declarationMap": false - }, - "references": [ - { - "path": "../rspack/tsconfig.build.json" - } - ] -} \ No newline at end of file diff --git a/packages/rspack-plugin-react-refresh/tsconfig.json b/packages/rspack-plugin-react-refresh/tsconfig.json deleted file mode 100644 index fe06cc39adc6..000000000000 --- a/packages/rspack-plugin-react-refresh/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "dist", - "rootDir": "src" - }, - "include": ["src"], - "references": [ - { - "path": "../rspack" - } - ] -} diff --git a/packages/rspack-test-tools/tests/errorCases/error-test-push.js b/packages/rspack-test-tools/tests/errorCases/error-test-push.js index 11524261882d..f690355fe46f 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-test-push.js +++ b/packages/rspack-test-tools/tests/errorCases/error-test-push.js @@ -20,7 +20,7 @@ module.exports = { Object { "message": " × Error: test push\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n", "moduleTrace": Array [], - "stack": "Error: test push\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/error-test-push.js:10:31)\\n at next (packages/rspack-lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (packages/rspack-lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (packages/rspack-lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", + "stack": "Error: test push\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/error-test-push.js:10:31)\\n at next (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", }, Object { "loc": "1:0-33", diff --git a/packages/rspack-test-tools/tests/errorCases/error-test-shift.js b/packages/rspack-test-tools/tests/errorCases/error-test-shift.js index a91b479d615f..504fa88f9e2d 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-test-shift.js +++ b/packages/rspack-test-tools/tests/errorCases/error-test-shift.js @@ -24,7 +24,7 @@ module.exports = { Object { "message": " × Error: test unshift\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n", "moduleTrace": Array [], - "stack": "Error: test unshift\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/error-test-shift.js:13:35)\\n at next (packages/rspack-lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (packages/rspack-lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (packages/rspack-lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", + "stack": "Error: test unshift\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/error-test-shift.js:13:35)\\n at next (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", }, ], "warnings": Array [], diff --git a/packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js b/packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js index 21e5b14f68ff..a12fd57ef079 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js +++ b/packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js @@ -20,7 +20,7 @@ module.exports = { Object { "message": " × Error: test splice\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n", "moduleTrace": Array [], - "stack": "Error: test splice\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js:10:39)\\n at next (packages/rspack-lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (packages/rspack-lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (packages/rspack-lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", + "stack": "Error: test splice\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js:10:39)\\n at next (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", }, ], "warnings": Array [], diff --git a/packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js b/packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js index 8d6b5a15f2b9..25940a01e318 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js +++ b/packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js @@ -20,7 +20,7 @@ module.exports = { Object { "message": " × Error: test splice\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n", "moduleTrace": Array [], - "stack": "Error: test splice\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js:10:39)\\n at next (packages/rspack-lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (packages/rspack-lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (packages/rspack-lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", + "stack": "Error: test splice\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js:10:39)\\n at next (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", }, Object { "loc": "1:0-33", diff --git a/packages/rspack-test-tools/tests/errorCases/warning-test-push.js b/packages/rspack-test-tools/tests/errorCases/warning-test-push.js index 4a2bb4a6fb00..d52d720aba77 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-test-push.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-test-push.js @@ -21,7 +21,7 @@ module.exports = { Object { "message": " ⚠ Error: test push\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n", "moduleTrace": Array [], - "stack": "Error: test push\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/warning-test-push.js:10:33)\\n at next (packages/rspack-lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (packages/rspack-lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (packages/rspack-lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", + "stack": "Error: test push\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/warning-test-push.js:10:33)\\n at next (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", }, Object { "message": " ⚠ Module parse warning:\\n ╰─▶ ⚠ Unsupported feature: require.main.require() is not supported by Rspack.\\n ╭────\\n 1 │ require.main.require('./file');\\n · ──────────────────────────────\\n ╰────\\n \\n", diff --git a/packages/rspack-test-tools/tests/errorCases/warning-test-shift.js b/packages/rspack-test-tools/tests/errorCases/warning-test-shift.js index fdadf70b0f24..70db5957243d 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-test-shift.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-test-shift.js @@ -25,7 +25,7 @@ module.exports = { Object { "message": " ⚠ Error: test unshift\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n", "moduleTrace": Array [], - "stack": "Error: test unshift\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/warning-test-shift.js:13:37)\\n at next (packages/rspack-lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (packages/rspack-lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (packages/rspack-lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", + "stack": "Error: test unshift\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/warning-test-shift.js:13:37)\\n at next (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", }, ], } diff --git a/packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js b/packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js index 5d827557213b..28a1b25d888a 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js @@ -21,7 +21,7 @@ module.exports = { Object { "message": " ⚠ Error: test splice\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n", "moduleTrace": Array [], - "stack": "Error: test splice\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js:10:41)\\n at next (packages/rspack-lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (packages/rspack-lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (packages/rspack-lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", + "stack": "Error: test splice\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js:10:41)\\n at next (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", }, ], } diff --git a/packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js b/packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js index fd893dda2336..c8dbfb245607 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js @@ -21,7 +21,7 @@ module.exports = { Object { "message": " ⚠ Error: test splice\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n │ at xxx\\n", "moduleTrace": Array [], - "stack": "Error: test splice\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js:10:41)\\n at next (packages/rspack-lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (packages/rspack-lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (packages/rspack-lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", + "stack": "Error: test splice\\n at Object.fn (packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js:10:41)\\n at next (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:523:25)\\n at AsyncSeriesHook.callAsyncStageRange (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:543:9)\\n at AsyncSeriesHook.callAsync (node_modules/.pnpm/@rspack+lite-tapable@1.0.0-beta.5/node_modules/@rspack/lite-tapable/dist/index.js:82:21)\\n at packages/rspack/dist/Compiler.js:462:41\\n at packages/rspack/dist/Compiler.js:529:23", }, Object { "message": " ⚠ Module parse warning:\\n ╰─▶ ⚠ Unsupported feature: require.main.require() is not supported by Rspack.\\n ╭────\\n 1 │ require.main.require('./file');\\n · ──────────────────────────────\\n ╰────\\n \\n", diff --git a/packages/rspack/package.json b/packages/rspack/package.json index dda613e0b5f2..af2b67f8a28c 100644 --- a/packages/rspack/package.json +++ b/packages/rspack/package.json @@ -69,7 +69,7 @@ "dependencies": { "@module-federation/runtime-tools": "0.2.3", "@rspack/binding": "workspace:*", - "@rspack/lite-tapable": "workspace:*", + "@rspack/lite-tapable": "1.0.0-beta.5", "caniuse-lite": "^1.0.30001616" }, "peerDependencies": { diff --git a/packages/rspack/tsconfig.build.json b/packages/rspack/tsconfig.build.json index d9abe1c28e07..ee3506c4470d 100644 --- a/packages/rspack/tsconfig.build.json +++ b/packages/rspack/tsconfig.build.json @@ -3,10 +3,5 @@ "compilerOptions": { "sourceMap": false, "declarationMap": false, - }, - "references": [ - { - "path": "../rspack-lite-tapable/tsconfig.build.json" - } - ] -} + } +} \ No newline at end of file diff --git a/packages/rspack/tsconfig.json b/packages/rspack/tsconfig.json index 72014bd8dc43..06fa41550826 100644 --- a/packages/rspack/tsconfig.json +++ b/packages/rspack/tsconfig.json @@ -5,30 +5,47 @@ "rootDir": "src", "resolveJsonModule": true, "paths": { - "zod": ["../compiled/zod"], - "neo-async": ["../compiled/neo-async"], - "watchpack": ["../compiled/watchpack"], - "graceful-fs": ["../compiled/graceful-fs"], - "browserslist": ["../compiled/browserslist"], - "enhanced-resolve": ["../compiled/enhanced-resolve"], + "zod": [ + "../compiled/zod" + ], + "neo-async": [ + "../compiled/neo-async" + ], + "watchpack": [ + "../compiled/watchpack" + ], + "graceful-fs": [ + "../compiled/graceful-fs" + ], + "browserslist": [ + "../compiled/browserslist" + ], + "enhanced-resolve": [ + "../compiled/enhanced-resolve" + ], "enhanced-resolve/lib/CachedInputFileSystem": [ "../compiled/enhanced-resolve/CachedInputFileSystem" ], - "zod-validation-error": ["../compiled/zod-validation-error"], + "zod-validation-error": [ + "../compiled/zod-validation-error" + ], "json-parse-even-better-errors": [ "../compiled/json-parse-even-better-errors" ], - "webpack-sources": ["../compiled/webpack-sources"] + "webpack-sources": [ + "../compiled/webpack-sources" + ] } }, - "include": ["src", "src/**/*.json"], - "exclude": ["src/config/schema.check.js", "src/container/default.runtime.js"], + "include": [ + "src", + "src/**/*.json" + ], + "exclude": [ + "src/config/schema.check.js", + "src/container/default.runtime.js" + ], "ts-node": { "transpileOnly": true - }, - "references": [ - { - "path": "../rspack-lite-tapable" - } - ] -} + } +} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 339a014da553..e7166cbd8c72 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -151,8 +151,8 @@ importers: specifier: workspace:* version: link:../../rspack '@rspack/plugin-react-refresh': - specifier: workspace:* - version: link:../../rspack-plugin-react-refresh + specifier: 1.0.0-beta.5 + version: 1.0.0-beta.5(react-refresh@0.14.0) '@types/react': specifier: ^18.2.48 version: 18.2.75 @@ -182,8 +182,8 @@ importers: specifier: workspace:* version: link:../../rspack '@rspack/plugin-react-refresh': - specifier: workspace:* - version: link:../../rspack-plugin-react-refresh + specifier: 1.0.0-beta.5 + version: 1.0.0-beta.5(react-refresh@0.14.0) '@types/react': specifier: ^18.2.48 version: 18.2.75 @@ -295,8 +295,8 @@ importers: specifier: workspace:* version: link:../rspack-dev-server '@rspack/plugin-react-refresh': - specifier: workspace:* - version: link:../rspack-plugin-react-refresh + specifier: 1.0.0-beta.5 + version: 1.0.0-beta.5(react-refresh@0.14.0) '@swc/helpers': specifier: 0.5.8 version: 0.5.8 @@ -358,8 +358,8 @@ importers: specifier: workspace:* version: link:../../crates/node_binding '@rspack/lite-tapable': - specifier: workspace:* - version: link:../rspack-lite-tapable + specifier: 1.0.0-beta.5 + version: 1.0.0-beta.5 '@swc/helpers': specifier: '>=0.5.1' version: 0.5.8 @@ -526,8 +526,8 @@ importers: specifier: workspace:* version: 'link:' '@rspack/plugin-react-refresh': - specifier: workspace:* - version: link:../rspack-plugin-react-refresh + specifier: 1.0.0-beta.5 + version: 1.0.0-beta.5(react-refresh@0.14.0) '@types/connect-history-api-fallback': specifier: 1.5.4 version: 1.5.4 @@ -547,61 +547,6 @@ importers: specifier: 5.0.2 version: 5.0.2 - packages/rspack-lite-tapable: - devDependencies: - typescript: - specifier: 5.0.2 - version: 5.0.2 - - packages/rspack-plugin-preact-refresh: - devDependencies: - '@prefresh/core': - specifier: ^1.5.0 - version: 1.5.2(preact@10.22.0) - '@prefresh/utils': - specifier: ^1.2.0 - version: 1.2.0 - '@rspack/core': - specifier: workspace:* - version: link:../rspack - '@rspack/test-tools': - specifier: workspace:* - version: link:../rspack-test-tools - '@swc/helpers': - specifier: 0.5.8 - version: 0.5.8 - '@swc/plugin-prefresh': - specifier: ^2.0.8 - version: 2.0.8 - preact: - specifier: ^10.15.1 - version: 10.22.0 - typescript: - specifier: 5.0.2 - version: 5.0.2 - - packages/rspack-plugin-react-refresh: - dependencies: - error-stack-parser: - specifier: ^2.0.6 - version: 2.1.4 - html-entities: - specifier: ^2.1.0 - version: 2.5.2 - devDependencies: - '@rspack/core': - specifier: workspace:* - version: link:../rspack - '@rspack/plugin-react-refresh': - specifier: workspace:* - version: 'link:' - react-refresh: - specifier: ^0.14.0 - version: 0.14.0 - typescript: - specifier: 5.0.2 - version: 5.0.2 - packages/rspack-test-tools: dependencies: '@babel/generator': @@ -922,8 +867,8 @@ importers: specifier: workspace:* version: link:../../../packages/rspack '@rspack/plugin-react-refresh': - specifier: workspace:* - version: link:../../../packages/rspack-plugin-react-refresh + specifier: 1.0.0-beta.5 + version: 1.0.0-beta.5(react-refresh@0.14.0) '@svgr/webpack': specifier: ^8.0.0 version: 8.1.0(typescript@5.4.2) @@ -2788,14 +2733,6 @@ packages: '@polka/url@1.0.0-next.25': resolution: {integrity: sha512-j7P6Rgr3mmtdkeDGTe0E/aYyWEWVtc5yFXtHCRHs28/jptDEWfaVOc5T7cblqy1XKPPfCxJc/8DwQ5YgLOZOVQ==} - '@prefresh/core@1.5.2': - resolution: {integrity: sha512-A/08vkaM1FogrCII5PZKCrygxSsc11obExBScm3JF1CryK2uDS3ZXeni7FeKCx1nYdUkj4UcJxzPzc1WliMzZA==} - peerDependencies: - preact: ^10.0.0 - - '@prefresh/utils@1.2.0': - resolution: {integrity: sha512-KtC/fZw+oqtwOLUFM9UtiitB0JsVX0zLKNyRTA332sqREqSALIIQQxdUCS1P3xR/jT1e2e8/5rwH6gdcMLEmsQ==} - '@rollup/rollup-android-arm-eabi@4.17.2': resolution: {integrity: sha512-NM0jFxY8bB8QLkoKxIQeObCaDlJKewVlIEkuyYKm5An1tdVZ966w2+MPQ2l8LBZLjR+SgyV+nRkTIunzOYBMLQ==} cpu: [arm] @@ -2876,6 +2813,18 @@ packages: cpu: [x64] os: [win32] + '@rspack/lite-tapable@1.0.0-beta.5': + resolution: {integrity: sha512-jTmLhUeZgR3u+cHp5Z46FuTWUg+6VWWwbWkIzgVvQoN7YK9ntFfm7k5+cImTEQ0qe1r6P43uV0qD606SoZspKg==} + engines: {node: '>=16.0.0'} + + '@rspack/plugin-react-refresh@1.0.0-beta.5': + resolution: {integrity: sha512-7pP8OBOkGa/D/ZnkXI7/atWIc5QJDlLHju/qpPGaomdE+Ut0qSzpW6Loya63CDwB0Ok8AQUGe1GsnbsRNset6w==} + peerDependencies: + react-refresh: '>=0.10.0 <1.0.0' + peerDependenciesMeta: + react-refresh: + optional: true + '@rushstack/node-core-library@4.1.0': resolution: {integrity: sha512-qz4JFBZJCf1YN5cAXa1dP6Mki/HrsQxc/oYGAGx29dF2cwF2YMxHoly0FBhMw3IEnxo5fMj0boVfoHVBkpkx/w==} peerDependencies: @@ -3075,9 +3024,6 @@ packages: '@swc/helpers@0.5.8': resolution: {integrity: sha512-lruDGw3pnfM3wmZHeW7JuhkGQaJjPyiKjxeGhdmfoOT53Ic9qb5JLDNaK2HUdl1zLDeX28H221UvKjfdvSLVMg==} - '@swc/plugin-prefresh@2.0.8': - resolution: {integrity: sha512-u/fKPR+ofEefjg6auJorh1Esd4/YuNXkS0AymFAERnf9ifHoP9sKYhx59CvbfRNEgmv7PHs3ndOiewnNInN8vg==} - '@swc/plugin-remove-console@2.0.8': resolution: {integrity: sha512-9Yctl9zb2r41Lnz50k1A1HXipt0uP4vl9DtStyUk6llVd6qx5cvOjtVzaJUUAlh9J+F6AIKbQr3MbRk8ub7Pew==} @@ -7394,9 +7340,6 @@ packages: resolution: {integrity: sha512-Wglpdk03BSfXkHoQa3b/oulrotAkwrlLDRSOb9D0bN86FdRyE9lppSp33aHNPgBa0JKCoB+drFLZkQoRRYae5A==} engines: {node: ^10 || ^12 || >=14} - preact@10.22.0: - resolution: {integrity: sha512-RRurnSjJPj4rp5K6XoP45Ui33ncb7e4H7WiOHVpjbkvqvA3U+N8Z6Qbo0AE6leGYBV66n8EhEaFixvIu3SkxFw==} - prebundle@1.1.0: resolution: {integrity: sha512-yTfRjx0+xiveeb7kO77OcODVB8RSHMKIiVl/qferU7ZHw4Y8pycXkCAtPDViF8YDo0a8ViDpm4C1O9PFKCw1ig==} hasBin: true @@ -11470,12 +11413,6 @@ snapshots: '@polka/url@1.0.0-next.25': {} - '@prefresh/core@1.5.2(preact@10.22.0)': - dependencies: - preact: 10.22.0 - - '@prefresh/utils@1.2.0': {} - '@rollup/rollup-android-arm-eabi@4.17.2': optional: true @@ -11524,6 +11461,15 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.17.2': optional: true + '@rspack/lite-tapable@1.0.0-beta.5': {} + + '@rspack/plugin-react-refresh@1.0.0-beta.5(react-refresh@0.14.0)': + dependencies: + error-stack-parser: 2.1.4 + html-entities: 2.5.2 + optionalDependencies: + react-refresh: 0.14.0 + '@rushstack/node-core-library@4.1.0(@types/node@20.12.7)': dependencies: fs-extra: 7.0.1 @@ -11766,10 +11712,6 @@ snapshots: dependencies: tslib: 2.6.2 - '@swc/plugin-prefresh@2.0.8': - dependencies: - '@swc/counter': 0.1.3 - '@swc/plugin-remove-console@2.0.8': dependencies: '@swc/counter': 0.1.3 @@ -17308,8 +17250,6 @@ snapshots: picocolors: 1.0.0 source-map-js: 1.2.0 - preact@10.22.0: {} - prebundle@1.1.0(typescript@5.0.2): dependencies: '@vercel/ncc': 0.38.1 diff --git a/tests/diff-test/arco-pro/package.json b/tests/diff-test/arco-pro/package.json index 6e4fa23f7880..8524a6b102c3 100644 --- a/tests/diff-test/arco-pro/package.json +++ b/tests/diff-test/arco-pro/package.json @@ -38,7 +38,7 @@ }, "devDependencies": { "@rspack/core": "workspace:*", - "@rspack/plugin-react-refresh": "workspace:*", + "@rspack/plugin-react-refresh": "1.0.0-beta.5", "@svgr/webpack": "^8.0.0", "@swc/core": "1.4.0", "@swc/helpers": "0.5.8", diff --git a/website/docs/en/guide/tech/preact.mdx b/website/docs/en/guide/tech/preact.mdx index ea225de5cb3b..8b0de9eb34e3 100644 --- a/website/docs/en/guide/tech/preact.mdx +++ b/website/docs/en/guide/tech/preact.mdx @@ -76,7 +76,7 @@ First you need to install the dependencies: The enabling of the [Preact Refresh](https://github.com/preactjs/prefresh) is divided into two parts: code injection and code transformation -- Code injection: injects code that interacts with `@prefresh/core` and `@prefresh/utils`, which has been integrated in the [@rspack/plugin-preact-refresh](https://github.com/web-infra-dev/rspack/tree/main/packages/rspack-plugin-preact-refresh) plugin +- Code injection: injects code that interacts with `@prefresh/core` and `@prefresh/utils`, which has been integrated in the [@rspack/plugin-preact-refresh](https://github.com/rspack-contrib/rspack-plugin-preact-refresh) plugin - Code transformation requires a loader - Use `builtin:swc-loader` or [`swc-loader`](https://swc.rs/docs/usage/swc-loader) - Enable `jsc.transform.react.refresh` to support common react transformation diff --git a/website/docs/en/guide/tech/react.mdx b/website/docs/en/guide/tech/react.mdx index 8e824ef06dcd..6e1e3fc67a6d 100644 --- a/website/docs/en/guide/tech/react.mdx +++ b/website/docs/en/guide/tech/react.mdx @@ -69,7 +69,7 @@ First you need to install [@rspack/plugin-react-refresh](https://www.npmjs.com/p Enabling [React Fast Refresh](https://reactnative.dev/docs/fast-refresh) functionality primarily involves two aspects: code injection and code transformation. -- Code injection will inject some code from the `react-refresh` package, as well as some custom runtime code, all of which are integrated in the [@rspack/plugin-react-refresh](https://github.com/web-infra-dev/rspack/tree/main/packages/rspack-plugin-react-refresh) plugin and can be injected through this plugin. +- Code injection will inject some code from the `react-refresh` package, as well as some custom runtime code, all of which are integrated in the [@rspack/plugin-react-refresh](https://github.com/rspack-contrib/rspack-plugin-react-refresh) plugin and can be injected through this plugin. - Code transformation can be added through loaders, such as [jsc.transform.react.refresh](https://swc.rs/docs/configuration/compilation#jsctransformreactrefresh) for swc-loader or the [react-refresh/babel](https://github.com/facebook/react/tree/main/packages/react-refresh) for babel-loader. ```js title=rspack.config.js diff --git a/website/docs/zh/guide/tech/preact.mdx b/website/docs/zh/guide/tech/preact.mdx index 3fa739b94d48..b9e50338c21b 100644 --- a/website/docs/zh/guide/tech/preact.mdx +++ b/website/docs/zh/guide/tech/preact.mdx @@ -76,7 +76,7 @@ module.exports = { [Preact Refresh](https://github.com/preactjs/prefresh) 功能的开启主要分为两部分:代码注入和代码转换 -- 代码注入:指注入与 `@prefresh/core` 和 `@prefresh/utils` 交互的代码,都已集成在 [@rspack/plugin-preact-refresh](https://github.com/web-infra-dev/rspack/tree/main/packages/rspack-plugin-preact-refresh) 插件中,可通过该插件实现 +- 代码注入:指注入与 `@prefresh/core` 和 `@prefresh/utils` 交互的代码,都已集成在 [@rspack/plugin-preact-refresh](https://github.com/rspack-contrib/rspack-plugin-preact-refresh) 插件中,可通过该插件实现 - 代码转换需要通过 loader 来完成: - 使用 `builtin:swc-loader` 或 [`swc-loader`](https://swc.rs/docs/usage/swc-loader) - 开启 `jsc.transform.react.refresh` 以支持通用的 react 转换 diff --git a/website/docs/zh/guide/tech/react.mdx b/website/docs/zh/guide/tech/react.mdx index 11df8a5f3eca..6e756f12428b 100644 --- a/website/docs/zh/guide/tech/react.mdx +++ b/website/docs/zh/guide/tech/react.mdx @@ -67,7 +67,7 @@ module.exports = { [React Fast Refresh](https://reactnative.dev/docs/fast-refresh) 功能的开启主要分为两部分:代码注入和代码转换 -- 代码注入会注入 `react-refresh` 包中的一些代码,以及一些自定义的运行时代码,都已集成在 [@rspack/plugin-react-refresh](https://github.com/web-infra-dev/rspack/tree/main/packages/rspack-plugin-react-refresh) 插件中,可通过该插件注入 +- 代码注入会注入 `react-refresh` 包中的一些代码,以及一些自定义的运行时代码,都已集成在 [@rspack/plugin-react-refresh](https://github.com/rspack-contrib/rspack-plugin-react-refresh) 插件中,可通过该插件注入 - 代码转换可通过 loader 来完成,比如 `swc-loader` 的 [jsc.transform.react.refresh](https://swc.rs/docs/configuration/compilation#jsctransformreactrefresh) 或 `babel-loader` 的 [react-refresh/babel 插件](https://github.com/facebook/react/tree/main/packages/react-refresh)。 ```js title=rspack.config.js