@linxin666/dsh-client-ui-skin-center 0.4.11 → 0.4.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.
package/lib/index.js CHANGED
@@ -4,7 +4,7 @@ import { basename, dirname, extname, join, resolve, sep } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { homedir } from "node:os";
7
- import { transform } from "lightningcss";
7
+ import { fork } from "node:child_process";
8
8
  //#region src/http.ts
9
9
  /** Default body cap for readJsonBody: 64 KiB. */
10
10
  const DEFAULT_JSON_BODY_MAX_BYTES = 65536;
@@ -914,10 +914,10 @@ function validateSkinManifestV2(input) {
914
914
  }
915
915
  //#endregion
916
916
  //#region src/core/css-safety/token-audit.ts
917
- const PRIMARY_ACTION_FILL$1 = "--dsw-alias-button-primary-fill";
918
- const PRIMARY_ACTION_HOVER$1 = "--dsw-alias-button-primary-hover";
919
- const PRIMARY_ACTION_DIMMED$1 = "--dsw-alias-button-primary-dimmed";
920
- const PRIMARY_ACTION_FOREGROUND$1 = "--dsw-alias-label-primary-foreground";
917
+ const PRIMARY_ACTION_FILL = "--dsw-alias-button-primary-fill";
918
+ const PRIMARY_ACTION_HOVER = "--dsw-alias-button-primary-hover";
919
+ const PRIMARY_ACTION_DIMMED = "--dsw-alias-button-primary-dimmed";
920
+ const PRIMARY_ACTION_FOREGROUND = "--dsw-alias-label-primary-foreground";
921
921
  const BRAND_PRIMARY = "--dsw-alias-brand-primary";
922
922
  const BRAND_PRIMARY_INVERT = "--dsw-alias-brand-primary-invert";
