@freshpack/webpack 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lach and Fresh authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,11 @@
1
+ import type { IslandPreparer, setBuildCache } from "@freshpack/core/internal";
2
+ import type * as Webpack from "webpack";
3
+
4
+ export type OriginalBuildCache<State> = Parameters<
5
+ typeof setBuildCache<State>
6
+ >[1];
7
+ export type ServerIslandRegistry = Parameters<IslandPreparer["prepare"]>[0];
8
+ export type OriginalStaticFile = ReturnType<
9
+ OriginalBuildCache<unknown>["readFile"]
10
+ >;
11
+ export type WebpackFS = Exclude<Webpack.Compiler["outputFileSystem"], null>;
package/denoEnv.ts ADDED
@@ -0,0 +1,78 @@
1
+ import Webpack, { type Compiler } from "webpack";
2
+
3
+ type JavascriptParser = Webpack.javascript.JavascriptParser;
4
+
5
+ const NAME = "DenoEnvPlugin";
6
+
7
+ const PARSER_TYPES = [
8
+ "javascript/auto",
9
+ "javascript/dynamic",
10
+ "javascript/esm",
11
+ ] as const;
12
+
13
+ export type DenoEnvOptions = {
14
+ allowedEnv?: (string | RegExp)[];
15
+ };
16
+
17
+ /**
18
+ * DenoEnvPlugin replaces calls to `Deno.env.get` with a constant expression of environment variable name.
19
+ */
20
+ export class DenoEnvPlugin {
21
+ #allowed: (string | RegExp)[];
22
+ constructor(opts: DenoEnvOptions = {}) {
23
+ this.#allowed = [
24
+ ...opts.allowedEnv ?? [],
25
+ /^FRESH_PUBLIC_/,
26
+ "NODE_ENV",
27
+ "DENO_DEPLOYMENT_ID",
28
+ "GITHUB_SHA",
29
+ "CI_COMMIT_SHA",
30
+ "CI",
31
+ ];
32
+ }
33
+ #isAllowed(name: string) {
34
+ return this.#allowed.some((allowed) =>
35
+ allowed instanceof RegExp ? allowed.test(name) : allowed === name
36
+ );
37
+ }
38
+ #value(name: string, compiler: Compiler) {
39
+ if (name === "NODE_ENV") {
40
+ const mode = compiler.options.mode;
41
+ if (mode !== undefined && mode !== "none") return mode;
42
+ }
43
+ return Deno.env.get(name);
44
+ }
45
+ apply(compiler: Compiler) {
46
+ compiler.hooks.compilation.tap(
47
+ NAME,
48
+ (_compilation, { normalModuleFactory }) => {
49
+ const handler = (parser: JavascriptParser) => {
50
+ parser.hooks.call.for("Deno.env.get").tap(NAME, (expr) => {
51
+ const [arg] = expr.arguments;
52
+ if (
53
+ expr.arguments.length !== 1 || arg.type !== "Literal" ||
54
+ typeof arg.value !== "string"
55
+ ) {
56
+ return;
57
+ }
58
+ const name = arg.value;
59
+ if (!this.#isAllowed(name)) {
60
+ throw new Error(`Env var is not allowed in bundling: ${name}`);
61
+ }
62
+ const value = this.#value(name, compiler);
63
+ const dep = new Webpack.dependencies.ConstDependency(
64
+ value === undefined ? "undefined" : JSON.stringify(value),
65
+ expr.range!,
66
+ );
67
+ if (expr.loc) dep.loc = expr.loc;
68
+ parser.state.module.addPresentationalDependency(dep);
69
+ return true;
70
+ });
71
+ };
72
+ for (const type of PARSER_TYPES) {
73
+ normalModuleFactory.hooks.parser.for(type).tap(NAME, handler);
74
+ }
75
+ },
76
+ );
77
+ }
78
+ }
package/fresh.ts ADDED
@@ -0,0 +1,391 @@
1
+ import {
2
+ crawlFsItem,
3
+ type FsRouteFileNoMod,
4
+ } from "@freshpack/core/internal-dev";
5
+ import Webpack from "webpack";
6
+ import {
7
+ assertAbsolutePath,
8
+ assertDirURL,
9
+ manglePath,
10
+ stripFileUrl,
11
+ } from "./util.ts";
12
+ import { assert } from "@std/assert";
13
+ import { IslandPreparer, ProdBuildCache } from "@freshpack/core/internal";
14
+ import {
15
+ extname as extnamePosix,
16
+ join as joinPosix,
17
+ relative as relativePosix,
18
+ } from "@std/path/posix";
19
+ import { contentType as getStdContentType } from "@std/media-types/content-type";
20
+ import { encodeHex } from "@std/encoding";
21
+ import { UnmapPlugin } from "./unmap.ts";
22
+ import { type DenoEnvOptions, DenoEnvPlugin } from "./denoEnv.ts";
23
+ import { ViteIgnorePlugin } from "./viteComment.ts";
24
+ import { type RawImportsOptions, RawImportsPlugin } from "./rawImports.ts";
25
+ import { js, type JsRaw, toJsRaw } from "./quasiquote.ts";
26
+
27
+ interface WebpackFreshCompilation extends Webpack.Compilation {
28
+ freshRoutes: FsRouteFileNoMod<unknown>[];
29
+ freshIslands: { entryName: string; filePath: string }[];
30
+ freshRoot: string;
31
+ buildId: string;
32
+
33
+ prodBuildCache: ProdBuildCache<unknown>;
34
+ }
35
+
36
+ export function assertFreshCompilation(
37
+ compilation: Webpack.Compilation,
38
+ ): asserts compilation is WebpackFreshCompilation {
39
+ assert(
40
+ "freshRoutes" in compilation && "freshIslands" in compilation &&
41
+ "freshRoot" in compilation,
42
+ "missing fresh data in compilation, did you add WebpackFreshEntries plugin?",
43
+ );
44
+ }
45
+
46
+ type CacheStaticFile = {
47
+ name: string;
48
+ filePath: string;
49
+ contentType: string;
50
+ hash: string;
51
+ data: Uint8Array;
52
+ size: number;
53
+ };
54
+
55
+ function getMainChunkName(
56
+ basePath: string,
57
+ e: Webpack.Entrypoint,
58
+ ): string {
59
+ const entryChunk = e.getEntrypointChunk();
60
+ const files = [...entryChunk.files].map((v) => joinPosix(basePath, v));
61
+ return files[0];
62
+ }
63
+ function getChunkFiles(
64
+ basePath: string,
65
+ e: Webpack.Entrypoint,
66
+ ): string[] {
67
+ return e.getFiles().map((v) => joinPosix(basePath, v));
68
+ }
69
+
70
+ export class FreshPlugin {
71
+ /**
72
+ * @param baseUrl Location of fresh project root directory, you can specify it as `new URL('.', import.meta.url)` in build.ts
73
+ * @param importHelper JSR dynamic file import workaround: You should pass `(path) => import(path)` here, where the function
74
+ * should be defined anywhere outside of JSR published package. See this for details: https://github.com/denoland/deno/discussions/26266
75
+ * This function will always be called with absolute path.
76
+ */
77
+ constructor(
78
+ public baseUrl: URL,
79
+ public importHelper: (path: string) => Promise<Record<string, unknown>>,
80
+ public options: { env?: DenoEnvOptions; rawImports?: RawImportsOptions } =
81
+ {},
82
+ ) {
83
+ assertDirURL(this.baseUrl);
84
+ if (!importHelper) {
85
+ console.warn(
86
+ "[FreshPlugin]",
87
+ "importHelper is not set, jsr release of @freshpack/webpack doesn't work without it: https://github.com/denoland/deno/discussions/26266#discussioncomment-12198284",
88
+ );
89
+ this.importHelper = (path: string) => import(path);
90
+ }
91
+ }
92
+ pathRelativeToBase(path: string) {
93
+ return relativePosix(this.baseUrl.pathname, path);
94
+ }
95
+ #dist?: string;
96
+ pathRelativeToDist(path: string) {
97
+ assert(this.#dist, "dist path was not determined yet");
98
+ return relativePosix(this.#dist, path);
99
+ }
100
+
101
+ apply(compiler: Webpack.Compiler) {
102
+ {
103
+ // HACK: Webpack does not export EntryDependency, and it is impossible to use EntryPlugin, as
104
+ // it wants to modify make stage, yet we have already reached this stage when we want to use
105
+ // this plugin.
106
+ //
107
+ // Solvable by creating custom dependency plugin, or requiring user to manually specify
108
+ // at least one entry... Or by registering EntryDependency manually as done here.
109
+ const EntryDependency =
110
+ Webpack.EntryPlugin.createDependency(`dummy`, {}).constructor;
111
+
112
+ compiler.hooks.compilation.tap(
113
+ FreshPlugin.name,
114
+ (compilation, { normalModuleFactory }) => {
115
+ compilation.dependencyFactories.set(
116
+ EntryDependency as any,
117
+ normalModuleFactory,
118
+ );
119
+ },
120
+ );
121
+ }
122
+
123
+ (new UnmapPlugin()).apply(compiler);
124
+ (new DenoEnvPlugin(this.options.env)).apply(compiler);
125
+ (new ViteIgnorePlugin()).apply(compiler);
126
+ (new RawImportsPlugin(this.options.rawImports)).apply(compiler);
127
+ // Some @std and other packages detect deno on presence of Deno global, dead-code-elimnate this stuff
128
+ (new Webpack.DefinePlugin({ Deno: "undefined" })).apply(compiler);
129
+
130
+ compiler.hooks.make.tapPromise(
131
+ FreshPlugin.name,
132
+ async (_compilation: Webpack.Compilation) => {
133
+ const compilation = _compilation as WebpackFreshCompilation;
134
+ this.#dist = compilation.outputOptions.path;
135
+
136
+ const compilationId = Date.now().toString(36);
137
+
138
+ // Ensure hot chunks are resolved from correct path, they can't contain compilationId in name
139
+ compilation.outputOptions.publicPath = "/";
140
+ {
141
+ // Chunks are content-addressed in prod, and have readable names using standard fresh cache pruning in dev
142
+ if (compiler.options.mode === "production") {
143
+ compilation.outputOptions.filename =
144
+ `_fresh/js/c/[contenthash].mjs`;
145
+ compilation.outputOptions.chunkFilename =
146
+ `_fresh/js/c/[contenthash].mjs`;
147
+ compilation.outputOptions.workerChunkFilename =
148
+ `_fresh/js/c/[contenthash].mjs`;
149
+ } else {
150
+ compilation.outputOptions.filename =
151
+ `_fresh/js/${compilationId}/[id].mjs`;
152
+ compilation.outputOptions.chunkFilename =
153
+ `_fresh/js/${compilationId}/[id].mjs`;
154
+ compilation.outputOptions.workerChunkFilename =
155
+ `_fresh/js/${compilationId}/[id].mjs`;
156
+ }
157
+ // Assets are always content-addressed
158
+ compilation.outputOptions.assetModuleFilename =
159
+ `_fresh/js/c/[hash][ext][query]`;
160
+ compilation.outputOptions.webassemblyModuleFilename =
161
+ `_fresh/js/c/[hash].wasm`;
162
+ }
163
+
164
+ compilation.hooks.processAssets.tapPromise(
165
+ {
166
+ name: FreshPlugin.name,
167
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
168
+ },
169
+ async (assets) => {
170
+ compilation.getAssets();
171
+
172
+ const cacheOut: JsRaw[] = [
173
+ js`import{IslandPreparer,ProdBuildCache}from"@freshpack/core/internal"`,
174
+ js`const islands=new Map()`,
175
+ js`const islandPreparer=new IslandPreparer()`,
176
+ ];
177
+
178
+ const staticFiles = new Map<string, CacheStaticFile>();
179
+
180
+ const islands = new Map();
181
+ const islandPreparer = new IslandPreparer();
182
+ for (const island of compilation.freshIslands) {
183
+ const entrypoint = compilation.entrypoints.get(island.entryName);
184
+ assert(
185
+ entrypoint,
186
+ `unable to find island entrypoint: ${island.entryName}`,
187
+ );
188
+ const file = getMainChunkName(
189
+ `/`,
190
+ entrypoint,
191
+ );
192
+
193
+ islandPreparer.prepare(
194
+ islands,
195
+ await this.importHelper(island.filePath),
196
+ file,
197
+ island.entryName,
198
+ [],
199
+ );
200
+ const importPath = this.pathRelativeToDist(island.filePath);
201
+ cacheOut.push(
202
+ js`islandPreparer.prepare(islands,await import(${importPath}),${file},${island.entryName},[])`,
203
+ );
204
+ }
205
+
206
+ const fsRoutesOut: JsRaw[] = [];
207
+ const fsRoutes = await Promise.all(
208
+ compilation.freshRoutes.map(async (v) => {
209
+ const importPath = this.pathRelativeToDist(v.filePath);
210
+ fsRoutesOut.push(toJsRaw({
211
+ id: v.id,
212
+ mod: v.lazy
213
+ ? js`()=>import(${importPath})`
214
+ : js`await import(${importPath})`,
215
+ type: v.type,
216
+ pattern: v.pattern,
217
+ routePattern: v.routePattern,
218
+ }));
219
+ assertAbsolutePath(v.filePath);
220
+ return {
221
+ ...v,
222
+ mod: v.lazy
223
+ ? () => this.importHelper(v.filePath)
224
+ : await this.importHelper(v.filePath),
225
+ };
226
+ }),
227
+ );
228
+ cacheOut.push(js`const fsRoutes=${fsRoutesOut}`);
229
+
230
+ const clientEntrypoint = compilation.entrypoints.get(
231
+ "client-entry",
232
+ );
233
+ assert(
234
+ clientEntrypoint,
235
+ `unable to find client entrypoint`,
236
+ );
237
+ const clientEntry = getMainChunkName(
238
+ `/`,
239
+ clientEntrypoint,
240
+ );
241
+ const clientEntryAssets = getChunkFiles(
242
+ `/`,
243
+ clientEntrypoint,
244
+ );
245
+ const staticFilesOut = new Map<string, JsRaw>();
246
+ for (const _asset of compilation.getAssets()) {
247
+ const asset = compilation.getAsset(_asset.name)!;
248
+ const file_: Uint8Array<ArrayBufferLike> = assets[asset.name]
249
+ .buffer();
250
+ const file = file_ as Uint8Array<ArrayBuffer>;
251
+ const hash = await crypto.subtle.digest("SHA-1", file.buffer);
252
+
253
+ const ext = extnamePosix(asset.name);
254
+ const contentType = getStdContentType(ext) ?? "text/plain";
255
+
256
+ const name = "/" + asset.name;
257
+ staticFiles.set(name, {
258
+ name,
259
+ filePath: asset.name,
260
+ contentType,
261
+ hash: encodeHex(hash),
262
+ data: file,
263
+ size: file.length,
264
+ });
265
+ staticFilesOut.set(
266
+ name,
267
+ toJsRaw({
268
+ name,
269
+ filePath:
270
+ js`new URL(${asset.name}, import.meta.url).pathname`,
271
+ hash: encodeHex(hash),
272
+ contentType,
273
+ }),
274
+ );
275
+ }
276
+ cacheOut.push(js`const staticFiles=${staticFilesOut}`);
277
+
278
+ cacheOut.push(
279
+ js`export default new ProdBuildCache(${compilation.freshRoot}, ${({
280
+ version: compilationId,
281
+ clientEntry,
282
+ entryAssets: toJsRaw(clientEntryAssets),
283
+ islands: js`islands`,
284
+ fsRoutes: js`fsRoutes`,
285
+ staticFiles: js`staticFiles`,
286
+ })})`,
287
+ );
288
+ // Here ProdBuildCache is being used as MemoryBuildCache from fresh
289
+ const cache = new ProdBuildCache(compilation.freshRoot, {
290
+ version: compilationId,
291
+ clientEntry,
292
+ fsRoutes,
293
+ staticFiles,
294
+ islands,
295
+ entryAssets: clientEntryAssets,
296
+ });
297
+ cache.readFile = (pathname) => {
298
+ const st = staticFiles.get(pathname);
299
+ if (!st) {
300
+ return Promise.resolve(null);
301
+ }
302
+ return Promise.resolve({
303
+ contentType: st.contentType,
304
+ hash: st.hash,
305
+ readable: new ReadableStream({
306
+ start(v) {
307
+ v.enqueue(st.data);
308
+ v.close();
309
+ },
310
+ }),
311
+ size: st.size,
312
+ close() {},
313
+ });
314
+ };
315
+ compilation.prodBuildCache = cache;
316
+
317
+ compilation.emitAsset(
318
+ "./cache.mjs",
319
+ new compiler.webpack.sources.RawSource(
320
+ cacheOut.map((v) => v._jsRaw).join("\n"),
321
+ ),
322
+ );
323
+ },
324
+ );
325
+
326
+ const item = await crawlFsItem({
327
+ islandDir: stripFileUrl(new URL("islands", this.baseUrl).href),
328
+ routeDir: stripFileUrl(new URL("routes", this.baseUrl).href),
329
+ ignore: [],
330
+ });
331
+ compilation.freshRoutes = item.routes;
332
+ compilation.freshIslands = [];
333
+ compilation.freshRoot = this.pathRelativeToBase(".");
334
+
335
+ const addEntryPromises = [];
336
+ let isId = 0;
337
+ for (const island of item.islands) {
338
+ const name = compiler.options.mode === "production"
339
+ ? `is${isId++}`
340
+ : manglePath(island);
341
+ compilation.freshIslands.push({ entryName: name, filePath: island });
342
+ addEntryPromises.push(
343
+ new Promise<void>((res, rej) =>
344
+ compilation.addEntry(
345
+ "",
346
+ Webpack.EntryPlugin.createDependency(`${island}`, {
347
+ name,
348
+ }),
349
+ {
350
+ name,
351
+ library: {
352
+ type: "module",
353
+ },
354
+ },
355
+ (err) => {
356
+ if (err) return rej(err);
357
+ res();
358
+ },
359
+ )
360
+ ),
361
+ );
362
+ }
363
+ {
364
+ const name = "client-entry";
365
+ const file = stripFileUrl(new URL("./client.ts", this.baseUrl).href);
366
+ addEntryPromises.push(
367
+ new Promise<void>((res, rej) =>
368
+ compilation.addEntry(
369
+ "",
370
+ Webpack.EntryPlugin.createDependency(file, {
371
+ name,
372
+ }),
373
+ {
374
+ name,
375
+ library: {
376
+ type: "module",
377
+ },
378
+ },
379
+ (e) => {
380
+ if (e) return rej(e);
381
+ res();
382
+ },
383
+ )
384
+ ),
385
+ );
386
+ }
387
+ await Promise.all(addEntryPromises);
388
+ },
389
+ );
390
+ }
391
+ }
package/mod.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { DenoEnvPlugin } from "./denoEnv.ts";
2
+ export { FreshPlugin } from "./fresh.ts";
3
+ export { ViteIgnorePlugin } from "./viteComment.ts";
4
+ export { DenoPreactRefreshPlugin } from "./prefresh-forked/index.ts";
5
+ export { DenoLoaderPlugin } from "./resolve.ts";
6
+ export { type RawImportsOptions, RawImportsPlugin } from "./rawImports.ts";
7
+ export { UnmapPlugin } from "./unmap.ts";
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "@freshpack/webpack",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./mod.ts",
7
+ "./fresh": "./fresh.ts",
8
+ "./util": "./util.ts",
9
+ "./unmap": "./unmap.ts",
10
+ "./requireHook": "./requireHook.ts"
11
+ },
12
+ "dependencies": {
13
+ "@deno/loader": "npm:@jsr/deno__loader@^0.5.0",
14
+ "@freshpack/core": "3.0.1",
15
+ "@prefresh/utils": "^1.2.1",
16
+ "@std/assert": "npm:@jsr/std__assert@^1.0.19",
17
+ "@std/encoding": "npm:@jsr/std__encoding@^1.0.11",
18
+ "@std/media-types": "npm:@jsr/std__media-types@^1.1.0",
19
+ "@std/path": "npm:@jsr/std__path@^1.1.6",
20
+ "webpack": "^5.111.1"
21
+ }
6
22
  }
