@stencil/dev-server 5.0.0-beta.11 → 5.0.0-beta.13

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.
@@ -1,4 +1,4 @@
1
- import { CompilerBuildResults, Diagnostic, HmrStyleUpdate, HotModuleReplacement, PrintLine } from "@stencil/core/compiler";
1
+ import { CompilerBuildResults, Diagnostic, HmrGlobalStyleUpdate, HmrStyleUpdate, HotModuleReplacement, PrintLine } from "@stencil/core/compiler";
2
2
  //#region src/client/types.d.ts
3
3
  interface DevClientWindow extends Window {
4
4
  's-dev-server'?: boolean;
@@ -41,6 +41,7 @@ interface HmrResults {
41
41
  updatedComponents: string[];
42
42
  updatedExternalStyles: string[];
43
43
  updatedInlineStyles: string[];
44
+ updatedGlobalStyles: string[];
44
45
  updatedImages: string[];
45
46
  versionId: string;
46
47
  }
@@ -128,4 +129,4 @@ declare const initClientWebSocket: (win: DevClientWindow, config: DevClientConfi
128
129
  */
129
130
  declare const initDevClient: (win: DevClientWindow, config: DevClientConfig) => void;
130
131
  //#endregion
131
- export { BUILD_LOG, BUILD_RESULTS, BUILD_STATUS, BuildLog, type CompilerBuildResults, DEV_SERVER_INIT_URL, DEV_SERVER_URL, DevClientConfig, DevClientWindow, DevServerEditor, DevServerMessage, type Diagnostic, HmrResults, type HmrStyleUpdate, HostElement, type HotModuleReplacement, NODE_TYPE_DOCUMENT_FRAGMENT, NODE_TYPE_ELEMENT, NORMAL_CLOSURE_CODE, OPEN_IN_EDITOR_URL, OpenInEditorData, type PrintLine, RECONNECT_ATTEMPTS, RECONNECT_RETRY_MS, REQUEST_BUILD_RESULTS_INTERVAL_MS, appError, clearAppErrorModal, emitBuildLog, emitBuildResults, emitBuildStatus, hmrWindow, initBuildProgress, initBuildStatus, initClientWebSocket, initDevClient, logBuild, logDiagnostic, logDisabled, logReload, logWarn, onBuildLog, onBuildResults, onBuildStatus, updateFavIcon };
132
+ export { BUILD_LOG, BUILD_RESULTS, BUILD_STATUS, BuildLog, type CompilerBuildResults, DEV_SERVER_INIT_URL, DEV_SERVER_URL, DevClientConfig, DevClientWindow, DevServerEditor, DevServerMessage, type Diagnostic, type HmrGlobalStyleUpdate, HmrResults, type HmrStyleUpdate, HostElement, type HotModuleReplacement, NODE_TYPE_DOCUMENT_FRAGMENT, NODE_TYPE_ELEMENT, NORMAL_CLOSURE_CODE, OPEN_IN_EDITOR_URL, OpenInEditorData, type PrintLine, RECONNECT_ATTEMPTS, RECONNECT_RETRY_MS, REQUEST_BUILD_RESULTS_INTERVAL_MS, appError, clearAppErrorModal, emitBuildLog, emitBuildResults, emitBuildStatus, hmrWindow, initBuildProgress, initBuildStatus, initClientWebSocket, initDevClient, logBuild, logDiagnostic, logDisabled, logReload, logWarn, onBuildLog, onBuildResults, onBuildStatus, updateFavIcon };
@@ -479,6 +479,43 @@ const hmrStylesheetLink = (styleSheetElm, versionId, cssFileName) => {
479
479
  setHmrAttr(styleSheetElm, versionId);
480
480
  }
481
481
  };
482
+ const GLOBAL_LINK_ATTR = "data-hmr-global";
483
+ /**
484
+ * Apply live CSS text updates for `global-style` output targets. Each update is matched
485
+ * to the `<link rel="stylesheet">` that loads it (by fileName) and delivered as a
486
+ * `<style>` inserted immediately after that `<link>`, so multiple global stylesheets
487
+ * keep their original cascade order. The matching `<link>` is disabled once a patch takes over.
488
+ *
489
+ * @param doc - the document to apply updates to
490
+ * @param versionId - the HMR version identifier
491
+ * @param updates - the global style updates, one per changed output target
492
+ * @returns the fileNames that were updated
493
+ */
494
+ const hmrGlobalStyleLinks = (doc, versionId, updates) => {
495
+ updates.forEach(({ fileName, styleText }) => {
496
+ const link = findMatchingStylesheetLink(doc, fileName);
497
+ if (link) link.disabled = true;
498
+ const existing = findGlobalStyleLinkPatch(doc, fileName);
499
+ if (existing) {
500
+ existing.innerHTML = styleText.replace(/\\n/g, "\n");
501
+ existing.setAttribute("data-hmr", versionId);
502
+ return;
503
+ }
504
+ const styleElm = doc.createElement("style");
505
+ styleElm.innerHTML = styleText.replace(/\\n/g, "\n");
506
+ styleElm.setAttribute(GLOBAL_LINK_ATTR, fileName);
507
+ styleElm.setAttribute("data-hmr", versionId);
508
+ if (link?.parentNode) link.parentNode.insertBefore(styleElm, link.nextSibling);
509
+ else doc.head.appendChild(styleElm);
510
+ });
511
+ return updates.map((u) => u.fileName).sort();
512
+ };
513
+ const findGlobalStyleLinkPatch = (doc, fileName) => {
514
+ return Array.from(doc.head.querySelectorAll(`style[${GLOBAL_LINK_ATTR}]`)).find((s) => s.getAttribute(GLOBAL_LINK_ATTR) === fileName) ?? null;
515
+ };
516
+ const findMatchingStylesheetLink = (doc, fileName) => {
517
+ return Array.from(doc.querySelectorAll("link[rel=\"stylesheet\"]")).find((link) => getUrlFileName(link.getAttribute("href") ?? "") === fileName) ?? null;
518
+ };
482
519
  const hmrInlineStyles = (elm, versionId, stylesUpdatedData) => {
483
520
  const trackers = stylesUpdatedData.map((styleUpdate) => ({
484
521
  styleUpdate,
@@ -589,6 +626,7 @@ const hmrWindow = (data) => {
589
626
  updatedComponents: [],
590
627
  updatedExternalStyles: [],
591
628
  updatedInlineStyles: [],
629
+ updatedGlobalStyles: [],
592
630
  updatedImages: [],
593
631
  versionId: ""
594
632
  };
@@ -602,6 +640,7 @@ const hmrWindow = (data) => {
602
640
  results.versionId = versionId;
603
641
  if (hmr.componentsUpdated) results.updatedComponents = hmrComponents(documentElement, versionId, hmr.componentsUpdated);
604
642
  if (hmr.inlineStylesUpdated) results.updatedInlineStyles = hmrInlineStyles(documentElement, versionId, hmr.inlineStylesUpdated);
643
+ if (hmr.globalStylesUpdated) results.updatedGlobalStyles = hmrGlobalStyleLinks(doc, versionId, hmr.globalStylesUpdated);
605
644
  if (hmr.externalStylesUpdated) results.updatedExternalStyles = hmrExternalStyles(documentElement, versionId, hmr.externalStylesUpdated);
606
645
  if (hmr.imagesUpdated) results.updatedImages = hmrImages(win, doc, versionId, hmr.imagesUpdated);
607
646
  setHmrAttr(documentElement, versionId);
@@ -1001,6 +1040,7 @@ const appHmr = (win, hmr) => {
1001
1040
  });
1002
1041
  if (results.updatedComponents.length > 0) logBuild(`Updated component${results.updatedComponents.length > 1 ? "s" : ""}: ${results.updatedComponents.join(", ")}`);
1003
1042
  if (results.updatedInlineStyles.length > 0) logBuild(`Updated styles: ${results.updatedInlineStyles.join(", ")}`);
1043
+ if (results.updatedGlobalStyles.length > 0) logBuild(`Updated global styles: ${results.updatedGlobalStyles.join(", ")}`);
1004
1044
  if (results.updatedExternalStyles.length > 0) logBuild(`Updated stylesheets: ${results.updatedExternalStyles.join(", ")}`);
1005
1045
  if (results.updatedImages.length > 0) logBuild(`Updated images: ${results.updatedImages.join(", ")}`);
1006
1046
  };
package/dist/index.mjs CHANGED
@@ -514,7 +514,7 @@ function getEditors() {
514
514
  /**
515
515
  * Generate a virtual HTML page for the dev server when no index.html is present.
516
516
  *
517
- * Renders all discovered components. For each component, usage markdown files
517
+ * Renders all discovered components, including CSS-only components. For each component, usage markdown files
518
518
  * (src/components/my-cmp/usage/*.md) are scanned for ```html``` code blocks, which
519
519
  * are used as preview snippets. Falls back to a bare tag if none are found.
520
520
  * @param buildResults The compiler build results containing component metadata and output file information.
@@ -523,11 +523,8 @@ function getEditors() {
523
523
  */
524
524
  const generateDevPreview = (buildResults, filterDirPath) => {
525
525
  const { namespace } = buildResults;
526
- let { components } = buildResults;
527
- if (filterDirPath) {
528
- const normalized = path.normalize(filterDirPath);
529
- components = components.filter((c) => path.normalize(path.dirname(c.sourceFilePath)) === normalized);
530
- }
526
+ let components = [...buildResults.components, ...buildResults.cssOnlyComponents ?? []];
527
+ if (filterDirPath) components = components.filter((c) => isComponentInDir(c, filterDirPath));
531
528
  const title = filterDirPath ? `${namespace} / ${path.basename(filterDirPath)}` : namespace;
532
529
  const loaderUrl = getLoaderUrl(buildResults);
533
530
  const globalCssUrls = getGlobalCssUrls(buildResults);
@@ -558,6 +555,13 @@ ${sections.join("\n")}
558
555
  </body>
559
556
  </html>`;
560
557
  };
558
+ /**
559
+ * Whether a component's source file lives directly in the given directory.
560
+ * @param component The component metadata.
561
+ * @param dirPath The directory path to check against.
562
+ * @returns true if the component's source file is in `dirPath`.
563
+ */
564
+ const isComponentInDir = (component, dirPath) => path.normalize(path.dirname(component.sourceFilePath)) === path.normalize(dirPath);
561
565
  const renderComponentSection = (component) => {
562
566
  const snippets = getUsageSnippets(component);
563
567
  const previews = snippets.length > 0 ? snippets.map((html) => ` <div class="component-preview">\n ${html}\n </div>`).join("\n") : ` <div class="component-preview">
@@ -612,15 +616,13 @@ const getLoaderUrl = ({ outputs, fsNamespace, rootDir }) => {
612
616
  return null;
613
617
  };
614
618
  /**
615
- * Collect server-relative URLs for all global-style CSS outputs.
619
+ * Collect server-relative URLs for all global-style CSS outputs, in the same order their
620
+ * output targets are declared in config - cascade order is meaningful when more than one
621
+ * `global-style` output target is configured.
616
622
  * @param buildResults The compiler build results containing output file information.
617
623
  * @returns An array of server-relative URLs to global-style CSS files.
618
624
  */
619
- const getGlobalCssUrls = ({ outputs, rootDir }) => {
620
- const globalStyle = outputs.find((o) => o.type === "global-style");
621
- if (!globalStyle) return [];
622
- return globalStyle.files.filter((f) => f.endsWith(".css") && !f.endsWith(".css.map")).map((f) => toServePath(f, rootDir));
623
- };
625
+ const getGlobalCssUrls = ({ globalStyleFiles, rootDir }) => globalStyleFiles.map((f) => toServePath(f, rootDir));
624
626
  //#endregion
625
627
  //#region src/server/ssr.ts
626
628
  /**
@@ -1063,7 +1065,7 @@ async function serveDirectoryIndex(devServerConfig, serverCtx, req, res) {
1063
1065
  if (!req.pathname.endsWith("/")) return serverCtx.serve302(req, res, req.pathname + "/");
1064
1066
  try {
1065
1067
  const dirFilePaths = await serverCtx.sys.readDir(req.filePath);
1066
- if (dirFilePaths.some((f) => f.endsWith(".tsx")) && !await hasNestedHtmlFile(serverCtx.sys, dirFilePaths)) return serveDevPreview(devServerConfig, serverCtx, req, res, req.filePath);
1068
+ if ((dirFilePaths.some((f) => f.endsWith(".tsx")) || await hasCssOnlyComponent(serverCtx, dirFilePaths, req.filePath)) && !await hasNestedHtmlFile(serverCtx.sys, dirFilePaths)) return serveDevPreview(devServerConfig, serverCtx, req, res, req.filePath);
1067
1069
  if (req.pathname === "/" || req.pathname === devServerConfig.basePath) {
1068
1070
  const srcPath = path.join(req.filePath, "src");
1069
1071
  try {
@@ -1091,6 +1093,20 @@ async function serveDirectoryIndex(devServerConfig, serverCtx, req, res) {
1091
1093
  return serverCtx.serve404(req, res, "serveDirectoryIndex");
1092
1094
  }
1093
1095
  }
1096
+ const STYLE_FILE_RE = /\.(css|scss|sass|less|styl|stylus|pcss)$/i;
1097
+ /**
1098
+ * Checks whether a directory directly contains a CSS-only component's source file. Only asks the
1099
+ * compiler for build results when the directory has a style file, to keep plain listings cheap.
1100
+ * @param serverCtx The dev server context, used to fetch the latest build results.
1101
+ * @param dirFilePaths The full paths of entries in the directory to check.
1102
+ * @param dirPath The directory being served.
1103
+ * @returns true if a CSS-only component is defined in this directory.
1104
+ */
1105
+ async function hasCssOnlyComponent(serverCtx, dirFilePaths, dirPath) {
1106
+ if (!dirFilePaths.some((f) => STYLE_FILE_RE.test(f))) return false;
1107
+ const { cssOnlyComponents = [] } = await serverCtx.getBuildResults();
1108
+ return cssOnlyComponents.some((c) => isComponentInDir(c, dirPath));
1109
+ }
1094
1110
  /**
1095
1111
  * Recursively checks a directory (and its subdirectories) for any .html/.htm file.
1096
1112
  * Used to decide whether the auto-generated component preview should be shown, or
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stencil/dev-server",
3
- "version": "5.0.0-beta.11",
3
+ "version": "5.0.0-beta.13",
4
4
  "description": "Development server for Stencil with DOM-based HMR",
5
5
  "keywords": [
6
6
  "dev server",
@@ -48,7 +48,7 @@
48
48
  "vitest-environment-stencil": "^1.14.0"
49
49
  },
50
50
  "peerDependencies": {
51
- "@stencil/core": "^5.0.0 || 5.0.0-beta.11"
51
+ "@stencil/core": "^5.0.0 || 5.0.0-beta.13"
52
52
  },
53
53
  "volta": {
54
54
  "extends": "../../package.json"