923
923
  /** Shell fill/foreground defaults per theme (both resolve to the official
@@ -1078,10 +1078,10 @@ function anchorDefined(defined) {
1078
1078
  return [...ANCHOR_TOKENS].some((token) => defined.has(token));
1079
1079
  }
1080
1080
  const ANCHOR_TOKENS = [
1081
- PRIMARY_ACTION_FILL$1,
1082
- PRIMARY_ACTION_HOVER$1,
1083
- PRIMARY_ACTION_DIMMED$1,
1084
- PRIMARY_ACTION_FOREGROUND$1,
1081
+ PRIMARY_ACTION_FILL,
1082
+ PRIMARY_ACTION_HOVER,
1083
+ PRIMARY_ACTION_DIMMED,
1084
+ PRIMARY_ACTION_FOREGROUND,
1085
1085
  BRAND_PRIMARY,
1086
1086
  BRAND_PRIMARY_INVERT
1087
1087
  ];
@@ -1717,801 +1717,505 @@ function seedDefaultActiveSkin(path, find) {
1717
1717
  return true;
1718
1718
  }
1719
1719
  //#endregion
1720
- //#region src/core/css-safety/official-tokens.generated.ts
1721
- /**
1722
- * GENERATED by scripts/official-tokens-snapshot.mjs — do not edit.
1723
- * Official shell custom-property surface (--dsw-*, static palette excluded).
1724
- */
1725
- const OFFICIAL_TOKENS = [
1726
- "--dsw-alias-bg-base",
1727
- "--dsw-alias-bg-document-preview",
1728
- "--dsw-alias-bg-document-selection",
1729
- "--dsw-alias-bg-layer-1",
1730
- "--dsw-alias-bg-layer-2",
1731
- "--dsw-alias-bg-layer-3",
1732
- "--dsw-alias-bg-layer-4",
1733
- "--dsw-alias-bg-mask-1",
1734
- "--dsw-alias-bg-mask-2",
1735
- "--dsw-alias-bg-mask-3",
1736
- "--dsw-alias-bg-mask-drop",
1737
- "--dsw-alias-bg-mask-photo",
1738
- "--dsw-alias-bg-module-platform",
1739
- "--dsw-alias-bg-multi-select",
1740
- "--dsw-alias-bg-overlay",
1741
- "--dsw-alias-bg-skeleton",
1742
- "--dsw-alias-border-inverted",
1743
- "--dsw-alias-border-inverted2",
1744
- "--dsw-alias-border-l1",
1745
- "--dsw-alias-border-l2",
1746
- "--dsw-alias-border-l2-darkmode-thin",
1747
- "--dsw-alias-border-l3",
1748
- "--dsw-alias-border-l4",
1749
- "--dsw-alias-brand-primary",
1750
- "--dsw-alias-brand-primary-invert",
1751
- "--dsw-alias-brand-primary-new-colorprimary-new-color",
1752
- "--dsw-alias-brand-text",
1753
- "--dsw-alias-button-contrast-fill",
1754
- "--dsw-alias-button-elevated-fill",
1755
- "--dsw-alias-button-floating-fill",
1756
- "--dsw-alias-button-floating-hover",
1757
- "--dsw-alias-button-ghost-active-border",
1758
- "--dsw-alias-button-ghost-active-fill",
1759
- "--dsw-alias-button-ghost-active-hover",
1760
- "--dsw-alias-button-info-fill",
1761
- "--dsw-alias-button-info-hover",
1762
- "--dsw-alias-button-primary-dimmed",
1763
- "--dsw-alias-button-primary-fill",
1764
- "--dsw-alias-button-primary-hover",
1765
- "--dsw-alias-button-tool-bar-fill",
1766
- "--dsw-alias-button-tool-bar-fill-invisible",
1767
- "--dsw-alias-button-tool-bar-hover",
1768
- "--dsw-alias-code-diff-added",
1769
- "--dsw-alias-code-diff-deleted",
1770
- "--dsw-alias-file-diff-added-bg",
1771
- "--dsw-alias-file-diff-added-gutter",
1772
- "--dsw-alias-file-diff-added-marker",
1773
- "--dsw-alias-file-diff-deleted-bg",
1774
- "--dsw-alias-file-diff-deleted-gutter",
1775
- "--dsw-alias-file-diff-deleted-marker",
1776
- "--dsw-alias-interactive-bg-active",
1777
- "--dsw-alias-interactive-bg-hover",
1778
- "--dsw-alias-interactive-bg-hover-accent",
1779
- "--dsw-alias-interactive-bg-hover-danger",
1780
- "--dsw-alias-interactive-bg-hover-solid",
1781
- "--dsw-alias-label-caption",
1782
- "--dsw-alias-label-deep-diving",
1783
- "--dsw-alias-label-deep-diving-shimmer",
1784
- "--dsw-alias-label-dimmed",
1785
- "--dsw-alias-label-document-preview",
1786
- "--dsw-alias-label-error",
1787
- "--dsw-alias-label-primary",
1788
- "--dsw-alias-label-primary-bluish",
1789
- "--dsw-alias-label-primary-dimmed",
1790
- "--dsw-alias-label-primary-foreground",
1791
- "--dsw-alias-label-primary-inverted",
1792
- "--dsw-alias-label-secondary",
1793
- "--dsw-alias-label-shimmer",
1794
- "--dsw-alias-label-tertiary",
1795
- "--dsw-alias-link",
1796
- "--dsw-alias-markdown-citation",
1797
- "--dsw-alias-markdown-code-block",
1798
- "--dsw-alias-markdown-code-block-banner",
1799
- "--dsw-alias-markdown-code-segment-selected",
1800
- "--dsw-alias-markdown-code-segment-unselected",
1801
- "--dsw-alias-markdown-inline-code",
1802
- "--dsw-alias-markdown-placeholder",
1803
- "--dsw-alias-markdown-tag",
1804
- "--dsw-alias-menu-group-header-fill",
1805
- "--dsw-alias-menu-icon",
1806
- "--dsw-alias-onboarding-accent",
1807
- "--dsw-alias-onboarding-card-fill",
1808
- "--dsw-alias-onboarding-checkbox-border",
1809
- "--dsw-alias-onboarding-secondary-fill",
1810
- "--dsw-alias-scrollbar-bg-l1",
1811
- "--dsw-alias-scrollbar-bg-l2",
1812
- "--dsw-alias-scrollbar-hover-l1",
1813
- "--dsw-alias-scrollbar-hover-l2",
1814
- "--dsw-alias-settings-card-fill",
1815
- "--dsw-alias-settings-card-stroke",
1816
- "--dsw-alias-state-business-primary",
1817
- "--dsw-alias-state-business-tertiary",
1818
- "--dsw-alias-state-error-primary",
1819
- "--dsw-alias-state-error-secondary",
1820
- "--dsw-alias-state-idle-primary",
1821
- "--dsw-alias-state-success-primary",
1822
- "--dsw-alias-state-success-secondary",
1823
- "--dsw-alias-state-success-tertiary",
1824
- "--dsw-alias-state-warn-label",
1825
- "--dsw-alias-state-warn-primary",
1826
- "--dsw-alias-state-warn-secondary",
1827
- "--dsw-alias-state-warn-tertiary",
1828
- "--dsw-alias-switch-thumb",
1829
- "--dsw-alias-toast-bg",
1830
- "--dsw-alias-toast-label",
1831
- "--dsw-alias-tooltip-bg",
1832
- "--dsw-alias-tooltip-key-bg",
1833
- "--dsw-alias-turn-trigger-bg",
1834
- "--dsw-alias-turn-trigger-bg-hover",
1835
- "--dsw-corner-shape",
1836
- "--dsw-elevation-panel",
1837
- "--dsw-elevation-prominent",
1838
- "--dsw-elevation-soft",
1839
- "--dsw-elevation-stroke",
1840
- "--dsw-elevation-stroke-color",
1841
- "--dsw-focus-ring-color",
1842
- "--dsw-focus-ring-width",
1843
- "--dsw-font-base-16",
1844
- "--dsw-font-base-16-font-family",
1845
- "--dsw-font-base-16-font-size",
1846
- "--dsw-font-base-16-font-style",
1847
- "--dsw-font-base-16-font-weight",
1848
- "--dsw-font-base-16-line-height",
1849
- "--dsw-font-base-strong-16",
1850
- "--dsw-font-base-strong-16-font-family",
1851
- "--dsw-font-base-strong-16-font-size",
1852
- "--dsw-font-base-strong-16-font-style",
1853
- "--dsw-font-base-strong-16-font-weight",
1854
- "--dsw-font-base-strong-16-line-height",
1855
- "--dsw-font-family",
1856
- "--dsw-font-family-brand",
1857
- "--dsw-font-l-20",
1858
- "--dsw-font-l-20-font-family",
1859
- "--dsw-font-l-20-font-size",
1860
- "--dsw-font-l-20-font-style",
1861
- "--dsw-font-l-20-font-weight",
1862
- "--dsw-font-l-20-line-height",
1863
- "--dsw-font-m-18",
1864
- "--dsw-font-m-18-font-family",
1865
- "--dsw-font-m-18-font-size",
1866
- "--dsw-font-m-18-font-style",
1867
- "--dsw-font-m-18-font-weight",
1868
- "--dsw-font-m-18-line-height",
1869
- "--dsw-font-markdown-base",
1870
- "--dsw-font-markdown-base-font-family",
1871
- "--dsw-font-markdown-base-font-size",
1872
- "--dsw-font-markdown-base-font-style",
1873
- "--dsw-font-markdown-base-font-weight",
1874
- "--dsw-font-markdown-base-italic",
1875
- "--dsw-font-markdown-base-italic-font-family",
1876
- "--dsw-font-markdown-base-italic-font-size",
1877
- "--dsw-font-markdown-base-italic-font-style",
1878
- "--dsw-font-markdown-base-italic-font-weight",
1879
- "--dsw-font-markdown-base-italic-line-height",
1880
- "--dsw-font-markdown-base-line-height",
1881
- "--dsw-font-markdown-base-strong",
1882
- "--dsw-font-markdown-base-strong-font-family",
1883
- "--dsw-font-markdown-base-strong-font-size",
1884
- "--dsw-font-markdown-base-strong-font-style",
1885
- "--dsw-font-markdown-base-strong-font-weight",
1886
- "--dsw-font-markdown-base-strong-italic",
1887
- "--dsw-font-markdown-base-strong-italic-font-family",
1888
- "--dsw-font-markdown-base-strong-italic-font-size",
1889
- "--dsw-font-markdown-base-strong-italic-font-style",
1890
- "--dsw-font-markdown-base-strong-italic-font-weight",
1891
- "--dsw-font-markdown-base-strong-italic-line-height",
1892
- "--dsw-font-markdown-base-strong-line-height",
1893
- "--dsw-font-markdown-code",
1894
- "--dsw-font-markdown-code-block",
1895
- "--dsw-font-markdown-code-block-font-family",
1896
- "--dsw-font-markdown-code-block-font-size",
1897
- "--dsw-font-markdown-code-block-font-style",
1898
- "--dsw-font-markdown-code-block-font-weight",
1899
- "--dsw-font-markdown-code-block-line-height",
1900
- "--dsw-font-markdown-code-block-small",
1901
- "--dsw-font-markdown-code-block-small-font-family",
1902
- "--dsw-font-markdown-code-block-small-font-size",
1903
- "--dsw-font-markdown-code-block-small-font-style",
1904
- "--dsw-font-markdown-code-block-small-font-weight",
1905
- "--dsw-font-markdown-code-block-small-line-height",
1906
- "--dsw-font-markdown-code-font-family",
1907
- "--dsw-font-markdown-code-font-size",
1908
- "--dsw-font-markdown-code-font-style",
1909
- "--dsw-font-markdown-code-font-weight",
1910
- "--dsw-font-markdown-code-line-height",
1911
- "--dsw-font-markdown-h1",
1912
- "--dsw-font-markdown-h1-font-family",
1913
- "--dsw-font-markdown-h1-font-size",
1914
- "--dsw-font-markdown-h1-font-style",
1915
- "--dsw-font-markdown-h1-font-weight",
1916
- "--dsw-font-markdown-h1-line-height",
1917
- "--dsw-font-markdown-h2",
1918
- "--dsw-font-markdown-h2-font-family",
1919
- "--dsw-font-markdown-h2-font-size",
1920
- "--dsw-font-markdown-h2-font-style",
1921
- "--dsw-font-markdown-h2-font-weight",
1922
- "--dsw-font-markdown-h2-line-height",
1923
- "--dsw-font-markdown-h3",
1924
- "--dsw-font-markdown-h3-font-family",
1925
- "--dsw-font-markdown-h3-font-size",
1926
- "--dsw-font-markdown-h3-font-style",
1927
- "--dsw-font-markdown-h3-font-weight",
1928
- "--dsw-font-markdown-h3-line-height",
1929
- "--dsw-font-markdown-h4",
1930
- "--dsw-font-markdown-h4-font-family",
1931
- "--dsw-font-markdown-h4-font-size",
1932
- "--dsw-font-markdown-h4-font-style",
1933
- "--dsw-font-markdown-h4-font-weight",
1934
- "--dsw-font-markdown-h4-line-height",
1935
- "--dsw-font-markdown-small",
1936
- "--dsw-font-markdown-small-font-family",
1937
- "--dsw-font-markdown-small-font-size",
1938
- "--dsw-font-markdown-small-font-style",
1939
- "--dsw-font-markdown-small-font-weight",
1940
- "--dsw-font-markdown-small-italic",
1941
- "--dsw-font-markdown-small-italic-font-family",
1942
- "--dsw-font-markdown-small-italic-font-size",
1943
- "--dsw-font-markdown-small-italic-font-style",
1944
- "--dsw-font-markdown-small-italic-font-weight",
1945
- "--dsw-font-markdown-small-italic-line-height",
1946
- "--dsw-font-markdown-small-line-height",
1947
- "--dsw-font-markdown-small-strong",
1948
- "--dsw-font-markdown-small-strong-font-family",
1949
- "--dsw-font-markdown-small-strong-font-size",
1950
- "--dsw-font-markdown-small-strong-font-style",
1951
- "--dsw-font-markdown-small-strong-font-weight",
1952
- "--dsw-font-markdown-small-strong-italic",
1953
- "--dsw-font-markdown-small-strong-italic-font-family",
1954
- "--dsw-font-markdown-small-strong-italic-font-size",
1955
- "--dsw-font-markdown-small-strong-italic-font-style",
1956
- "--dsw-font-markdown-small-strong-italic-font-weight",
1957
- "--dsw-font-markdown-small-strong-italic-line-height",
1958
- "--dsw-font-markdown-small-strong-line-height",
1959
- "--dsw-font-markdown-table",
1960
- "--dsw-font-markdown-table-font-family",
1961
- "--dsw-font-markdown-table-font-size",
1962
- "--dsw-font-markdown-table-font-style",
1963
- "--dsw-font-markdown-table-font-weight",
1964
- "--dsw-font-markdown-table-head",
1965
- "--dsw-font-markdown-table-head-font-family",
1966
- "--dsw-font-markdown-table-head-font-size",
1967
- "--dsw-font-markdown-table-head-font-style",
1968
- "--dsw-font-markdown-table-head-font-weight",
1969
- "--dsw-font-markdown-table-head-line-height",
1970
- "--dsw-font-markdown-table-line-height",
1971
- "--dsw-font-s-14",
1972
- "--dsw-font-s-14-font-family",
1973
- "--dsw-font-s-14-font-size",
1974
- "--dsw-font-s-14-font-style",
1975
- "--dsw-font-s-14-font-weight",
1976
- "--dsw-font-s-14-line-height",
1977
- "--dsw-font-s-strong-14",
1978
- "--dsw-font-s-strong-14-font-family",
1979
- "--dsw-font-s-strong-14-font-size",
1980
- "--dsw-font-s-strong-14-font-style",
1981
- "--dsw-font-s-strong-14-font-weight",
1982
- "--dsw-font-s-strong-14-line-height",
1983
- "--dsw-font-xl-24",
1984
- "--dsw-font-xl-24-font-family",
1985
- "--dsw-font-xl-24-font-size",
1986
- "--dsw-font-xl-24-font-style",
1987
- "--dsw-font-xl-24-font-weight",
1988
- "--dsw-font-xl-24-line-height",
1989
- "--dsw-font-xs-13",
1990
- "--dsw-font-xs-13-font-family",
1991
- "--dsw-font-xs-13-font-size",
1992
- "--dsw-font-xs-13-font-style",
1993
- "--dsw-font-xs-13-font-weight",
1994
- "--dsw-font-xs-13-line-height",
1995
- "--dsw-font-xs-strong-13",
1996
- "--dsw-font-xs-strong-13-font-family",
1997
- "--dsw-font-xs-strong-13-font-size",
1998
- "--dsw-font-xs-strong-13-font-style",
1999
- "--dsw-font-xs-strong-13-font-weight",
2000
- "--dsw-font-xs-strong-13-line-height",
2001
- "--dsw-font-xxs-12",
2002
- "--dsw-font-xxs-12-font-family",
2003
- "--dsw-font-xxs-12-font-size",
2004
- "--dsw-font-xxs-12-font-style",
2005
- "--dsw-font-xxs-12-font-weight",
2006
- "--dsw-font-xxs-12-line-height",
2007
- "--dsw-font-xxs-strong-12",
2008
- "--dsw-font-xxs-strong-12-font-family",
2009
- "--dsw-font-xxs-strong-12-font-size",
2010
- "--dsw-font-xxs-strong-12-font-style",
2011
- "--dsw-font-xxs-strong-12-font-weight",
2012
- "--dsw-font-xxs-strong-12-line-height",
2013
- "--dsw-font-xxxs-11",
2014
- "--dsw-font-xxxs-11-font-family",
2015
- "--dsw-font-xxxs-11-font-size",
2016
- "--dsw-font-xxxs-11-font-style",
2017
- "--dsw-font-xxxs-11-font-weight",
2018
- "--dsw-font-xxxs-11-line-height",
2019
- "--dsw-font-xxxs-strong-11",
2020
- "--dsw-font-xxxs-strong-11-font-family",
2021
- "--dsw-font-xxxs-strong-11-font-size",
2022
- "--dsw-font-xxxs-strong-11-font-style",
2023
- "--dsw-font-xxxs-strong-11-font-weight",
2024
- "--dsw-font-xxxs-strong-11-line-height",
2025
- "--dsw-gradient-onboarding-blue-stops",
2026
- "--dsw-gradient-onboarding-cyan-stops",
2027
- "--dsw-gradient-onboarding-violet-stops",
2028
- "--dsw-hovercard-bg",
2029
- "--dsw-linear-gradient-think",
2030
- "--dsw-linear-think-select",
2031
- "--dsw-mask-blur",
2032
- "--dsw-menu-backdrop-filter",
2033
- "--dsw-menu-surface-fill",
2034
- "--dsw-radius-lg",
2035
- "--dsw-radius-md",
2036
- "--dsw-radius-panel",
2037
- "--dsw-radius-sm",
2038
- "--dsw-radius-xl",
2039
- "--dsw-radius-xs",
2040
- "--dsw-shadow-lv1",
2041
- "--dsw-shadow-lv1-blur",
2042
- "--dsw-shadow-lv2",
2043
- "--dsw-shadow-lv3",
2044
- "--dsw-specific-bubble",
2045
- "--dsw-specific-bubble-highlight",
2046
- "--dsw-specific-input-major",
2047
- "--dsw-specific-login-input",
2048
- "--dsw-specific-menu",
2049
- "--dsw-specific-selector",
2050
- "--dsw-specific-sidebar-fill",
2051
- "--dsw-specific-sidebar-nav-item-active",
2052
- "--dsw-specific-sidebar-nav-item-active-accent",
2053
- "--dsw-specific-sidebar-nav-item-hover",
2054
- "--dsw-specific-tip"
2055
- ];
2056
- //#endregion
2057
- //#region src/core/css-safety/fallback.ts
1720
+ //#region src/core/css-safety/errors.ts
2058
1721
  /**
2059
- * Automatic token fallbacks (issue #506 follow-up): for every official
2060
- * --dsw-* token a skin does NOT remap, derive a translucent tint of the
2061
- * skin's own palette — the skin's main color, "blurred" over whatever sits
2062
- * behind the surface. The official shell keeps adding surfaces (e.g. the
2063
- * composer's --dsw-specific-input-major); without this, an uncovered
2064
- * surface snaps back to the official default gray-blue and breaks the
2065
- * skin's palette. The fallback keeps skins future-proof across official
2066
- * upgrades: any new token simply inherits the skin's tint instead of the
2067
- * stock look.
1722
+ * CSS safety error types (lightningcss-free).
2068
1723
  *
2069
- * Rules (fail-closed, conservative):
2070
- * - never touch the static palette (not in the registry at all);
2071
- * - never override a token the skin defines;
2072
- * - never derive when the skin defines no anchor for the group;
2073
- * - semantic / structural groups (buttons, state colors, masks, shadows,
2074
- * inverted/foreground labels, fonts, easing) are skipped: a tint there
2075
- * would break contrast or layout instead of filling a gap. State colors
2076
- * are matched by role word, not by prefix, because the official surface
2077
- * names them inconsistently (--dsw-alias-state-error-primary but also
2078
- * --dsw-alias-label-error and --dsw-alias-interactive-bg-hover-danger).
2079
- *
2080
- * The derivation is textual (color-mix with a var() reference), so it
2081
- * resolves against the skin's own remap — including the dark-theme block —
2082
- * and stays theme-aware with zero runtime logic.
2083
- */
2084
- /**
2085
- * Roles that must never be tinted: a translucent skin tint would break
2086
- * contrast, layout, or the meaning of a state instead of filling a gap.
2087
- * State roles get one word each — the official surface is not uniformly
2088
- * prefixed (state-error-primary, label-error, interactive-bg-hover-danger),
2089
- * so matching the role word is the only reliable rule.
1724
+ * The host half and the worker half must agree on what a failure means, but
1725
+ * the host half may not import anything that reaches lightningcss (issue
1726
+ * #98). These error classes therefore live in their own module: the worker
1727
+ * raises them, the host re-raises them from the IPC answer, and the HTTP
1728
+ * layer maps them (whitelist violation -> 422, overloaded -> 503, everything
1729
+ * else -> 500).
1730
+ * @module @linxin666/dsh-client-ui-skin-center/css-safety/errors
2090
1731
  */
