@utoo/pack 1.4.4-alpha.0 → 1.4.4

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/cjs/binding.d.ts CHANGED
@@ -9,11 +9,6 @@ export declare class ExternalObject<T> {
9
9
  [K: symbol]: T
10
10
  }
11
11
  }
12
- export type Lockfile = { __napiType: "Lockfile" }
13
- export declare function lockfileTryAcquireSync(path: string, content?: string | undefined | null): Lockfile | null
14
- export declare function lockfileTryAcquire(path: string, content?: string | undefined | null): Promise<Lockfile | null>
15
- export declare function lockfileUnlockSync(lockfile: Lockfile): void
16
- export declare function lockfileUnlock(lockfile: Lockfile): Promise<void>
17
12
  export declare function registerWorkerScheduler(creator: (arg: NapiWorkerCreation) => any, terminator: (arg: NapiWorkerTermination) => any): void
18
13
  export declare function workerCreated(workerId: number): void
19
14
  export interface NapiWorkerCreation {
package/cjs/binding.js CHANGED
@@ -319,11 +319,7 @@ if (!nativeBinding) {
319
319
  }
320
320
  throw new Error(`Failed to load native binding`);
321
321
  }
322
- const { lockfileTryAcquireSync, lockfileTryAcquire, lockfileUnlockSync, lockfileUnlock, registerWorkerScheduler, workerCreated, recvTaskMessageInWorker, sendTaskMessage, endpointWriteToDisk, endpointServerChangedSubscribe, endpointClientChangedSubscribe, projectNew, projectUpdate, projectOnExit, projectShutdown, projectWriteAllEntrypointsToDisk, projectEntrypointsSubscribe, projectHmrEvents, projectHmrIdentifiersSubscribe, projectUpdateInfoSubscribe, projectTraceSource, projectGetSourceForAsset, projectGetSourceMap, projectGetSourceMapSync, rootTaskDispose, initCustomTraceSubscriber, teardownTraceSubscriber } = nativeBinding;
323
- module.exports.lockfileTryAcquireSync = lockfileTryAcquireSync;
324
- module.exports.lockfileTryAcquire = lockfileTryAcquire;
325
- module.exports.lockfileUnlockSync = lockfileUnlockSync;
326
- module.exports.lockfileUnlock = lockfileUnlock;
322
+ const { registerWorkerScheduler, workerCreated, recvTaskMessageInWorker, sendTaskMessage, endpointWriteToDisk, endpointServerChangedSubscribe, endpointClientChangedSubscribe, projectNew, projectUpdate, projectOnExit, projectShutdown, projectWriteAllEntrypointsToDisk, projectEntrypointsSubscribe, projectHmrEvents, projectHmrIdentifiersSubscribe, projectUpdateInfoSubscribe, projectTraceSource, projectGetSourceForAsset, projectGetSourceMap, projectGetSourceMapSync, rootTaskDispose, initCustomTraceSubscriber, teardownTraceSubscriber } = nativeBinding;
327
323
  module.exports.registerWorkerScheduler = registerWorkerScheduler;
328
324
  module.exports.workerCreated = workerCreated;
329
325
  module.exports.recvTaskMessageInWorker = recvTaskMessageInWorker;
@@ -12,12 +12,12 @@ const path_1 = __importDefault(require("path"));
12
12
  const webpackCompat_1 = require("../config/webpackCompat");
13
13
  const project_1 = require("../core/project");
14
14
  const HtmlPlugin_1 = require("../plugins/HtmlPlugin");
15
+ const cleanOutput_1 = require("../utils/cleanOutput");
15
16
  const common_1 = require("../utils/common");
16
17
  const findRoot_1 = require("../utils/findRoot");
17
18
  const getInitialAssets_1 = require("../utils/getInitialAssets");
18
19
  const htmlEntry_1 = require("../utils/htmlEntry");
19
- const lockfile_1 = require("../utils/lockfile");
20
- const normalize_path_1 = require("../utils/normalize-path");
20
+ const normalizePath_1 = require("../utils/normalizePath");
21
21
  const runtimePluginStratety_1 = require("../utils/runtimePluginStratety");
22
22
  const validateEntry_1 = require("../utils/validateEntry");
23
23
  const xcodeProfile_1 = require("../utils/xcodeProfile");
@@ -30,7 +30,7 @@ function build(options, projectPath, rootPath) {
30
30
  return buildInternal(bundleOptions, projectPath, rootPath);
31
31
  }
