@moonwitness/ui 7.1.1 → 7.1.4
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/README.md +3 -3
- package/dist/components/riot-sticker.d.ts +1 -1
- package/dist/css-exports.d.ts +77 -0
- package/dist/css-exports.js +116 -0
- package/dist/pixelfx-boundary.d.ts +79 -0
- package/dist/pixelfx-boundary.js +114 -0
- package/dist/pixelfx.d.ts +2 -2
- package/dist/pixelfx.js +59 -35
- package/dist/provider.d.ts +1 -1
- package/dist/provider.js +1 -1
- package/dist/skin-catalog.d.ts +11 -0
- package/dist/skin-catalog.js +27 -0
- package/dist/ssr/init-script.d.ts +36 -0
- package/dist/ssr/init-script.js +135 -0
- package/dist/ssr/resolve-skin.d.ts +34 -0
- package/dist/ssr/resolve-skin.js +168 -0
- package/dist/ssr/theme-mismatch-dev.d.ts +58 -0
- package/dist/ssr/theme-mismatch-dev.js +133 -0
- package/dist/themes/index.d.ts +3 -1
- package/dist/themes/index.js +3 -1
- package/dist/themes/provider.js +16 -1
- package/package.json +16 -7
- package/scripts/consumer-smoke.mjs +45 -0
- package/src/css-exports.ts +142 -0
- package/src/pixelfx-boundary.ts +188 -0
- package/src/pixelfx.tsx +66 -38
- package/src/provider.tsx +2 -2
- package/src/skin-catalog.ts +36 -0
- package/src/ssr/init-script.ts +281 -0
- package/src/ssr/resolve-skin.ts +217 -0
- package/src/ssr/theme-mismatch-dev.ts +181 -0
- package/src/themes/index.ts +13 -0
- package/src/themes/provider.tsx +22 -1
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* T13 — Client pre-hydration init script for SSR skin parity.
|
|
3
|
+
*
|
|
4
|
+
* INV-013: Theme state is carried by request data.
|
|
5
|
+
* Generates a dependency-free IIFE that runs before React hydration.
|
|
6
|
+
* Precedence: explicit inline state > server data-* attrs > mw-theme cookie > legacy localStorage > defaults.
|
|
7
|
+
* Dev mismatch warning integrates T09 theme-mismatch-dev.ts when `dev: true`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
DEFAULT_SKIN_ID,
|
|
12
|
+
themeRegistry,
|
|
13
|
+
} from "../skin-catalog.js";
|
|
14
|
+
import type {
|
|
15
|
+
ColorMode,
|
|
16
|
+
SkinDensity,
|
|
17
|
+
SkinId,
|
|
18
|
+
SkinMetadata,
|
|
19
|
+
ThemeRegistry,
|
|
20
|
+
UserThemePreferences,
|
|
21
|
+
} from "../themes/types.js";
|
|
22
|
+
|
|
23
|
+
export interface SkinInitScriptOptionsSsr {
|
|
24
|
+
/** Explicit server-rendered state (inline data-* attributes win) */
|
|
25
|
+
serverState?: Partial<UserThemePreferences>;
|
|
26
|
+
/** Raw cookie value from the client (cookie wins over defaults) */
|
|
27
|
+
cookieValue?: string | null;
|
|
28
|
+
/** Development mode: emit console warning when server/client disagree */
|
|
29
|
+
dev?: boolean;
|
|
30
|
+
/** Theme registry to validate against */
|
|
31
|
+
registry?: ThemeRegistry;
|
|
32
|
+
/** Storage key for legacy localStorage fallback */
|
|
33
|
+
storageKey?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const VALID_MODES = new Set<ColorMode>(["light", "dark"]);
|
|
37
|
+
const VALID_DENSITIES = new Set<SkinDensity>(["comfortable", "compact"]);
|
|
38
|
+
|
|
39
|
+
function isValidMode(value: unknown): value is ColorMode {
|
|
40
|
+
return typeof value === "string" && VALID_MODES.has(value as ColorMode);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isValidDensity(value: unknown): value is SkinDensity {
|
|
44
|
+
return typeof value === "string" && VALID_DENSITIES.has(value as SkinDensity);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isValidSkinId(value: unknown, registry: ThemeRegistry): value is SkinId {
|
|
48
|
+
return typeof value === "string" && registry.has(value);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function resolveFromCookie(
|
|
52
|
+
cookieValue: string | undefined | null,
|
|
53
|
+
registry: ThemeRegistry,
|
|
54
|
+
): Partial<UserThemePreferences> {
|
|
55
|
+
if (!cookieValue) return {};
|
|
56
|
+
let raw = cookieValue.trim();
|
|
57
|
+
try {
|
|
58
|
+
raw = decodeURIComponent(raw);
|
|
59
|
+
} catch {
|
|
60
|
+
// keep raw
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Handle legacy bare mode like "dark"
|
|
64
|
+
if (isValidMode(raw)) return { theme_mode: raw };
|
|
65
|
+
|
|
66
|
+
const result: { skin?: SkinId; theme_mode?: ColorMode; density?: SkinDensity } = {};
|
|
67
|
+
for (const pair of raw.split(";")) {
|
|
68
|
+
const idx = pair.indexOf("=");
|
|
69
|
+
if (idx <= 0) continue;
|
|
70
|
+
const key = pair.slice(0, idx).trim().toLowerCase();
|
|
71
|
+
const val = decodeURIComponent(pair.slice(idx + 1).trim());
|
|
72
|
+
if (key === "skin" && isValidSkinId(val, registry)) {
|
|
73
|
+
result.skin = val;
|
|
74
|
+
} else if ((key === "mode" || key === "theme") && isValidMode(val)) {
|
|
75
|
+
result.theme_mode = val;
|
|
76
|
+
} else if (key === "density" && isValidDensity(val)) {
|
|
77
|
+
result.density = val;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function normalizeState(
|
|
84
|
+
partial: Partial<UserThemePreferences>,
|
|
85
|
+
registry: ThemeRegistry,
|
|
86
|
+
): UserThemePreferences {
|
|
87
|
+
const skinId: SkinId =
|
|
88
|
+
isValidSkinId(partial.skin, registry) ? partial.skin : registry.defaultSkinId;
|
|
89
|
+
const metadata: SkinMetadata = registry.resolve(skinId);
|
|
90
|
+
const mode: ColorMode =
|
|
91
|
+
isValidMode(partial.theme_mode) ? partial.theme_mode : metadata.defaultMode;
|
|
92
|
+
const density: SkinDensity =
|
|
93
|
+
isValidDensity(partial.density) ? partial.density : metadata.defaultDensity;
|
|
94
|
+
return { skin: metadata.id, theme_mode: mode, density };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Create a pre-hydration init script that applies theme state to documentElement
|
|
99
|
+
* before React hydrates. The generated IIFE has zero dependencies and runs
|
|
100
|
+
* synchronously in the <head> or at the top of <body>.
|
|
101
|
+
*
|
|
102
|
+
* Precedence (highest first):
|
|
103
|
+
* 1. `serverState` passed explicitly (inline data-* attrs from server render)
|
|
104
|
+
* 2. `cookieValue` from mw-theme cookie (passed from server, or read at runtime)
|
|
105
|
+
* 3. Legacy localStorage keys (mw-ui-theme, mw-board-preferences, mw-theme)
|
|
106
|
+
* 4. Registry defaults
|
|
107
|
+
*
|
|
108
|
+
* When `dev: true`, emits a console.warn if the resolved skin differs from what
|
|
109
|
+
* the server would have resolved from the same cookie (T09 parity check).
|
|
110
|
+
*/
|
|
111
|
+
export function createSkinInitScript(
|
|
112
|
+
options: SkinInitScriptOptionsSsr = {},
|
|
113
|
+
): string {
|
|
114
|
+
const {
|
|
115
|
+
serverState,
|
|
116
|
+
cookieValue,
|
|
117
|
+
dev = false,
|
|
118
|
+
registry = themeRegistry,
|
|
119
|
+
storageKey = "mw-ui-theme",
|
|
120
|
+
} = options;
|
|
121
|
+
|
|
122
|
+
// Build the explicit server state if provided
|
|
123
|
+
const serverStatePayload = serverState
|
|
124
|
+
? normalizeState(serverState, registry)
|
|
125
|
+
: null;
|
|
126
|
+
|
|
127
|
+
// Resolve what the cookie would produce (for dev parity check)
|
|
128
|
+
const cookieState = cookieValue
|
|
129
|
+
? normalizeState(resolveFromCookie(cookieValue, registry), registry)
|
|
130
|
+
: null;
|
|
131
|
+
|
|
132
|
+
// Serialize registry skin IDs for client-side validation
|
|
133
|
+
const skinIdsJson = JSON.stringify(registry.list().map((s) => s.id));
|
|
134
|
+
const defaultSkinIdJson = JSON.stringify(DEFAULT_SKIN_ID);
|
|
135
|
+
const storageKeyJson = JSON.stringify(storageKey);
|
|
136
|
+
|
|
137
|
+
// Build the IIFE body as a template
|
|
138
|
+
const parts: string[] = [];
|
|
139
|
+
parts.push("(function(){");
|
|
140
|
+
parts.push("try{");
|
|
141
|
+
|
|
142
|
+
// 1. Apply explicit server state if provided (inline data-* wins)
|
|
143
|
+
if (serverStatePayload) {
|
|
144
|
+
parts.push(
|
|
145
|
+
`var s=${JSON.stringify(serverStatePayload)};`,
|
|
146
|
+
`document.documentElement.dataset.skin=s.skin;`,
|
|
147
|
+
`document.documentElement.dataset.density=s.density;`,
|
|
148
|
+
`document.documentElement.dataset.theme=s.theme_mode;`,
|
|
149
|
+
`document.documentElement.classList.toggle('dark',s.theme_mode==='dark');`,
|
|
150
|
+
`document.documentElement.classList.toggle('high-contrast',s.theme_mode==='high-contrast');`,
|
|
151
|
+
);
|
|
152
|
+
} else if (cookieValue !== undefined && cookieValue !== null) {
|
|
153
|
+
// 2a. Explicit cookieValue passed from server - use it directly if valid
|
|
154
|
+
const cookieParsed = resolveFromCookie(cookieValue, registry);
|
|
155
|
+
if (Object.keys(cookieParsed).length > 0) {
|
|
156
|
+
parts.push(
|
|
157
|
+
`var c=${JSON.stringify(normalizeState(cookieParsed, registry))};`,
|
|
158
|
+
`document.documentElement.dataset.skin=c.skin;`,
|
|
159
|
+
`document.documentElement.dataset.density=c.density;`,
|
|
160
|
+
`document.documentElement.dataset.theme=c.theme_mode;`,
|
|
161
|
+
`document.documentElement.classList.toggle('dark',c.theme_mode==='dark');`,
|
|
162
|
+
`document.documentElement.classList.toggle('high-contrast',c.theme_mode==='high-contrast');`,
|
|
163
|
+
);
|
|
164
|
+
} else {
|
|
165
|
+
// 2b. Explicit cookieValue but invalid - fall through to runtime cookie + localStorage
|
|
166
|
+
parts.push(
|
|
167
|
+
`var cookieVal=null;`,
|
|
168
|
+
`var cookieHeader=document.cookie||'';`,
|
|
169
|
+
`for(var i=0;i<cookieHeader.split(';').length;i++){`,
|
|
170
|
+
` var part=cookieHeader.split(';')[i].trim();`,
|
|
171
|
+
` var eq=part.indexOf('=');`,
|
|
172
|
+
` var key=eq>=0?part.slice(0,eq):part;`,
|
|
173
|
+
` if(key==='mw-theme'){ cookieVal=eq>=0?decodeURIComponent(part.slice(eq+1)):''; break; }`,
|
|
174
|
+
`}`,
|
|
175
|
+
`if(cookieVal){`,
|
|
176
|
+
` var parsed={};`,
|
|
177
|
+
` try{ cookieVal=decodeURIComponent(cookieVal); }catch(e){}`,
|
|
178
|
+
` if(cookieVal==='dark'||cookieVal==='light'){ parsed.theme_mode=cookieVal; }`,
|
|
179
|
+
` else{ for(var j=0;j<cookieVal.split(';').length;j++){ var p=cookieVal.split(';')[j].trim(); var ei=p.indexOf('='); if(ei<=0) continue; var pk=p.slice(0,ei).trim().toLowerCase(); var pv=decodeURIComponent(p.slice(ei+1).trim()); if(pk==='skin') parsed.skin=pv; else if(pk==='mode'||pk==='theme') parsed.theme_mode=pv; else if(pk==='density') parsed.density=pv; } }`,
|
|
180
|
+
` var allowed=${skinIdsJson};`,
|
|
181
|
+
` var skin=(parsed.skin&&allowed.indexOf(parsed.skin)!==-1)?parsed.skin:${defaultSkinIdJson};`,
|
|
182
|
+
` var mode=(parsed.theme_mode==='dark'||parsed.theme_mode==='light')?parsed.theme_mode:'light';`,
|
|
183
|
+
` var density=(parsed.density==='compact')?'compact':'comfortable';`,
|
|
184
|
+
` document.documentElement.dataset.skin=skin;`,
|
|
185
|
+
` document.documentElement.dataset.density=density;`,
|
|
186
|
+
` document.documentElement.dataset.theme=mode;`,
|
|
187
|
+
` document.documentElement.classList.toggle('dark',mode==='dark');`,
|
|
188
|
+
` document.documentElement.classList.toggle('high-contrast',mode==='high-contrast');`,
|
|
189
|
+
`} else {`,
|
|
190
|
+
// 3. Legacy localStorage fallback
|
|
191
|
+
`var raw=localStorage.getItem(${storageKeyJson})||localStorage.getItem('mw-board-preferences')||localStorage.getItem('mw-theme');`,
|
|
192
|
+
`var p=raw?JSON.parse(raw):null;`,
|
|
193
|
+
`var allowed=${skinIdsJson};`,
|
|
194
|
+
`var k=p&&typeof p.skin==='string'&&allowed.indexOf(p.skin)!==-1?p.skin:${defaultSkinIdJson};`,
|
|
195
|
+
`var d=p&&p.density==='compact'?'compact':'comfortable';`,
|
|
196
|
+
`var rawMode=p&&(p.mode||p.theme);`,
|
|
197
|
+
`var m=(rawMode==='dark'||rawMode==='light'||rawMode==='high-contrast')?rawMode:'light';`,
|
|
198
|
+
`document.documentElement.dataset.skin=k;`,
|
|
199
|
+
`document.documentElement.dataset.density=d;`,
|
|
200
|
+
`document.documentElement.dataset.theme=m;`,
|
|
201
|
+
`document.documentElement.classList.toggle('dark',m==='dark');`,
|
|
202
|
+
`document.documentElement.classList.toggle('high-contrast',m==='high-contrast');`,
|
|
203
|
+
`}`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
} else {
|
|
207
|
+
// 2c. No explicit cookieValue - read mw-theme cookie at runtime, then localStorage
|
|
208
|
+
parts.push(
|
|
209
|
+
`var cookieVal=null;`,
|
|
210
|
+
`var cookieHeader=document.cookie||'';`,
|
|
211
|
+
`for(var i=0;i<cookieHeader.split(';').length;i++){`,
|
|
212
|
+
` var part=cookieHeader.split(';')[i].trim();`,
|
|
213
|
+
` var eq=part.indexOf('=');`,
|
|
214
|
+
` var key=eq>=0?part.slice(0,eq):part;`,
|
|
215
|
+
` if(key==='mw-theme'){ cookieVal=eq>=0?decodeURIComponent(part.slice(eq+1)):''; break; }`,
|
|
216
|
+
`}`,
|
|
217
|
+
`if(cookieVal){`,
|
|
218
|
+
` var parsed={};`,
|
|
219
|
+
` try{ cookieVal=decodeURIComponent(cookieVal); }catch(e){}`,
|
|
220
|
+
` if(cookieVal==='dark'||cookieVal==='light'){ parsed.theme_mode=cookieVal; }`,
|
|
221
|
+
` else{ for(var j=0;j<cookieVal.split(';').length;j++){ var p=cookieVal.split(';')[j].trim(); var ei=p.indexOf('='); if(ei<=0) continue; var pk=p.slice(0,ei).trim().toLowerCase(); var pv=decodeURIComponent(p.slice(ei+1).trim()); if(pk==='skin') parsed.skin=pv; else if(pk==='mode'||pk==='theme') parsed.theme_mode=pv; else if(pk==='density') parsed.density=pv; } }`,
|
|
222
|
+
` var allowed=${skinIdsJson};`,
|
|
223
|
+
` var skin=(parsed.skin&&allowed.indexOf(parsed.skin)!==-1)?parsed.skin:${defaultSkinIdJson};`,
|
|
224
|
+
` var mode=(parsed.theme_mode==='dark'||parsed.theme_mode==='light')?parsed.theme_mode:'light';`,
|
|
225
|
+
` var density=(parsed.density==='compact')?'compact':'comfortable';`,
|
|
226
|
+
` document.documentElement.dataset.skin=skin;`,
|
|
227
|
+
` document.documentElement.dataset.density=density;`,
|
|
228
|
+
` document.documentElement.dataset.theme=mode;`,
|
|
229
|
+
` document.documentElement.classList.toggle('dark',mode==='dark');`,
|
|
230
|
+
` document.documentElement.classList.toggle('high-contrast',mode==='high-contrast');`,
|
|
231
|
+
`} else {`,
|
|
232
|
+
// 3. Legacy localStorage fallback
|
|
233
|
+
`var raw=localStorage.getItem(${storageKeyJson})||localStorage.getItem('mw-board-preferences')||localStorage.getItem('mw-theme');`,
|
|
234
|
+
`var p=raw?JSON.parse(raw):null;`,
|
|
235
|
+
`var allowed=${skinIdsJson};`,
|
|
236
|
+
`var k=p&&typeof p.skin==='string'&&allowed.indexOf(p.skin)!==-1?p.skin:${defaultSkinIdJson};`,
|
|
237
|
+
`var d=p&&p.density==='compact'?'compact':'comfortable';`,
|
|
238
|
+
`var rawMode=p&&(p.mode||p.theme);`,
|
|
239
|
+
`var m=(rawMode==='dark'||rawMode==='light'||rawMode==='high-contrast')?rawMode:'light';`,
|
|
240
|
+
`document.documentElement.dataset.skin=k;`,
|
|
241
|
+
`document.documentElement.dataset.density=d;`,
|
|
242
|
+
`document.documentElement.dataset.theme=m;`,
|
|
243
|
+
`document.documentElement.classList.toggle('dark',m==='dark');`,
|
|
244
|
+
`document.documentElement.classList.toggle('high-contrast',m==='high-contrast');`,
|
|
245
|
+
`}`,
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Dev mismatch warning (T09 integration)
|
|
250
|
+
if (dev && serverStatePayload && cookieState) {
|
|
251
|
+
const serverSkin = serverStatePayload.skin;
|
|
252
|
+
const serverMode = serverStatePayload.theme_mode;
|
|
253
|
+
const serverDensity = serverStatePayload.density;
|
|
254
|
+
const cookieSkin = cookieState.skin;
|
|
255
|
+
const cookieMode = cookieState.theme_mode;
|
|
256
|
+
const cookieDensity = cookieState.density;
|
|
257
|
+
|
|
258
|
+
if (
|
|
259
|
+
serverSkin !== cookieSkin ||
|
|
260
|
+
serverMode !== cookieMode ||
|
|
261
|
+
serverDensity !== cookieDensity
|
|
262
|
+
) {
|
|
263
|
+
parts.push(
|
|
264
|
+
`console.warn('[MoonWitness SSR] Theme mismatch: server={skin:"${serverSkin}",mode:"${serverMode}",density:"${serverDensity}"} cookie={skin:"${cookieSkin}",mode:"${cookieMode}",density:"${cookieDensity}"}. Inline state wins.');`,
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
parts.push("}catch(e){");
|
|
270
|
+
// Final safety net: apply defaults on any error
|
|
271
|
+
parts.push(
|
|
272
|
+
`document.documentElement.dataset.skin=${defaultSkinIdJson};`,
|
|
273
|
+
`document.documentElement.dataset.density='comfortable';`,
|
|
274
|
+
`document.documentElement.dataset.theme='light';`,
|
|
275
|
+
`document.documentElement.classList.remove('dark','high-contrast');`,
|
|
276
|
+
);
|
|
277
|
+
parts.push("}");
|
|
278
|
+
parts.push("})();");
|
|
279
|
+
|
|
280
|
+
return parts.join("");
|
|
281
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* T13 — SSR skin resolution from request data.
|
|
3
|
+
*
|
|
4
|
+
* INV-013: Theme state is carried by request data.
|
|
5
|
+
* No `localStorage`, `window`, or `document` access on this server path.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_SKIN_ID,
|
|
10
|
+
themeRegistry,
|
|
11
|
+
} from "../skin-catalog.js";
|
|
12
|
+
import type {
|
|
13
|
+
ColorMode,
|
|
14
|
+
SkinDensity,
|
|
15
|
+
SkinId,
|
|
16
|
+
SkinMetadata,
|
|
17
|
+
ThemeRegistry,
|
|
18
|
+
UserThemePreferences,
|
|
19
|
+
} from "../themes/types.js";
|
|
20
|
+
|
|
21
|
+
export const THEME_COOKIE_NAME = "mw-theme";
|
|
22
|
+
export const THEME_HEADER_NAME = "x-mw-theme";
|
|
23
|
+
|
|
24
|
+
export type ThemeSource = "cookie" | "header" | "default";
|
|
25
|
+
|
|
26
|
+
export interface ResolvedSkin extends UserThemePreferences {
|
|
27
|
+
readonly source: ThemeSource;
|
|
28
|
+
readonly valid: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type CookieInput =
|
|
32
|
+
| string
|
|
33
|
+
| null
|
|
34
|
+
| undefined
|
|
35
|
+
| Headers
|
|
36
|
+
| Record<string, string | string[] | undefined>
|
|
37
|
+
| Map<string, string>;
|
|
38
|
+
|
|
39
|
+
export interface ResolveSkinOptions {
|
|
40
|
+
readonly registry?: ThemeRegistry;
|
|
41
|
+
readonly cookieName?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const THEME_VALUE_KEYS = new Set(["skin", "mode", "theme", "density"]);
|
|
45
|
+
const VALID_MODES = new Set<string>(["light", "dark"]);
|
|
46
|
+
const VALID_DENSITIES = new Set<string>(["comfortable", "compact"]);
|
|
47
|
+
|
|
48
|
+
function hasGet(input: CookieInput): input is Headers {
|
|
49
|
+
return typeof (input as Headers | undefined)?.get === "function";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function headerValue(
|
|
53
|
+
input: Headers | Record<string, string | string[] | undefined> | Map<string, string>,
|
|
54
|
+
name: string,
|
|
55
|
+
): string | undefined {
|
|
56
|
+
if (hasGet(input)) return input.get(name) ?? undefined;
|
|
57
|
+
if (input instanceof Map) return input.get(name) ?? input.get(name.toLowerCase());
|
|
58
|
+
const direct = input[name] ?? input[name.toLowerCase()];
|
|
59
|
+
if (Array.isArray(direct)) return direct[0];
|
|
60
|
+
return direct;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function safeDecode(value: string): string {
|
|
64
|
+
try {
|
|
65
|
+
return decodeURIComponent(value);
|
|
66
|
+
} catch {
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Parse a theme value: `skin=x;mode=dark;density=compact` or legacy `dark`. */
|
|
72
|
+
function parseThemeValue(rawValue: string | undefined): Record<string, string> {
|
|
73
|
+
if (!rawValue) return {};
|
|
74
|
+
let raw = rawValue.trim();
|
|
75
|
+
if (/%3d/i.test(raw)) raw = safeDecode(raw);
|
|
76
|
+
if (VALID_MODES.has(raw)) return { mode: raw };
|
|
77
|
+
|
|
78
|
+
const result: Record<string, string> = {};
|
|
79
|
+
for (const pair of raw.split(";")) {
|
|
80
|
+
const separator = pair.indexOf("=");
|
|
81
|
+
if (separator <= 0) {
|
|
82
|
+
const bare = pair.trim();
|
|
83
|
+
if (VALID_MODES.has(bare)) result.mode = bare;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const key = pair.slice(0, separator).trim().toLowerCase();
|
|
87
|
+
if (!THEME_VALUE_KEYS.has(key)) continue;
|
|
88
|
+
result[key] = safeDecode(pair.slice(separator + 1).trim());
|
|
89
|
+
}
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Read a cookie value from a Cookie header, including semicolon-delimited theme pairs. */
|
|
94
|
+
function rawCookieFromHeader(cookieHeader: string, name: string): string | undefined {
|
|
95
|
+
let active = false;
|
|
96
|
+
let value: string | undefined;
|
|
97
|
+
for (const segment of cookieHeader.split(";")) {
|
|
98
|
+
const part = segment.trim();
|
|
99
|
+
if (!part) continue;
|
|
100
|
+
const separator = part.indexOf("=");
|
|
101
|
+
const key = (separator >= 0 ? part.slice(0, separator) : part).trim();
|
|
102
|
+
if (separator < 0 && active) {
|
|
103
|
+
value += `;${part}`;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (THEME_VALUE_KEYS.has(key.toLowerCase()) && active) {
|
|
107
|
+
value += `;${part}`;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
active = key === name;
|
|
111
|
+
if (active) value = separator >= 0 ? part.slice(separator + 1).trim() : "";
|
|
112
|
+
}
|
|
113
|
+
return value;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function readThemeRaw(input: CookieInput, cookieName: string): string | undefined {
|
|
117
|
+
if (typeof input === "string") {
|
|
118
|
+
if (!input.includes("=")) return VALID_MODES.has(input.trim()) ? input.trim() : undefined;
|
|
119
|
+
return rawCookieFromHeader(input, cookieName);
|
|
120
|
+
}
|
|
121
|
+
if (input === null || input === undefined) return undefined;
|
|
122
|
+
|
|
123
|
+
const direct = headerValue(input as Headers | Record<string, string | string[] | undefined> | Map<string, string>, cookieName);
|
|
124
|
+
if (direct !== undefined) return direct;
|
|
125
|
+
const cookieHeader = headerValue(input as Headers | Record<string, string | string[] | undefined> | Map<string, string>, "cookie");
|
|
126
|
+
return cookieHeader ? rawCookieFromHeader(cookieHeader, cookieName) : undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function readHeaderRaw(input: CookieInput): string | undefined {
|
|
130
|
+
if (typeof input === "string" || input === null || input === undefined) return undefined;
|
|
131
|
+
return headerValue(input as Headers | Record<string, string | string[] | undefined> | Map<string, string>, THEME_HEADER_NAME);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function hasUsableTheme(value: Record<string, string>, registry: ThemeRegistry): boolean {
|
|
135
|
+
if (typeof value.skin === "string" && registry.has(value.skin)) return true;
|
|
136
|
+
// legacy bare mode (e.g., "dark" without skin) — treat as unusable so default applies
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function normalize(
|
|
141
|
+
value: Record<string, string>,
|
|
142
|
+
registry: ThemeRegistry,
|
|
143
|
+
): UserThemePreferences {
|
|
144
|
+
const skinId: SkinId =
|
|
145
|
+
typeof value.skin === "string" && registry.has(value.skin)
|
|
146
|
+
? value.skin
|
|
147
|
+
: registry.defaultSkinId;
|
|
148
|
+
const metadata: SkinMetadata = registry.resolve(skinId);
|
|
149
|
+
const rawMode = value.mode ?? value.theme;
|
|
150
|
+
const mode: ColorMode = typeof rawMode === "string" && VALID_MODES.has(rawMode)
|
|
151
|
+
? (rawMode as ColorMode)
|
|
152
|
+
: metadata.defaultMode;
|
|
153
|
+
const density: SkinDensity =
|
|
154
|
+
typeof value.density === "string" && VALID_DENSITIES.has(value.density)
|
|
155
|
+
? (value.density as SkinDensity)
|
|
156
|
+
: metadata.defaultDensity;
|
|
157
|
+
|
|
158
|
+
return { skin: metadata.id, theme_mode: mode, density };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function defaultState(registry: ThemeRegistry): ResolvedSkin {
|
|
162
|
+
const fallback = registry.resolve(DEFAULT_SKIN_ID);
|
|
163
|
+
return {
|
|
164
|
+
skin: fallback.id,
|
|
165
|
+
theme_mode: fallback.defaultMode,
|
|
166
|
+
density: fallback.defaultDensity,
|
|
167
|
+
source: "default",
|
|
168
|
+
valid: false,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Resolve theme state from a cookie raw value, Cookie header, `Headers`,
|
|
174
|
+
* `x-mw-theme` header, or a plain header/cookie map.
|
|
175
|
+
*
|
|
176
|
+
* Precedence: mw-theme request data > x-mw-theme fallback > defaults.
|
|
177
|
+
*/
|
|
178
|
+
export function resolveSkin(
|
|
179
|
+
input: CookieInput,
|
|
180
|
+
options: ResolveSkinOptions = {},
|
|
181
|
+
): ResolvedSkin {
|
|
182
|
+
const registry = options.registry ?? themeRegistry;
|
|
183
|
+
const cookieName = options.cookieName ?? THEME_COOKIE_NAME;
|
|
184
|
+
const fromCookie = parseThemeValue(readThemeRaw(input, cookieName));
|
|
185
|
+
if (hasUsableTheme(fromCookie, registry)) {
|
|
186
|
+
return { ...normalize(fromCookie, registry), source: "cookie", valid: true };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const fromHeader = parseThemeValue(readHeaderRaw(input));
|
|
190
|
+
if (hasUsableTheme(fromHeader, registry)) {
|
|
191
|
+
return { ...normalize(fromHeader, registry), source: "header", valid: true };
|
|
192
|
+
}
|
|
193
|
+
return defaultState(registry);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Serialize resolved state into the URL-safe mw-theme cookie value. */
|
|
197
|
+
export function serializeSkinCookie(state: UserThemePreferences): string {
|
|
198
|
+
return `skin=${encodeURIComponent(state.skin)};mode=${encodeURIComponent(state.theme_mode)};density=${encodeURIComponent(state.density)}`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
type MutableUserThemePreferences = { -readonly [K in keyof UserThemePreferences]: UserThemePreferences[K] };
|
|
202
|
+
|
|
203
|
+
/** Parse a raw mw-theme cookie value without registry normalization. */
|
|
204
|
+
export function parseSkinCookie(
|
|
205
|
+
value: string | undefined | null,
|
|
206
|
+
registry?: ThemeRegistry,
|
|
207
|
+
): Partial<MutableUserThemePreferences> {
|
|
208
|
+
const parsed = parseThemeValue(value ?? undefined);
|
|
209
|
+
const result: Partial<MutableUserThemePreferences> = {};
|
|
210
|
+
if (parsed.skin && (!registry || registry.has(parsed.skin))) result.skin = parsed.skin;
|
|
211
|
+
const rawMode = parsed.mode ?? parsed.theme;
|
|
212
|
+
if (rawMode === "light" || rawMode === "dark") result.theme_mode = rawMode;
|
|
213
|
+
if (parsed.density === "compact" || parsed.density === "comfortable") {
|
|
214
|
+
result.density = parsed.density;
|
|
215
|
+
}
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dev-only SSR theme mismatch fixture for the W1/T09 smoke gate.
|
|
3
|
+
*
|
|
4
|
+
* INV-009: Theme state is visible to server and client.
|
|
5
|
+
*
|
|
6
|
+
* This module is intentionally small and dependency-free so the same
|
|
7
|
+
* deterministic logic can be exercised by:
|
|
8
|
+
* - the Playwright smoke spec (browser console hydration detection), and
|
|
9
|
+
* - a Node self-check when this file is executed directly (bunx fallback).
|
|
10
|
+
*
|
|
11
|
+
* Do not suppress hydration warnings. The gate must fail closed.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const THEME_COOKIE_NAME = "mw-theme";
|
|
15
|
+
export const THEME_FIXTURES = ["light", "dark"] as const;
|
|
16
|
+
|
|
17
|
+
export type Theme = (typeof THEME_FIXTURES)[number];
|
|
18
|
+
|
|
19
|
+
export interface ThemeHtmlState {
|
|
20
|
+
theme: Theme;
|
|
21
|
+
attributes: Record<string, string>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface HydrationCheck {
|
|
25
|
+
passed: boolean;
|
|
26
|
+
warning: string | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SelfTestCheck {
|
|
30
|
+
name: string;
|
|
31
|
+
passed: boolean;
|
|
32
|
+
detail?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface SelfTestResult {
|
|
36
|
+
passed: boolean;
|
|
37
|
+
checks: SelfTestCheck[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Deterministic theme resolution: unknown/empty cookies fall back to light. */
|
|
41
|
+
export function resolveTheme(cookieValue: string | undefined | null): Theme {
|
|
42
|
+
return cookieValue === "dark" ? "dark" : "light";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Deterministic server-side theme state derived from the request cookie. */
|
|
46
|
+
export function serverRender(cookieValue: string | undefined | null): ThemeHtmlState {
|
|
47
|
+
const theme = resolveTheme(cookieValue);
|
|
48
|
+
return {
|
|
49
|
+
theme,
|
|
50
|
+
attributes: {
|
|
51
|
+
"data-theme": theme,
|
|
52
|
+
class: `theme-${theme}`,
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Client hydration attributes derived from the same cookie. */
|
|
58
|
+
export function clientHydrationAttributes(
|
|
59
|
+
cookieValue: string | undefined | null,
|
|
60
|
+
): Record<string, string> {
|
|
61
|
+
const theme = resolveTheme(cookieValue);
|
|
62
|
+
return {
|
|
63
|
+
"data-theme": theme,
|
|
64
|
+
class: `theme-${theme}`,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Stable serialization used on both sides so comparison is deterministic. */
|
|
69
|
+
export function serializeHtmlAttributes(attributes: Record<string, string>): string {
|
|
70
|
+
return Object.keys(attributes)
|
|
71
|
+
.sort()
|
|
72
|
+
.map((key) => `${key}="${attributes[key]}"`)
|
|
73
|
+
.join(" ");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Full deterministic <html> open tag for a fixture cookie. */
|
|
77
|
+
export function renderServerHtml(cookieValue: string | undefined | null): string {
|
|
78
|
+
return `<html ${serializeHtmlAttributes(serverRender(cookieValue).attributes)}>`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Negative fixture: simulate a client that ignores the cookie and hydrates
|
|
83
|
+
* with the light default while the server rendered dark.
|
|
84
|
+
*/
|
|
85
|
+
export function mismatchedClientAttributes(
|
|
86
|
+
_cookieValue: string | undefined | null,
|
|
87
|
+
): Record<string, string> {
|
|
88
|
+
// Simulate a client that ignores the cookie and always hydrates light.
|
|
89
|
+
return {
|
|
90
|
+
"data-theme": "light",
|
|
91
|
+
class: "theme-light",
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** True when a console message is a hydration warning. Fail closed on these. */
|
|
96
|
+
export function isHydrationWarning(message: string): boolean {
|
|
97
|
+
return /hydrat|did not match|text content does not match|server rendered html/i.test(message);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Gate predicate used by the smoke spec: any hydration warning fails. */
|
|
101
|
+
export function gateFailsOnWarnings(messages: string[]): boolean {
|
|
102
|
+
return messages.some(isHydrationWarning);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Compare server attributes with the attributes the client hydrates with. */
|
|
106
|
+
export function checkHydration(
|
|
107
|
+
cookieValue: string | undefined | null,
|
|
108
|
+
clientAttributes: Record<string, string> = clientHydrationAttributes(cookieValue),
|
|
109
|
+
): HydrationCheck {
|
|
110
|
+
const server = serializeHtmlAttributes(serverRender(cookieValue).attributes);
|
|
111
|
+
const client = serializeHtmlAttributes(clientAttributes);
|
|
112
|
+
|
|
113
|
+
if (server !== client) {
|
|
114
|
+
return {
|
|
115
|
+
passed: false,
|
|
116
|
+
warning: `Hydration attribute mismatch: server="${server}" client="${client}"`,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
return { passed: true, warning: null };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Deterministic Node-side verification for the three T09 acceptance criteria.
|
|
124
|
+
* Used when the bun/bunx shim is unavailable.
|
|
125
|
+
*/
|
|
126
|
+
export function runSelfTest(): SelfTestResult {
|
|
127
|
+
const checks: SelfTestCheck[] = [];
|
|
128
|
+
|
|
129
|
+
// AC2: server html attribute equals client html attribute for fixture cookie.
|
|
130
|
+
for (const cookie of THEME_FIXTURES) {
|
|
131
|
+
const result = checkHydration(cookie);
|
|
132
|
+
checks.push({
|
|
133
|
+
name: `server/client attribute parity for cookie=${cookie}`,
|
|
134
|
+
passed: result.passed,
|
|
135
|
+
detail: result.warning ?? undefined,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// AC3: two cookie values produce two deterministic server renders.
|
|
140
|
+
for (const cookie of THEME_FIXTURES) {
|
|
141
|
+
const first = renderServerHtml(cookie);
|
|
142
|
+
const second = renderServerHtml(cookie);
|
|
143
|
+
checks.push({
|
|
144
|
+
name: `deterministic server render for cookie=${cookie}`,
|
|
145
|
+
passed: first === second,
|
|
146
|
+
detail: first === second ? undefined : `"${first}" !== "${second}"`,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const lightHtml = renderServerHtml("light");
|
|
151
|
+
const darkHtml = renderServerHtml("dark");
|
|
152
|
+
checks.push({
|
|
153
|
+
name: "two cookie values produce distinct server renders",
|
|
154
|
+
passed: lightHtml !== darkHtml,
|
|
155
|
+
detail: lightHtml !== darkHtml ? undefined : `${lightHtml} === ${darkHtml}`,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// AC1: hydration warning fails the test (negative control).
|
|
159
|
+
const negative = checkHydration("dark", mismatchedClientAttributes("dark"));
|
|
160
|
+
const warningDetected = negative.passed === false && isHydrationWarning(negative.warning ?? "");
|
|
161
|
+
const gateFails = gateFailsOnWarnings([negative.warning ?? ""]);
|
|
162
|
+
checks.push({
|
|
163
|
+
name: "hydration warning fails the gate",
|
|
164
|
+
passed: warningDetected && gateFails,
|
|
165
|
+
detail: negative.warning ?? undefined,
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
passed: checks.every((check) => check.passed),
|
|
170
|
+
checks,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Direct-run CLI fallback (Node 24 can execute .ts directly).
|
|
175
|
+
if (typeof process !== "undefined" && process.argv?.[1]?.endsWith("theme-mismatch-dev.ts")) {
|
|
176
|
+
const result = runSelfTest();
|
|
177
|
+
console.log(JSON.stringify(result, null, 2));
|
|
178
|
+
if (!result.passed) {
|
|
179
|
+
process.exitCode = 1;
|
|
180
|
+
}
|
|
181
|
+
}
|