2091
- const EXCLUDED = /(^|-)(mask|shadow|button|state|error|warning|success|danger|info|caution|brand|scrollbar|foreground|inverted|dimmed)(-|$)|-font-|linear-|ease|duration|transition/;
2092
- /** Matched in order; the first group whose pattern hits wins. */
2093
- const GROUPS = [
2094
- {
2095
- skip: /-bg-/,
2096
- anchors: ["--dsw-alias-bg-layer-1", "--dsw-alias-bg-base"],
2097
- alpha: 65
2098
- },
2099
- {
2100
- skip: /-label-/,
2101
- anchors: ["--dsw-alias-label-primary"],
2102
- alpha: 70
2103
- },
2104
- {
2105
- skip: /-border-/,
2106
- anchors: ["--dsw-alias-border-l2", "--dsw-alias-border-l1"],
2107
- alpha: 55
2108
- },
2109
- {
2110
- skip: /-interactive-/,
2111
- anchors: ["--dsw-alias-bg-layer-1"],
2112
- alpha: 50
2113
- },
2114
- {
2115
- skip: /-specific-/,
2116
- anchors: ["--dsw-alias-bg-layer-1", "--dsw-alias-bg-base"],
2117
- alpha: 60
2118
- }
2119
- ];
2120
- function groupFor(token) {
2121
- if (EXCLUDED.test(token)) return null;
2122
- for (const group of GROUPS) if (group.skip.test(token)) return group;
2123
- return null;
2124
- }
2125
1732
  /**
2126
- * Build fallback declarations for the official tokens the skin does not
2127
- * define. Returns declaration strings ("--x: color-mix(...);" per token).
2128
- */
2129
- function deriveFallbackTokens(defined) {
2130
- const out = [];
2131
- for (const token of OFFICIAL_TOKENS) {
2132
- if (defined.has(token)) continue;
2133
- const group = groupFor(token);
2134
- if (group === null) continue;
2135
- const anchor = group.anchors.find((candidate) => defined.has(candidate));
2136
- if (anchor === void 0) continue;
2137
- out.push(`${token}: color-mix(in srgb, var(${anchor}) ${group.alpha}%, transparent);`);
2138
- }
2139
- return out;
2140
- }
2141
- /**
2142
- * Primary-action completion (issue #506 follow-up): filled primary buttons
2143
- * render from one matched set — button-primary-fill, button-primary-hover,
2144
- * label-primary-foreground. The official theme itself wires
2145
- * button-primary-fill to brand-primary, so a skin that remaps the brand
2146
- * already colors the fill; hover and foreground do NOT follow the brand and
2147
- * would snap to the shell's static values. To keep a partially-declared or
2148
- * legacy (brand-primary + brand-primary-invert) skin coherent, the loader
2149
- * completes the set here:
1733
+ * The stable kind marker of a whitelist violation.
2150
1734
  *
2151
- * - fill: derive from brand-primary when the skin declares its brand but
2152
- * no explicit fill (the shell chain does this anyway; the derivation
2153
- * makes the intent explicit and keeps the textual derivation table
2154
- * self-contained);
2155
- * - hover / dimmed: blend the fill toward the surface (color-mix) — a
2156
- * direction-agnostic press/disabled tint that works in both themes;
2157
- * - foreground: inherit the skin's own brand-primary-invert ONLY when the
2158
- * skin declares both brand tokens (the legacy matched convention); the
2159
- * shell foreground stands in otherwise.
2160
- *
2161
- * Never overrides a token the skin defines, and never derives without an
2162
- * anchor: a skin with no brand and no button tokens keeps the official
2163
- * shell's own matched CTA.
2164
- */
2165
- /** The primary-action token family (see ./token-audit.ts for the audit). */
2166
- const PRIMARY_ACTION_FILL = "--dsw-alias-button-primary-fill";
2167
- const PRIMARY_ACTION_HOVER = "--dsw-alias-button-primary-hover";
2168
- const PRIMARY_ACTION_DIMMED = "--dsw-alias-button-primary-dimmed";
2169
- const PRIMARY_ACTION_FOREGROUND = "--dsw-alias-label-primary-foreground";
2170
- const PRIMARY_ACTION_BRAND = "--dsw-alias-brand-primary";
2171
- const PRIMARY_ACTION_BRAND_INVERT = "--dsw-alias-brand-primary-invert";
2172
- /** Derive the primary-action tokens the skin did not define. */
2173
- function derivePrimaryActionFallbacks(defined) {
2174
- const out = [];
2175
- const hasBrand = defined.has(PRIMARY_ACTION_BRAND);
2176
- const branded = hasBrand || defined.has("--dsw-alias-button-primary-fill");
2177
- if (!hasBrand && !defined.has("--dsw-alias-button-primary-fill")) return out;
2178
- if (!defined.has("--dsw-alias-button-primary-fill") && hasBrand) out.push(`${PRIMARY_ACTION_FILL}: var(${PRIMARY_ACTION_BRAND});`);
2179
- if (branded && !defined.has("--dsw-alias-button-primary-hover")) out.push(`${PRIMARY_ACTION_HOVER}: color-mix(in srgb, var(${PRIMARY_ACTION_FILL}) 82%, var(--dsw-alias-bg-layer-1));`);
2180
- if (branded && !defined.has("--dsw-alias-button-primary-dimmed")) out.push(`${PRIMARY_ACTION_DIMMED}: color-mix(in srgb, var(${PRIMARY_ACTION_FILL}) 60%, var(--dsw-alias-bg-layer-1));`);
2181
- if (!defined.has("--dsw-alias-label-primary-foreground") && hasBrand && defined.has("--dsw-alias-brand-primary-invert")) out.push(`${PRIMARY_ACTION_FOREGROUND}: var(${PRIMARY_ACTION_BRAND_INVERT});`);
2182
- return out;
2183
- }
2184
- //#endregion
2185
- //#region src/core/css-safety/transform.ts
2186
- /**
2187
- * Skin CSS safety pipeline (issue #506, contract section "校验纪律").
2188
- *
2189
- * Every skin stylesheet passes through this transform before it is served or
2190
- * injected — built-in or community, skin.css or patches.css. It is the
2191
- * technical enforcement of the coupling boundary:
2192
- *
2193
- * - SCOPING: every selector is force-scoped under
2194
- * `html[data-dsh-skin="<id>"]`. Root-ish heads are rewritten, not nested:
2195
- * `:root` / `html` merge into the scope; `body` and bare official
2196
- * `[data-ds-*]` heads (the official dark-theme attribute lives on BODY)
2197
- * become descendants of the scope; everything else becomes a descendant.
2198
- * - ROOT THEME TOKENS: per-theme `--dsw-alias-*` and
2199
- * `--dsw-specific-*` declarations from bare `:root` / `html` are reset
2200
- * on the scope and cloned to body. Root-level shell variables therefore
2201
- * cannot capture a light token while its dark variant belongs on body (#646).
2202
- * - WHITELIST (fail-closed): no `@import`, no remote or protocol-relative
2203
- * URLs, no absolute paths escaping the skin directory; only relative
2204
- * in-directory assets (and `data:`, which warns — prefer assets/ files).
2205
- * - WARNINGS: reliance on CSS-Modules hash class names (`[class*=...]`)
2206
- * warns; generic @keyframes names warn.
2207
- *
2208
- * Two-pass design (do NOT collapse): selector scoping is a text-level
2209
- * surgery guided by lightningcss rule locations, and lightningcss itself is
2210
- * only used to PARSE/validate (read-only visitors). Returning mutated rules
2211
- * from a lightningcss 1.32/1.33 style visitor crashes declaration
2212
- * deserialization on any var() declaration ("failed to deserialize; expected
2213
- * an object-like struct named Specifier") — an upstream serialization defect
2214
- * the text-level pass sidesteps entirely. A side benefit: the output keeps
2215
- * the author's formatting and values byte-for-byte outside selector heads.
2216
- *
2217
- * NOTE: this module runs host-side (node) in the M2 loader. lightningcss is
2218
- * a native dependency and must stay OUT of the browser bundle (external in
2219
- * tsdown.config.ts).
2220
- * @module @linxin666/dsh-client-ui-skin-center/css-safety
1735
+ * The worker and the transform live in DIFFERENT bundles, so an
1736
+ * `instanceof` check cannot see the same class identity. The kind marker is
1737
+ * a plain string that both bundles agree on, which is what lets the worker
1738
+ * tell a whitelist violation from any other error.
2221
1739
  */
