balm-core 6.0.0-alpha.5 → 6.0.0-alpha.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # balm-core
2
2
 
3
+ ## 6.0.0-alpha.6
4
+
5
+ ### Patch Changes
6
+
7
+ - 52ba9c2: Fix HTML5 history mode support in production builds and the dev server
8
+ - Emit auxiliary HTML files (such as `404.html`) from `templateDir` in `HtmlTask` even when `scripts.htmlPluginOptions.template` is set, excluding stale `index.html` and skipping entry script, analytics, and live-reload injection on `404.html` and auxiliary HTML templates
9
+ - Reorder `ServerTask` middlewares (`proxy` -> `historyOptions` -> static mounts) and evaluate the dot rule strictly against URL pathnames so SPA routes matching directory names (e.g. `/styles`) fall back to `index.html` cleanly
10
+ - Preserve `entry.context` as `pathFilter` for proxy configs and add object `historyOptions` support (`index`, `disableDotRule`, `htmlAcceptHeaders`, `rewrites`)
11
+
3
12
  ## 6.0.0-alpha.5
4
13
 
5
14
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -62,6 +62,8 @@ __export(index_exports, {
62
62
  ZipTask: () => ZipTask,
63
63
  balm: () => balm,
64
64
  createDefaultConfig: () => createDefaultConfig,
65
+ createDevServerApp: () => createDevServerApp,
66
+ createHistoryFallbackMiddleware: () => createHistoryFallbackMiddleware,
65
67
  deepMerge: () => deepMerge,
66
68
  default: () => index_default,
67
69
  file: () => file,
@@ -1706,160 +1708,174 @@ var LIVE_RELOAD_SCRIPT = `
1706
1708
  })();
1707
1709
  </script>
1708
1710
  `;
1711
+ function shouldDecorateEntryHtml(file2, isAuxiliary) {
1712
+ return /\.html$/i.test(file2.extname) && !isAuxiliary && file2.basename.toLowerCase() !== "404.html";
1713
+ }
1714
+ function getTemplatePatterns(templateDir, config) {
1715
+ const patterns = [import_node_path13.default.join(templateDir, "*.html")];
1716
+ if (config.pwa.manifest) {
1717
+ const manifestPattern = import_node_path13.default.join(templateDir, config.pwa.manifest);
1718
+ const resolvedManifest = import_node_path13.default.isAbsolute(manifestPattern) ? manifestPattern : import_node_path13.default.join(config.workspace, manifestPattern);
1719
+ if ((0, import_node_fs4.existsSync)(resolvedManifest)) {
1720
+ patterns.push(manifestPattern);
1721
+ }
1722
+ }
1723
+ return patterns;
1724
+ }
1725
+ function injectEntryScripts(content, config) {
1726
+ const entryNames = typeof config.scripts.entry === "object" && !Array.isArray(config.scripts.entry) ? Object.keys(config.scripts.entry) : ["main"];
1727
+ const vendorName = config.scripts.vendorName || "vendor";
1728
+ const entries = config.scripts.extractAllVendors ? [vendorName, ...entryNames] : entryNames;
1729
+ const jsDir = config.env.isProd ? config.paths.target.js : config.paths.tmp.js;
1730
+ const jsPathPrefix = config.assets.virtualDir ? `/${config.assets.virtualDir}/${jsDir}` : `/${jsDir}`;
1731
+ const destJsFolder = config.dest.js;
1732
+ const scriptTags = entries.filter(
1733
+ (entryName) => !new RegExp(`<script[^>]+src=["'][^"']*${entryName}[^"']*\\.js["']`, "i").test(
1734
+ content
1735
+ )
1736
+ ).map((entryName) => {
1737
+ let actualFilename = `${entryName}.js`;
1738
+ const hasUnhashed = (0, import_node_fs4.existsSync)(import_node_path13.default.join(destJsFolder, actualFilename));
1739
+ let found = hasUnhashed;
1740
+ try {
1741
+ const matched = import_fast_glob3.default.sync(`${entryName}.*.js`, { cwd: destJsFolder });
1742
+ if (matched.length) {
1743
+ const valid = matched.find((f) => !f.endsWith(".map") && !f.endsWith(".txt"));
1744
+ if (valid) {
1745
+ actualFilename = valid;
1746
+ found = true;
1747
+ }
1748
+ }
1749
+ } catch {
1750
+ }
1751
+ if (entryName === vendorName && config.scripts.extractAllVendors && !found) {
1752
+ return "";
1753
+ }
1754
+ return `<script defer src="${jsPathPrefix}/${actualFilename}"></script>`;
1755
+ }).filter(Boolean).join("\n");
1756
+ if (!scriptTags) {
1757
+ return content;
1758
+ }
1759
+ return content.includes("</body>") ? content.replace("</body>", `${scriptTags}
1760
+ </body>`) : `${content}
1761
+ ${scriptTags}`;
1762
+ }
1763
+ function injectAnalytics(content, config) {
1764
+ const { custom, google } = config.html.analytics;
1765
+ let nextContent = content;
1766
+ if (custom && custom.src) {
1767
+ const attrs = [
1768
+ `src="${custom.src}"`,
1769
+ custom.siteId !== void 0 ? `data-website-id="${custom.siteId}"` : "",
1770
+ custom.defer !== false ? "defer" : "",
1771
+ custom.async ? "async" : ""
1772
+ ].filter(Boolean).join(" ");
1773
+ const customTag = `<script ${attrs}></script>`;
1774
+ nextContent = nextContent.includes("</head>") ? nextContent.replace("</head>", ` ${customTag}
1775
+ </head>`) : `${customTag}
1776
+ ${nextContent}`;
1777
+ }
1778
+ if (google) {
1779
+ const gaSnippet = [
1780
+ `<script async src="https://www.googletagmanager.com/gtag/js?id=${google}"></script>`,
1781
+ "<script>",
1782
+ " window.dataLayer = window.dataLayer || [];",
1783
+ " function gtag(){dataLayer.push(arguments);}",
1784
+ " gtag('js', new Date());",
1785
+ ` gtag('config', '${google}');`,
1786
+ "</script>"
1787
+ ].join("\n");
1788
+ nextContent = nextContent.includes("</body>") ? nextContent.replace("</body>", `${gaSnippet}
1789
+ </body>`) : `${nextContent}
1790
+ ${gaSnippet}`;
1791
+ }
1792
+ return nextContent;
1793
+ }
1794
+ async function processHtmlPipeline(pipeline, config, isAuxiliary) {
1795
+ const publicUrlReplacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
1796
+ pipeline.pipe(transformReplace(new RegExp(PUBLIC_URL, "g"), publicUrlReplacement));
1797
+ if (shouldUseTargetPaths(config)) {
1798
+ pipeline.pipe(async (file2) => {
1799
+ if (/\.html$/i.test(file2.extname) || isManifestFile(file2, config)) {
1800
+ file2.contents = Buffer.from(rewriteHtmlAssetPaths(file2.toString(), config));
1801
+ }
1802
+ return file2;
1803
+ });
1804
+ }
1805
+ if (config.scripts.injectHtml) {
1806
+ pipeline.pipe(async (file2) => {
1807
+ if (shouldDecorateEntryHtml(file2, isAuxiliary)) {
1808
+ const updated = injectEntryScripts(file2.toString(), config);
1809
+ file2.contents = Buffer.from(updated);
1810
+ }
1811
+ return file2;
1812
+ });
1813
+ }
1814
+ if (config.env.isProd && config.html.analytics) {
1815
+ pipeline.pipe(async (file2) => {
1816
+ if (shouldDecorateEntryHtml(file2, isAuxiliary)) {
1817
+ const updated = injectAnalytics(file2.toString(), config);
1818
+ file2.contents = Buffer.from(updated);
1819
+ }
1820
+ return file2;
1821
+ });
1822
+ }
1823
+ if (config.env.isProd) {
1824
+ pipeline.pipe(transformHtmlmin(config.html.options));
1825
+ } else {
1826
+ pipeline.pipe(async (file2) => {
1827
+ if (shouldDecorateEntryHtml(file2, isAuxiliary)) {
1828
+ const content = file2.toString();
1829
+ const updated = content.includes("</body>") ? content.replace("</body>", `${LIVE_RELOAD_SCRIPT}
1830
+ </body>`) : `${content}
1831
+ ${LIVE_RELOAD_SCRIPT}`;
1832
+ file2.contents = Buffer.from(updated);
1833
+ }
1834
+ return file2;
1835
+ });
1836
+ }
1837
+ await pipeline.dest(config.dest.html);
1838
+ }
1709
1839
  var HtmlTask = class extends BaseTask {
1710
1840
  constructor() {
1711
1841
  super({ name: "html", description: "Process HTML templates" });
1712
1842
  }
1713
1843
  async run(config) {
1714
1844
  const customTemplate = config.scripts.htmlPluginOptions?.template;
1715
- let pipeline;
1845
+ const customFilename = config.scripts.htmlPluginOptions?.filename;
1846
+ const outputBasename = typeof customFilename === "string" && customFilename.trim() ? import_node_path13.default.basename(customFilename) : "index.html";
1847
+ const templateDir = config.scripts.injectHtml ? config.src.base : config.src.html;
1716
1848
  if (customTemplate) {
1717
- const templatePath = import_node_path13.default.isAbsolute(customTemplate) ? customTemplate : import_node_path13.default.join(config.workspace, customTemplate);
1718
- pipeline = Pipeline.from(templatePath, {
1849
+ const resolvedTemplatePath = import_node_path13.default.resolve(config.workspace, customTemplate);
1850
+ const entryPipeline = Pipeline.from(resolvedTemplatePath, {
1719
1851
  cwd: config.workspace,
1720
- base: import_node_path13.default.dirname(templatePath)
1852
+ base: import_node_path13.default.dirname(resolvedTemplatePath)
1721
1853
  });
1722
- } else {
1723
- const templateDir = config.scripts.injectHtml ? config.src.base : config.src.html;
1724
- const patterns = [import_node_path13.default.join(templateDir, "*.html")];
1725
- if (config.pwa.manifest) {
1726
- const manifestPattern = import_node_path13.default.join(templateDir, config.pwa.manifest);
1727
- if ((0, import_node_fs4.existsSync)(import_node_path13.default.isAbsolute(manifestPattern) ? manifestPattern : import_node_path13.default.join(config.workspace, manifestPattern))) {
1728
- patterns.push(manifestPattern);
1729
- }
1730
- }
1731
- pipeline = Pipeline.from(patterns, {
1732
- cwd: config.workspace,
1733
- base: templateDir
1734
- });
1735
- }
1736
- const publicUrlReplacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
1737
- pipeline.pipe(transformReplace(new RegExp(PUBLIC_URL, "g"), publicUrlReplacement));
1738
- if (customTemplate) {
1739
- pipeline.pipe(async (file2) => {
1740
- file2.basename = "index.html";
1741
- return file2;
1742
- });
1743
- }
1744
- if (shouldUseTargetPaths(config)) {
1745
- pipeline.pipe(async (file2) => {
1746
- if (/\.html$/i.test(file2.extname) || isManifestFile(file2, config)) {
1747
- file2.contents = Buffer.from(rewriteHtmlAssetPaths(file2.toString(), config));
1748
- }
1854
+ entryPipeline.pipe(async (file2) => {
1855
+ file2.basename = outputBasename;
1749
1856
  return file2;
1750
1857
  });
1751
- }
1752
- if (config.scripts.injectHtml) {
1753
- pipeline.pipe(async (file2) => {
1754
- if (/\.html$/i.test(file2.extname)) {
1755
- let content = file2.toString();
1756
- const entryNames = typeof config.scripts.entry === "object" && !Array.isArray(config.scripts.entry) ? Object.keys(config.scripts.entry) : ["main"];
1757
- const vendorName = config.scripts.vendorName || "vendor";
1758
- const entries = config.scripts.extractAllVendors ? [vendorName, ...entryNames] : entryNames;
1759
- const jsDir = config.env.isProd ? config.paths.target.js : config.paths.tmp.js;
1760
- const jsPathPrefix = config.assets.virtualDir ? `/${config.assets.virtualDir}/${jsDir}` : `/${jsDir}`;
1761
- const destJsFolder = config.dest.js;
1762
- const scriptTags = entries.filter(
1763
- (entryName) => !new RegExp(`<script[^>]+src=["'][^"']*${entryName}[^"']*\\.js["']`, "i").test(
1764
- content
1765
- )
1766
- ).map((entryName) => {
1767
- let actualFilename = `${entryName}.js`;
1768
- const hasUnhashed = (0, import_node_fs4.existsSync)(import_node_path13.default.join(destJsFolder, actualFilename));
1769
- let found = hasUnhashed;
1770
- try {
1771
- const matched = import_fast_glob3.default.sync(`${entryName}.*.js`, { cwd: destJsFolder });
1772
- if (matched.length) {
1773
- const valid = matched.find((f) => !f.endsWith(".map") && !f.endsWith(".txt"));
1774
- if (valid) {
1775
- actualFilename = valid;
1776
- found = true;
1777
- }
1778
- }
1779
- } catch {
1780
- }
1781
- if (entryName === vendorName && config.scripts.extractAllVendors && !found) {
1782
- return "";
1783
- }
1784
- return `<script defer src="${jsPathPrefix}/${actualFilename}"></script>`;
1785
- }).filter(Boolean).join("\n");
1786
- if (scriptTags) {
1787
- if (content.includes("</body>")) {
1788
- content = content.replace("</body>", `${scriptTags}
1789
- </body>`);
1790
- } else {
1791
- content += `
1792
- ${scriptTags}`;
1793
- }
1794
- file2.contents = Buffer.from(content);
1795
- }
1796
- }
1797
- return file2;
1858
+ await processHtmlPipeline(entryPipeline, config, false);
1859
+ const auxPatterns = getTemplatePatterns(templateDir, config);
1860
+ const auxPipeline = Pipeline.from(auxPatterns, {
1861
+ cwd: config.workspace,
1862
+ base: templateDir
1798
1863
  });
1799
- }
1800
- if (config.env.isProd && config.html.analytics) {
1801
- pipeline.pipe(async (file2) => {
1802
- if (/\.html$/i.test(file2.extname)) {
1803
- let content = file2.toString();
1804
- const { custom, google } = config.html.analytics;
1805
- if (custom && custom.src) {
1806
- const attrs = [
1807
- `src="${custom.src}"`,
1808
- custom.siteId !== void 0 ? `data-website-id="${custom.siteId}"` : "",
1809
- custom.defer !== false ? "defer" : "",
1810
- custom.async ? "async" : ""
1811
- ].filter(Boolean).join(" ");
1812
- const customTag = `<script ${attrs}></script>`;
1813
- if (content.includes("</head>")) {
1814
- content = content.replace("</head>", ` ${customTag}
1815
- </head>`);
1816
- } else {
1817
- content = `${customTag}
1818
- ${content}`;
1819
- }
1820
- }
1821
- if (google) {
1822
- const gaSnippet = [
1823
- `<script async src="https://www.googletagmanager.com/gtag/js?id=${google}"></script>`,
1824
- "<script>",
1825
- " window.dataLayer = window.dataLayer || [];",
1826
- " function gtag(){dataLayer.push(arguments);}",
1827
- " gtag('js', new Date());",
1828
- ` gtag('config', '${google}');`,
1829
- "</script>"
1830
- ].join("\n");
1831
- if (content.includes("</body>")) {
1832
- content = content.replace("</body>", `${gaSnippet}
1833
- </body>`);
1834
- } else {
1835
- content += `
1836
- ${gaSnippet}`;
1837
- }
1838
- }
1839
- file2.contents = Buffer.from(content);
1864
+ auxPipeline.pipe(async (file2) => {
1865
+ if (import_node_path13.default.resolve(file2.path) === resolvedTemplatePath || file2.basename.toLowerCase() === outputBasename.toLowerCase()) {
1866
+ return null;
1840
1867
  }
1841
1868
  return file2;
1842
1869
  });
1843
- }
1844
- if (config.env.isProd) {
1845
- pipeline.pipe(transformHtmlmin(config.html.options));
1870
+ await processHtmlPipeline(auxPipeline, config, true);
1846
1871
  } else {
1847
- pipeline.pipe(async (file2) => {
1848
- if (/\.html$/i.test(file2.extname)) {
1849
- let content = file2.toString();
1850
- if (content.includes("</body>")) {
1851
- content = content.replace("</body>", `${LIVE_RELOAD_SCRIPT}
1852
- </body>`);
1853
- } else {
1854
- content += `
1855
- ${LIVE_RELOAD_SCRIPT}`;
1856
- }
1857
- file2.contents = Buffer.from(content);
1858
- }
1859
- return file2;
1872
+ const patterns = getTemplatePatterns(templateDir, config);
1873
+ const pipeline = Pipeline.from(patterns, {
1874
+ cwd: config.workspace,
1875
+ base: templateDir
1860
1876
  });
1877
+ await processHtmlPipeline(pipeline, config, false);
1861
1878
  }
1862
- await pipeline.dest(config.dest.html);
1863
1879
  }
1864
1880
  };
1865
1881
 
@@ -2532,6 +2548,180 @@ var FileWatcher = class {
2532
2548
 
2533
2549
  // src/tasks/server.ts
2534
2550
  var import_picocolors4 = __toESM(require("picocolors"), 1);
2551
+ function resolveServedFile(config, targetPath) {
2552
+ const normalizedTarget = targetPath.split("?")[0].replace(/^\/+/, "");
2553
+ const candidates = [
2554
+ import_node_path24.default.join(config.dest.html, normalizedTarget),
2555
+ import_node_path24.default.join(config.dest.base, normalizedTarget),
2556
+ import_node_path24.default.join(config.src.base, normalizedTarget)
2557
+ ];
2558
+ return candidates.find((filePath) => {
2559
+ try {
2560
+ return import_node_fs8.default.existsSync(filePath) && import_node_fs8.default.statSync(filePath).isFile();
2561
+ } catch {
2562
+ return false;
2563
+ }
2564
+ }) || null;
2565
+ }
2566
+ function createHistoryFallbackMiddleware(config) {
2567
+ const rawOptions = config.server.historyOptions;
2568
+ const opts = rawOptions && typeof rawOptions === "object" ? rawOptions : {};
2569
+ const defaultIndex = typeof opts.index === "string" ? opts.index : "/index.html";
2570
+ const htmlAcceptHeaders = Array.isArray(opts.htmlAcceptHeaders) ? opts.htmlAcceptHeaders : ["text/html", "application/xhtml+xml"];
2571
+ const rewrites = Array.isArray(opts.rewrites) ? opts.rewrites : [];
2572
+ return (req, res, next) => {
2573
+ const isGetOrHead = req.method === "GET" || req.method === "HEAD";
2574
+ if (!isGetOrHead || !req.url) {
2575
+ return next();
2576
+ }
2577
+ const accept = req.headers?.accept;
2578
+ const isHtmlAccept = typeof accept === "string" && htmlAcceptHeaders.some((header) => accept.includes(header));
2579
+ if (!isHtmlAccept) {
2580
+ return next();
2581
+ }
2582
+ let parsedUrl;
2583
+ try {
2584
+ parsedUrl = new URL(req.url, "http://localhost");
2585
+ } catch {
2586
+ return next();
2587
+ }
2588
+ const { pathname } = parsedUrl;
2589
+ let rewriteTarget = null;
2590
+ for (const rule of rewrites) {
2591
+ const match = rule.from instanceof RegExp ? pathname.match(rule.from) : pathname === rule.from ? [pathname] : null;
2592
+ if (match) {
2593
+ rewriteTarget = typeof rule.to === "function" ? rule.to({ parsedUrl, match, request: req }) : rule.to;
2594
+ break;
2595
+ }
2596
+ }
2597
+ if (!rewriteTarget) {
2598
+ if (!opts.disableDotRule) {
2599
+ const lastSlash = pathname.lastIndexOf("/");
2600
+ const lastDot = pathname.lastIndexOf(".");
2601
+ if (lastDot > lastSlash) {
2602
+ return next();
2603
+ }
2604
+ }
2605
+ rewriteTarget = defaultIndex;
2606
+ }
2607
+ const fileToServe = resolveServedFile(config, rewriteTarget);
2608
+ if (fileToServe && /\.html?$/i.test(fileToServe)) {
2609
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
2610
+ if (req.method === "HEAD") {
2611
+ return res.end();
2612
+ }
2613
+ return import_node_fs8.default.createReadStream(fileToServe).pipe(res);
2614
+ }
2615
+ req.url = rewriteTarget;
2616
+ return next();
2617
+ };
2618
+ }
2619
+ function createDevServerApp(config) {
2620
+ const app = (0, import_connect.default)();
2621
+ app.use((req, _res, next) => {
2622
+ if (req.url?.includes("%PUBLIC_URL%")) {
2623
+ req.url = req.url.replace("/%PUBLIC_URL%", "").replace("%PUBLIC_URL%", "") || "/";
2624
+ }
2625
+ next();
2626
+ });
2627
+ app.use((req, res, next) => {
2628
+ if (req.url === "/manifest.json" || req.url?.endsWith("/manifest.json")) {
2629
+ const candidates = [
2630
+ import_node_path24.default.join(config.dest.base, "manifest.json"),
2631
+ import_node_path24.default.join(config.src.base, "manifest.json"),
2632
+ import_node_path24.default.join(config.workspace, "manifest.json")
2633
+ ];
2634
+ const file2 = candidates.find((f) => import_node_fs8.default.existsSync(f));
2635
+ if (file2) {
2636
+ let content = import_node_fs8.default.readFileSync(file2, "utf-8");
2637
+ const replacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2638
+ content = content.replaceAll("%PUBLIC_URL%", replacement);
2639
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
2640
+ return res.end(content);
2641
+ }
2642
+ }
2643
+ next();
2644
+ });
2645
+ if (config.server.proxy && typeof config.server.proxy === "object") {
2646
+ const proxyEntries = Array.isArray(config.server.proxy) ? config.server.proxy : [config.server.proxy];
2647
+ for (const entry of proxyEntries) {
2648
+ if (entry.context && entry.options) {
2649
+ app.use((0, import_http_proxy_middleware.createProxyMiddleware)({ pathFilter: entry.context, ...entry.options }));
2650
+ } else if (entry.target || entry.pathFilter) {
2651
+ app.use((0, import_http_proxy_middleware.createProxyMiddleware)(entry));
2652
+ }
2653
+ }
2654
+ }
2655
+ if (config.server.historyOptions) {
2656
+ app.use(createHistoryFallbackMiddleware(config));
2657
+ }
2658
+ if (config.paths.source.css) {
2659
+ app.use("/" + config.paths.source.css, (0, import_serve_static.default)(config.dest.css));
2660
+ }
2661
+ if (config.paths.tmp.css && config.paths.tmp.css !== config.paths.source.css) {
2662
+ app.use("/" + config.paths.tmp.css, (0, import_serve_static.default)(config.dest.css));
2663
+ }
2664
+ if (config.paths.source.js) {
2665
+ app.use("/" + config.paths.source.js, (0, import_serve_static.default)(config.dest.js));
2666
+ }
2667
+ if (config.paths.tmp.js && config.paths.tmp.js !== config.paths.source.js) {
2668
+ app.use("/" + config.paths.tmp.js, (0, import_serve_static.default)(config.dest.js));
2669
+ }
2670
+ app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "chunk")));
2671
+ app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "chunk")));
2672
+ if (config.paths.source.img) {
2673
+ app.use(
2674
+ "/" + config.paths.source.img,
2675
+ (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.img))
2676
+ );
2677
+ }
2678
+ if (config.paths.tmp.img) {
2679
+ app.use("/" + config.paths.tmp.img, (0, import_serve_static.default)(config.dest.img));
2680
+ }
2681
+ app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "img")));
2682
+ app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "img")));
2683
+ if (config.paths.source.font) {
2684
+ app.use(
2685
+ "/" + config.paths.source.font,
2686
+ (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.font))
2687
+ );
2688
+ }
2689
+ if (config.paths.tmp.font) {
2690
+ app.use("/" + config.paths.tmp.font, (0, import_serve_static.default)(config.dest.font));
2691
+ }
2692
+ app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "font")));
2693
+ app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "font")));
2694
+ app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, "fonts")));
2695
+ app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "fonts")));
2696
+ if (config.server.serveStatic) {
2697
+ const staticEntries = Array.isArray(config.server.serveStatic) ? config.server.serveStatic : [config.server.serveStatic];
2698
+ for (const entry of staticEntries) {
2699
+ if (typeof entry === "string") {
2700
+ const absoluteDir = import_node_path24.default.isAbsolute(entry) ? entry : import_node_path24.default.join(config.workspace, entry);
2701
+ if (import_node_fs8.default.existsSync(absoluteDir)) {
2702
+ app.use((0, import_serve_static.default)(absoluteDir));
2703
+ }
2704
+ } else if (entry && typeof entry === "object") {
2705
+ const route = entry.route ? entry.route.startsWith("/") ? entry.route : `/${entry.route}` : "";
2706
+ const dirs = Array.isArray(entry.dir) ? entry.dir : [entry.dir];
2707
+ for (const dir of dirs) {
2708
+ const absoluteDir = import_node_path24.default.isAbsolute(dir) ? dir : import_node_path24.default.join(config.workspace, dir);
2709
+ if (import_node_fs8.default.existsSync(absoluteDir)) {
2710
+ if (route) {
2711
+ app.use(route, (0, import_serve_static.default)(absoluteDir));
2712
+ } else {
2713
+ app.use((0, import_serve_static.default)(absoluteDir));
2714
+ }
2715
+ }
2716
+ }
2717
+ }
2718
+ }
2719
+ }
2720
+ app.use((0, import_serve_static.default)(config.dest.base));
2721
+ app.use((0, import_serve_static.default)(config.src.base));
2722
+ app.use((0, import_serve_static.default)(config.workspace));
2723
+ return app;
2724
+ }
2535
2725
  var ServerTask = class extends BaseTask {
2536
2726
  watcher = null;
2537
2727
  wsServer = null;
@@ -2552,125 +2742,9 @@ var ServerTask = class extends BaseTask {
2552
2742
  logger.warn("server", "Development server is disabled in production mode");
2553
2743
  return;
2554
2744
  }
2555
- const app = (0, import_connect.default)();
2745
+ const app = createDevServerApp(config);
2556
2746
  const port = config.server.port || 3e3;
2557
2747
  const host = config.server.host || "localhost";
2558
- app.use((req, _res, next) => {
2559
- if (req.url?.includes("%PUBLIC_URL%")) {
2560
- req.url = req.url.replace("/%PUBLIC_URL%", "").replace("%PUBLIC_URL%", "") || "/";
2561
- }
2562
- next();
2563
- });
2564
- app.use((req, res, next) => {
2565
- if (req.url === "/manifest.json" || req.url?.endsWith("/manifest.json")) {
2566
- const candidates = [
2567
- import_node_path24.default.join(config.dest.base, "manifest.json"),
2568
- import_node_path24.default.join(config.src.base, "manifest.json"),
2569
- import_node_path24.default.join(config.workspace, "manifest.json")
2570
- ];
2571
- const file2 = candidates.find((f) => import_node_fs8.default.existsSync(f));
2572
- if (file2) {
2573
- let content = import_node_fs8.default.readFileSync(file2, "utf-8");
2574
- const replacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2575
- content = content.replaceAll("%PUBLIC_URL%", replacement);
2576
- res.setHeader("Content-Type", "application/json; charset=utf-8");
2577
- return res.end(content);
2578
- }
2579
- }
2580
- next();
2581
- });
2582
- if (config.paths.source.css) {
2583
- app.use("/" + config.paths.source.css, (0, import_serve_static.default)(config.dest.css));
2584
- }
2585
- if (config.paths.tmp.css && config.paths.tmp.css !== config.paths.source.css) {
2586
- app.use("/" + config.paths.tmp.css, (0, import_serve_static.default)(config.dest.css));
2587
- }
2588
- if (config.paths.source.js) {
2589
- app.use("/" + config.paths.source.js, (0, import_serve_static.default)(config.dest.js));
2590
- }
2591
- if (config.paths.tmp.js && config.paths.tmp.js !== config.paths.source.js) {
2592
- app.use("/" + config.paths.tmp.js, (0, import_serve_static.default)(config.dest.js));
2593
- }
2594
- app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "chunk")));
2595
- app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "chunk")));
2596
- if (config.paths.source.img) {
2597
- app.use(
2598
- "/" + config.paths.source.img,
2599
- (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.img))
2600
- );
2601
- }
2602
- if (config.paths.tmp.img) {
2603
- app.use("/" + config.paths.tmp.img, (0, import_serve_static.default)(config.dest.img));
2604
- }
2605
- app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "img")));
2606
- app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "img")));
2607
- if (config.paths.source.font) {
2608
- app.use(
2609
- "/" + config.paths.source.font,
2610
- (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.font))
2611
- );
2612
- }
2613
- if (config.paths.tmp.font) {
2614
- app.use("/" + config.paths.tmp.font, (0, import_serve_static.default)(config.dest.font));
2615
- }
2616
- app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "font")));
2617
- app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "font")));
2618
- app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, "fonts")));
2619
- app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "fonts")));
2620
- if (config.server.serveStatic) {
2621
- const staticEntries = Array.isArray(config.server.serveStatic) ? config.server.serveStatic : [config.server.serveStatic];
2622
- for (const entry of staticEntries) {
2623
- if (typeof entry === "string") {
2624
- const absoluteDir = import_node_path24.default.isAbsolute(entry) ? entry : import_node_path24.default.join(config.workspace, entry);
2625
- if (import_node_fs8.default.existsSync(absoluteDir)) {
2626
- app.use((0, import_serve_static.default)(absoluteDir));
2627
- }
2628
- } else if (entry && typeof entry === "object") {
2629
- const route = entry.route ? entry.route.startsWith("/") ? entry.route : `/${entry.route}` : "";
2630
- const dirs = Array.isArray(entry.dir) ? entry.dir : [entry.dir];
2631
- for (const dir of dirs) {
2632
- const absoluteDir = import_node_path24.default.isAbsolute(dir) ? dir : import_node_path24.default.join(config.workspace, dir);
2633
- if (import_node_fs8.default.existsSync(absoluteDir)) {
2634
- if (route) {
2635
- app.use(route, (0, import_serve_static.default)(absoluteDir));
2636
- } else {
2637
- app.use((0, import_serve_static.default)(absoluteDir));
2638
- }
2639
- }
2640
- }
2641
- }
2642
- }
2643
- }
2644
- app.use((0, import_serve_static.default)(config.dest.base));
2645
- app.use((0, import_serve_static.default)(config.src.base));
2646
- app.use((0, import_serve_static.default)(config.workspace));
2647
- if (config.server.historyOptions) {
2648
- app.use((req, res, next) => {
2649
- const isGetOrHead = req.method === "GET" || req.method === "HEAD";
2650
- const isHtmlNav = !req.url?.includes(".") || req.headers.accept?.includes("text/html");
2651
- if (isGetOrHead && isHtmlNav) {
2652
- const indexPath = import_node_path24.default.join(config.dest.html, "index.html");
2653
- const srcIndexPath = import_node_path24.default.join(config.src.base, "index.html");
2654
- const fileToServe = import_node_fs8.default.existsSync(indexPath) ? indexPath : srcIndexPath;
2655
- if (import_node_fs8.default.existsSync(fileToServe)) {
2656
- res.setHeader("Content-Type", "text/html; charset=utf-8");
2657
- if (req.method === "HEAD") {
2658
- return res.end();
2659
- }
2660
- return import_node_fs8.default.createReadStream(fileToServe).pipe(res);
2661
- }
2662
- }
2663
- next();
2664
- });
2665
- }
2666
- if (config.server.proxy && typeof config.server.proxy === "object") {
2667
- const proxyEntries = Array.isArray(config.server.proxy) ? config.server.proxy : [config.server.proxy];
2668
- for (const entry of proxyEntries) {
2669
- if (entry.context && entry.options) {
2670
- app.use((0, import_http_proxy_middleware.createProxyMiddleware)(entry.options));
2671
- }
2672
- }
2673
- }
2674
2748
  const server = import_node_http.default.createServer(app);
2675
2749
  this.wsServer = new import_ws.WebSocketServer({ server, path: "/__balm_ws" });
2676
2750
  this.wsServer.on("connection", (socket) => {
@@ -3065,6 +3139,8 @@ var index_default = balm;
3065
3139
  ZipTask,
3066
3140
  balm,
3067
3141
  createDefaultConfig,
3142
+ createDevServerApp,
3143
+ createHistoryFallbackMiddleware,
3068
3144
  deepMerge,
3069
3145
  file,
3070
3146
  getWorkspaces,