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

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