1740
+ const SKIN_CSS_SAFETY_ERROR_KIND = "SkinCssSafetyError";
2222
1741
  /** Violation of the CSS whitelist. Always fatal (fail-closed). */
2223
1742
  var SkinCssSafetyError = class extends Error {
2224
- name = "SkinCssSafetyError";
1743
+ name = SKIN_CSS_SAFETY_ERROR_KIND;
1744
+ /** The stable marker the worker classifies on (bundle-independent). */
1745
+ kind = SKIN_CSS_SAFETY_ERROR_KIND;
2225
1746
  violations;
2226
1747
  constructor(message, violations) {
2227
1748
  super(message);
2228
1749
  this.violations = violations;
2229
1750
  }
2230
1751
  };
2231
- /** Convert a lightningcss Location2 (0-based line, 1-based column) to a char offset. */
2232
- function locToOffset(source, line, column) {
2233
- let offset = 0;
2234
- let currentLine = 0;
2235
- while (currentLine < line) {
2236
- const next = source.indexOf("\n", offset);
2237
- if (next === -1) return source.length;
2238
- offset = next + 1;
2239
- currentLine += 1;
2240
- }
2241
- return offset + column - 1;
2242
- }
2243
1752
  /**
2244
- * Find the opening '{' of a rule whose selector starts at `start`,
2245
- * tracking parens/brackets/strings so :is(...), [title="{"] etc. cannot
2246
- * fake an early brace.
1753
+ * The transform could not be produced at all: the worker crashed, the
1754
+ * request timed out, or the pipeline was disposed. Distinct from a whitelist
1755
+ * violation, which is a rejected stylesheet rather than a broken pipeline.
2247
1756
  */