@@ -0,0 +1,114 @@
1
+ /* FIXME: Typings are awful in this file, the port was very crude */
2
+
3
+ import Webpack from "webpack";
4
+ import {
5
+ injectRefreshFunctions,
6
+ matcherOptions,
7
+ NAME,
8
+ prefreshUtils,
9
+ } from "./utils/constants.ts";
10
+ import { PrefreshRuntimeModule } from "./utils/Runtime.ts";
11
+ import { defineRequire } from "../requireHook.ts";
12
+
13
+ type Options = {
14
+ overlay?: {
15
+ module: string;
16
+ };
17
+ entryOptions?: string | Webpack.EntryOptions;
18
+ };
19
+
20
+ const internalPrefreshLoader = defineRequire(
21
+ "@freshpack/webpack/internal-prefresh-loader",
22
+ await import("./loader/index.ts"),
23
+ );
24
+
25
+ export class DenoPreactRefreshPlugin {
26
+ matcher;
27
+ constructor(public options: Options) {
28
+ this.matcher = Webpack.ModuleFilenameHelpers.matchObject.bind(
29
+ undefined,
30
+ matcherOptions,
31
+ );
32
+ }
33
+
34
+ webpack5(
35
+ compiler: Webpack.Compiler,
36
+ RuntimeGlobals: typeof Webpack.RuntimeGlobals,
37
+ ) {
38
+ compiler.hooks.compilation.tap(
39
+ NAME,
40
+ (compilation, { normalModuleFactory }) => {
41
+ if (compilation.compiler !== compiler) {
42
+ return;
43
+ }
44
+
45
+ injectRefreshFunctions(compilation);
46
+
47
+ compilation.hooks.additionalTreeRuntimeRequirements.tap(
48
+ NAME,
49
+ (chunk, runtimeRequirements) => {
50
+ runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution);
51
+ compilation.addRuntimeModule(chunk, new PrefreshRuntimeModule());
52
+ },
53
+ );
54
+
55
+ normalModuleFactory.hooks.afterResolve.tap(
56
+ NAME,
57
+ ({ createData: data }) => {
58
+ if (
59
+ this.matcher(data.resource!) &&
60
+ !data.resource!.includes("@prefresh") &&
61
+ !data.resource!.includes("/prefresh-forked/loader/") &&
62
+ !data.resource!.includes("/prefresh-forked/utils/")
63
+ ) {
64
+ data.loaders!.unshift({
65
+ loader: internalPrefreshLoader,
66
+ options: undefined,
67
+ });
68
+ }
69
+ },
70
+ );
71
+ },
72
+ );
73
+ }
74
+
75
+ apply(compiler: Webpack.Compiler) {
76
+ if (
77
+ compiler.options.mode === "production"
78
+ ) {
79
+ return;
80
+ }
81
+
82
+ const provide = {
83
+ [prefreshUtils]: import.meta.resolve("./utils/prefresh.ts"),
84
+ };
85
+
86
+ if (this.options.overlay) {
87
+ (provide as any).__prefresh_errors__ = import.meta.resolve(
88
+ this.options.overlay.module,
89
+ );
90
+ }
91
+
92
+ const providePlugin = new Webpack.ProvidePlugin(provide);
93
+ providePlugin.apply(compiler);
94
+ const dependency = Webpack.EntryPlugin.createDependency(
95
+ "@prefresh/core",
96
+ { name: "@prefresh/core" },
97
+ );
98
+ compiler.hooks.make.tapAsync(NAME, (compilation, callback) => {
99
+ compilation.addEntry(
100
+ compiler.context,
101
+ dependency,
102
+ this.options.entryOptions ?? {},
103
+ callback as any,
104
+ );
105
+ });
106
+
107
+ this.webpack5(
108
+ compiler,
109
+ compiler.webpack
110
+ ? compiler.webpack.RuntimeGlobals
111
+ : Webpack.RuntimeGlobals,
112
+ );
113
+ }
114
+ }
@@ -0,0 +1,10 @@
1
+ import type Webpack from "webpack";
2
+ import runtimeText from "./runtime.js" with { type: "text" };
3
+
4
+ export default function RefreshHotLoader(
5
+ this: any,
6
+ source: Webpack.sources.SourceMapSource,
7
+ inputSourceMap: Webpack.sources.SourceMapSource["source"],
8
+ ) {
9
+ this.callback(null, source + "\n\n" + runtimeText, inputSourceMap);
10
+ }