32
32
  async function buildInternal(bundleOptions, projectPath, rootPath) {
33
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
33
+ var _a, _b, _c, _d, _e, _f, _g;
34
34
  (0, common_1.blockStdout)();
35
35
  if (process.env.XCODE_PROFILE) {
36
36
  await (0, xcodeProfile_1.xcodeProfilingReady)();
@@ -40,69 +40,63 @@ async function buildInternal(bundleOptions, projectPath, rootPath) {
40
40
  const persistentCaching = (_a = bundleOptions.config.persistentCaching) !== null && _a !== void 0 ? _a : false;
41
41
  (0, htmlEntry_1.processHtmlEntry)(bundleOptions.config, resolvedProjectPath);
42
42
  (0, validateEntry_1.validateEntryPaths)(bundleOptions.config, resolvedProjectPath);
43
+ await (0, cleanOutput_1.cleanOutput)(bundleOptions.config, resolvedProjectPath);
43
44
  const createProject = (0, project_1.projectFactory)();
44
- const persistentCacheLock = await (0, lockfile_1.acquirePersistentCacheLock)(resolvedProjectPath, "utoo pack build", persistentCaching);
45
- let project;
46
- try {
47
- project = await createProject({
48
- processEnv: (_b = bundleOptions.processEnv) !== null && _b !== void 0 ? _b : {},
49
- watch: {
50
- enable: false,
51
- },
52
- dev: (_c = bundleOptions.dev) !== null && _c !== void 0 ? _c : false,
53
- buildId: bundleOptions.buildId || (0, nanoid_1.nanoid)(),
54
- tracing: (_d = bundleOptions.tracing) !== null && _d !== void 0 ? _d : true,
55
- config: {
56
- ...bundleOptions.config,
57
- stats: Boolean(process.env.ANALYZE) ||
58
- bundleOptions.config.stats ||
59
- bundleOptions.config.entry.some((e) => !!e.html),
60
- pluginRuntimeStrategy: (_f = (_e = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _e === void 0 ? void 0 : _e.pluginRuntimeStrategy) !== null && _f !== void 0 ? _f : ((0, runtimePluginStratety_1.useWorkerThreads)() ? "workerThreads" : "childProcesses"),
61
- },
62
- projectPath: (0, normalize_path_1.normalizePath)(resolvedProjectPath),
63
- rootPath: resolvedRootPath,
64
- packPath: (0, common_1.getPackPath)(),
65
- }, {
66
- persistentCaching,
67
- // Build mode is a short-lived, one-shot compilation, so avoid paying
68
- // dependency graph bookkeeping cost unless the persistent cache needs it.
69
- dependencyTracking: persistentCaching,
70
- isShortSession: true,
71
- });
72
- const entrypoints = await project.writeAllEntrypointsToDisk();
73
- (0, pack_shared_1.handleIssues)(entrypoints.issues);
74
- const htmlConfigs = [
75
- ...(Array.isArray(bundleOptions.config.html)
76
- ? bundleOptions.config.html
77
- : bundleOptions.config.html
78
- ? [bundleOptions.config.html]
79
- : []),
80
- ...bundleOptions.config.entry
81
- .filter((e) => !!e.html)
82
- .map((e) => e.html),
83
- ];
84
- if (htmlConfigs.length > 0) {
85
- const assets = { js: [], css: [] };
86
- const outputDir = ((_g = bundleOptions.config.output) === null || _g === void 0 ? void 0 : _g.path) || path_1.default.join(process.cwd(), "dist");
87
- if (assets.js.length === 0 && assets.css.length === 0) {
88
- const discovered = (0, getInitialAssets_1.getInitialAssetsFromStats)(outputDir);
89
- assets.js.push(...discovered.js);
90
- assets.css.push(...discovered.css);
91
- }
92
- const publicPath = (_h = bundleOptions.config.output) === null || _h === void 0 ? void 0 : _h.publicPath;
93
- for (const config of htmlConfigs) {
94
- const plugin = new HtmlPlugin_1.HtmlPlugin(config);
95
- await plugin.generate(outputDir, assets, publicPath);
96
- }
45
+ const project = await createProject({
46
+ processEnv: (_b = bundleOptions.processEnv) !== null && _b !== void 0 ? _b : {},
47
+ watch: {
48
+ enable: false,
49
+ },
50
+ dev: (_c = bundleOptions.dev) !== null && _c !== void 0 ? _c : false,
51
+ buildId: bundleOptions.buildId || (0, nanoid_1.nanoid)(),
52
+ tracing: (_d = bundleOptions.tracing) !== null && _d !== void 0 ? _d : true,
53
+ config: {
54
+ ...bundleOptions.config,
55
+ stats: Boolean(process.env.ANALYZE) ||
56
+ bundleOptions.config.stats ||
57
+ bundleOptions.config.entry.some((e) => !!e.html),
58
+ pluginRuntimeStrategy: (_f = (_e = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _e === void 0 ? void 0 : _e.pluginRuntimeStrategy) !== null && _f !== void 0 ? _f : ((0, runtimePluginStratety_1.useWorkerThreads)() ? "workerThreads" : "childProcesses"),
59
+ },
60
+ projectPath: (0, normalizePath_1.normalizePath)(resolvedProjectPath),
61
+ rootPath: resolvedRootPath,
62
+ packPath: (0, common_1.getPackPath)(),
63
+ }, {
64
+ persistentCaching,
65
+ // Build mode is a short-lived, one-shot compilation, so avoid paying
66
+ // dependency graph bookkeeping cost unless the persistent cache needs it.
67
+ dependencyTracking: persistentCaching,
68
+ isShortSession: true,
69
+ });
70
+ const entrypoints = await project.writeAllEntrypointsToDisk();
71
+ (0, pack_shared_1.handleIssues)(entrypoints.issues);
72
+ const htmlConfigs = [
73
+ ...(Array.isArray(bundleOptions.config.html)
74
+ ? bundleOptions.config.html
75
+ : bundleOptions.config.html
76
+ ? [bundleOptions.config.html]
77
+ : []),
78
+ ...bundleOptions.config.entry
79
+ .filter((e) => !!e.html)
80
+ .map((e) => e.html),
81
+ ];
82
+ if (htmlConfigs.length > 0) {
83
+ const assets = { js: [], css: [] };
84
+ const outputDir = (0, cleanOutput_1.getOutputPath)(bundleOptions.config, resolvedProjectPath);
85
+ if (assets.js.length === 0 && assets.css.length === 0) {
86
+ const discovered = (0, getInitialAssets_1.getInitialAssetsFromStats)(outputDir);
87
+ assets.js.push(...discovered.js);
88
+ assets.css.push(...discovered.css);
97
89
  }
98
- if (process.env.ANALYZE) {
99
- await analyzeBundle(((_j = bundleOptions.config.output) === null || _j === void 0 ? void 0 : _j.path) || "dist");
90
+ const publicPath = (_g = bundleOptions.config.output) === null || _g === void 0 ? void 0 : _g.publicPath;
91
+ for (const config of htmlConfigs) {
92
+ const plugin = new HtmlPlugin_1.HtmlPlugin(config);
93
+ await plugin.generate(outputDir, assets, publicPath);
100
94
  }
101
95
  }
102
- finally {
103
- await (project === null || project === void 0 ? void 0 : project.shutdown());
104
- persistentCacheLock === null || persistentCacheLock === void 0 ? void 0 : persistentCacheLock.unlockSync();
96
+ if (process.env.ANALYZE) {
97
+ await analyzeBundle((0, cleanOutput_1.getOutputPath)(bundleOptions.config, resolvedProjectPath));
105
98
  }
99
+ await project.shutdown();
106
100
  // TODO: Maybe run tasks in worker is a better way, see
107
101
  // https://github.com/vercel/next.js/blob/512d8283054407ab92b2583ecce3b253c3be7b85/packages/next/src/lib/worker.ts
108
102
  }
@@ -15,10 +15,10 @@ const fs_1 = __importDefault(require("fs"));
15
15
  const get_port_1 = __importDefault(require("get-port"));
16
16
  const hono_1 = require("hono");
17
17
  const https_1 = __importDefault(require("https"));
18
- const path_1 = __importDefault(require("path"));
19
18
  const webpackCompat_1 = require("../config/webpackCompat");
20
19
  const hmr_1 = require("../core/hmr");
21
- const proxy_hono_1 = require("../core/proxy-hono");
20
+ const proxyHono_1 = require("../core/proxyHono");
21
+ const cleanOutput_1 = require("../utils/cleanOutput");
22
22
  const common_1 = require("../utils/common");
23
23
  const findRoot_1 = require("../utils/findRoot");
24
24
  const mkcert_1 = require("../utils/mkcert");
@@ -139,7 +139,7 @@ function serve(options, projectPath, rootPath, serverOptions) {
139
139
  }
140
140
  const HMR_PATH = "/turbopack-hmr";
141
141
  async function runDev(options, projectPath, rootPath, serverOptions) {
142
- var _a, _b, _d, _e, _f, _g, _h;
142
+ var _a, _b, _d, _e, _f;
143
143
  (0, common_1.blockStdout)();
144
144
  process.title = "utoopack-dev-server";
145
145
  if (process.env.XCODE_PROFILE) {
@@ -149,8 +149,8 @@ async function runDev(options, projectPath, rootPath, serverOptions) {
149
149
  const { bundleOptions, projectPathResolved, rootPathResolved, serveOptsBase, } = await resolveDevConfig(options, projectPath, rootPath, serverOptions);
150
150
  const hotReloader = await (0, hmr_1.createHotReloader)(bundleOptions, projectPathResolved, rootPathResolved);
151
151
  await hotReloader.start();
152
- const distRoot = path_1.default.resolve(projectPathResolved, ((_b = (_a = options.config) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.path) || "./dist");
153
- const publicPath = (_e = (_d = options.config) === null || _d === void 0 ? void 0 : _d.output) === null || _e === void 0 ? void 0 : _e.publicPath;
152
+ const distRoot = (0, cleanOutput_1.getOutputPath)(options.config, projectPathResolved);
153
+ const publicPath = (_b = (_a = options.config) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.publicPath;
154
154
  // Skip prefix stripping for "runtime" and when publicPath is absent (match dev.ts).
155
155
  const normalizedPrefix = publicPath && publicPath !== "runtime"
156
156
  ? normalizedPublicPath(publicPath)
@@ -191,9 +191,9 @@ async function runDev(options, projectPath, rootPath, serverOptions) {
191
191
  console.error("HMR WebSocket error", err);
192
192
  },
193
193
  })));
194
- const proxyRules = (_g = (_f = bundleOptions.config) === null || _f === void 0 ? void 0 : _f.devServer) === null || _g === void 0 ? void 0 : _g.proxy;
194
+ const proxyRules = (_e = (_d = bundleOptions.config) === null || _d === void 0 ? void 0 : _d.devServer) === null || _e === void 0 ? void 0 : _e.proxy;
195
195
  if (proxyRules && proxyRules.length > 0) {
196
- app.use("*", (0, proxy_hono_1.createHttpProxyMiddleware)(proxyRules));
196
+ app.use("*", (0, proxyHono_1.createHttpProxyMiddleware)(proxyRules));
197
197
  }
198
198
  // GET handles HEAD automatically in Hono; serveStatic serves both
199
199
  app.get("/*", (0, serve_static_1.serveStatic)({
@@ -220,7 +220,7 @@ async function runDev(options, projectPath, rootPath, serverOptions) {
220
220
  server.once("error", onError);
221
221
  });
222
222
  }
223
- await ((_h = serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.onReady) === null || _h === void 0 ? void 0 : _h.call(serverOptions, {
223
+ await ((_f = serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.onReady) === null || _f === void 0 ? void 0 : _f.call(serverOptions, {
224
224
  port: serveOptsBase.port,
225
225
  hostname: serveOptsBase.hostname,
226
226
  }));
package/cjs/core/hmr.js CHANGED
@@ -1,20 +1,16 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.FAST_REFRESH_RUNTIME_RELOAD = exports.HMR_ACTIONS_SENT_TO_BROWSER = void 0;
7
4
  exports.createHotReloader = createHotReloader;
8
5
  const pack_shared_1 = require("@utoo/pack-shared");
9
6
  const nanoid_1 = require("nanoid");
10
- const path_1 = __importDefault(require("path"));
11
7
  const ws_1 = require("ws");
12
8
  const HtmlPlugin_1 = require("../plugins/HtmlPlugin");
9
+ const cleanOutput_1 = require("../utils/cleanOutput");
13
10
  const common_1 = require("../utils/common");
14
11
  const getInitialAssets_1 = require("../utils/getInitialAssets");
15
12
  const htmlEntry_1 = require("../utils/htmlEntry");
16
- const lockfile_1 = require("../utils/lockfile");
17
- const normalize_path_1 = require("../utils/normalize-path");
13
+ const normalizePath_1 = require("../utils/normalizePath");
18
14
  const runtimePluginStratety_1 = require("../utils/runtimePluginStratety");
19
15
  const validateEntry_1 = require("../utils/validateEntry");
20
16
  const project_1 = require("./project");
@@ -30,44 +26,36 @@ async function createHotReloader(bundleOptions, projectPath, rootPath) {
30
26
  const resolvedRootPath = rootPath || projectPath || process.cwd();
31
27
  (0, htmlEntry_1.processHtmlEntry)(bundleOptions.config, resolvedProjectPath);
32
28
  (0, validateEntry_1.validateEntryPaths)(bundleOptions.config, resolvedProjectPath);
29
+ await (0, cleanOutput_1.cleanOutput)(bundleOptions.config, resolvedProjectPath);
33
30
  const createProject = (0, project_1.projectFactory)();
34
- const persistentCaching = (_a = bundleOptions.config.persistentCaching) !== null && _a !== void 0 ? _a : false;
35
- const persistentCacheLock = await (0, lockfile_1.acquirePersistentCacheLock)(resolvedProjectPath, "utoo pack dev", persistentCaching);
36
- let project;
37
- try {
38
- project = await createProject({
39
- processEnv: (_b = bundleOptions.processEnv) !== null && _b !== void 0 ? _b : {},
40
- watch: {
41
- enable: true,
42
- },
43
- dev: true,
44
- buildId: bundleOptions.buildId || (0, nanoid_1.nanoid)(),
45
- tracing: (_c = bundleOptions.tracing) !== null && _c !== void 0 ? _c : true,
46
- config: {
47
- ...bundleOptions.config,
48
- mode: "development",
49
- stats: Boolean(process.env.ANALYZE) ||
50
- bundleOptions.config.stats ||
51
- bundleOptions.config.entry.some((e) => !!e.html),
52
- optimization: {
53
- ...bundleOptions.config.optimization,
54
- minify: false,
55
- moduleIds: "named",
56
- },
57
- persistentCaching: (_e = (_d = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _d === void 0 ? void 0 : _d.persistentCaching) !== null && _e !== void 0 ? _e : true,
58
- pluginRuntimeStrategy: (_g = (_f = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _f === void 0 ? void 0 : _f.pluginRuntimeStrategy) !== null && _g !== void 0 ? _g : ((0, runtimePluginStratety_1.useWorkerThreads)() ? "workerThreads" : "childProcesses"),
31
+ const project = await createProject({
32
+ processEnv: (_a = bundleOptions.processEnv) !== null && _a !== void 0 ? _a : {},
33
+ watch: {
34
+ enable: true,
35
+ },
36
+ dev: true,
37
+ buildId: bundleOptions.buildId || (0, nanoid_1.nanoid)(),
38
+ tracing: (_b = bundleOptions.tracing) !== null && _b !== void 0 ? _b : true,
39
+ config: {
40
+ ...bundleOptions.config,
41
+ mode: "development",
42
+ stats: Boolean(process.env.ANALYZE) ||
43
+ bundleOptions.config.stats ||
44
+ bundleOptions.config.entry.some((e) => !!e.html),
45
+ optimization: {
46
+ ...bundleOptions.config.optimization,
47
+ minify: false,
48
+ moduleIds: "named",
59
49
  },
60
- projectPath: (0, normalize_path_1.normalizePath)(resolvedProjectPath),
61
- rootPath: resolvedRootPath,
62
- packPath: (0, common_1.getPackPath)(),
63
- }, {
64
- persistentCaching,
65
- });
66
- }
67
- catch (error) {
68
- persistentCacheLock === null || persistentCacheLock === void 0 ? void 0 : persistentCacheLock.unlockSync();
69
- throw error;
70
- }
50
+ persistentCaching: (_d = (_c = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _c === void 0 ? void 0 : _c.persistentCaching) !== null && _d !== void 0 ? _d : true,
51
+ pluginRuntimeStrategy: (_f = (_e = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _e === void 0 ? void 0 : _e.pluginRuntimeStrategy) !== null && _f !== void 0 ? _f : ((0, runtimePluginStratety_1.useWorkerThreads)() ? "workerThreads" : "childProcesses"),
52
+ },
53
+ projectPath: (0, normalizePath_1.normalizePath)(resolvedProjectPath),
54
+ rootPath: resolvedRootPath,
55
+ packPath: (0, common_1.getPackPath)(),
56
+ }, {
57
+ persistentCaching: (_g = bundleOptions.config.persistentCaching) !== null && _g !== void 0 ? _g : false,
58
+ });
71
59
  const entrypointsSubscription = project.entrypointsSubscribe();
72
60
  let currentEntriesHandlingResolve;
73
61
  let currentEntriesHandling = new Promise((resolve) => (currentEntriesHandlingResolve = resolve));
@@ -91,7 +79,6 @@ async function createHotReloader(bundleOptions, projectPath, rootPath) {
91
79
  let backgroundWatchGeneration = 0;
92
80
  const backgroundWriteTasks = new Map();
93
81
  let closed = false;
94
- let closePromise;
95
82
  function sendToClient(client, payload) {
96
83
  client.send(JSON.stringify(payload));
97
84
  }
@@ -126,12 +113,12 @@ async function createHotReloader(bundleOptions, projectPath, rootPath) {
126
113
  sendEnqueuedMessagesDebounce();
127
114
  }
128
115
  async function regenerateHtml() {
129
- var _a, _b;
116
+ var _a;
130
117
  if (htmlConfigs.length === 0) {
131
118
  return;
132
119
  }
133
- const outputDir = ((_a = bundleOptions.config.output) === null || _a === void 0 ? void 0 : _a.path) || path_1.default.join(process.cwd(), "dist");
134
- const publicPath = (_b = bundleOptions.config.output) === null || _b === void 0 ? void 0 : _b.publicPath;
120
+ const outputDir = (0, cleanOutput_1.getOutputPath)(bundleOptions.config, resolvedProjectPath);
121
+ const publicPath = (_a = bundleOptions.config.output) === null || _a === void 0 ? void 0 : _a.publicPath;
135
122
  const assets = (0, getInitialAssets_1.getInitialAssetsFromStats)(outputDir);
136
123
  for (const config of htmlConfigs) {
137
124
  const plugin = new HtmlPlugin_1.HtmlPlugin(config);
@@ -263,7 +250,6 @@ async function createHotReloader(bundleOptions, projectPath, rootPath) {
263
250
  subscription === null || subscription === void 0 ? void 0 : subscription.return();
264
251
  }
265
252
  async function handleEntrypointsSubscription() {
266
- var _a, _b;
267
253
  for await (const entrypoints of entrypointsSubscription) {
268
254
  if (!currentEntriesHandlingResolve) {
269
255
  currentEntriesHandling = new Promise(
@@ -271,8 +257,8 @@ async function createHotReloader(bundleOptions, projectPath, rootPath) {
271
257
  (resolve) => (currentEntriesHandlingResolve = resolve));
272
258
  }
273
259
  currentWatchedEntrypoints = [
274
- ...((_a = entrypoints.apps) !== null && _a !== void 0 ? _a : []),
275
- ...((_b = entrypoints.libraries) !== null && _b !== void 0 ? _b : []),
260
+ ...entrypoints.apps,
261
+ ...entrypoints.libraries,
276
262
  ];
277
263
  await writeEntrypointsToDisk(currentWatchedEntrypoints);
278
264
  if (backgroundWatchersStarted) {
@@ -457,14 +443,6 @@ async function createHotReloader(bundleOptions, projectPath, rootPath) {
457
443
  close() {
458
444
  closed = true;
459
445
  void disposeBackgroundWatchSubscriptions();
460
- closePromise !== null && closePromise !== void 0 ? closePromise : (closePromise = project
461
- .onExit()
462
- .catch((err) => {
463
- console.error(err);
464
- })
465
- .finally(() => {
466
- persistentCacheLock === null || persistentCacheLock === void 0 ? void 0 : persistentCacheLock.unlockSync();
467
- }));
468
446
  for (const wsClient of clients) {
469
447
  wsClient.close();
470
448
  }
@@ -40,7 +40,7 @@ const path_1 = require("path");
40
40
  const util_1 = require("util");
41
41
  const binding = __importStar(require("../binding"));
42
42
  const common_1 = require("../utils/common");
43
- const normalize_path_1 = require("../utils/normalize-path");
43
+ const normalizePath_1 = require("../utils/normalizePath");
44
44
  const loaderWorkerPool_1 = require("./loaderWorkerPool");
45
45
  /**
46
46
  * An error caused by a bug in Turbopack, and not the user's code (e.g. a Rust panic). These should
@@ -240,15 +240,15 @@ async function rustifyPartialProjectOptions(options) {
240
240
  function normalizePathOption(pathLike) {
241
241
  if (pathLike === undefined)
242
242
  return undefined;
243
- return (0, normalize_path_1.normalizePath)(pathLike);
243
+ return (0, normalizePath_1.normalizePath)(pathLike);
244
244
  }
245
245
  async function rustifyProjectOptions(options) {
246
246
  var _a;
247
247
  return {
248
248
  ...options,
249
- rootPath: (0, normalize_path_1.normalizePath)(options.rootPath),
250
- projectPath: (0, normalize_path_1.normalizePath)(options.projectPath),
251
- packPath: (0, normalize_path_1.normalizePath)(options.packPath),
249
+ rootPath: (0, normalizePath_1.normalizePath)(options.rootPath),
250
+ projectPath: (0, normalizePath_1.normalizePath)(options.projectPath),
251
+ packPath: (0, normalizePath_1.normalizePath)(options.packPath),
252
252
  config: await serializeConfig(options.config, options.dev),
253
253
  processEnv: (0, common_1.rustifyEnv)((_a = options.processEnv) !== null && _a !== void 0 ? _a : {}),
254
254
  };
@@ -0,0 +1,3 @@
1
+ import type { ConfigComplete } from "../config/types";
2
+ export declare function getOutputPath(config: ConfigComplete, projectPath: string): string;
3
+ export declare function cleanOutput(config: ConfigComplete, projectPath: string): Promise<void>;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getOutputPath = getOutputPath;
7
+ exports.cleanOutput = cleanOutput;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ function getOutputPath(config, projectPath) {
11
+ var _a;
12
+ return path_1.default.resolve(projectPath, ((_a = config.output) === null || _a === void 0 ? void 0 : _a.path) || "dist");
13
+ }
14
+ async function cleanOutput(config, projectPath) {
15
+ var _a;
16
+ if (!((_a = config.output) === null || _a === void 0 ? void 0 : _a.clean)) {
17
+ return;
18
+ }
19
+ const outputPath = getOutputPath(config, projectPath);
20
+ let entries;
21
+ try {
22
+ entries = await fs_1.default.promises.readdir(outputPath, { withFileTypes: true });
23
+ }
24
+ catch (error) {
25
+ if (isNodeError(error) && error.code === "ENOENT") {
26
+ return;
27
+ }
28
+ throw error;
29
+ }
30
+ await Promise.all(entries.map((entry) => fs_1.default.promises.rm(path_1.default.join(outputPath, entry.name), {
31
+ force: true,
32
+ maxRetries: 3,
33
+ recursive: true,
34
+ retryDelay: 50,
35
+ })));
36
+ }
37
+ function isNodeError(error) {
38
+ return error instanceof Error && "code" in error;
39
+ }
package/esm/binding.d.ts CHANGED
@@ -9,11 +9,6 @@ export declare class ExternalObject<T> {
9
9
  [K: symbol]: T
10
10
  }
11
11
  }
12
- export type Lockfile = { __napiType: "Lockfile" }
13
- export declare function lockfileTryAcquireSync(path: string, content?: string | undefined | null): Lockfile | null
14
- export declare function lockfileTryAcquire(path: string, content?: string | undefined | null): Promise<Lockfile | null>
15
- export declare function lockfileUnlockSync(lockfile: Lockfile): void
16
- export declare function lockfileUnlock(lockfile: Lockfile): Promise<void>
17
12
  export declare function registerWorkerScheduler(creator: (arg: NapiWorkerCreation) => any, terminator: (arg: NapiWorkerTermination) => any): void
18
13
  export declare function workerCreated(workerId: number): void
19
14
  export interface NapiWorkerCreation {
package/esm/binding.js CHANGED
@@ -319,11 +319,7 @@ if (!nativeBinding) {
319
319
  }
320
320
  throw new Error(`Failed to load native binding`);
321
321
  }
322
- const { lockfileTryAcquireSync, lockfileTryAcquire, lockfileUnlockSync, lockfileUnlock, registerWorkerScheduler, workerCreated, recvTaskMessageInWorker, sendTaskMessage, endpointWriteToDisk, endpointServerChangedSubscribe, endpointClientChangedSubscribe, projectNew, projectUpdate, projectOnExit, projectShutdown, projectWriteAllEntrypointsToDisk, projectEntrypointsSubscribe, projectHmrEvents, projectHmrIdentifiersSubscribe, projectUpdateInfoSubscribe, projectTraceSource, projectGetSourceForAsset, projectGetSourceMap, projectGetSourceMapSync, rootTaskDispose, initCustomTraceSubscriber, teardownTraceSubscriber } = nativeBinding;
323
- module.exports.lockfileTryAcquireSync = lockfileTryAcquireSync;
324
- module.exports.lockfileTryAcquire = lockfileTryAcquire;
325
- module.exports.lockfileUnlockSync = lockfileUnlockSync;
326
- module.exports.lockfileUnlock = lockfileUnlock;
322
+ const { registerWorkerScheduler, workerCreated, recvTaskMessageInWorker, sendTaskMessage, endpointWriteToDisk, endpointServerChangedSubscribe, endpointClientChangedSubscribe, projectNew, projectUpdate, projectOnExit, projectShutdown, projectWriteAllEntrypointsToDisk, projectEntrypointsSubscribe, projectHmrEvents, projectHmrIdentifiersSubscribe, projectUpdateInfoSubscribe, projectTraceSource, projectGetSourceForAsset, projectGetSourceMap, projectGetSourceMapSync, rootTaskDispose, initCustomTraceSubscriber, teardownTraceSubscriber } = nativeBinding;
327
323
  module.exports.registerWorkerScheduler = registerWorkerScheduler;
328
324
  module.exports.workerCreated = workerCreated;
329
325
  module.exports.recvTaskMessageInWorker = recvTaskMessageInWorker;
@@ -6,12 +6,12 @@ import path from "path";
6
6
  import { resolveBundleOptions } from "../config/webpackCompat.js";
7
7
  import { projectFactory } from "../core/project.js";
8
8
  import { HtmlPlugin } from "../plugins/HtmlPlugin.js";
9
+ import { cleanOutput, getOutputPath } from "../utils/cleanOutput.js";
9
10
  import { blockStdout, getPackPath } from "../utils/common.js";
10
11
  import { findRootDir } from "../utils/findRoot.js";
11
12
  import { getInitialAssetsFromStats } from "../utils/getInitialAssets.js";
12
13
  import { processHtmlEntry } from "../utils/htmlEntry.js";
13
- import { acquirePersistentCacheLock } from "../utils/lockfile.js";
14
- import { normalizePath } from "../utils/normalize-path.js";
14
+ import { normalizePath } from "../utils/normalizePath.js";
15
15
  import { useWorkerThreads } from "../utils/runtimePluginStratety.js";
16
16
  import { validateEntryPaths } from "../utils/validateEntry.js";
17
17
  import { xcodeProfilingReady } from "../utils/xcodeProfile.js";
@@ -24,7 +24,7 @@ export function build(options, projectPath, rootPath) {
24
24
  return buildInternal(bundleOptions, projectPath, rootPath);
25
25
  }
26
26
  async function buildInternal(bundleOptions, projectPath, rootPath) {
27
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
27
+ var _a, _b, _c, _d, _e, _f, _g;
28
28
  blockStdout();
29
29
  if (process.env.XCODE_PROFILE) {
30
30
  await xcodeProfilingReady();
@@ -34,69 +34,63 @@ async function buildInternal(bundleOptions, projectPath, rootPath) {
34
34
  const persistentCaching = (_a = bundleOptions.config.persistentCaching) !== null && _a !== void 0 ? _a : false;
35
35
  processHtmlEntry(bundleOptions.config, resolvedProjectPath);
36
36
  validateEntryPaths(bundleOptions.config, resolvedProjectPath);
37
+ await cleanOutput(bundleOptions.config, resolvedProjectPath);
37
38
  const createProject = projectFactory();
38
- const persistentCacheLock = await acquirePersistentCacheLock(resolvedProjectPath, "utoo pack build", persistentCaching);
39
- let project;
40
- try {
41
- project = await createProject({
42
- processEnv: (_b = bundleOptions.processEnv) !== null && _b !== void 0 ? _b : {},
43
- watch: {
44
- enable: false,
45
- },
46
- dev: (_c = bundleOptions.dev) !== null && _c !== void 0 ? _c : false,
47
- buildId: bundleOptions.buildId || nanoid(),
48
- tracing: (_d = bundleOptions.tracing) !== null && _d !== void 0 ? _d : true,
49
- config: {
50
- ...bundleOptions.config,
51
- stats: Boolean(process.env.ANALYZE) ||
52
- bundleOptions.config.stats ||
53
- bundleOptions.config.entry.some((e) => !!e.html),
54
- pluginRuntimeStrategy: (_f = (_e = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _e === void 0 ? void 0 : _e.pluginRuntimeStrategy) !== null && _f !== void 0 ? _f : (useWorkerThreads() ? "workerThreads" : "childProcesses"),
55
- },
56
- projectPath: normalizePath(resolvedProjectPath),
57
- rootPath: resolvedRootPath,
58
- packPath: getPackPath(),
59
- }, {
60
- persistentCaching,
61
- // Build mode is a short-lived, one-shot compilation, so avoid paying
62
- // dependency graph bookkeeping cost unless the persistent cache needs it.
63
- dependencyTracking: persistentCaching,
64
- isShortSession: true,
65
- });
66
- const entrypoints = await project.writeAllEntrypointsToDisk();
67
- handleIssues(entrypoints.issues);
68
- const htmlConfigs = [
69
- ...(Array.isArray(bundleOptions.config.html)
70
- ? bundleOptions.config.html
71
- : bundleOptions.config.html
72
- ? [bundleOptions.config.html]
73
- : []),
74
- ...bundleOptions.config.entry
75
- .filter((e) => !!e.html)
76
- .map((e) => e.html),
77
- ];
78
- if (htmlConfigs.length > 0) {
79
- const assets = { js: [], css: [] };
80
- const outputDir = ((_g = bundleOptions.config.output) === null || _g === void 0 ? void 0 : _g.path) || path.join(process.cwd(), "dist");
81
- if (assets.js.length === 0 && assets.css.length === 0) {
82
- const discovered = getInitialAssetsFromStats(outputDir);
83
- assets.js.push(...discovered.js);
84
- assets.css.push(...discovered.css);
85
- }
86
- const publicPath = (_h = bundleOptions.config.output) === null || _h === void 0 ? void 0 : _h.publicPath;
87
- for (const config of htmlConfigs) {
88
- const plugin = new HtmlPlugin(config);
89
- await plugin.generate(outputDir, assets, publicPath);
90
- }
39
+ const project = await createProject({
40
+ processEnv: (_b = bundleOptions.processEnv) !== null && _b !== void 0 ? _b : {},
41
+ watch: {
42
+ enable: false,
43
+ },
44
+ dev: (_c = bundleOptions.dev) !== null && _c !== void 0 ? _c : false,
45
+ buildId: bundleOptions.buildId || nanoid(),
46
+ tracing: (_d = bundleOptions.tracing) !== null && _d !== void 0 ? _d : true,
47
+ config: {
48
+ ...bundleOptions.config,
49
+ stats: Boolean(process.env.ANALYZE) ||
50
+ bundleOptions.config.stats ||
51
+ bundleOptions.config.entry.some((e) => !!e.html),
52
+ pluginRuntimeStrategy: (_f = (_e = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _e === void 0 ? void 0 : _e.pluginRuntimeStrategy) !== null && _f !== void 0 ? _f : (useWorkerThreads() ? "workerThreads" : "childProcesses"),
53
+ },
54
+ projectPath: normalizePath(resolvedProjectPath),
55
+ rootPath: resolvedRootPath,
56
+ packPath: getPackPath(),
57
+ }, {
58
+ persistentCaching,
59
+ // Build mode is a short-lived, one-shot compilation, so avoid paying
60
+ // dependency graph bookkeeping cost unless the persistent cache needs it.
61
+ dependencyTracking: persistentCaching,
62
+ isShortSession: true,
63
+ });
64
+ const entrypoints = await project.writeAllEntrypointsToDisk();
65
+ handleIssues(entrypoints.issues);
66
+ const htmlConfigs = [
67
+ ...(Array.isArray(bundleOptions.config.html)
68
+ ? bundleOptions.config.html
69
+ : bundleOptions.config.html
70
+ ? [bundleOptions.config.html]
71
+ : []),
72
+ ...bundleOptions.config.entry
73
+ .filter((e) => !!e.html)
74
+ .map((e) => e.html),
75
+ ];
76
+ if (htmlConfigs.length > 0) {
77
+ const assets = { js: [], css: [] };
78
+ const outputDir = getOutputPath(bundleOptions.config, resolvedProjectPath);
79
+ if (assets.js.length === 0 && assets.css.length === 0) {
80
+ const discovered = getInitialAssetsFromStats(outputDir);
81
+ assets.js.push(...discovered.js);
82
+ assets.css.push(...discovered.css);
91
83
  }
92
- if (process.env.ANALYZE) {
93
- await analyzeBundle(((_j = bundleOptions.config.output) === null || _j === void 0 ? void 0 : _j.path) || "dist");
84
+ const publicPath = (_g = bundleOptions.config.output) === null || _g === void 0 ? void 0 : _g.publicPath;
85
+ for (const config of htmlConfigs) {
86
+ const plugin = new HtmlPlugin(config);
87
+ await plugin.generate(outputDir, assets, publicPath);
94
88
  }
95
89
  }
96
- finally {
97
- await (project === null || project === void 0 ? void 0 : project.shutdown());
98
- persistentCacheLock === null || persistentCacheLock === void 0 ? void 0 : persistentCacheLock.unlockSync();
90
+ if (process.env.ANALYZE) {
91
+ await analyzeBundle(getOutputPath(bundleOptions.config, resolvedProjectPath));
99
92
  }
93
+ await project.shutdown();
100
94
  // TODO: Maybe run tasks in worker is a better way, see
101
95
  // https://github.com/vercel/next.js/blob/512d8283054407ab92b2583ecce3b253c3be7b85/packages/next/src/lib/worker.ts
102
96
  }
@@ -9,10 +9,10 @@ import fs from "fs";
9
9
  import getPort from "get-port";
10
10
  import { Hono } from "hono";
11
11
  import https from "https";
12
- import path from "path";
13
12
  import { resolveBundleOptions, } from "../config/webpackCompat.js";
14
13
  import { createHotReloader } from "../core/hmr.js";
15
- import { createHttpProxyMiddleware } from "../core/proxy-hono.js";
14
+ import { createHttpProxyMiddleware } from "../core/proxyHono.js";
15
+ import { getOutputPath } from "../utils/cleanOutput.js";
16
16
  import { blockStdout, getPackPath } from "../utils/common.js";
17
17
  import { findRootDir } from "../utils/findRoot.js";
18
18
  import { createSelfSignedCertificate } from "../utils/mkcert.js";
@@ -133,7 +133,7 @@ export function serve(options, projectPath, rootPath, serverOptions) {
133
133
  }
134
134
  const HMR_PATH = "/turbopack-hmr";
135
135
  async function runDev(options, projectPath, rootPath, serverOptions) {
136
- var _a, _b, _d, _e, _f, _g, _h;
136
+ var _a, _b, _d, _e, _f;
137
137
  blockStdout();
138
138
  process.title = "utoopack-dev-server";
139
139
  if (process.env.XCODE_PROFILE) {
@@ -143,8 +143,8 @@ async function runDev(options, projectPath, rootPath, serverOptions) {
143
143
  const { bundleOptions, projectPathResolved, rootPathResolved, serveOptsBase, } = await resolveDevConfig(options, projectPath, rootPath, serverOptions);
144
144
  const hotReloader = await createHotReloader(bundleOptions, projectPathResolved, rootPathResolved);
145
145
  await hotReloader.start();
146
- const distRoot = path.resolve(projectPathResolved, ((_b = (_a = options.config) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.path) || "./dist");
147
- const publicPath = (_e = (_d = options.config) === null || _d === void 0 ? void 0 : _d.output) === null || _e === void 0 ? void 0 : _e.publicPath;
146
+ const distRoot = getOutputPath(options.config, projectPathResolved);
147
+ const publicPath = (_b = (_a = options.config) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.publicPath;
148
148
  // Skip prefix stripping for "runtime" and when publicPath is absent (match dev.ts).
149
149
  const normalizedPrefix = publicPath && publicPath !== "runtime"
150
150
  ? normalizedPublicPath(publicPath)
@@ -185,7 +185,7 @@ async function runDev(options, projectPath, rootPath, serverOptions) {
185
185
  console.error("HMR WebSocket error", err);
186
186
  },
187
187
  })));
188
- const proxyRules = (_g = (_f = bundleOptions.config) === null || _f === void 0 ? void 0 : _f.devServer) === null || _g === void 0 ? void 0 : _g.proxy;
188
+ const proxyRules = (_e = (_d = bundleOptions.config) === null || _d === void 0 ? void 0 : _d.devServer) === null || _e === void 0 ? void 0 : _e.proxy;
189
189
  if (proxyRules && proxyRules.length > 0) {
190
190
  app.use("*", createHttpProxyMiddleware(proxyRules));
191
191
  }
@@ -214,7 +214,7 @@ async function runDev(options, projectPath, rootPath, serverOptions) {
214
214
  server.once("error", onError);
215
215
  });
216
216
  }
217
- await ((_h = serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.onReady) === null || _h === void 0 ? void 0 : _h.call(serverOptions, {
217
+ await ((_f = serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.onReady) === null || _f === void 0 ? void 0 : _f.call(serverOptions, {
218
218
  port: serveOptsBase.port,
219
219
  hostname: serveOptsBase.hostname,
220
220
  }));
package/esm/core/hmr.js CHANGED
@@ -1,13 +1,12 @@
1
1
  import { HMR_ACTIONS_SENT_TO_BROWSER, } from "@utoo/pack-shared";
2
2
  import { nanoid } from "nanoid";
3
- import path from "path";
4
3
  import { WebSocketServer } from "ws";
5
4
  import { HtmlPlugin } from "../plugins/HtmlPlugin.js";
5
+ import { cleanOutput, getOutputPath } from "../utils/cleanOutput.js";
6
6
  import { debounce, getPackPath, processIssues } from "../utils/common.js";
7
7
  import { getInitialAssetsFromStats } from "../utils/getInitialAssets.js";
8
8
  import { processHtmlEntry } from "../utils/htmlEntry.js";
9
- import { acquirePersistentCacheLock } from "../utils/lockfile.js";
10
- import { normalizePath } from "../utils/normalize-path.js";
9
+ import { normalizePath } from "../utils/normalizePath.js";
11
10
  import { useWorkerThreads } from "../utils/runtimePluginStratety.js";
12
11
  import { validateEntryPaths } from "../utils/validateEntry.js";
13
12
  import { projectFactory } from "./project.js";
@@ -22,44 +21,36 @@ export async function createHotReloader(bundleOptions, projectPath, rootPath) {
22
21
  const resolvedRootPath = rootPath || projectPath || process.cwd();
23
22
  processHtmlEntry(bundleOptions.config, resolvedProjectPath);
24
23
  validateEntryPaths(bundleOptions.config, resolvedProjectPath);
24
+ await cleanOutput(bundleOptions.config, resolvedProjectPath);
25
25
  const createProject = projectFactory();
26
- const persistentCaching = (_a = bundleOptions.config.persistentCaching) !== null && _a !== void 0 ? _a : false;
27
- const persistentCacheLock = await acquirePersistentCacheLock(resolvedProjectPath, "utoo pack dev", persistentCaching);
28
- let project;
29
- try {
30
- project = await createProject({
31
- processEnv: (_b = bundleOptions.processEnv) !== null && _b !== void 0 ? _b : {},
32
- watch: {
33
- enable: true,
34
- },
35
- dev: true,
36
- buildId: bundleOptions.buildId || nanoid(),
37
- tracing: (_c = bundleOptions.tracing) !== null && _c !== void 0 ? _c : true,
38
- config: {
39
- ...bundleOptions.config,
40
- mode: "development",
41
- stats: Boolean(process.env.ANALYZE) ||
42
- bundleOptions.config.stats ||
43
- bundleOptions.config.entry.some((e) => !!e.html),
44
- optimization: {
45
- ...bundleOptions.config.optimization,
46
- minify: false,
47
- moduleIds: "named",
48
- },
49
- persistentCaching: (_e = (_d = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _d === void 0 ? void 0 : _d.persistentCaching) !== null && _e !== void 0 ? _e : true,
50
- pluginRuntimeStrategy: (_g = (_f = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _f === void 0 ? void 0 : _f.pluginRuntimeStrategy) !== null && _g !== void 0 ? _g : (useWorkerThreads() ? "workerThreads" : "childProcesses"),
26
+ const project = await createProject({
27
+ processEnv: (_a = bundleOptions.processEnv) !== null && _a !== void 0 ? _a : {},
28
+ watch: {
29
+ enable: true,
30
+ },
31
+ dev: true,
32
+ buildId: bundleOptions.buildId || nanoid(),
33
+ tracing: (_b = bundleOptions.tracing) !== null && _b !== void 0 ? _b : true,
34
+ config: {
35
+ ...bundleOptions.config,
36
+ mode: "development",
37
+ stats: Boolean(process.env.ANALYZE) ||
38
+ bundleOptions.config.stats ||
39
+ bundleOptions.config.entry.some((e) => !!e.html),
40
+ optimization: {
41
+ ...bundleOptions.config.optimization,
42
+ minify: false,
43
+ moduleIds: "named",
51
44
  },
52
- projectPath: normalizePath(resolvedProjectPath),
53
- rootPath: resolvedRootPath,
54
- packPath: getPackPath(),
55
- }, {
56
- persistentCaching,
57
- });
58
- }
59
- catch (error) {
60
- persistentCacheLock === null || persistentCacheLock === void 0 ? void 0 : persistentCacheLock.unlockSync();
61
- throw error;
62
- }
45
+ persistentCaching: (_d = (_c = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _c === void 0 ? void 0 : _c.persistentCaching) !== null && _d !== void 0 ? _d : true,
46
+ pluginRuntimeStrategy: (_f = (_e = bundleOptions === null || bundleOptions === void 0 ? void 0 : bundleOptions.config) === null || _e === void 0 ? void 0 : _e.pluginRuntimeStrategy) !== null && _f !== void 0 ? _f : (useWorkerThreads() ? "workerThreads" : "childProcesses"),
47
+ },
48
+ projectPath: normalizePath(resolvedProjectPath),
49
+ rootPath: resolvedRootPath,
50
+ packPath: getPackPath(),
51
+ }, {
52
+ persistentCaching: (_g = bundleOptions.config.persistentCaching) !== null && _g !== void 0 ? _g : false,
53
+ });
63
54
  const entrypointsSubscription = project.entrypointsSubscribe();
64
55
  let currentEntriesHandlingResolve;
65
56
  let currentEntriesHandling = new Promise((resolve) => (currentEntriesHandlingResolve = resolve));
@@ -83,7 +74,6 @@ export async function createHotReloader(bundleOptions, projectPath, rootPath) {
83
74
  let backgroundWatchGeneration = 0;
84
75
  const backgroundWriteTasks = new Map();
85
76
  let closed = false;
86
- let closePromise;
87
77
  function sendToClient(client, payload) {
88
78
  client.send(JSON.stringify(payload));
89
79
  }
@@ -118,12 +108,12 @@ export async function createHotReloader(bundleOptions, projectPath, rootPath) {
118
108
  sendEnqueuedMessagesDebounce();
119
109
  }
120
110
  async function regenerateHtml() {
121
- var _a, _b;
111
+ var _a;
122
112
  if (htmlConfigs.length === 0) {
123
113
  return;
124
114
  }
125
- const outputDir = ((_a = bundleOptions.config.output) === null || _a === void 0 ? void 0 : _a.path) || path.join(process.cwd(), "dist");
126
- const publicPath = (_b = bundleOptions.config.output) === null || _b === void 0 ? void 0 : _b.publicPath;
115
+ const outputDir = getOutputPath(bundleOptions.config, resolvedProjectPath);
116
+ const publicPath = (_a = bundleOptions.config.output) === null || _a === void 0 ? void 0 : _a.publicPath;
127
117
  const assets = getInitialAssetsFromStats(outputDir);
128
118
  for (const config of htmlConfigs) {
129
119
  const plugin = new HtmlPlugin(config);
@@ -255,7 +245,6 @@ export async function createHotReloader(bundleOptions, projectPath, rootPath) {
255
245
  subscription === null || subscription === void 0 ? void 0 : subscription.return();
256
246
  }
257
247
  async function handleEntrypointsSubscription() {
258
- var _a, _b;
259
248
  for await (const entrypoints of entrypointsSubscription) {
260
249
  if (!currentEntriesHandlingResolve) {
261
250
  currentEntriesHandling = new Promise(
@@ -263,8 +252,8 @@ export async function createHotReloader(bundleOptions, projectPath, rootPath) {
263
252
  (resolve) => (currentEntriesHandlingResolve = resolve));
264
253
  }
265
254
  currentWatchedEntrypoints = [
266
- ...((_a = entrypoints.apps) !== null && _a !== void 0 ? _a : []),
267
- ...((_b = entrypoints.libraries) !== null && _b !== void 0 ? _b : []),
255
+ ...entrypoints.apps,
256
+ ...entrypoints.libraries,
268
257
  ];
269
258
  await writeEntrypointsToDisk(currentWatchedEntrypoints);
270
259
  if (backgroundWatchersStarted) {
@@ -449,14 +438,6 @@ export async function createHotReloader(bundleOptions, projectPath, rootPath) {
449
438
  close() {
450
439
  closed = true;
451
440
  void disposeBackgroundWatchSubscriptions();
452
- closePromise !== null && closePromise !== void 0 ? closePromise : (closePromise = project
453
- .onExit()
454
- .catch((err) => {
455
- console.error(err);
456
- })
457
- .finally(() => {
458
- persistentCacheLock === null || persistentCacheLock === void 0 ? void 0 : persistentCacheLock.unlockSync();
459
- }));
460
441
  for (const wsClient of clients) {
461
442
  wsClient.close();
462
443
  }
@@ -2,7 +2,7 @@ import { resolve } from "path";
2
2
  import { isDeepStrictEqual } from "util";
3
3
  import * as binding from "../binding.js";
4
4
  import { getPackPath, rustifyEnv } from "../utils/common.js";
5
- import { normalizePath } from "../utils/normalize-path.js";
5
+ import { normalizePath } from "../utils/normalizePath.js";
6
6
  import { runLoaderWorkerPool } from "./loaderWorkerPool.js";
7
7
  /**
8
8
  * An error caused by a bug in Turbopack, and not the user's code (e.g. a Rust panic). These should
@@ -0,0 +1,3 @@
1
+ import type { ConfigComplete } from "../config/types";
2
+ export declare function getOutputPath(config: ConfigComplete, projectPath: string): string;
3
+ export declare function cleanOutput(config: ConfigComplete, projectPath: string): Promise<void>;
@@ -0,0 +1,32 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ export function getOutputPath(config, projectPath) {
4
+ var _a;
5
+ return path.resolve(projectPath, ((_a = config.output) === null || _a === void 0 ? void 0 : _a.path) || "dist");
6
+ }
7
+ export async function cleanOutput(config, projectPath) {
8
+ var _a;
9
+ if (!((_a = config.output) === null || _a === void 0 ? void 0 : _a.clean)) {
10
+ return;
11
+ }
12
+ const outputPath = getOutputPath(config, projectPath);
13
+ let entries;
14
+ try {
15
+ entries = await fs.promises.readdir(outputPath, { withFileTypes: true });
16
+ }
17
+ catch (error) {
18
+ if (isNodeError(error) && error.code === "ENOENT") {
19
+ return;
20
+ }
21
+ throw error;
22
+ }
23
+ await Promise.all(entries.map((entry) => fs.promises.rm(path.join(outputPath, entry.name), {
24
+ force: true,
25
+ maxRetries: 3,
26
+ recursive: true,
27
+ retryDelay: 50,
28
+ })));
29
+ }
30
+ function isNodeError(error) {
31
+ return error instanceof Error && "code" in error;
32
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@utoo/pack",
3
- "version": "1.4.4-alpha.0",
3
+ "version": "1.4.4",
4
4
  "main": "cjs/index.js",
5
5
  "module": "esm/index.js",
6
6
  "types": "esm/index.d.ts",
@@ -41,7 +41,7 @@
41
41
  "@hono/node-server": "^1.19.11",
42
42
  "@hono/node-ws": "^1.3.0",
43
43
  "@swc/helpers": "0.5.15",
44
- "@utoo/pack-shared": "1.4.4-alpha.0",
44
+ "@utoo/pack-shared": "1.4.4",
45
45
  "domparser-rs": "^0.0.7",
46
46
  "find-up": "4.1.0",
47
47
  "get-port": "5.1.1",
@@ -92,12 +92,12 @@
92
92
  },
93
93
  "repository": "git@github.com:utooland/utoo.git",
94
94
  "optionalDependencies": {
95
- "@utoo/pack-darwin-arm64": "1.4.4-alpha.0",
96
- "@utoo/pack-darwin-x64": "1.4.4-alpha.0",
97
- "@utoo/pack-linux-arm64-gnu": "1.4.4-alpha.0",
98
- "@utoo/pack-linux-arm64-musl": "1.4.4-alpha.0",
99
- "@utoo/pack-linux-x64-gnu": "1.4.4-alpha.0",
100
- "@utoo/pack-linux-x64-musl": "1.4.4-alpha.0",
101
- "@utoo/pack-win32-x64-msvc": "1.4.4-alpha.0"
95
+ "@utoo/pack-darwin-arm64": "1.4.4",
96
+ "@utoo/pack-darwin-x64": "1.4.4",
97
+ "@utoo/pack-linux-arm64-gnu": "1.4.4",
98
+ "@utoo/pack-linux-arm64-musl": "1.4.4",
99
+ "@utoo/pack-linux-x64-gnu": "1.4.4",
100
+ "@utoo/pack-linux-x64-musl": "1.4.4",
101
+ "@utoo/pack-win32-x64-msvc": "1.4.4"
102
102
  }
103
103
  }
@@ -1,10 +0,0 @@
1
- export declare class PersistentCacheLock {
2
- private listener;
3
- private nativeLockfile;
4
- private constructor();
5
- static tryAcquire(lockPath: string, content?: string): PersistentCacheLock | undefined;
6
- static acquireWithRetries(lockPath: string, processName: string): Promise<PersistentCacheLock>;
7
- unlock(): Promise<void>;
8
- unlockSync(): void;
9
- }
10
- export declare function acquirePersistentCacheLock(projectPath: string, processName: string, persistentCaching: boolean): Promise<PersistentCacheLock | undefined>;
@@ -1,121 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.PersistentCacheLock = void 0;
40
- exports.acquirePersistentCacheLock = acquirePersistentCacheLock;
41
- const fs_1 = __importDefault(require("fs"));
42
- const path_1 = __importDefault(require("path"));
43
- const picocolors_1 = __importDefault(require("picocolors"));
44
- const binding = __importStar(require("../binding"));
45
- const RETRY_DELAY_MS = 10;
46
- const MAX_RETRY_MS = 1000;
47
- class PersistentCacheLock {
48
- constructor(nativeLockfile) {
49
- this.nativeLockfile = nativeLockfile;
50
- this.listener = () => this.unlockSync();
51
- process.on("exit", this.listener);
52
- }
53
- static tryAcquire(lockPath, content) {
54
- const nativeLockfile = binding.lockfileTryAcquireSync(lockPath, content);
55
- return nativeLockfile ? new PersistentCacheLock(nativeLockfile) : undefined;
56
- }
57
- static async acquireWithRetries(lockPath, processName) {
58
- const content = JSON.stringify({
59
- pid: process.pid,
60
- processName,
61
- startedAt: Date.now(),
62
- });
63
- const startMs = Date.now();
64
- let lockfile;
65
- while (Date.now() - startMs < MAX_RETRY_MS) {
66
- lockfile = PersistentCacheLock.tryAcquire(lockPath, content);
67
- if (lockfile) {
68
- return lockfile;
69
- }
70
- await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
71
- }
72
- throw new Error(formatLockError(lockPath, processName));
73
- }
74
- async unlock() {
75
- const lockfile = this.nativeLockfile;
76
- this.nativeLockfile = undefined;
77
- if (this.listener) {
78
- process.off("exit", this.listener);
79
- this.listener = undefined;
80
- }
81
- if (lockfile) {
82
- await binding.lockfileUnlock(lockfile);
83
- }
84
- }
85
- unlockSync() {
86
- const lockfile = this.nativeLockfile;
87
- this.nativeLockfile = undefined;
88
- if (this.listener) {
89
- process.off("exit", this.listener);
90
- this.listener = undefined;
91
- }
92
- if (lockfile) {
93
- binding.lockfileUnlockSync(lockfile);
94
- }
95
- }
96
- }
97
- exports.PersistentCacheLock = PersistentCacheLock;
98
- async function acquirePersistentCacheLock(projectPath, processName, persistentCaching) {
99
- if (!persistentCaching) {
100
- return undefined;
101
- }
102
- const internalDir = path_1.default.join(path_1.default.resolve(projectPath), ".turbopack");
103
- fs_1.default.mkdirSync(internalDir, { recursive: true });
104
- return PersistentCacheLock.acquireWithRetries(path_1.default.join(internalDir, "lock"), processName);
105
- }
106
- function formatLockError(lockPath, processName) {
107
- let owner = "";
108
- try {
109
- const data = JSON.parse(fs_1.default.readFileSync(lockPath, "utf-8"));
110
- if (data.pid) {
111
- const killCommand = process.platform === "win32"
112
- ? `taskkill /PID ${data.pid} /F`
113
- : `kill ${data.pid}`;
114
- owner = `\nExisting process: ${data.processName || "unknown"} (PID ${data.pid}).\nStop it with ${picocolors_1.default.cyan(killCommand)} if it is stale.`;
115
- }
116
- }
117
- catch (_a) {
118
- // The lock holder might be a version that did not write metadata.
119
- }
120
- return `Unable to acquire ${processName} persistent cache lock at ${picocolors_1.default.cyan(lockPath)}. Another utoo pack process may be using the same .turbopack cache.${owner}`;
121
- }
@@ -1,10 +0,0 @@
1
- export declare class PersistentCacheLock {
2
- private listener;
3
- private nativeLockfile;
4
- private constructor();
5
- static tryAcquire(lockPath: string, content?: string): PersistentCacheLock | undefined;
6
- static acquireWithRetries(lockPath: string, processName: string): Promise<PersistentCacheLock>;
7
- unlock(): Promise<void>;
8
- unlockSync(): void;
9
- }
10
- export declare function acquirePersistentCacheLock(projectPath: string, processName: string, persistentCaching: boolean): Promise<PersistentCacheLock | undefined>;
@@ -1,80 +0,0 @@
1
- import fs from "fs";
2
- import path from "path";
3
- import pc from "picocolors";
4
- import * as binding from "../binding.js";
5
- const RETRY_DELAY_MS = 10;
6
- const MAX_RETRY_MS = 1000;
7
- export class PersistentCacheLock {
8
- constructor(nativeLockfile) {
9
- this.nativeLockfile = nativeLockfile;
10
- this.listener = () => this.unlockSync();
11
- process.on("exit", this.listener);
12
- }
13
- static tryAcquire(lockPath, content) {
14
- const nativeLockfile = binding.lockfileTryAcquireSync(lockPath, content);
15
- return nativeLockfile ? new PersistentCacheLock(nativeLockfile) : undefined;
16
- }
17
- static async acquireWithRetries(lockPath, processName) {
18
- const content = JSON.stringify({
19
- pid: process.pid,
20
- processName,
21
- startedAt: Date.now(),
22
- });
23
- const startMs = Date.now();
24
- let lockfile;
25
- while (Date.now() - startMs < MAX_RETRY_MS) {
26
- lockfile = PersistentCacheLock.tryAcquire(lockPath, content);
27
- if (lockfile) {
28
- return lockfile;
29
- }
30
- await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
31
- }
32
- throw new Error(formatLockError(lockPath, processName));
33
- }
34
- async unlock() {
35
- const lockfile = this.nativeLockfile;
36
- this.nativeLockfile = undefined;
37
- if (this.listener) {
38
- process.off("exit", this.listener);
39
- this.listener = undefined;
40
- }
41
- if (lockfile) {
42
- await binding.lockfileUnlock(lockfile);
43
- }
44
- }
45
- unlockSync() {
46
- const lockfile = this.nativeLockfile;
47
- this.nativeLockfile = undefined;
48
- if (this.listener) {
49
- process.off("exit", this.listener);
50
- this.listener = undefined;
51
- }
52
- if (lockfile) {
53
- binding.lockfileUnlockSync(lockfile);
54
- }
55
- }
56
- }
57
- export async function acquirePersistentCacheLock(projectPath, processName, persistentCaching) {
58
- if (!persistentCaching) {
59
- return undefined;
60
- }
61
- const internalDir = path.join(path.resolve(projectPath), ".turbopack");
62
- fs.mkdirSync(internalDir, { recursive: true });
63
- return PersistentCacheLock.acquireWithRetries(path.join(internalDir, "lock"), processName);
64
- }
65
- function formatLockError(lockPath, processName) {
66
- let owner = "";
67
- try {
68
- const data = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
69
- if (data.pid) {
70
- const killCommand = process.platform === "win32"
71
- ? `taskkill /PID ${data.pid} /F`
72
- : `kill ${data.pid}`;
73
- owner = `\nExisting process: ${data.processName || "unknown"} (PID ${data.pid}).\nStop it with ${pc.cyan(killCommand)} if it is stale.`;
74
- }
75
- }
76
- catch (_a) {
77
- // The lock holder might be a version that did not write metadata.
78
- }
79
- return `Unable to acquire ${processName} persistent cache lock at ${pc.cyan(lockPath)}. Another utoo pack process may be using the same .turbopack cache.${owner}`;
80
- }
File without changes
File without changes
File without changes
File without changes