2248
- function findOpenBrace(source, start) {
2249
- let parens = 0;
2250
- let brackets = 0;
2251
- let quote = null;
2252
- for (let i = start; i < source.length; i += 1) {
2253
- const ch = source[i];
2254
- if (quote !== null) {
2255
- if (ch === "\\") i += 1;
2256
- else if (ch === quote) quote = null;
2257
- continue;
2258
- }
2259
- if (ch === "\"" || ch === "'") {
2260
- quote = ch;
2261
- continue;
2262
- }
2263
- if (ch === "(") parens += 1;
2264
- else if (ch === ")") parens -= 1;
2265
- else if (ch === "[") brackets += 1;
2266
- else if (ch === "]") brackets -= 1;
2267
- else if (ch === "{" && parens === 0 && brackets === 0) return i;
2268
- else if (ch === ";" && parens === 0 && brackets === 0) return -1;
2269
- }
2270
- return -1;
2271
- }
2272
- /** Split a selector list on top-level commas (paren/bracket/string aware). */
2273
- function splitSelectors(selectorText) {
2274
- const parts = [];
2275
- let parens = 0;
2276
- let brackets = 0;
2277
- let quote = null;
2278
- let current = "";
2279
- for (let i = 0; i < selectorText.length; i += 1) {
2280
- const ch = selectorText[i];
2281
- if (quote !== null) {
2282
- current += ch;
2283
- if (ch === "\\") {
2284
- current += selectorText[i + 1] ?? "";
2285
- i += 1;
2286
- } else if (ch === quote) quote = null;
2287
- continue;
2288
- }
2289
- if (ch === "\"" || ch === "'") {
2290
- quote = ch;
2291
- current += ch;
2292
- continue;
2293
- }
2294
- if (ch === "(") parens += 1;
2295
- else if (ch === ")") parens -= 1;
2296
- else if (ch === "[") brackets += 1;
2297
- else if (ch === "]") brackets -= 1;
2298
- if (ch === "," && parens === 0 && brackets === 0) {
2299
- parts.push(current);
2300
- current = "";
2301
- continue;
2302
- }
2303
- current += ch;
2304
- }
2305
- parts.push(current);
2306
- return parts;
2307
- }
2308
- const HEAD_DATA_DS = /^\[data-ds-[a-z0-9-]+/;
1757
+ var SkinCssTransformFailureError = class extends Error {
1758
+ name = "SkinCssTransformFailureError";
1759
+ /** The stable marker of this error family. */
1760
+ kind = "SkinCssTransformFailureError";
1761
+ };
2309
1762
  /**
2310
- * Scope one selector under html[data-dsh-skin="<id>"]. Text-level and
2311
- * conservative: only the well-defined root-ish heads get rewritten; any
2312
- * other selector simply becomes a descendant of the scope.
1763
+ * The pipeline already holds as many requests as it may. The request is
1764
+ * refused immediately instead of waiting for a free slot.
2313
1765
  */
2314
- function scopeSelectorText(selector, skinId) {
2315
- const scope = `html[data-dsh-skin="${skinId}"]`;
2316
- const trimmed = selector.trim();
2317
- const leading = selector.slice(0, selector.length - selector.trimStart().length);
2318
- const trailing = selector.slice(leading.length + trimmed.length);
2319
- if (trimmed === ":root" || trimmed.startsWith(":root ") || trimmed.startsWith(":root,")) return leading + scope + trimmed.slice(5) + trailing;
2320
- if (/^html\[data-ds-/.test(trimmed)) return `${leading}${scope} body${trimmed.slice(4)}${trailing}`;
2321
- if (trimmed === "html" || trimmed.startsWith("html ")) return leading + scope + trimmed.slice(4) + trailing;
2322
- if (trimmed === "body" || trimmed.startsWith("body ") || trimmed.startsWith("body[") || trimmed.startsWith("body:")) return `${leading}${scope} ${trimmed}${trailing}`;
2323
- if (HEAD_DATA_DS.test(trimmed)) return `${leading}${scope} body${trimmed}${trailing}`;
2324
- return `${leading}${scope} ${trimmed}${trailing}`;
2325
- }
2326
- /** Scope every selector in one selector-list text, preserving separators. */
2327
- function scopeSelectorList(selectorText, skinId) {
2328
- return splitSelectors(selectorText).map((sel) => scopeSelectorText(sel, skinId)).join(",");
2329
- }
2330
- const ROOT_BODY_TOKEN = /^(?:--dsw-alias-|--dsw-specific-)/;
2331
- /** A bare root selector owns custom properties evaluated on html itself. */
2332
- function hasBareRootSelector(selectorText) {
2333
- return splitSelectors(selectorText).some((selector) => {
2334
- const trimmed = selector.trim();
2335
- return trimmed === ":root" || trimmed === "html";
2336
- });
2337
- }
2338
- function withoutCssComments(value) {
2339
- return value.replace(/\/\*[\s\S]*?\*\//g, "");
2340
- }
2341
- /** Per-theme root declarations that must instead take effect from body. */
2342
- function rootBodyTokens(block) {
2343
- const tokens = /* @__PURE__ */ new Map();
2344
- const declarations = withoutCssComments(block);
2345
- for (const match of declarations.matchAll(/(?:^|[;{])\s*(--[\w-]+)\s*:\s*([^;}]*)/gm)) {
2346
- const name = match[1];
2347
- if (name !== void 0 && ROOT_BODY_TOKEN.test(name)) tokens.set(name, /!\s*important\s*$/i.test(match[2] ?? ""));
1766
+ var SkinCssOverloadedError = class extends SkinCssTransformFailureError {
1767
+ name = "SkinCssOverloadedError";
1768
+ kind = "SkinCssOverloadedError";
1769
+ };
1770
+ /** The transform did not finish inside the per-request budget. */
1771
+ var SkinCssTransformTimeoutError = class extends SkinCssTransformFailureError {
1772
+ name = "SkinCssTransformTimeoutError";
1773
+ kind = "SkinCssTransformTimeoutError";
1774
+ };
1775
+ /** The pipeline was disposed before the request could run. */
1776
+ var SkinCssWorkerDisposedError = class extends SkinCssTransformFailureError {
1777
+ name = "SkinCssWorkerDisposedError";
1778
+ kind = "SkinCssWorkerDisposedError";
1779
+ };
1780
+ //#endregion
1781
+ //#region src/core/css-safety/host-transform.ts
1782
+ /**
1783
+ * Host-side CSS safety scheduler (issue #98).
1784
+ *
1785
+ * The CSS safety pipeline needs lightningcss, whose Windows build ships a
1786
+ * native addon. A top-level import in the host half maps that addon into the
1787
+ * DSH host process, and Windows refuses to replace a mapped file: while the
1788
+ * host holds the addon, `pnpm add` fails with ERR_PNPM_EPERM when it
1789
+ * renames lightningcss-win32-x64-msvc.
1790
+ *
1791
+ * This module is the host half of the fix and never imports lightningcss.
1792
+ * Every request is served by a short-lived worker process that is forked for
1793
+ * that request alone, answers over IPC, and is terminated and awaited before
1794
+ * the stylesheet response settles. The native addon therefore exists only
1795
+ * inside the worker, and the host process holds no mapping at all.
1796
+ *
1797
+ * Rules:
1798
+ * - one worker at a time: the pipeline serializes requests, so the addon
1799
+ * exists in exactly one process at any moment;
1800
+ * - at most SKIN_CSS_MAX_OUTSTANDING requests are held at once, the active
1801
+ * one and every waiting one included; a request beyond that cap is
1802
+ * refused immediately with a typed overload error;
1803
+ * - every request carries a total budget (queue wait + transform +
1804
+ * settlement) of SKIN_CSS_REQUEST_TIMEOUT_MS, which also covers a worker
1805
+ * that answered but refuses to exit;
1806
+ * - a request settles only after its worker process has exited, and a
1807
+ * worker that cannot be killed still cannot make a request hang.
1808
+ *
1809
+ * Lifecycle: a scheduler belongs to ONE plugin mount. The mount creates it,
1810
+ * injects its transform into the route factory and disposes it with the
1811
+ * mount. A global singleton would be wrong here: the loader may mount a new
1812
+ * instance while the old one is still tearing down, and the old mount's
1813
+ * disposal must not disable the new mount.
1814
+ *
1815
+ * Residual window: while one transform runs, the worker holds the addon, so
1816
+ * a package install in that exact window still sees a mapped addon. The
1817
+ * window is one stylesheet transform long; the host process itself holds
1818
+ * nothing.
1819
+ * @module @linxin666/dsh-client-ui-skin-center/css-safety/host-transform
1820
+ */
1821
+ /** Requests the pipeline holds at once, the active one included. */
1822
+ const SKIN_CSS_MAX_OUTSTANDING = 8;
1823
+ /** Total per-request budget in milliseconds (queue wait + transform + settlement). */
1824
+ const SKIN_CSS_REQUEST_TIMEOUT_MS = 1e4;
1825
+ /** How long a request may wait for a worker that refuses to die. */
1826
+ const SKIN_CSS_FORCE_SETTLE_MS = 1500;
1827
+ /** Worker bundle file name inside the package lib/ directory. */
1828
+ const WORKER_FILE = "css-safety-worker.js";
1829
+ /**
1830
+ * The schedulers that currently hold a worker.
1831
+ *
1832
+ * The process exit hook is shared by all of them and installed only while
1833
+ * at least one scheduler is live, so a remount never accumulates listeners.
1834
+ */
1835
+ const liveSchedulers = /* @__PURE__ */ new Set();
1836
+ let exitHookInstalled = false;
1837
+ /** End every live worker's process when the host exits. */
1838
+ function killLiveSchedulers() {
1839
+ for (const scheduler of liveSchedulers) scheduler.killActiveSync();
1840
+ }
1841
+ /** Register a scheduler and install the shared exit hook when it is the first. */
1842
+ function registerScheduler(scheduler) {
1843
+ liveSchedulers.add(scheduler);
1844
+ if (exitHookInstalled) return;
1845
+ exitHookInstalled = true;
1846
+ process.on("exit", killLiveSchedulers);
1847
+ }
1848
+ /** Unregister a scheduler and drop the shared exit hook when the last one goes. */
1849
+ function unregisterScheduler(scheduler) {
1850
+ liveSchedulers.delete(scheduler);
1851
+ if (liveSchedulers.size > 0 || !exitHookInstalled) return;
1852
+ exitHookInstalled = false;
1853
+ process.removeListener("exit", killLiveSchedulers);
1854
+ }
1855
+ /** Keep a pending timer from holding the host process open. */
1856
+ function unrefTimer(timer) {
1857
+ timer.unref?.();
1858
+ }
1859
+ /**
1860
+ * Locate the worker bundle.
1861
+ *
1862
+ * The worker is resolved from THIS module's URL, never from the process
1863
+ * working directory: the host may run from anywhere (a profile directory, a
1864
+ * service manager's cwd), and the worker must always be the sibling bundle
1865
+ * of the skin-center package that asked for it.
1866
+ * @returns the absolute path of the worker entry script.
1867
+ */
1868
+ function resolveSkinCssWorkerPath() {
1869
+ const here = dirname(fileURLToPath(import.meta.url));
1870
+ const candidates = [join(here, WORKER_FILE), join(here, "..", "..", "..", "lib", WORKER_FILE)];
1871
+ for (const candidate of candidates) if (existsSync(candidate)) return candidate;
1872
+ throw new SkinCssTransformFailureError(`skin CSS safety worker not found (${WORKER_FILE} beside the skin-center module)`);
1873
+ }
1874
+ /**
1875
+ * The request pipeline: fork a worker per request, serialize the work, and
1876
+ * settle only after the worker process has exited.
1877
+ */
1878
+ var SkinCssScheduler = class {
1879
+ workerPath;
1880
+ timeoutMs;
1881
+ maxOutstanding;
1882
+ forkImpl;
1883
+ pending = [];
1884
+ active = null;
1885
+ disposed = false;
1886
+ peakOutstanding = 0;
1887
+ rejected = 0;
1888
+ lastWorkerPid = null;
1889
+ lastWorkerExited = true;
1890
+ constructor(options = {}) {
1891
+ this.workerPath = options.workerPath ?? null;
1892
+ this.timeoutMs = options.timeoutMs ?? 1e4;
1893
+ this.maxOutstanding = options.maxOutstanding ?? 8;
1894
+ this.forkImpl = options.forkImpl ?? ((modulePath, forkOptions) => fork(modulePath, forkOptions));
1895
+ }
1896
+ /**
1897
+ * Transform one stylesheet through a short-lived worker process.
1898
+ * @param css - the raw stylesheet bytes.
1899
+ * @param options - the skin id, logical filename and fallback flag.
1900
+ * @returns the transformed stylesheet and the pipeline warnings.
1901
+ */
1902
+ transform(css, options) {
1903
+ if (this.disposed) return Promise.reject(new SkinCssWorkerDisposedError("skin CSS safety worker was disposed"));
1904
+ if (this.heldCount() >= this.maxOutstanding) {
1905
+ this.rejected += 1;
1906
+ return Promise.reject(new SkinCssOverloadedError(`skin CSS safety pipeline is full (${this.maxOutstanding} requests held)`));
1907
+ }
1908
+ return new Promise((resolve, reject) => {
1909
+ const request = {
1910
+ css,
1911
+ options,
1912
+ resolve,
1913
+ reject,
1914
+ timer: null,
1915
+ settled: false
1916
+ };
1917
+ request.timer = setTimeout(() => {
1918
+ this.onTimeout(request);
1919
+ }, this.timeoutMs);
1920
+ unrefTimer(request.timer);
1921
+ this.pending.push(request);
1922
+ this.peakOutstanding = Math.max(this.peakOutstanding, this.heldCount());
1923
+ this.pump();
1924
+ });
2348
1925
  }
2349
- return [...tokens].map(([name, important]) => ({
2350
- name,
2351
- important
2352
- }));
2353
- }
2354
- /** Normalize cloned root tokens so dark body declarations can override them. */
2355
- function bodyCloneProperty(line) {
2356
- const custom = line.match(/^(--[\w-]+)\s*:/);
2357
- if (custom !== null) {
2358
- const name = custom[1] ?? "";
2359
- return ROOT_BODY_TOKEN.test(name) ? line.replace(/\s*!important(?=\s*;?\s*$)/i, "") : line;
1926
+ /** Current pipeline counters. */
1927
+ stats() {
1928
+ return {
1929
+ active: this.active ? 1 : 0,
1930
+ pending: this.pending.length,
1931
+ held: this.heldCount(),
1932
+ maxOutstanding: this.maxOutstanding,
1933
+ rejected: this.rejected,
1934
+ peakOutstanding: this.peakOutstanding,
1935
+ lastWorkerPid: this.lastWorkerPid,
1936
+ lastWorkerExited: this.lastWorkerExited
1937
+ };
2360
1938
  }
2361
- return /^background-(color|image)\s*:/.test(line) ? line : null;
2362
- }
2363
- /** Check one url() target against the whitelist. */
2364
- function checkUrl(raw, context, violations, warnings) {
2365
- const url = raw.trim().replace(/^["']|["']$/g, "");
2366
- if (/^https?:\/\//i.test(url)) violations.push(`${context}: remote URL "${url}" is not allowed; ship the asset in the skin directory`);
2367
- else if (url.startsWith("//")) violations.push(`${context}: protocol-relative URL "${url}" is not allowed`);
2368
- else if (url.startsWith("/")) violations.push(`${context}: absolute path "${url}" escapes the skin directory`);
2369
- else if (/^(?:\.\.\/)/.test(url)) violations.push(`${context}: path "${url}" escapes the skin directory`);
2370
- else if (/^data:/i.test(url)) warnings.push(`${context}: inline data: URL — prefer a file under assets/`);
2371
- }
2372
- const GENERIC_KEYFRAMES = /* @__PURE__ */ new Set([
2373
- "spin",
2374
- "pulse",
2375
- "fade",
2376
- "fadein",
2377
- "fade-in",
2378
- "fadeout",
2379
- "fade-out",
2380
- "slide",
2381
- "slidein",
2382
- "slide-in",
2383
- "bounce",
2384
- "glow",
2385
- "blink",
2386
- "shake",
2387
- "float"
2388
- ]);
2389
- /**
2390
- * Transform a skin stylesheet: force-scope every selector under
2391
- * html[data-dsh-skin="<id>"] and enforce the whitelist. Throws
2392
- * SkinCssSafetyError on any violation (fail-closed); lightningcss parse
2393
- * errors propagate as-is (malformed CSS is also a hard failure).
2394
- */
2395
- function transformSkinCss(css, options) {
2396
- const { skinId } = options;
2397
- const filename = options.filename ?? "skin.css";
2398
- const violations = [];
2399
- const warnings = [];
2400
- const spans = [];
2401
- const defined = /* @__PURE__ */ new Set();
2402
- transform({
2403
- filename,
2404
- code: Buffer.from(css),
2405
- visitor: {
2406
- Rule: {
2407
- import(rule) {
2408
- violations.push(`${filename}: @import "${rule.value.url}" is not allowed; skins are single-file stylesheets`);
2409
- },
2410
- keyframes(rule) {
2411
- const name = rule.value.name;
2412
- const value = typeof name === "string" ? name : name?.value;
2413
- if (typeof value === "string" && GENERIC_KEYFRAMES.has(value.toLowerCase())) warnings.push(`${filename}: generic @keyframes name "${value}" may collide across skins; prefix it (e.g. ${skinId}-${value})`);
1939
+ /**
1940
+ * Stop the pipeline: queued work is rejected, the running worker is
1941
+ * terminated and awaited, and no worker is left behind.
1942
+ * @returns a promise that resolves once the active worker has exited.
1943
+ */
1944
+ async dispose() {
1945
+ if (this.disposed) return;
1946
+ this.disposed = true;
1947
+ const error = new SkinCssWorkerDisposedError("skin CSS safety worker was disposed");
1948
+ for (const request of this.pending.splice(0)) this.settle(request, error);
1949
+ const run = this.active;
1950
+ if (run) {
1951
+ run.disposed = true;
1952
+ this.terminate(run);
1953
+ await this.waitForExit(run);
1954
+ this.finish(run, error);
1955
+ }
1956
+ unregisterScheduler(this);
1957
+ }
1958
+ /** Terminate the running worker without waiting (process exit path). */
1959
+ killActiveSync() {
1960
+ if (this.active) this.terminate(this.active);
1961
+ }
1962
+ /** Requests the pipeline holds, the active one included. */
1963
+ heldCount() {
1964
+ return this.pending.length + (this.active ? 1 : 0);
1965
+ }
1966
+ /** Admit waiting requests and start the next worker when the pipeline is free. */
1967
+ pump() {
1968
+ if (this.disposed) return;
1969
+ while (this.active === null && this.pending.length > 0) {
1970
+ const request = this.pending.shift();
1971
+ this.start(request);
1972
+ }
1973
+ }
1974
+ /** Fork one worker for one request. */
1975
+ start(request) {
1976
+ let workerPath;
1977
+ try {
1978
+ workerPath = this.workerPath ?? resolveSkinCssWorkerPath();
1979
+ } catch (error) {
1980
+ this.settle(request, error);
1981
+ return;
1982
+ }
1983
+ let child;
1984
+ try {
1985
+ child = this.forkImpl(workerPath, {
1986
+ env: {
1987
+ ...process.env,
1988
+ ELECTRON_RUN_AS_NODE: "1"
2414
1989
  },
2415
- style(rule) {
2416
- const loc = rule.value.loc;
2417
- if (loc) {
2418
- const start = locToOffset(css, loc.line, loc.column);
2419
- const openBrace = findOpenBrace(css, start);
2420
- if (openBrace !== -1) spans.push({
2421
- start,
2422
- openBrace
2423
- });
2424
- }
2425
- for (const sel of rule.value.selectors) for (const c of sel) if (c.type === "attribute" && c.name === "class" && [
2426
- "substring",
2427
- "prefix",
2428
- "suffix"
2429
- ].includes(c.operation?.operator)) warnings.push(`${filename}: [class*=...]-style attribute matching relies on CSS-Modules hash class names and may break on any official rebuild`);
2430
- }
2431
- },
2432
- Declaration: { custom(property) {
2433
- defined.add(property.name);
2434
- } },
2435
- Url(url) {
2436
- checkUrl(url.url, filename, violations, warnings);
2437
- }
1990
+ execArgv: [],
1991
+ stdio: [
1992
+ "ignore",
1993
+ "ignore",
1994
+ "inherit",
1995
+ "ipc"
1996
+ ]
1997
+ });
1998
+ } catch (error) {
1999
+ const detail = error instanceof Error ? error.message : String(error);
2000
+ this.settle(request, new SkinCssTransformFailureError(`skin CSS safety worker could not start: ${detail}`));
2001
+ return;
2438
2002
  }
2439
- });
2440
- if (violations.length > 0) throw new SkinCssSafetyError(`skin CSS violates the whitelist:\n - ${violations.join("\n - ")}`, violations);
2441
- const sorted = [...spans].sort((a, b) => a.start - b.start);
2442
- const scope = `html[data-dsh-skin="${skinId}"]`;
2443
- let out = "";
2444
- let cursor = 0;
2445
- for (const span of sorted) {
2446
- const selectorText = css.slice(span.start, span.openBrace);
2447
- const close = findCloseBrace(css, span.openBrace);
2448
- out += css.slice(cursor, span.start);
2449
- const scoped = scopeSelectorList(selectorText, skinId);
2450
- const block = close === -1 ? css.slice(span.openBrace) : css.slice(span.openBrace, close + 1);
2451
- out += scoped + block;
2452
- if (close !== -1 && hasBareRootSelector(selectorText)) {
2453
- const tokens = rootBodyTokens(block);
2454
- if (tokens.length > 0) out += `\n${scope} {\n ${tokens.map(({ name, important }) => `${name}: initial${important ? " !important" : ""};`).join("\n ")}\n}\n`;
2003
+ const run = {
2004
+ child,
2005
+ request,
2006
+ response: null,
2007
+ spawnError: null,
2008
+ timedOut: false,
2009
+ disposed: false,
2010
+ exited: false,
2011
+ finished: false,
2012
+ killTimer: null,
2013
+ forceTimer: null,
2014
+ exitWaiters: []
2015
+ };
2016
+ this.active = run;
2017
+ this.lastWorkerPid = child.pid ?? null;
2018
+ this.lastWorkerExited = false;
2019
+ registerScheduler(this);
2020
+ child.on("message", (message) => {
2021
+ this.onMessage(run, message);
2022
+ });
2023
+ child.on("error", (error) => {
2024
+ this.onError(run, error);
2025
+ });
2026
+ child.on("disconnect", () => {
2027
+ this.onDisconnect(run);
2028
+ });
2029
+ child.on("exit", () => {
2030
+ this.onExit(run);
2031
+ });
2032
+ }
2033
+ /** Handle one message from the worker. */
2034
+ onMessage(run, message) {
2035
+ if (message && message.type === "ready") {
2036
+ try {
2037
+ run.child.send({
2038
+ type: "transform",
2039
+ css: run.request.css,
2040
+ options: run.request.options
2041
+ });
2042
+ } catch (error) {
2043
+ run.spawnError = error instanceof Error ? error : new Error(String(error));
2044
+ this.terminate(run);
2045
+ }
2046
+ return;
2455
2047
  }
2456
- if (hasBareRootSelector(selectorText) && close !== -1) {
2457
- const props = withoutCssComments(css.slice(span.openBrace + 1, close)).split("\n").map((line) => bodyCloneProperty(line.trim())).filter((line) => line !== null);
2458
- if (props.length > 0) out += `\n${scope} body {\n ${props.join("\n ")}\n}\n`;
2048
+ run.response = message;
2049
+ this.terminate(run);
2050
+ }
2051
+ /**
2052
+ * The worker process failed.
2053
+ *
2054
+ * A spawn failure never produces an exit event, so the request must be
2055
+ * settled here; the pipeline advances at once.
2056
+ */
2057
+ onError(run, error) {
2058
+ run.spawnError = error;
2059
+ if (run.child.pid === void 0) {
2060
+ this.finish(run, new SkinCssTransformFailureError(`skin CSS safety worker could not start: ${error.message}`));
2061
+ return;
2459
2062
  }
2460
- cursor = close === -1 ? span.openBrace : close + 1;
2063
+ this.terminate(run);
2461
2064
  }
2462
- out += css.slice(cursor);
2463
- out += `\n${scope} [id="root"] { background: transparent; }\n`;
2464
- out += `\n${scope} body { --shiki-background: var(--dsw-alias-markdown-code-block); }\n`;
2465
- if (options.deriveFallbacks === true) {
2466
- const fallbacks = [...deriveFallbackTokens(defined), ...derivePrimaryActionFallbacks(defined)];
2467
- if (fallbacks.length > 0) out += `\n${scope} body {\n ${fallbacks.join("\n ")}\n}\n`;
2065
+ /** The worker lost its IPC channel; it cannot answer any more. */
2066
+ onDisconnect(run) {
2067
+ if (run.exited) return;
2068
+ this.terminate(run);
2468
2069
  }
2469
- return {
2470
- code: out,
2471
- warnings
2472
- };
2473
- }
2474
- /**
2475
- * Find the matching closing brace for the block opening at openBrace.
2476
- * Conservative: counts braces, skips strings and comments; returns -1 when
2477
- * the block never closes (callers then keep the remainder as-is).
2478
- */
2479
- function findCloseBrace(css, openBrace) {
2480
- let depth = 0;
2481
- let i = openBrace;
2482
- let inString = null;
2483
- let inComment = false;
2484
- for (; i < css.length; i++) {
2485
- const ch = css[i];
2486
- const next = css[i + 1];
2487
- if (inComment) {
2488
- if (ch === "*" && next === "/") {
2489
- inComment = false;
2490
- i++;
2491
- }
2492
- continue;
2493
- }
2494
- if (inString !== null) {
2495
- if (ch === "\\") i++;
2496
- else if (ch === inString) inString = null;
2497
- continue;
2070
+ /** End the worker process if it is still running. */
2071
+ terminate(run) {
2072
+ if (run.exited) return;
2073
+ if (run.child.exitCode !== null || run.child.signalCode !== null) return;
2074
+ try {
2075
+ run.child.kill();
2076
+ } catch {}
2077
+ if (run.killTimer !== null) return;
2078
+ run.killTimer = setTimeout(() => {
2079
+ run.killTimer = null;
2080
+ if (run.exited) return;
2081
+ try {
2082
+ run.child.kill("SIGKILL");
2083
+ } catch {}
2084
+ }, 500);
2085
+ unrefTimer(run.killTimer);
2086
+ }
2087
+ /** The worker process exited: settle the request it served. */
2088
+ onExit(run) {
2089
+ run.exited = true;
2090
+ this.lastWorkerExited = true;
2091
+ for (const waiter of run.exitWaiters.splice(0)) waiter();
2092
+ if (run.disposed) {
2093
+ this.finish(run, new SkinCssWorkerDisposedError("skin CSS safety worker was disposed"));
2094
+ return;
2498
2095
  }
2499
- if (ch === "/" && next === "*") {
2500
- inComment = true;
2501
- i++;
2502
- continue;
2096
+ if (run.timedOut) {
2097
+ this.finish(run, new SkinCssTransformTimeoutError(`skin CSS safety transform timed out after ${this.timeoutMs}ms`));
2098
+ return;
2503
2099
  }
2504
- if (ch === "\"" || ch === "'") {
2505
- inString = ch;
2506
- continue;
2100
+ if (run.response === null) {
2101
+ const detail = run.spawnError?.message ?? "worker exited without a result";
2102
+ this.finish(run, new SkinCssTransformFailureError(`skin CSS safety worker failed: ${detail}`));
2103
+ return;
2507
2104
  }
2508
- if (ch === "{") depth++;
2509
- else if (ch === "}") {
2510
- depth--;
2511
- if (depth === 0) return i;
2105
+ try {
2106
+ this.finish(run, void 0, this.toResult(run.response));
2107
+ } catch (error) {
2108
+ this.finish(run, error);
2109
+ }
2110
+ }
2111
+ /**
2112
+ * Close one run: clear its timers, settle its request and free the slot.
2113
+ * @param run - the finished run.
2114
+ * @param error - the failure to report, if any.
2115
+ * @param result - the transform result, if the run succeeded.
2116
+ */
2117
+ finish(run, error, result) {
2118
+ if (run.finished) return;
2119
+ run.finished = true;
2120
+ if (run.killTimer !== null) {
2121
+ clearTimeout(run.killTimer);
2122
+ run.killTimer = null;
2123
+ }
2124
+ if (run.forceTimer !== null) {
2125
+ clearTimeout(run.forceTimer);
2126
+ run.forceTimer = null;
2127
+ }
2128
+ if (this.active === run) this.active = null;
2129
+ if (!run.request.settled) {
2130
+ if (error !== void 0) this.settle(run.request, error);
2131
+ else this.settle(run.request, void 0, result);
2132
+ }
2133
+ this.pump();
2134
+ }
2135
+ /** Map one worker answer onto the host contract. */
2136
+ toResult(response) {
2137
+ if (!response || typeof response !== "object") throw new SkinCssTransformFailureError("skin CSS safety worker sent a malformed answer");
2138
+ if (response.type === "result") return {
2139
+ code: response.code,
2140
+ warnings: response.warnings ?? []
2141
+ };
2142
+ if (response.type === "violation") throw new SkinCssSafetyError(response.message, response.violations ?? []);
2143
+ throw new SkinCssTransformFailureError(response.message);
2144
+ }
2145
+ /**
2146
+ * The request ran out of budget.
2147
+ *
2148
+ * The budget covers the whole request, including a worker that answered
2149
+ * but refuses to exit: the late answer is never turned into a result.
2150
+ */
2151
+ onTimeout(request) {
2152
+ if (request.settled) return;
2153
+ const run = this.active;
2154
+ if (run && run.request === request) {
2155
+ if (run.timedOut) return;
2156
+ run.timedOut = true;
2157
+ this.terminate(run);
2158
+ run.forceTimer = setTimeout(() => {
2159
+ run.forceTimer = null;
2160
+ if (request.settled) return;
2161
+ this.settle(request, new SkinCssTransformTimeoutError(`skin CSS safety transform timed out after ${this.timeoutMs}ms`));
2162
+ }, SKIN_CSS_FORCE_SETTLE_MS);
2163
+ unrefTimer(run.forceTimer);
2164
+ return;
2512
2165
  }
2166
+ this.removeQueued(request);
2167
+ this.settle(request, new SkinCssTransformTimeoutError(`skin CSS safety transform timed out after ${this.timeoutMs}ms`));
2168
+ this.pump();
2169
+ }
2170
+ /** Remove a queued request from the pipeline. */
2171
+ removeQueued(request) {
2172
+ const index = this.pending.indexOf(request);
2173
+ if (index !== -1) this.pending.splice(index, 1);
2174
+ }
2175
+ /** Resolve or reject one request exactly once. */
2176
+ settle(request, error, result) {
2177
+ if (request.settled) return;
2178
+ request.settled = true;
2179
+ if (request.timer) {
2180
+ clearTimeout(request.timer);
2181
+ request.timer = null;
2182
+ }
2183
+ if (error !== void 0) request.reject(error);
2184
+ else request.resolve(result);
2185
+ }
2186
+ /**
2187
+ * Resolve once the worker process has exited, or after a bounded grace.
2188
+ * @param run - the run to wait for.
2189
+ * @returns a promise that resolves on the exit or after the grace.
2190
+ */
2191
+ waitForExit(run) {
2192
+ if (run.exited) return Promise.resolve();
2193
+ return new Promise((resolve) => {
2194
+ let done = false;
2195
+ const settle = () => {
2196
+ if (done) return;
2197
+ done = true;
2198
+ clearTimeout(timer);
2199
+ resolve();
2200
+ };
2201
+ const timer = setTimeout(settle, SKIN_CSS_FORCE_SETTLE_MS);
2202
+ unrefTimer(timer);
2203
+ run.exitWaiters.push(settle);
2204
+ });
2513
2205
  }
2514
- return -1;
2206
+ };
2207
+ /**
2208
+ * The pipeline used when no scheduler was injected.
2209
+ *
2210
+ * It exists for direct callers of the route factory (tests, tools). A plugin
2211
+ * mount creates its own scheduler instead, so a mount disposal can never
2212
+ * disable another mount.
2213
+ */
2214
+ let defaultScheduler = null;
2215
+ /** The fallback transform used when the route factory gets no scheduler. */
2216
+ function defaultSkinCssTransform(css, options) {
2217
+ defaultScheduler ??= new SkinCssScheduler();
2218
+ return defaultScheduler.transform(css, options);
2515
2219
  }
2516
2220
  //#endregion
2517
2221
  //#region src/core/profile-plugin-probe.ts
@@ -2953,8 +2657,18 @@ function sendCss(res, status, code) {
2953
2657
  });
2954
2658
  res.end(code);
2955
2659
  }
2956
- /** Serve one manifest-referenced stylesheet through the safety pipeline. */
2957
- function serveStylesheet(res, entry, relPath, filename) {
2660
+ /**
2661
+ * Serve one manifest-referenced stylesheet through the safety pipeline.
2662
+ *
2663
+ * The transform runs in a short-lived worker process (issue #98), so this
2664
+ * handler awaits it: the response is written only after the worker has
2665
+ * answered and exited.
2666
+ * @param res - the HTTP response.
2667
+ * @param entry - the catalog row of the skin being served.
2668
+ * @param relPath - the manifest-relative stylesheet path.
2669
+ * @param filename - the logical filename used in pipeline diagnostics.
2670
+ */
2671
+ async function serveStylesheet(res, entry, relPath, filename, transformCss) {
2958
2672
  const abs = resolveInsideSkin(entry, relPath);
2959
2673
  if (!abs || !existsSync(abs)) {
2960
2674
  writeJson(res, 404, {
@@ -2964,7 +2678,7 @@ function serveStylesheet(res, entry, relPath, filename) {
2964
2678
  return;
2965
2679
  }
2966
2680
  try {
2967
- const { code } = transformSkinCss(readFileSync(abs, "utf8"), {
2681
+ const { code } = await transformCss(readFileSync(abs, "utf8"), {
2968
2682
  skinId: entry.manifest.id,
2969
2683
  filename,
2970
2684
  deriveFallbacks: filename === "skin.css"
@@ -2979,6 +2693,14 @@ function serveStylesheet(res, entry, relPath, filename) {
2979
2693
  });
2980
2694
  return;
2981
2695
  }
2696
+ if (error instanceof SkinCssOverloadedError) {
2697
+ writeJson(res, 503, {
2698
+ ok: false,
2699
+ error: "css-transform-overloaded",
2700
+ detail: error?.message ?? String(error)
2701
+ });
2702
+ return;
2703
+ }
2982
2704
  writeJson(res, 500, {
2983
2705
  ok: false,
2984
2706
  error: "css-transform-failed",
@@ -3042,6 +2764,7 @@ function serveAsset(req, res, entry, relPath) {
3042
2764
  */
3043
2765
  function makeSkinCenterV2Routes(deps = {}) {
3044
2766
  const loadCatalog = deps.loadCatalog ?? (() => loadSkinCatalog());
2767
+ const transformCss = deps.transformCss ?? defaultSkinCssTransform;
3045
2768
  const activeStatePath = deps.activeStatePath ?? defaultActiveStatePath();
3046
2769
  const shippedSet = (deps.shippedSkinIds ?? shippedSkinIds)();
3047
2770
  const listDelegatedSkins = deps.listDelegatedSkins ?? (() => delegatedSkinRows());
@@ -3219,7 +2942,7 @@ function makeSkinCenterV2Routes(deps = {}) {
3219
2942
  return;
3220
2943
  }
3221
2944
  if (sub === "stylesheet") {
3222
- serveStylesheet(res, entry, entry.manifest.contributes.stylesheet, "skin.css");
2945
+ await serveStylesheet(res, entry, entry.manifest.contributes.stylesheet, "skin.css", transformCss);
3223
2946
  return;
3224
2947
  }
3225
2948
  if (sub === "patches") {
@@ -3231,7 +2954,7 @@ function makeSkinCenterV2Routes(deps = {}) {
3231
2954
  });
3232
2955
  return;
3233
2956
  }
3234
- serveStylesheet(res, entry, patches, "patches.css");
2957
+ await serveStylesheet(res, entry, patches, "patches.css", transformCss);
3235
2958
  return;
3236
2959
  }
3237
2960
  if (sub === "hooks.mjs") {
@@ -4069,7 +3792,8 @@ function applyImpl(ctx, config) {
4069
3792
  } catch (error) {
4070
3793
  console.error("[ui-skin-center] background migration failed:", error);
4071
3794
  }
4072
- const routes = [...makeSkinCenterV2Routes()];
3795
+ const cssScheduler = new SkinCssScheduler();
3796
+ const routes = [...makeSkinCenterV2Routes({ transformCss: (css, options) => cssScheduler.transform(css, options) })];
4073
3797
  try {
4074
3798
  ctx.effect(() => {
4075
3799
  const disposers = [];
@@ -4089,12 +3813,14 @@ function applyImpl(ctx, config) {
4089
3813
  for (const dispose of disposers) dispose();
4090
3814
  throw error;
4091
3815
  }
4092
- return () => {
3816
+ return async () => {
4093
3817
  for (const dispose of disposers) dispose();
3818
+ await cssScheduler.dispose();
4094
3819
  };
4095
3820
  }, "ui-skin-center: routes");
4096
3821
  } catch (error) {
4097
3822
  console.error("[ui-skin-center] route registration failed:", error);
3823
+ cssScheduler.dispose();
4098
3824
  }
4099
3825
  try {
4100
3826
  seedDefaultActiveSkin(defaultActiveStatePath(), (id) => findSkin(loadSkinCatalog(), id) !== null);
@@ -4114,4 +3840,4 @@ function applyImpl(ctx, config) {
4114
3840
  }
4115
3841
  }
4116
3842
  //#endregion
4117
- export { Config, SKIN_BACKGROUND_NAMESPACE, SKIN_CENTER_V2_PREFIX, SKIN_CUSTOM_THEME_NAMESPACE, SkinBackgroundConfigSchema, SkinCssSafetyError, SkinCustomThemeConfigSchema, apply, auditTokenContract, builtinSkinsDir, canServeSkinHooks, defaultActiveStatePath, findSkin, inject, loadSkinCatalog, makeSkinCenterV2Routes, name, readActiveSelection, resolveInsideSkin, transformSkinCss, userSkinsDir, validateSkinManifestV2, writeActiveSelection };
3843
+ export { Config, SKIN_BACKGROUND_NAMESPACE, SKIN_CENTER_V2_PREFIX, SKIN_CSS_MAX_OUTSTANDING, SKIN_CSS_REQUEST_TIMEOUT_MS, SKIN_CUSTOM_THEME_NAMESPACE, SkinBackgroundConfigSchema, SkinCssOverloadedError, SkinCssSafetyError, SkinCssScheduler, SkinCssTransformFailureError, SkinCssTransformTimeoutError, SkinCssWorkerDisposedError, SkinCustomThemeConfigSchema, apply, auditTokenContract, builtinSkinsDir, canServeSkinHooks, defaultActiveStatePath, findSkin, inject, loadSkinCatalog, makeSkinCenterV2Routes, name, readActiveSelection, resolveInsideSkin, userSkinsDir, validateSkinManifestV2, writeActiveSelection };