balm-core 6.0.0-alpha.7 → 6.0.0-alpha.9

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/dist/index.cjs CHANGED
@@ -61,8 +61,10 @@ __export(index_exports, {
61
61
  VirtualFile: () => VirtualFile,
62
62
  ZipTask: () => ZipTask,
63
63
  balm: () => balm,
64
+ buildEsbuildOptions: () => buildEsbuildOptions,
64
65
  createDefaultConfig: () => createDefaultConfig,
65
66
  createDevServerApp: () => createDevServerApp,
67
+ createEsbuildRunner: () => createEsbuildRunner,
66
68
  createHistoryFallbackMiddleware: () => createHistoryFallbackMiddleware,
67
69
  deepMerge: () => deepMerge,
68
70
  default: () => index_default,
@@ -76,10 +78,12 @@ __export(index_exports, {
76
78
  isFunction: () => isFunction,
77
79
  isManifestFile: () => isManifestFile,
78
80
  isObject: () => isObject,
81
+ isPortAvailable: () => isPortAvailable,
79
82
  isString: () => isString,
80
83
  localResolve: () => localResolve,
81
84
  localWorkspace: () => localWorkspace,
82
85
  logger: () => logger,
86
+ resolveAvailablePort: () => resolveAvailablePort,
83
87
  resolveConfig: () => resolveConfig,
84
88
  resolveDefaultEntry: () => resolveDefaultEntry,
85
89
  resolveServerHost: () => resolveServerHost,
@@ -249,6 +253,7 @@ function createDefaultConfig(workspace = process.cwd()) {
249
253
  const server = {
250
254
  host: null,
251
255
  port: 3e3,
256
+ strictPort: false,
252
257
  open: true,
253
258
  proxy: false,
254
259
  proxyOptions: false,
@@ -759,11 +764,18 @@ var CleanTask = class extends BaseTask {
759
764
  super({ name: "clean", description: "Clean output directories" });
760
765
  }
761
766
  async run(config) {
762
- const targets = [
763
- import_node_path5.default.join(config.workspace, config.roots.tmp),
764
- import_node_path5.default.join(config.workspace, config.roots.target)
765
- ];
766
- const deleted = await file.remove(targets);
767
+ const workspaceRoot = import_node_path5.default.resolve(config.workspace);
768
+ const activeDestBase = import_node_path5.default.resolve(
769
+ config.dest?.base || import_node_path5.default.join(
770
+ workspaceRoot,
771
+ config.env.isProd || !config.inFrontend ? config.roots.target : config.roots.tmp
772
+ )
773
+ );
774
+ if (activeDestBase === workspaceRoot || workspaceRoot.startsWith(`${activeDestBase}${import_node_path5.default.sep}`)) {
775
+ logger.warn("clean", `Skipping unsafe clean target: ${activeDestBase}`);
776
+ return;
777
+ }
778
+ const deleted = await file.remove([activeDestBase]);
767
779
  logger.info("clean", `Deleted ${deleted.length} directories`);
768
780
  }
769
781
  };
@@ -1575,13 +1587,13 @@ async function runRollup(config, customInputOptions = {}, customOutputOptions =
1575
1587
 
1576
1588
  // src/bundler/esbuild.ts
1577
1589
  var esbuild = __toESM(require("esbuild"), 1);
1578
- async function runEsbuild(config, customOptions = {}) {
1590
+ function buildEsbuildOptions(config, customOptions = {}) {
1579
1591
  const isProd = config.env.isProd;
1580
1592
  let entryPoints = customOptions.entryPoints || config.scripts.entry;
1581
1593
  if (!entryPoints) {
1582
1594
  entryPoints = [resolveDefaultEntry(config.src.js)];
1583
1595
  }
1584
- const defaultOptions = {
1596
+ return {
1585
1597
  entryPoints: Array.isArray(entryPoints) ? entryPoints : typeof entryPoints === "string" ? [entryPoints] : entryPoints,
1586
1598
  absWorkingDir: config.workspace,
1587
1599
  bundle: true,
@@ -1597,18 +1609,53 @@ async function runEsbuild(config, customOptions = {}) {
1597
1609
  ...config.scripts.esbuildOptions,
1598
1610
  ...customOptions
1599
1611
  };
1612
+ }
1613
+ async function runEsbuild(config, customOptions = {}) {
1614
+ const options = buildEsbuildOptions(config, customOptions);
1600
1615
  try {
1601
- return await esbuild.build(defaultOptions);
1616
+ return await esbuild.build(options);
1602
1617
  } catch (err) {
1603
1618
  logger.error("esbuild", err.message || err);
1604
1619
  throw err;
1605
1620
  }
1606
1621
  }
1622
+ async function createEsbuildRunner(config, customOptions = {}) {
1623
+ const options = buildEsbuildOptions(config, customOptions);
1624
+ const ctx = await esbuild.context(options);
1625
+ return {
1626
+ async rebuild() {
1627
+ try {
1628
+ return await ctx.rebuild();
1629
+ } catch (err) {
1630
+ logger.error("esbuild", err.message || err);
1631
+ throw err;
1632
+ }
1633
+ },
1634
+ async dispose() {
1635
+ await ctx.dispose();
1636
+ }
1637
+ };
1638
+ }
1607
1639
 
1608
1640
  // src/tasks/script.ts
1609
1641
  var ScriptTask = class extends BaseTask {
1610
- constructor() {
1642
+ incremental;
1643
+ esbuildRunner = null;
1644
+ esbuildConfigKey = null;
1645
+ constructor(options = {}) {
1611
1646
  super({ name: "script", description: "Bundle JavaScript/TypeScript" });
1647
+ this.incremental = Boolean(options.incremental);
1648
+ }
1649
+ getEsbuildConfigKey(config) {
1650
+ return JSON.stringify({
1651
+ workspace: config.workspace,
1652
+ outdir: config.dest.js,
1653
+ entry: config.scripts.entry,
1654
+ alias: config.alias,
1655
+ scriptAlias: config.scripts.alias,
1656
+ target: config.scripts.target,
1657
+ minify: config.env.isProd || config.scripts.minify
1658
+ });
1612
1659
  }
1613
1660
  async run(config) {
1614
1661
  const bundler = config.scripts.bundler;
@@ -1617,7 +1664,17 @@ var ScriptTask = class extends BaseTask {
1617
1664
  await runRollup(config);
1618
1665
  break;
1619
1666
  case "esbuild" /* esbuild */:
1620
- await runEsbuild(config);
1667
+ if (this.incremental && !config.env.isProd) {
1668
+ const nextKey = this.getEsbuildConfigKey(config);
1669
+ if (!this.esbuildRunner || this.esbuildConfigKey !== nextKey) {
1670
+ await this.dispose();
1671
+ this.esbuildRunner = await createEsbuildRunner(config);
1672
+ this.esbuildConfigKey = nextKey;
1673
+ }
1674
+ await this.esbuildRunner.rebuild();
1675
+ } else {
1676
+ await runEsbuild(config);
1677
+ }
1621
1678
  break;
1622
1679
  case "webpack" /* webpack */:
1623
1680
  default:
@@ -1625,6 +1682,14 @@ var ScriptTask = class extends BaseTask {
1625
1682
  break;
1626
1683
  }
1627
1684
  }
1685
+ async dispose() {
1686
+ if (this.esbuildRunner) {
1687
+ const runner = this.esbuildRunner;
1688
+ this.esbuildRunner = null;
1689
+ this.esbuildConfigKey = null;
1690
+ await runner.dispose();
1691
+ }
1692
+ }
1628
1693
  };
1629
1694
 
1630
1695
  // src/tasks/html.ts
@@ -1685,28 +1750,175 @@ var LIVE_RELOAD_SCRIPT = `
1685
1750
  <!-- BalmJS Live Reload -->
1686
1751
  <script>
1687
1752
  (() => {
1753
+ if (window.__BALM_LIVE_RELOAD__) return;
1754
+ window.__BALM_LIVE_RELOAD__ = true;
1755
+
1688
1756
  const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
1689
- const ws = new WebSocket(\`\${protocol}//\${location.host}/__balm_ws\`);
1690
- ws.onmessage = (e) => {
1757
+ const wsUrl = \`\${protocol}//\${location.host}/__balm_ws\`;
1758
+ let ws = null;
1759
+ let reconnectTimer = null;
1760
+ let syncTimeout = null;
1761
+ let retryDelay = 500;
1762
+ let serverId = null;
1763
+ let lastBuildVersion = null;
1764
+ let reloading = false;
1765
+
1766
+ const clearTimers = () => {
1767
+ if (reconnectTimer) {
1768
+ clearTimeout(reconnectTimer);
1769
+ reconnectTimer = null;
1770
+ }
1771
+ if (syncTimeout) {
1772
+ clearTimeout(syncTimeout);
1773
+ syncTimeout = null;
1774
+ }
1775
+ };
1776
+
1777
+ const triggerReload = (reason) => {
1778
+ if (reloading) return;
1779
+ reloading = true;
1780
+ clearTimers();
1781
+ console.log(\`[BalmJS] Reloading page (\${reason})...\`);
1782
+ location.reload();
1783
+ };
1784
+
1785
+ const reloadLocalStylesheets = () => {
1786
+ const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
1787
+ const stamp = Date.now().toString();
1788
+ for (const link of links) {
1789
+ if (!link.href || link.dataset.balmStale === '1') continue;
1790
+ let url;
1791
+ try {
1792
+ url = new URL(link.href, location.href);
1793
+ } catch {
1794
+ continue;
1795
+ }
1796
+ if (url.origin !== location.origin) continue;
1797
+ url.searchParams.set('_balm_t', stamp);
1798
+
1799
+ const next = link.cloneNode(false);
1800
+ next.href = url.href;
1801
+ link.dataset.balmStale = '1';
1802
+ const cleanupOld = () => {
1803
+ if (link.parentNode) link.parentNode.removeChild(link);
1804
+ };
1805
+ next.addEventListener('load', cleanupOld, { once: true });
1806
+ next.addEventListener('error', cleanupOld, { once: true });
1807
+ if (link.parentNode) {
1808
+ link.parentNode.insertBefore(next, link.nextSibling);
1809
+ }
1810
+ }
1811
+ };
1812
+
1813
+ const scheduleReconnect = () => {
1814
+ if (reconnectTimer || reloading) return;
1815
+ reconnectTimer = setTimeout(() => {
1816
+ reconnectTimer = null;
1817
+ connect();
1818
+ }, retryDelay);
1819
+ retryDelay = Math.min(retryDelay * 2, 3000);
1820
+ };
1821
+
1822
+ const connect = () => {
1823
+ if (reloading) return;
1824
+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
1825
+ return;
1826
+ }
1827
+
1691
1828
  try {
1692
- const msg = JSON.parse(e.data);
1693
- if (msg.type === 'reload') {
1694
- console.log('[BalmJS] Reloading page...');
1695
- location.reload();
1696
- } else if (msg.type === 'reload-css') {
1697
- console.log('[BalmJS] Reloading CSS...');
1698
- const links = document.querySelectorAll('link[rel="stylesheet"]');
1699
- for (const link of links) {
1700
- const url = new URL(link.href);
1701
- url.searchParams.set('_balm_t', Date.now().toString());
1702
- link.href = url.href;
1829
+ ws = new WebSocket(wsUrl);
1830
+ } catch {
1831
+ scheduleReconnect();
1832
+ return;
1833
+ }
1834
+
1835
+ ws.onopen = () => {
1836
+ retryDelay = 500;
1837
+ };
1838
+
1839
+ ws.onmessage = (e) => {
1840
+ try {
1841
+ const msg = JSON.parse(e.data);
1842
+ if (syncTimeout) {
1843
+ clearTimeout(syncTimeout);
1844
+ syncTimeout = null;
1845
+ }
1846
+ if (msg.type === 'connected') {
1847
+ if (serverId !== null && msg.serverId && msg.serverId !== serverId) {
1848
+ triggerReload('server restarted');
1849
+ return;
1850
+ }
1851
+ if (
1852
+ lastBuildVersion !== null &&
1853
+ typeof msg.buildVersion === 'number' &&
1854
+ msg.buildVersion > lastBuildVersion
1855
+ ) {
1856
+ triggerReload('missed rebuild');
1857
+ return;
1858
+ }
1859
+ if (msg.serverId) serverId = msg.serverId;
1860
+ if (typeof msg.buildVersion === 'number') lastBuildVersion = msg.buildVersion;
1861
+ } else if (msg.type === 'reload') {
1862
+ if (typeof msg.buildVersion === 'number') lastBuildVersion = msg.buildVersion;
1863
+ triggerReload('file changed');
1864
+ } else if (msg.type === 'reload-css') {
1865
+ if (typeof msg.buildVersion === 'number') lastBuildVersion = msg.buildVersion;
1866
+ console.log('[BalmJS] Reloading CSS...');
1867
+ reloadLocalStylesheets();
1703
1868
  }
1869
+ } catch {}
1870
+ };
1871
+
1872
+ ws.onerror = () => {
1873
+ try {
1874
+ ws?.close();
1875
+ } catch {}
1876
+ };
1877
+
1878
+ ws.onclose = () => {
1879
+ ws = null;
1880
+ if (syncTimeout) {
1881
+ clearTimeout(syncTimeout);
1882
+ syncTimeout = null;
1704
1883
  }
1705
- } catch {}
1884
+ scheduleReconnect();
1885
+ };
1706
1886
  };
1707
- ws.onclose = () => {
1708
- setTimeout(() => location.reload(), 2000);
1887
+
1888
+ const syncOrReconnect = () => {
1889
+ if (reloading) return;
1890
+ retryDelay = 500;
1891
+ if (reconnectTimer) {
1892
+ clearTimeout(reconnectTimer);
1893
+ reconnectTimer = null;
1894
+ }
1895
+ if (ws && ws.readyState === WebSocket.OPEN) {
1896
+ try {
1897
+ ws.send(JSON.stringify({ type: 'sync' }));
1898
+ if (syncTimeout) clearTimeout(syncTimeout);
1899
+ syncTimeout = setTimeout(() => {
1900
+ syncTimeout = null;
1901
+ try {
1902
+ ws?.close();
1903
+ } catch {}
1904
+ ws = null;
1905
+ connect();
1906
+ }, 1500);
1907
+ return;
1908
+ } catch {}
1909
+ }
1910
+ connect();
1709
1911
  };
1912
+
1913
+ document.addEventListener('visibilitychange', () => {
1914
+ if (document.visibilityState === 'visible') {
1915
+ syncOrReconnect();
1916
+ }
1917
+ });
1918
+
1919
+ window.addEventListener('online', syncOrReconnect);
1920
+
1921
+ connect();
1710
1922
  })();
1711
1923
  </script>
1712
1924
  `;
@@ -2427,84 +2639,362 @@ var FtpTask = class extends BaseTask {
2427
2639
 
2428
2640
  // src/tasks/server.ts
2429
2641
  var import_node_http = __toESM(require("http"), 1);
2430
- var import_node_fs8 = __toESM(require("fs"), 1);
2642
+ var import_node_net = __toESM(require("net"), 1);
2643
+ var import_node_crypto2 = __toESM(require("crypto"), 1);
2644
+ var import_node_fs9 = __toESM(require("fs"), 1);
2431
2645
  var import_node_os = __toESM(require("os"), 1);
2432
- var import_node_path24 = __toESM(require("path"), 1);
2646
+ var import_node_path25 = __toESM(require("path"), 1);
2433
2647
  var import_connect = __toESM(require("connect"), 1);
2434
2648
  var import_serve_static = __toESM(require("serve-static"), 1);
2435
2649
  var import_ws = require("ws");
2436
2650
  var import_http_proxy_middleware = require("http-proxy-middleware");
2437
2651
 
2438
2652
  // src/watcher/index.ts
2439
- var import_node_fs7 = __toESM(require("fs"), 1);
2653
+ var import_node_fs8 = __toESM(require("fs"), 1);
2654
+ var import_node_path24 = __toESM(require("path"), 1);
2655
+
2656
+ // src/tasks/static.ts
2440
2657
  var import_node_path23 = __toESM(require("path"), 1);
2658
+ var import_node_fs7 = require("fs");
2659
+ var StaticTask = class extends BaseTask {
2660
+ constructor() {
2661
+ super({ name: "static", description: "Copy static assets, images, fonts, and manifest" });
2662
+ }
2663
+ async run(config) {
2664
+ const srcBase = config.src.base;
2665
+ const destBase = config.dest.base;
2666
+ const staticPatterns = [
2667
+ import_node_path23.default.join(srcBase, "*.{ico,png,svg,json,txt,xml,webmanifest}"),
2668
+ `!${import_node_path23.default.join(srcBase, "*.html")}`
2669
+ ];
2670
+ const extraIncludes = [
2671
+ ...config.extras?.includes || [],
2672
+ ...config.assets?.includes || []
2673
+ ];
2674
+ const extraExcludes = [
2675
+ ...config.extras?.excludes || [],
2676
+ ...config.assets?.excludes || []
2677
+ ];
2678
+ for (const inc of extraIncludes) {
2679
+ const pattern = import_node_path23.default.isAbsolute(inc) ? inc : import_node_path23.default.join(srcBase, inc);
2680
+ staticPatterns.push(pattern);
2681
+ }
2682
+ for (const exc of extraExcludes) {
2683
+ const pattern = import_node_path23.default.isAbsolute(exc) ? exc : import_node_path23.default.join(srcBase, exc);
2684
+ staticPatterns.push(`!${pattern}`);
2685
+ }
2686
+ const pipeline = Pipeline.from(staticPatterns, {
2687
+ cwd: config.workspace,
2688
+ base: srcBase
2689
+ });
2690
+ const publicUrlReplacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2691
+ pipeline.pipe(async (file2) => {
2692
+ const isManifest = isManifestFile(file2, config);
2693
+ if (isManifest || file2.extname === ".json") {
2694
+ let content = file2.toString();
2695
+ content = content.replaceAll(PUBLIC_URL, publicUrlReplacement);
2696
+ if (isManifest) {
2697
+ content = rewriteHtmlAssetPaths(content, config);
2698
+ }
2699
+ file2.contents = Buffer.from(content);
2700
+ }
2701
+ return file2;
2702
+ });
2703
+ await pipeline.dest(destBase);
2704
+ if (config.src.img && (0, import_node_fs7.existsSync)(config.src.img)) {
2705
+ const imgPipeline = Pipeline.from(import_node_path23.default.join(config.src.img, "**/*"), {
2706
+ cwd: config.workspace,
2707
+ base: config.src.img
2708
+ });
2709
+ await imgPipeline.dest(config.dest.img);
2710
+ }
2711
+ if (config.src.font && (0, import_node_fs7.existsSync)(config.src.font)) {
2712
+ const fontPipeline = Pipeline.from(import_node_path23.default.join(config.src.font, "**/*"), {
2713
+ cwd: config.workspace,
2714
+ base: config.src.font
2715
+ });
2716
+ await fontPipeline.dest(config.dest.font);
2717
+ }
2718
+ if (config.src.media && (0, import_node_fs7.existsSync)(config.src.media)) {
2719
+ const mediaPipeline = Pipeline.from(import_node_path23.default.join(config.src.media, "**/*"), {
2720
+ cwd: config.workspace,
2721
+ base: config.src.media
2722
+ });
2723
+ await mediaPipeline.dest(config.dest.media);
2724
+ }
2725
+ const publicDir = import_node_path23.default.join(config.workspace, "public");
2726
+ if ((0, import_node_fs7.existsSync)(publicDir)) {
2727
+ const pubPipeline = Pipeline.from(import_node_path23.default.join(publicDir, "**/*"), {
2728
+ cwd: config.workspace,
2729
+ base: publicDir
2730
+ });
2731
+ await pubPipeline.dest(destBase);
2732
+ }
2733
+ }
2734
+ };
2735
+
2736
+ // src/watcher/index.ts
2441
2737
  var import_picocolors3 = __toESM(require("picocolors"), 1);
2738
+ var IGNORED_BASENAMES = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", "4913"]);
2739
+ var CONFIG_FILENAMES = [
2740
+ "balm.config.js",
2741
+ "balm.config.mjs",
2742
+ "balm.config.cjs",
2743
+ "balm.config.ts"
2744
+ ];
2745
+ function isSubPath(targetPath, parentDir) {
2746
+ const normalizedTarget = import_node_path24.default.resolve(targetPath);
2747
+ const normalizedParent = import_node_path24.default.resolve(parentDir);
2748
+ return normalizedTarget === normalizedParent || normalizedTarget.startsWith(`${normalizedParent}${import_node_path24.default.sep}`);
2749
+ }
2750
+ function isIgnoredWatchFile(filePath, excludedDirs = []) {
2751
+ if (!filePath) return true;
2752
+ const normalized = filePath.replace(/\\/g, "/");
2753
+ if (normalized.includes("/node_modules/") || normalized.startsWith("node_modules/") || normalized.includes("/.git/") || normalized.startsWith(".git/")) {
2754
+ return true;
2755
+ }
2756
+ const base = import_node_path24.default.basename(normalized);
2757
+ if (IGNORED_BASENAMES.has(base) || base.startsWith(".#") || base.startsWith("#") || base.startsWith(".~") || /(\.(swp|swo|swx|tmp|bak)|~)$/i.test(base)) {
2758
+ return true;
2759
+ }
2760
+ if (import_node_path24.default.isAbsolute(filePath)) {
2761
+ for (const dir of excludedDirs) {
2762
+ if (dir && isSubPath(filePath, dir)) {
2763
+ return true;
2764
+ }
2765
+ }
2766
+ }
2767
+ return false;
2768
+ }
2442
2769
  var FileWatcher = class {
2443
2770
  config;
2444
2771
  broadcast;
2445
2772
  debounceTimer = null;
2773
+ configWarnTimer = null;
2446
2774
  pendingFiles = /* @__PURE__ */ new Set();
2447
2775
  styleTask;
2448
2776
  scriptTask;
2449
2777
  htmlTask;
2778
+ staticTask;
2450
2779
  watchers = [];
2451
2780
  isRebuilding = false;
2781
+ needsRebuild = false;
2782
+ recoveryPromise = null;
2452
2783
  constructor(config, broadcast) {
2453
2784
  this.config = config;
2454
2785
  this.broadcast = broadcast;
2455
2786
  this.styleTask = new StyleTask();
2456
- this.scriptTask = new ScriptTask();
2787
+ this.scriptTask = new ScriptTask({ incremental: true });
2457
2788
  this.htmlTask = new HtmlTask();
2789
+ this.staticTask = new StaticTask();
2790
+ }
2791
+ getExcludedOutputDirs() {
2792
+ const workspaceRoot = import_node_path24.default.resolve(this.config.workspace);
2793
+ const candidates = [
2794
+ this.config.dest?.base,
2795
+ this.config.roots?.tmp ? import_node_path24.default.join(workspaceRoot, this.config.roots.tmp) : "",
2796
+ this.config.roots?.target ? import_node_path24.default.join(workspaceRoot, this.config.roots.target) : ""
2797
+ ].filter((dir) => Boolean(dir));
2798
+ return Array.from(
2799
+ new Set(
2800
+ candidates.map((dir) => import_node_path24.default.resolve(dir)).filter((dir) => dir !== workspaceRoot)
2801
+ )
2802
+ );
2803
+ }
2804
+ resolveAliasWatchDirs(excludedDirs) {
2805
+ const workspaceRoot = import_node_path24.default.resolve(this.config.workspace);
2806
+ const mergedAliases = {
2807
+ ...this.config.alias,
2808
+ ...this.config.scripts?.alias,
2809
+ ...this.config.styles?.alias
2810
+ };
2811
+ const dirs = [];
2812
+ for (const target of Object.values(mergedAliases)) {
2813
+ if (typeof target !== "string" || !target.trim()) continue;
2814
+ const resolved = import_node_path24.default.isAbsolute(target) ? import_node_path24.default.resolve(target) : import_node_path24.default.resolve(workspaceRoot, target);
2815
+ if (resolved.includes(`${import_node_path24.default.sep}node_modules`)) continue;
2816
+ if (!import_node_fs8.default.existsSync(resolved)) continue;
2817
+ try {
2818
+ const stat = import_node_fs8.default.statSync(resolved);
2819
+ const watchDir = stat.isDirectory() ? resolved : import_node_path24.default.dirname(resolved);
2820
+ if (watchDir === workspaceRoot || watchDir.includes(`${import_node_path24.default.sep}node_modules`) || excludedDirs.some((excluded) => isSubPath(watchDir, excluded))) {
2821
+ continue;
2822
+ }
2823
+ dirs.push(watchDir);
2824
+ } catch {
2825
+ }
2826
+ }
2827
+ return dirs;
2458
2828
  }
2459
2829
  getWatchDirs() {
2830
+ const workspaceRoot = import_node_path24.default.resolve(this.config.workspace);
2831
+ const excludedDirs = this.getExcludedOutputDirs();
2832
+ const publicDir = import_node_path24.default.join(workspaceRoot, "public");
2833
+ const customTemplate = this.config.scripts?.htmlPluginOptions?.template;
2834
+ const customTemplateDir = typeof customTemplate === "string" && customTemplate.trim() ? import_node_path24.default.dirname(import_node_path24.default.resolve(workspaceRoot, customTemplate)) : "";
2460
2835
  const candidates = [
2461
2836
  this.config.src.base,
2837
+ publicDir,
2838
+ customTemplateDir,
2462
2839
  ...this.config.scripts.includeJsResource || [],
2463
- ...this.config.styles.atImportPaths || []
2840
+ ...this.config.styles.atImportPaths || [],
2841
+ ...this.resolveAliasWatchDirs(excludedDirs)
2464
2842
  ];
2465
- const resolved = candidates.filter(Boolean).map((dir) => import_node_path23.default.isAbsolute(dir) ? dir : import_node_path23.default.resolve(this.config.workspace, dir)).filter((dir) => import_node_fs7.default.existsSync(dir) && !dir.includes(`${import_node_path23.default.sep}node_modules`));
2843
+ const resolved = candidates.filter(Boolean).map(
2844
+ (dir) => import_node_path24.default.isAbsolute(dir) ? import_node_path24.default.resolve(dir) : import_node_path24.default.resolve(workspaceRoot, dir)
2845
+ ).filter((dir) => {
2846
+ if (dir.includes(`${import_node_path24.default.sep}node_modules`)) return false;
2847
+ if (excludedDirs.some((excluded) => isSubPath(dir, excluded))) return false;
2848
+ try {
2849
+ return import_node_fs8.default.existsSync(dir) && import_node_fs8.default.statSync(dir).isDirectory();
2850
+ } catch {
2851
+ return false;
2852
+ }
2853
+ });
2466
2854
  const unique = Array.from(new Set(resolved)).sort((a, b) => a.length - b.length);
2467
2855
  return unique.filter(
2468
- (dir, index) => !unique.slice(0, index).some((parent) => dir.startsWith(`${parent}${import_node_path23.default.sep}`))
2856
+ (dir, index) => !unique.slice(0, index).some((parent) => dir.startsWith(`${parent}${import_node_path24.default.sep}`))
2469
2857
  );
2470
2858
  }
2859
+ watchConfigFile() {
2860
+ const workspaceRoot = import_node_path24.default.resolve(this.config.workspace);
2861
+ for (const name of CONFIG_FILENAMES) {
2862
+ const configPath = import_node_path24.default.join(workspaceRoot, name);
2863
+ if (!import_node_fs8.default.existsSync(configPath)) continue;
2864
+ try {
2865
+ const watcher = import_node_fs8.default.watch(configPath, () => {
2866
+ if (this.configWarnTimer) clearTimeout(this.configWarnTimer);
2867
+ this.configWarnTimer = setTimeout(() => {
2868
+ logger.warn(
2869
+ "watch",
2870
+ `${import_picocolors3.default.yellow(name)} changed \u2014 restart dev server to apply config updates`
2871
+ );
2872
+ }, 200);
2873
+ });
2874
+ watcher.on("error", (err) => {
2875
+ logger.warn("watch", `Config watcher error for ${name}: ${err.message}`);
2876
+ });
2877
+ this.watchers.push(watcher);
2878
+ } catch {
2879
+ }
2880
+ break;
2881
+ }
2882
+ }
2471
2883
  start() {
2472
2884
  const watchDirs = this.getWatchDirs();
2473
- if (!watchDirs.length) return;
2885
+ const excludedDirs = this.getExcludedOutputDirs();
2474
2886
  for (const watchDir of watchDirs) {
2475
2887
  logger.info("watch", `Watching for file changes in ${import_picocolors3.default.cyan(watchDir)}`);
2476
2888
  try {
2477
- const watcher = import_node_fs7.default.watch(watchDir, { recursive: true }, (_eventType, filename) => {
2889
+ const watcher = import_node_fs8.default.watch(watchDir, { recursive: true }, (_eventType, filename) => {
2478
2890
  if (!filename) return;
2479
- const normalized = filename.replace(/\\/g, "/");
2480
- if (normalized.includes("node_modules/") || normalized.startsWith(".git/")) {
2891
+ const fullPath = import_node_path24.default.join(watchDir, filename.toString());
2892
+ if (isIgnoredWatchFile(fullPath, excludedDirs)) {
2481
2893
  return;
2482
2894
  }
2483
- this.pendingFiles.add(filename);
2895
+ this.pendingFiles.add(fullPath);
2484
2896
  if (this.debounceTimer) clearTimeout(this.debounceTimer);
2485
2897
  this.debounceTimer = setTimeout(() => {
2486
- this.handleChanges();
2898
+ void this.handleChanges();
2487
2899
  }, 50);
2488
2900
  });
2901
+ watcher.on("error", (err) => {
2902
+ logger.warn("watch", `Watcher error for ${watchDir}: ${err.message}`);
2903
+ });
2489
2904
  this.watchers.push(watcher);
2490
2905
  } catch (err) {
2491
2906
  logger.warn("watch", `Native recursive watch failed for ${watchDir}: ${err.message}`);
2492
2907
  }
2493
2908
  }
2909
+ this.watchConfigFile();
2910
+ }
2911
+ async rebuildAll() {
2912
+ if (this.recoveryPromise) {
2913
+ return this.recoveryPromise;
2914
+ }
2915
+ this.recoveryPromise = (async () => {
2916
+ this.isRebuilding = true;
2917
+ try {
2918
+ const start = performance.now();
2919
+ await this.styleTask.run(this.config);
2920
+ await this.scriptTask.run(this.config);
2921
+ await this.staticTask.run(this.config);
2922
+ await this.htmlTask.run(this.config);
2923
+ const duration = (performance.now() - start).toFixed(1);
2924
+ logger.info("watch", `Recovered dev workspace in ${import_picocolors3.default.bold(duration + "ms")}`);
2925
+ } finally {
2926
+ this.isRebuilding = false;
2927
+ }
2928
+ })();
2929
+ try {
2930
+ await this.recoveryPromise;
2931
+ } finally {
2932
+ this.recoveryPromise = null;
2933
+ }
2934
+ }
2935
+ classifyChanges(changed) {
2936
+ const publicDir = import_node_path24.default.resolve(this.config.workspace, "public");
2937
+ const staticAssetDirs = [
2938
+ this.config.src.img,
2939
+ this.config.src.font,
2940
+ this.config.src.media
2941
+ ].filter(Boolean).map((dir) => import_node_path24.default.resolve(dir));
2942
+ const manifestBasename = import_node_path24.default.basename(this.config.pwa?.manifest || "manifest.json");
2943
+ let hasStyle = false;
2944
+ let hasScript = false;
2945
+ let hasHtml = false;
2946
+ let hasStatic = false;
2947
+ let hasOther = false;
2948
+ for (const filePath of changed) {
2949
+ const isAbs = import_node_path24.default.isAbsolute(filePath);
2950
+ const base = import_node_path24.default.basename(filePath);
2951
+ if (isAbs && isSubPath(filePath, publicDir)) {
2952
+ hasStatic = true;
2953
+ continue;
2954
+ }
2955
+ if (isAbs && staticAssetDirs.some((dir) => isSubPath(filePath, dir))) {
2956
+ hasStatic = true;
2957
+ continue;
2958
+ }
2959
+ if (base === manifestBasename || /\.webmanifest$/i.test(base)) {
2960
+ hasStatic = true;
2961
+ hasHtml = true;
2962
+ continue;
2963
+ }
2964
+ if (/\.html?$/i.test(base)) {
2965
+ hasHtml = true;
2966
+ continue;
2967
+ }
2968
+ if (/\.(scss|sass|less|css)$/i.test(base)) {
2969
+ hasStyle = true;
2970
+ continue;
2971
+ }
2972
+ if (/\.(js|mjs|cjs|ts|jsx|tsx|vue|md|json)$/i.test(base)) {
2973
+ hasScript = true;
2974
+ continue;
2975
+ }
2976
+ if (/\.(ico|png|jpe?g|gif|webp|avif|svg|txt|xml|woff2?|ttf|eot|otf|mp4|webm|mp3|ogg|wav)$/i.test(
2977
+ base
2978
+ )) {
2979
+ hasStatic = true;
2980
+ continue;
2981
+ }
2982
+ hasOther = true;
2983
+ }
2984
+ return { hasStyle, hasScript, hasHtml, hasStatic, hasOther };
2494
2985
  }
2495
2986
  async handleChanges() {
2496
2987
  if (this.isRebuilding) {
2497
- this.debounceTimer = setTimeout(() => this.handleChanges(), 50);
2988
+ this.needsRebuild = true;
2498
2989
  return;
2499
2990
  }
2500
- const changed = Array.from(this.pendingFiles);
2991
+ const excludedDirs = this.getExcludedOutputDirs();
2992
+ const changed = Array.from(this.pendingFiles).filter(
2993
+ (f) => !isIgnoredWatchFile(f, excludedDirs)
2994
+ );
2501
2995
  this.pendingFiles.clear();
2502
2996
  if (!changed.length) return;
2503
- const hasStyle = changed.some((f) => /\.(scss|sass|less|css)$/i.test(f));
2504
- const hasScript = changed.some(
2505
- (f) => /\.(js|mjs|cjs|ts|jsx|tsx|vue|md|json)$/i.test(f)
2506
- );
2507
- const hasHtml = changed.some((f) => /\.html$/i.test(f));
2997
+ const { hasStyle, hasScript, hasHtml, hasStatic, hasOther } = this.classifyChanges(changed);
2508
2998
  this.isRebuilding = true;
2509
2999
  try {
2510
3000
  if (hasStyle) {
@@ -2512,29 +3002,40 @@ var FileWatcher = class {
2512
3002
  await this.styleTask.run(this.config);
2513
3003
  const duration = (performance.now() - start).toFixed(1);
2514
3004
  logger.info("watch", `Recompiled styles in ${import_picocolors3.default.bold(duration + "ms")}`);
2515
- this.broadcast({ type: "reload-css" });
2516
3005
  }
2517
3006
  if (hasScript) {
2518
3007
  const start = performance.now();
2519
3008
  await this.scriptTask.run(this.config);
2520
3009
  const duration = (performance.now() - start).toFixed(1);
2521
3010
  logger.info("watch", `Rebundled scripts in ${import_picocolors3.default.bold(duration + "ms")}`);
2522
- this.broadcast({ type: "reload" });
3011
+ }
3012
+ if (hasStatic) {
3013
+ const start = performance.now();
3014
+ await this.staticTask.run(this.config);
3015
+ const duration = (performance.now() - start).toFixed(1);
3016
+ logger.info("watch", `Synced static assets in ${import_picocolors3.default.bold(duration + "ms")}`);
2523
3017
  }
2524
3018
  if (hasHtml) {
2525
3019
  const start = performance.now();
2526
3020
  await this.htmlTask.run(this.config);
2527
3021
  const duration = (performance.now() - start).toFixed(1);
2528
3022
  logger.info("watch", `Recompiled HTML in ${import_picocolors3.default.bold(duration + "ms")}`);
2529
- this.broadcast({ type: "reload" });
2530
3023
  }
2531
- if (!hasStyle && !hasScript && !hasHtml && changed.length > 0) {
3024
+ if (hasScript || hasHtml || hasStatic || hasOther) {
2532
3025
  this.broadcast({ type: "reload" });
3026
+ } else if (hasStyle) {
3027
+ this.broadcast({ type: "reload-css" });
2533
3028
  }
2534
3029
  } catch (err) {
2535
3030
  logger.error("watch", `Incremental rebuild failed: ${err?.message || err}`);
2536
3031
  } finally {
2537
3032
  this.isRebuilding = false;
3033
+ if (this.needsRebuild || this.pendingFiles.size > 0) {
3034
+ this.needsRebuild = false;
3035
+ this.debounceTimer = setTimeout(() => {
3036
+ void this.handleChanges();
3037
+ }, 50);
3038
+ }
2538
3039
  }
2539
3040
  }
2540
3041
  stop() {
@@ -2542,25 +3043,35 @@ var FileWatcher = class {
2542
3043
  clearTimeout(this.debounceTimer);
2543
3044
  this.debounceTimer = null;
2544
3045
  }
3046
+ if (this.configWarnTimer) {
3047
+ clearTimeout(this.configWarnTimer);
3048
+ this.configWarnTimer = null;
3049
+ }
2545
3050
  for (const watcher of this.watchers) {
2546
3051
  watcher.close();
2547
3052
  }
2548
3053
  this.watchers = [];
3054
+ void this.scriptTask.dispose();
2549
3055
  }
2550
3056
  };
2551
3057
 
2552
3058
  // src/tasks/server.ts
2553
3059
  var import_picocolors4 = __toESM(require("picocolors"), 1);
3060
+ var DEV_STATIC_OPTIONS = {
3061
+ etag: false,
3062
+ lastModified: false,
3063
+ cacheControl: false
3064
+ };
2554
3065
  function resolveServedFile(config, targetPath) {
2555
3066
  const normalizedTarget = targetPath.split("?")[0].replace(/^\/+/, "");
2556
3067
  const candidates = [
2557
- import_node_path24.default.join(config.dest.html, normalizedTarget),
2558
- import_node_path24.default.join(config.dest.base, normalizedTarget),
2559
- import_node_path24.default.join(config.src.base, normalizedTarget)
3068
+ import_node_path25.default.join(config.dest.html, normalizedTarget),
3069
+ import_node_path25.default.join(config.dest.base, normalizedTarget),
3070
+ import_node_path25.default.join(config.src.base, normalizedTarget)
2560
3071
  ];
2561
3072
  return candidates.find((filePath) => {
2562
3073
  try {
2563
- return import_node_fs8.default.existsSync(filePath) && import_node_fs8.default.statSync(filePath).isFile();
3074
+ return import_node_fs9.default.existsSync(filePath) && import_node_fs9.default.statSync(filePath).isFile();
2564
3075
  } catch {
2565
3076
  return false;
2566
3077
  }
@@ -2613,14 +3124,34 @@ function createHistoryFallbackMiddleware(config) {
2613
3124
  if (req.method === "HEAD") {
2614
3125
  return res.end();
2615
3126
  }
2616
- return import_node_fs8.default.createReadStream(fileToServe).pipe(res);
3127
+ return import_node_fs9.default.createReadStream(fileToServe).pipe(res);
2617
3128
  }
2618
3129
  req.url = rewriteTarget;
2619
3130
  return next();
2620
3131
  };
2621
3132
  }
2622
- function createDevServerApp(config) {
3133
+ function createDevServerApp(config, options = {}) {
2623
3134
  const app = (0, import_connect.default)();
3135
+ app.use((_req, res, next) => {
3136
+ res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
3137
+ res.setHeader("Pragma", "no-cache");
3138
+ res.setHeader("Expires", "0");
3139
+ next();
3140
+ });
3141
+ if (options.ensureBuildReady) {
3142
+ app.use((_req, _res, next) => {
3143
+ try {
3144
+ const result = options.ensureBuildReady();
3145
+ if (result && typeof result.then === "function") {
3146
+ result.then(() => next()).catch((err) => next(err));
3147
+ } else {
3148
+ next();
3149
+ }
3150
+ } catch (err) {
3151
+ next(err);
3152
+ }
3153
+ });
3154
+ }
2624
3155
  app.use((req, _res, next) => {
2625
3156
  if (req.url?.includes("%PUBLIC_URL%")) {
2626
3157
  req.url = req.url.replace("/%PUBLIC_URL%", "").replace("%PUBLIC_URL%", "") || "/";
@@ -2630,13 +3161,13 @@ function createDevServerApp(config) {
2630
3161
  app.use((req, res, next) => {
2631
3162
  if (req.url === "/manifest.json" || req.url?.endsWith("/manifest.json")) {
2632
3163
  const candidates = [
2633
- import_node_path24.default.join(config.dest.base, "manifest.json"),
2634
- import_node_path24.default.join(config.src.base, "manifest.json"),
2635
- import_node_path24.default.join(config.workspace, "manifest.json")
3164
+ import_node_path25.default.join(config.dest.base, "manifest.json"),
3165
+ import_node_path25.default.join(config.src.base, "manifest.json"),
3166
+ import_node_path25.default.join(config.workspace, "manifest.json")
2636
3167
  ];
2637
- const file2 = candidates.find((f) => import_node_fs8.default.existsSync(f));
3168
+ const file2 = candidates.find((f) => import_node_fs9.default.existsSync(f));
2638
3169
  if (file2) {
2639
- let content = import_node_fs8.default.readFileSync(file2, "utf-8");
3170
+ let content = import_node_fs9.default.readFileSync(file2, "utf-8");
2640
3171
  const replacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2641
3172
  content = content.replaceAll("%PUBLIC_URL%", replacement);
2642
3173
  res.setHeader("Content-Type", "application/json; charset=utf-8");
@@ -2659,79 +3190,79 @@ function createDevServerApp(config) {
2659
3190
  app.use(createHistoryFallbackMiddleware(config));
2660
3191
  }
2661
3192
  if (config.paths.source.css) {
2662
- app.use("/" + config.paths.source.css, (0, import_serve_static.default)(config.dest.css));
3193
+ app.use("/" + config.paths.source.css, (0, import_serve_static.default)(config.dest.css, DEV_STATIC_OPTIONS));
2663
3194
  }
2664
3195
  if (config.paths.tmp.css && config.paths.tmp.css !== config.paths.source.css) {
2665
- app.use("/" + config.paths.tmp.css, (0, import_serve_static.default)(config.dest.css));
3196
+ app.use("/" + config.paths.tmp.css, (0, import_serve_static.default)(config.dest.css, DEV_STATIC_OPTIONS));
2666
3197
  }
2667
3198
  if (config.paths.source.js) {
2668
- app.use("/" + config.paths.source.js, (0, import_serve_static.default)(config.dest.js));
3199
+ app.use("/" + config.paths.source.js, (0, import_serve_static.default)(config.dest.js, DEV_STATIC_OPTIONS));
2669
3200
  }
2670
3201
  if (config.paths.tmp.js && config.paths.tmp.js !== config.paths.source.js) {
2671
- app.use("/" + config.paths.tmp.js, (0, import_serve_static.default)(config.dest.js));
3202
+ app.use("/" + config.paths.tmp.js, (0, import_serve_static.default)(config.dest.js, DEV_STATIC_OPTIONS));
2672
3203
  }
2673
- app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "chunk")));
2674
- app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "chunk")));
3204
+ app.use("/chunk", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.js, "chunk"), DEV_STATIC_OPTIONS));
3205
+ app.use("/chunk", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.base, "chunk"), DEV_STATIC_OPTIONS));
2675
3206
  if (config.paths.source.img) {
2676
3207
  app.use(
2677
3208
  "/" + config.paths.source.img,
2678
- (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.img))
3209
+ (0, import_serve_static.default)(import_node_path25.default.join(config.src.base, config.paths.source.img), DEV_STATIC_OPTIONS)
2679
3210
  );
2680
3211
  }
2681
3212
  if (config.paths.tmp.img) {
2682
- app.use("/" + config.paths.tmp.img, (0, import_serve_static.default)(config.dest.img));
3213
+ app.use("/" + config.paths.tmp.img, (0, import_serve_static.default)(config.dest.img, DEV_STATIC_OPTIONS));
2683
3214
  }
2684
- app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "img")));
2685
- app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "img")));
3215
+ app.use("/img", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.base, "img"), DEV_STATIC_OPTIONS));
3216
+ app.use("/img", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.js, "img"), DEV_STATIC_OPTIONS));
2686
3217
  if (config.paths.source.font) {
2687
3218
  app.use(
2688
3219
  "/" + config.paths.source.font,
2689
- (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.font))
3220
+ (0, import_serve_static.default)(import_node_path25.default.join(config.src.base, config.paths.source.font), DEV_STATIC_OPTIONS)
2690
3221
  );
2691
3222
  }
2692
3223
  if (config.paths.tmp.font) {
2693
- app.use("/" + config.paths.tmp.font, (0, import_serve_static.default)(config.dest.font));
3224
+ app.use("/" + config.paths.tmp.font, (0, import_serve_static.default)(config.dest.font, DEV_STATIC_OPTIONS));
2694
3225
  }
2695
- app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "font")));
2696
- app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "font")));
2697
- app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, "fonts")));
2698
- app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "fonts")));
3226
+ app.use("/font", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.base, "font"), DEV_STATIC_OPTIONS));
3227
+ app.use("/font", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.js, "font"), DEV_STATIC_OPTIONS));
3228
+ app.use("/fonts", (0, import_serve_static.default)(import_node_path25.default.join(config.src.base, "fonts"), DEV_STATIC_OPTIONS));
3229
+ app.use("/fonts", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.base, "fonts"), DEV_STATIC_OPTIONS));
2699
3230
  if (config.server.serveStatic) {
2700
3231
  const staticEntries = Array.isArray(config.server.serveStatic) ? config.server.serveStatic : [config.server.serveStatic];
2701
3232
  for (const entry of staticEntries) {
2702
3233
  if (typeof entry === "string") {
2703
- const absoluteDir = import_node_path24.default.isAbsolute(entry) ? entry : import_node_path24.default.join(config.workspace, entry);
2704
- if (import_node_fs8.default.existsSync(absoluteDir)) {
2705
- app.use((0, import_serve_static.default)(absoluteDir));
3234
+ const absoluteDir = import_node_path25.default.isAbsolute(entry) ? entry : import_node_path25.default.join(config.workspace, entry);
3235
+ if (import_node_fs9.default.existsSync(absoluteDir)) {
3236
+ app.use((0, import_serve_static.default)(absoluteDir, DEV_STATIC_OPTIONS));
2706
3237
  }
2707
3238
  } else if (entry && typeof entry === "object") {
2708
3239
  const route = entry.route ? entry.route.startsWith("/") ? entry.route : `/${entry.route}` : "";
2709
3240
  const dirs = Array.isArray(entry.dir) ? entry.dir : [entry.dir];
2710
3241
  for (const dir of dirs) {
2711
- const absoluteDir = import_node_path24.default.isAbsolute(dir) ? dir : import_node_path24.default.join(config.workspace, dir);
2712
- if (import_node_fs8.default.existsSync(absoluteDir)) {
3242
+ const absoluteDir = import_node_path25.default.isAbsolute(dir) ? dir : import_node_path25.default.join(config.workspace, dir);
3243
+ if (import_node_fs9.default.existsSync(absoluteDir)) {
2713
3244
  if (route) {
2714
- app.use(route, (0, import_serve_static.default)(absoluteDir));
3245
+ app.use(route, (0, import_serve_static.default)(absoluteDir, DEV_STATIC_OPTIONS));
2715
3246
  } else {
2716
- app.use((0, import_serve_static.default)(absoluteDir));
3247
+ app.use((0, import_serve_static.default)(absoluteDir, DEV_STATIC_OPTIONS));
2717
3248
  }
2718
3249
  }
2719
3250
  }
2720
3251
  }
2721
3252
  }
2722
3253
  }
2723
- app.use((0, import_serve_static.default)(config.dest.base));
2724
- app.use((0, import_serve_static.default)(config.src.base));
2725
- app.use((0, import_serve_static.default)(config.workspace));
3254
+ app.use((0, import_serve_static.default)(config.dest.base, DEV_STATIC_OPTIONS));
3255
+ app.use((0, import_serve_static.default)(config.src.base, DEV_STATIC_OPTIONS));
3256
+ app.use((0, import_serve_static.default)(config.workspace, DEV_STATIC_OPTIONS));
2726
3257
  return app;
2727
3258
  }
2728
3259
  function getNetworkAddresses() {
2729
3260
  const addresses = [];
2730
3261
  const interfaces = import_node_os.default.networkInterfaces();
2731
3262
  for (const entries of Object.values(interfaces)) {
2732
- for (const net of entries || []) {
2733
- if (net.family === "IPv4" && !net.internal) {
2734
- addresses.push(net.address);
3263
+ for (const net2 of entries || []) {
3264
+ if (net2.family === "IPv4" && !net2.internal) {
3265
+ addresses.push(net2.address);
2735
3266
  }
2736
3267
  }
2737
3268
  }
@@ -2752,156 +3283,264 @@ function resolveServerHost(rawHost, envHost = process.env.HOST) {
2752
3283
  isWildcard: host === "0.0.0.0" || host === "::"
2753
3284
  };
2754
3285
  }
3286
+ var LOCAL_OR_WILDCARD_HOSTS = /* @__PURE__ */ new Set([
3287
+ "localhost",
3288
+ "127.0.0.1",
3289
+ "::1",
3290
+ "0.0.0.0",
3291
+ "::"
3292
+ ]);
3293
+ var IGNORABLE_SECONDARY_PROBE_ERRORS = /* @__PURE__ */ new Set([
3294
+ "EADDRNOTAVAIL",
3295
+ "EAFNOSUPPORT",
3296
+ "EINVAL",
3297
+ "ENOTFOUND"
3298
+ ]);
3299
+ function probePortOnHost(port, host, ignoreUnsupportedFamily) {
3300
+ return new Promise((resolve) => {
3301
+ const tester = import_node_net.default.createServer();
3302
+ tester.unref();
3303
+ tester.once("error", (err) => {
3304
+ if (ignoreUnsupportedFamily && err.code && IGNORABLE_SECONDARY_PROBE_ERRORS.has(err.code)) {
3305
+ resolve(true);
3306
+ return;
3307
+ }
3308
+ resolve(false);
3309
+ });
3310
+ tester.once("listening", () => {
3311
+ tester.close(() => resolve(true));
3312
+ });
3313
+ tester.listen({ port, host, exclusive: true });
3314
+ });
3315
+ }
3316
+ async function isPortAvailable(port, host) {
3317
+ if (port === 0) return true;
3318
+ if (LOCAL_OR_WILDCARD_HOSTS.has(host)) {
3319
+ const primaryProbes = [
3320
+ { host, optional: false },
3321
+ { host: "127.0.0.1", optional: host !== "127.0.0.1" },
3322
+ { host: "0.0.0.0", optional: host !== "0.0.0.0" },
3323
+ { host: "::1", optional: host !== "::1" },
3324
+ { host: "::", optional: host !== "::" }
3325
+ ];
3326
+ const seen = /* @__PURE__ */ new Set();
3327
+ for (const probe of primaryProbes) {
3328
+ if (seen.has(probe.host)) continue;
3329
+ seen.add(probe.host);
3330
+ const free = await probePortOnHost(port, probe.host, probe.optional);
3331
+ if (!free) {
3332
+ return false;
3333
+ }
3334
+ }
3335
+ return true;
3336
+ }
3337
+ return probePortOnHost(port, host, false);
3338
+ }
3339
+ async function resolveAvailablePort(requestedPort, host, options = {}) {
3340
+ if (requestedPort === 0) {
3341
+ return 0;
3342
+ }
3343
+ const strictPort = Boolean(options.strictPort);
3344
+ const maxAttempts = options.maxAttempts ?? 100;
3345
+ const maxPort = Math.min(65535, requestedPort + maxAttempts);
3346
+ for (let candidate = requestedPort; candidate <= maxPort; candidate++) {
3347
+ if (await isPortAvailable(candidate, host)) {
3348
+ return candidate;
3349
+ }
3350
+ if (strictPort) {
3351
+ const err2 = new Error(
3352
+ `Port ${requestedPort} is already in use (strictPort is enabled).`
3353
+ );
3354
+ err2.code = "EADDRINUSE";
3355
+ throw err2;
3356
+ }
3357
+ }
3358
+ const err = new Error(
3359
+ `No available port found in range ${requestedPort}-${maxPort} for host "${host}".`
3360
+ );
3361
+ err.code = "EADDRINUSE";
3362
+ throw err;
3363
+ }
2755
3364
  var ServerTask = class extends BaseTask {
2756
3365
  watcher = null;
2757
3366
  wsServer = null;
2758
3367
  clients = /* @__PURE__ */ new Set();
3368
+ serverId = import_node_crypto2.default.randomUUID();
3369
+ buildVersion = 1;
3370
+ recoveryPromise = null;
2759
3371
  constructor() {
2760
3372
  super({ name: "serve", description: "Start development server with live reload" });
2761
3373
  }
3374
+ getHandshakePayload() {
3375
+ return JSON.stringify({
3376
+ type: "connected",
3377
+ serverId: this.serverId,
3378
+ buildVersion: this.buildVersion
3379
+ });
3380
+ }
2762
3381
  broadcast(data) {
2763
- const payload = JSON.stringify(data);
3382
+ this.buildVersion += 1;
3383
+ const payload = JSON.stringify({
3384
+ ...data,
3385
+ serverId: this.serverId,
3386
+ buildVersion: this.buildVersion
3387
+ });
2764
3388
  for (const client of this.clients) {
2765
3389
  if (client.readyState === import_ws.WebSocket.OPEN) {
2766
3390
  client.send(payload);
2767
3391
  }
2768
3392
  }
2769
3393
  }
2770
- async run(config) {
2771
- if (config.env.isProd) {
2772
- logger.warn("server", "Development server is disabled in production mode");
3394
+ ensureBuildReady(config) {
3395
+ if (import_node_fs9.default.existsSync(config.dest.base)) {
2773
3396
  return;
2774
3397
  }
2775
- const app = createDevServerApp(config);
2776
- const port = config.server.port ?? 3e3;
2777
- const { host, isWildcard } = resolveServerHost(config.server.host);
2778
- const server = import_node_http.default.createServer(app);
2779
- this.wsServer = new import_ws.WebSocketServer({ server, path: "/__balm_ws" });
2780
- this.wsServer.on("connection", (socket) => {
3398
+ if (!this.watcher) {
3399
+ return;
3400
+ }
3401
+ if (this.recoveryPromise) {
3402
+ return this.recoveryPromise;
3403
+ }
3404
+ logger.warn(
3405
+ "server",
3406
+ `Dev output directory (${config.dest.base}) missing \u2014 rebuilding workspace...`
3407
+ );
3408
+ const activeRecovery = this.watcher.rebuildAll().then(() => {
3409
+ this.buildVersion += 1;
3410
+ }).finally(() => {
3411
+ if (this.recoveryPromise === activeRecovery) {
3412
+ this.recoveryPromise = null;
3413
+ }
3414
+ });
3415
+ this.recoveryPromise = activeRecovery;
3416
+ return activeRecovery;
3417
+ }
3418
+ attachLiveReloadServer(server) {
3419
+ const wsServer = new import_ws.WebSocketServer({ server, path: "/__balm_ws" });
3420
+ wsServer.on("connection", (socket) => {
2781
3421
  this.clients.add(socket);
3422
+ socket.send(this.getHandshakePayload());
3423
+ socket.on("message", (raw) => {
3424
+ try {
3425
+ const msg = JSON.parse(raw.toString());
3426
+ if (msg?.type === "sync" && socket.readyState === import_ws.WebSocket.OPEN) {
3427
+ socket.send(this.getHandshakePayload());
3428
+ }
3429
+ } catch {
3430
+ }
3431
+ });
2782
3432
  socket.on("close", () => this.clients.delete(socket));
2783
3433
  });
3434
+ this.wsServer = wsServer;
3435
+ return wsServer;
3436
+ }
3437
+ async run(config) {
3438
+ if (config.env.isProd) {
3439
+ logger.warn("server", "Development server is disabled in production mode");
3440
+ return;
3441
+ }
2784
3442
  this.watcher = new FileWatcher(config, (data) => {
2785
3443
  this.broadcast(data);
2786
3444
  });
2787
3445
  this.watcher.start();
2788
- return new Promise((resolve) => {
2789
- server.listen(port, host, () => {
3446
+ const app = createDevServerApp(config, {
3447
+ ensureBuildReady: () => this.ensureBuildReady(config)
3448
+ });
3449
+ const requestedPort = config.server.port ?? 3e3;
3450
+ const strictPort = Boolean(config.server.strictPort);
3451
+ const { host, isWildcard } = resolveServerHost(config.server.host);
3452
+ const server = import_node_http.default.createServer(app);
3453
+ const maxAttempts = 100;
3454
+ const maxPort = requestedPort === 0 ? 0 : Math.min(65535, requestedPort + maxAttempts);
3455
+ const listenOnPort = (candidatePort) => new Promise((resolveListen, rejectListen) => {
3456
+ const onError = (err) => {
3457
+ server.removeListener("listening", onListening);
3458
+ rejectListen(err);
3459
+ };
3460
+ const onListening = () => {
3461
+ server.removeListener("error", onError);
2790
3462
  const address = server.address();
2791
- const activePort = address && typeof address === "object" ? address.port : port;
2792
- const localHost = isWildcard ? "localhost" : host;
2793
- console.log("");
2794
- logger.success("server", import_picocolors4.default.bold("BalmJS Dev Server is ready!"));
2795
- console.log(
2796
- ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Local:")} ${import_picocolors4.default.cyan(`http://${localHost}:${activePort}/`)}`
3463
+ resolveListen(
3464
+ address && typeof address === "object" ? address.port : candidatePort
2797
3465
  );
2798
- if (isWildcard) {
2799
- const networkIps = getNetworkAddresses();
2800
- if (networkIps.length > 0) {
2801
- for (const ip of networkIps) {
2802
- console.log(
2803
- ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Network:")} ${import_picocolors4.default.cyan(`http://${ip}:${activePort}/`)}`
2804
- );
2805
- }
2806
- } else {
2807
- console.log(
2808
- ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Network:")} ${import_picocolors4.default.cyan(`http://127.0.0.1:${activePort}/`)}`
2809
- );
2810
- }
2811
- } else if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
2812
- console.log(
2813
- ` ${import_picocolors4.default.dim("\u279C Network: use --host or server.host = true to expose")}`
2814
- );
2815
- }
2816
- console.log("");
2817
- if (config.env.isTest) {
2818
- this.watcher?.stop();
2819
- this.wsServer?.close();
2820
- server.close();
2821
- resolve();
2822
- }
2823
- });
3466
+ };
3467
+ server.once("error", onError);
3468
+ server.once("listening", onListening);
3469
+ server.listen(candidatePort, host);
2824
3470
  });
2825
- }
2826
- };
2827
-
2828
- // src/tasks/static.ts
2829
- var import_node_path25 = __toESM(require("path"), 1);
2830
- var import_node_fs9 = require("fs");
2831
- var StaticTask = class extends BaseTask {
2832
- constructor() {
2833
- super({ name: "static", description: "Copy static assets, images, fonts, and manifest" });
2834
- }
2835
- async run(config) {
2836
- const srcBase = config.src.base;
2837
- const destBase = config.dest.base;
2838
- const staticPatterns = [
2839
- import_node_path25.default.join(srcBase, "*.{ico,png,svg,json,txt,xml,webmanifest}"),
2840
- `!${import_node_path25.default.join(srcBase, "*.html")}`
2841
- ];
2842
- const extraIncludes = [
2843
- ...config.extras?.includes || [],
2844
- ...config.assets?.includes || []
2845
- ];
2846
- const extraExcludes = [
2847
- ...config.extras?.excludes || [],
2848
- ...config.assets?.excludes || []
2849
- ];
2850
- for (const inc of extraIncludes) {
2851
- const pattern = import_node_path25.default.isAbsolute(inc) ? inc : import_node_path25.default.join(srcBase, inc);
2852
- staticPatterns.push(pattern);
3471
+ let activePort = await resolveAvailablePort(requestedPort, host, {
3472
+ strictPort,
3473
+ maxAttempts
3474
+ });
3475
+ while (true) {
3476
+ try {
3477
+ activePort = await listenOnPort(activePort);
3478
+ break;
3479
+ } catch (err) {
3480
+ if (err?.code === "EADDRINUSE" && !strictPort && activePort > 0 && activePort < maxPort) {
3481
+ activePort = await resolveAvailablePort(activePort + 1, host, {
3482
+ strictPort: false,
3483
+ maxAttempts: maxPort - activePort
3484
+ });
3485
+ continue;
3486
+ }
3487
+ this.watcher?.stop();
3488
+ throw err;
3489
+ }
2853
3490
  }
2854
- for (const exc of extraExcludes) {
2855
- const pattern = import_node_path25.default.isAbsolute(exc) ? exc : import_node_path25.default.join(srcBase, exc);
2856
- staticPatterns.push(`!${pattern}`);
3491
+ this.attachLiveReloadServer(server);
3492
+ const localHost = isWildcard ? "localhost" : host;
3493
+ console.log("");
3494
+ if (requestedPort !== 0 && activePort !== requestedPort) {
3495
+ logger.warn(
3496
+ "server",
3497
+ `Port ${requestedPort} is in use, automatically switched to ${activePort}`
3498
+ );
2857
3499
  }
2858
- const pipeline = Pipeline.from(staticPatterns, {
2859
- cwd: config.workspace,
2860
- base: srcBase
2861
- });
2862
- const publicUrlReplacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2863
- pipeline.pipe(async (file2) => {
2864
- const isManifest = isManifestFile(file2, config);
2865
- if (isManifest || file2.extname === ".json") {
2866
- let content = file2.toString();
2867
- content = content.replaceAll(PUBLIC_URL, publicUrlReplacement);
2868
- if (isManifest) {
2869
- content = rewriteHtmlAssetPaths(content, config);
3500
+ logger.success("server", import_picocolors4.default.bold("BalmJS Dev Server is ready!"));
3501
+ console.log(
3502
+ ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Local:")} ${import_picocolors4.default.cyan(`http://${localHost}:${activePort}/`)}`
3503
+ );
3504
+ if (isWildcard) {
3505
+ const networkIps = getNetworkAddresses();
3506
+ if (networkIps.length > 0) {
3507
+ for (const ip of networkIps) {
3508
+ console.log(
3509
+ ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Network:")} ${import_picocolors4.default.cyan(`http://${ip}:${activePort}/`)}`
3510
+ );
2870
3511
  }
2871
- file2.contents = Buffer.from(content);
3512
+ } else {
3513
+ console.log(
3514
+ ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Network:")} ${import_picocolors4.default.cyan(`http://127.0.0.1:${activePort}/`)}`
3515
+ );
2872
3516
  }
2873
- return file2;
2874
- });
2875
- await pipeline.dest(destBase);
2876
- if (config.src.img && (0, import_node_fs9.existsSync)(config.src.img)) {
2877
- const imgPipeline = Pipeline.from(import_node_path25.default.join(config.src.img, "**/*"), {
2878
- cwd: config.workspace,
2879
- base: config.src.img
2880
- });
2881
- await imgPipeline.dest(config.dest.img);
3517
+ } else if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
3518
+ console.log(
3519
+ ` ${import_picocolors4.default.dim("\u279C Network: use --host or server.host = true to expose")}`
3520
+ );
2882
3521
  }
2883
- if (config.src.font && (0, import_node_fs9.existsSync)(config.src.font)) {
2884
- const fontPipeline = Pipeline.from(import_node_path25.default.join(config.src.font, "**/*"), {
2885
- cwd: config.workspace,
2886
- base: config.src.font
2887
- });
2888
- await fontPipeline.dest(config.dest.font);
3522
+ console.log("");
3523
+ if (config.env.isTest) {
3524
+ this.watcher?.stop();
3525
+ this.wsServer?.close();
3526
+ await new Promise((resolveClose) => server.close(() => resolveClose()));
3527
+ return;
2889
3528
  }
2890
- if (config.src.media && (0, import_node_fs9.existsSync)(config.src.media)) {
2891
- const mediaPipeline = Pipeline.from(import_node_path25.default.join(config.src.media, "**/*"), {
2892
- cwd: config.workspace,
2893
- base: config.src.media
3529
+ return new Promise((_resolve) => {
3530
+ const cleanup = () => {
3531
+ this.watcher?.stop();
3532
+ this.wsServer?.close();
3533
+ server.close();
3534
+ };
3535
+ process.once("SIGINT", () => {
3536
+ cleanup();
3537
+ process.exit(0);
2894
3538
  });
2895
- await mediaPipeline.dest(config.dest.media);
2896
- }
2897
- const publicDir = import_node_path25.default.join(config.workspace, "public");
2898
- if ((0, import_node_fs9.existsSync)(publicDir)) {
2899
- const pubPipeline = Pipeline.from(import_node_path25.default.join(publicDir, "**/*"), {
2900
- cwd: config.workspace,
2901
- base: publicDir
3539
+ process.once("SIGTERM", () => {
3540
+ cleanup();
3541
+ process.exit(0);
2902
3542
  });
2903
- await pubPipeline.dest(destBase);
2904
- }
3543
+ });
2905
3544
  }
2906
3545
  };
2907
3546
 
@@ -3190,8 +3829,10 @@ var index_default = balm;
3190
3829
  VirtualFile,
3191
3830
  ZipTask,
3192
3831
  balm,
3832
+ buildEsbuildOptions,
3193
3833
  createDefaultConfig,
3194
3834
  createDevServerApp,
3835
+ createEsbuildRunner,
3195
3836
  createHistoryFallbackMiddleware,
3196
3837
  deepMerge,
3197
3838
  file,
@@ -3204,10 +3845,12 @@ var index_default = balm;
3204
3845
  isFunction,
3205
3846
  isManifestFile,
3206
3847
  isObject,
3848
+ isPortAvailable,
3207
3849
  isString,
3208
3850
  localResolve,
3209
3851
  localWorkspace,
3210
3852
  logger,
3853
+ resolveAvailablePort,
3211
3854
  resolveConfig,
3212
3855
  resolveDefaultEntry,
3213
3856
  resolveServerHost,