balm-core 6.0.0-alpha.4 → 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/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, {
1719
- cwd: config.workspace,
1720
- base: import_node_path13.default.dirname(templatePath)
1721
- });
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, {
1849
+ const resolvedTemplatePath = import_node_path13.default.resolve(config.workspace, customTemplate);
1850
+ const entryPipeline = Pipeline.from(resolvedTemplatePath, {
1732
1851
  cwd: config.workspace,
1733
- base: templateDir
1852
+ base: import_node_path13.default.dirname(resolvedTemplatePath)
1734
1853
  });
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";
1854
+ entryPipeline.pipe(async (file2) => {
1855
+ file2.basename = outputBasename;
1741
1856
  return file2;
1742
1857
  });
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
- }
1749
- return file2;
1750
- });
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
 
@@ -1988,6 +2004,7 @@ var AssetRevisioner = class {
1988
2004
  "*.webmanifest",
1989
2005
  "robots.txt",
1990
2006
  "*.ico",
2007
+ "*.map",
1991
2008
  "workbox-sw.js",
1992
2009
  "workbox-sw.js.map",
1993
2010
  "service-worker.js",
@@ -2008,12 +2025,18 @@ var AssetRevisioner = class {
2008
2025
  }
2009
2026
  }
2010
2027
  process(files) {
2028
+ this.manifest = {};
2011
2029
  const hashLength = this.options.hashLength || 8;
2030
+ const alreadyHashedRegex = hashLength === 8 ? /\.[a-f0-9]{8}$/i : new RegExp(`\\.(?:[a-f0-9]{8}|[a-f0-9]{${hashLength}})$`, "i");
2031
+ const alreadyHashedExtRegex = hashLength === 8 ? /\.[a-f0-9]{8}(\.[^.]+)$/i : new RegExp(`\\.(?:[a-f0-9]{8}|[a-f0-9]{${hashLength}})(\\.[^.]+)$`, "i");
2012
2032
  const outputFiles = [];
2033
+ const renames = [];
2034
+ const renamedOrigs = /* @__PURE__ */ new Set();
2035
+ const alreadyHashedUniques = /* @__PURE__ */ new Map();
2013
2036
  for (const file2 of files) {
2014
- const origRelative = file2.relative;
2037
+ const origRelative = file2.relative.replace(/\\/g, "/");
2015
2038
  file2.revPathOriginal = file2.path;
2016
- const alreadyHashed = /\.[a-f0-9]{8}$/i.test(file2.stem);
2039
+ const alreadyHashed = alreadyHashedRegex.test(file2.stem);
2017
2040
  const shouldRename = !alreadyHashed && !matchesAny(file2.path, this.options.dontRenameFile) && !matchesAny(file2.relative, this.options.dontRenameFile);
2018
2041
  if (shouldRename) {
2019
2042
  const fileHash = file.hash(file2.contents, hashLength);
@@ -2021,27 +2044,57 @@ var AssetRevisioner = class {
2021
2044
  const newFilename = `${file2.stem}.${fileHash}${file2.extname}`;
2022
2045
  file2.path = import_node_path18.default.join(dir, newFilename);
2023
2046
  }
2047
+ const revedRelative = file2.relative.replace(/\\/g, "/");
2024
2048
  if (alreadyHashed) {
2025
- const unhashedRelative = file2.relative.replace(/\.[a-f0-9]{8}(\.[^.]+)$/i, "$1");
2026
- this.manifest[unhashedRelative] = file2.relative;
2049
+ const unhashedRelative = revedRelative.replace(alreadyHashedExtRegex, "$1");
2050
+ alreadyHashedUniques.set(
2051
+ unhashedRelative,
2052
+ alreadyHashedUniques.has(unhashedRelative) ? null : revedRelative
2053
+ );
2054
+ } else if (origRelative !== revedRelative) {
2055
+ renames.push([origRelative, revedRelative]);
2056
+ renamedOrigs.add(origRelative);
2027
2057
  }
2028
- this.manifest[origRelative] = file2.relative;
2058
+ this.manifest[origRelative] = revedRelative;
2029
2059
  outputFiles.push(file2);
2030
2060
  }
2031
- const manifestEntries = Object.entries(this.manifest).filter(([orig, reved]) => orig !== reved).sort((a, b) => b[0].length - a[0].length);
2032
- for (const file2 of outputFiles) {
2033
- const shouldUpdate = !matchesAny(file2.path, this.options.dontUpdateReference) && !matchesAny(file2.relative, this.options.dontUpdateReference);
2034
- if (shouldUpdate && /\.(html|css|js)$/i.test(file2.extname)) {
2035
- let content = file2.toString();
2036
- for (const [orig, reved] of manifestEntries) {
2037
- content = content.replaceAll(orig, reved);
2038
- const origBase = import_node_path18.default.basename(orig);
2039
- const revedBase = import_node_path18.default.basename(reved);
2040
- const escapedBase = origBase.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2041
- const baseRegex = new RegExp(`${escapedBase}(?![a-zA-Z0-9_])`, "g");
2042
- content = content.replace(baseRegex, revedBase);
2061
+ const lookup = /* @__PURE__ */ new Map();
2062
+ for (const [unhashedRelative, revedRelative] of alreadyHashedUniques) {
2063
+ if (revedRelative && !renamedOrigs.has(unhashedRelative) && unhashedRelative !== revedRelative) {
2064
+ this.manifest[unhashedRelative] = revedRelative;
2065
+ lookup.set(unhashedRelative, revedRelative);
2066
+ }
2067
+ }
2068
+ const basenameCounts = /* @__PURE__ */ new Map();
2069
+ for (const [orig] of renames) {
2070
+ const base = import_node_path18.default.posix.basename(orig);
2071
+ basenameCounts.set(base, (basenameCounts.get(base) || 0) + 1);
2072
+ }
2073
+ for (const [orig, reved] of renames) {
2074
+ const origBase = import_node_path18.default.posix.basename(orig);
2075
+ const revedBase = import_node_path18.default.posix.basename(reved);
2076
+ if (basenameCounts.get(origBase) === 1 && !lookup.has(origBase)) {
2077
+ lookup.set(origBase, revedBase);
2078
+ }
2079
+ }
2080
+ for (const [orig, reved] of renames) {
2081
+ lookup.set(orig, reved);
2082
+ }
2083
+ if (lookup.size > 0) {
2084
+ const patterns = [...lookup.keys()].sort((a, b) => b.length - a.length).map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
2085
+ const replaceRegex = new RegExp(
2086
+ `(?<![a-zA-Z0-9_.@-])(?:${patterns.join("|")})(?![a-zA-Z0-9_.@-])`,
2087
+ "g"
2088
+ );
2089
+ for (const file2 of outputFiles) {
2090
+ const shouldUpdate = !matchesAny(file2.path, this.options.dontUpdateReference) && !matchesAny(file2.relative, this.options.dontUpdateReference);
2091
+ if (shouldUpdate && /\.(html|css|js)$/i.test(file2.extname)) {
2092
+ const content = file2.toString();
2093
+ const updated = content.replace(replaceRegex, (matched) => lookup.get(matched) || matched);
2094
+ if (updated !== content) {
2095
+ file2.contents = Buffer.from(updated);
2096
+ }
2043
2097
  }
2044
- file2.contents = Buffer.from(content);
2045
2098
  }
2046
2099
  }
2047
2100
  const manifestName = this.options.fileNameManifest || "rev-manifest.json";
@@ -2081,17 +2134,22 @@ var CacheTask = class extends BaseTask {
2081
2134
  logger.warn("cache", "No files found to cache");
2082
2135
  return;
2083
2136
  }
2137
+ const originalContents = /* @__PURE__ */ new Map();
2084
2138
  const virtualFiles = await Promise.all(
2085
2139
  filesToRev.map(async (filePath) => {
2086
2140
  const buffer = await import_promises3.default.readFile(filePath);
2087
- return new VirtualFile({
2141
+ const vFile = new VirtualFile({
2088
2142
  cwd: config.workspace,
2089
2143
  base: destDir,
2090
2144
  path: filePath,
2091
2145
  contents: buffer
2092
2146
  });
2147
+ originalContents.set(vFile, buffer);
2148
+ return vFile;
2093
2149
  })
2094
2150
  );
2151
+ const isWebpack = !config.scripts.bundler || config.scripts.bundler === "webpack" /* webpack */;
2152
+ const webpackOwnedGlobs = isWebpack ? [`${config.paths.target.js}/**/*`, `${config.paths.target.css}/async/**/*`] : [];
2095
2153
  const cacheOptions = {
2096
2154
  ...config.assets.options,
2097
2155
  dontRenameFile: [
@@ -2101,13 +2159,19 @@ var CacheTask = class extends BaseTask {
2101
2159
  "*.webmanifest",
2102
2160
  "robots.txt",
2103
2161
  "*.ico",
2162
+ "*.map",
2104
2163
  "icons/*",
2105
2164
  "**/icons/**",
2106
2165
  "sw.js",
2107
2166
  "service-worker.js",
2108
2167
  "workbox-sw.js",
2168
+ ...webpackOwnedGlobs,
2109
2169
  ...config.assets.excludes || [],
2110
2170
  ...config.assets.options?.dontRenameFile || []
2171
+ ],
2172
+ dontUpdateReference: [
2173
+ ...webpackOwnedGlobs,
2174
+ ...config.assets.options?.dontUpdateReference || []
2111
2175
  ]
2112
2176
  };
2113
2177
  const revisioner = new AssetRevisioner(cacheOptions);
@@ -2118,7 +2182,12 @@ var CacheTask = class extends BaseTask {
2118
2182
  }
2119
2183
  }
2120
2184
  for (const vFile of resultFiles) {
2121
- await file.writeFile(vFile.path, vFile.contents);
2185
+ const origBuf = originalContents.get(vFile);
2186
+ const isRenamed = Boolean(vFile.revPathOriginal && vFile.revPathOriginal !== vFile.path);
2187
+ const isUpdated = !origBuf || !origBuf.equals(vFile.contents);
2188
+ if (isRenamed || isUpdated) {
2189
+ await file.writeFile(vFile.path, vFile.contents);
2190
+ }
2122
2191
  }
2123
2192
  logger.success("cache", "Asset revisioning and rev-manifest.json completed");
2124
2193
  }
@@ -2479,6 +2548,180 @@ var FileWatcher = class {
2479
2548
 
2480
2549
  // src/tasks/server.ts
2481
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
+ }
2482
2725
  var ServerTask = class extends BaseTask {
2483
2726
  watcher = null;
2484
2727
  wsServer = null;
@@ -2499,125 +2742,9 @@ var ServerTask = class extends BaseTask {
2499
2742
  logger.warn("server", "Development server is disabled in production mode");
2500
2743
  return;
2501
2744
  }
2502
- const app = (0, import_connect.default)();
2745
+ const app = createDevServerApp(config);
2503
2746
  const port = config.server.port || 3e3;
2504
2747
  const host = config.server.host || "localhost";
2505
- app.use((req, _res, next) => {
2506
- if (req.url?.includes("%PUBLIC_URL%")) {
2507
- req.url = req.url.replace("/%PUBLIC_URL%", "").replace("%PUBLIC_URL%", "") || "/";
2508
- }
2509
- next();
2510
- });
2511
- app.use((req, res, next) => {
2512
- if (req.url === "/manifest.json" || req.url?.endsWith("/manifest.json")) {
2513
- const candidates = [
2514
- import_node_path24.default.join(config.dest.base, "manifest.json"),
2515
- import_node_path24.default.join(config.src.base, "manifest.json"),
2516
- import_node_path24.default.join(config.workspace, "manifest.json")
2517
- ];
2518
- const file2 = candidates.find((f) => import_node_fs8.default.existsSync(f));
2519
- if (file2) {
2520
- let content = import_node_fs8.default.readFileSync(file2, "utf-8");
2521
- const replacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2522
- content = content.replaceAll("%PUBLIC_URL%", replacement);
2523
- res.setHeader("Content-Type", "application/json; charset=utf-8");
2524
- return res.end(content);
2525
- }
2526
- }
2527
- next();
2528
- });
2529
- if (config.paths.source.css) {
2530
- app.use("/" + config.paths.source.css, (0, import_serve_static.default)(config.dest.css));
2531
- }
2532
- if (config.paths.tmp.css && config.paths.tmp.css !== config.paths.source.css) {
2533
- app.use("/" + config.paths.tmp.css, (0, import_serve_static.default)(config.dest.css));
2534
- }
2535
- if (config.paths.source.js) {
2536
- app.use("/" + config.paths.source.js, (0, import_serve_static.default)(config.dest.js));
2537
- }
2538
- if (config.paths.tmp.js && config.paths.tmp.js !== config.paths.source.js) {
2539
- app.use("/" + config.paths.tmp.js, (0, import_serve_static.default)(config.dest.js));
2540
- }
2541
- app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "chunk")));
2542
- app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "chunk")));
2543
- if (config.paths.source.img) {
2544
- app.use(
2545
- "/" + config.paths.source.img,
2546
- (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.img))
2547
- );
2548
- }
2549
- if (config.paths.tmp.img) {
2550
- app.use("/" + config.paths.tmp.img, (0, import_serve_static.default)(config.dest.img));
2551
- }
2552
- app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "img")));
2553
- app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "img")));
2554
- if (config.paths.source.font) {
2555
- app.use(
2556
- "/" + config.paths.source.font,
2557
- (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.font))
2558
- );
2559
- }
2560
- if (config.paths.tmp.font) {
2561
- app.use("/" + config.paths.tmp.font, (0, import_serve_static.default)(config.dest.font));
2562
- }
2563
- app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "font")));
2564
- app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "font")));
2565
- app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, "fonts")));
2566
- app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "fonts")));
2567
- if (config.server.serveStatic) {
2568
- const staticEntries = Array.isArray(config.server.serveStatic) ? config.server.serveStatic : [config.server.serveStatic];
2569
- for (const entry of staticEntries) {
2570
- if (typeof entry === "string") {
2571
- const absoluteDir = import_node_path24.default.isAbsolute(entry) ? entry : import_node_path24.default.join(config.workspace, entry);
2572
- if (import_node_fs8.default.existsSync(absoluteDir)) {
2573
- app.use((0, import_serve_static.default)(absoluteDir));
2574
- }
2575
- } else if (entry && typeof entry === "object") {
2576
- const route = entry.route ? entry.route.startsWith("/") ? entry.route : `/${entry.route}` : "";
2577
- const dirs = Array.isArray(entry.dir) ? entry.dir : [entry.dir];
2578
- for (const dir of dirs) {
2579
- const absoluteDir = import_node_path24.default.isAbsolute(dir) ? dir : import_node_path24.default.join(config.workspace, dir);
2580
- if (import_node_fs8.default.existsSync(absoluteDir)) {
2581
- if (route) {
2582
- app.use(route, (0, import_serve_static.default)(absoluteDir));
2583
- } else {
2584
- app.use((0, import_serve_static.default)(absoluteDir));
2585
- }
2586
- }
2587
- }
2588
- }
2589
- }
2590
- }
2591
- app.use((0, import_serve_static.default)(config.dest.base));
2592
- app.use((0, import_serve_static.default)(config.src.base));
2593
- app.use((0, import_serve_static.default)(config.workspace));
2594
- if (config.server.historyOptions) {
2595
- app.use((req, res, next) => {
2596
- const isGetOrHead = req.method === "GET" || req.method === "HEAD";
2597
- const isHtmlNav = !req.url?.includes(".") || req.headers.accept?.includes("text/html");
2598
- if (isGetOrHead && isHtmlNav) {
2599
- const indexPath = import_node_path24.default.join(config.dest.html, "index.html");
2600
- const srcIndexPath = import_node_path24.default.join(config.src.base, "index.html");
2601
- const fileToServe = import_node_fs8.default.existsSync(indexPath) ? indexPath : srcIndexPath;
2602
- if (import_node_fs8.default.existsSync(fileToServe)) {
2603
- res.setHeader("Content-Type", "text/html; charset=utf-8");
2604
- if (req.method === "HEAD") {
2605
- return res.end();
2606
- }
2607
- return import_node_fs8.default.createReadStream(fileToServe).pipe(res);
2608
- }
2609
- }
2610
- next();
2611
- });
2612
- }
2613
- if (config.server.proxy && typeof config.server.proxy === "object") {
2614
- const proxyEntries = Array.isArray(config.server.proxy) ? config.server.proxy : [config.server.proxy];
2615
- for (const entry of proxyEntries) {
2616
- if (entry.context && entry.options) {
2617
- app.use((0, import_http_proxy_middleware.createProxyMiddleware)(entry.options));
2618
- }
2619
- }
2620
- }
2621
2748
  const server = import_node_http.default.createServer(app);
2622
2749
  this.wsServer = new import_ws.WebSocketServer({ server, path: "/__balm_ws" });
2623
2750
  this.wsServer.on("connection", (socket) => {
@@ -3012,6 +3139,8 @@ var index_default = balm;
3012
3139
  ZipTask,
3013
3140
  balm,
3014
3141
  createDefaultConfig,
3142
+ createDevServerApp,
3143
+ createHistoryFallbackMiddleware,
3015
3144
  deepMerge,
3016
3145
  file,
3017
3146
  getWorkspaces,