stoop 0.2.1 → 0.4.0

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.
Files changed (56) hide show
  1. package/README.md +48 -103
  2. package/dist/api/core-api.d.ts +34 -0
  3. package/dist/api/core-api.js +135 -0
  4. package/dist/api/global-css.d.ts +0 -11
  5. package/dist/api/global-css.js +42 -0
  6. package/dist/api/styled.d.ts +0 -1
  7. package/dist/api/styled.js +419 -0
  8. package/dist/api/theme-provider.d.ts +41 -0
  9. package/dist/api/theme-provider.js +223 -0
  10. package/dist/constants.d.ts +13 -4
  11. package/dist/constants.js +154 -0
  12. package/dist/core/cache.d.ts +5 -9
  13. package/dist/core/cache.js +68 -0
  14. package/dist/core/compiler.d.ts +11 -0
  15. package/dist/core/compiler.js +206 -0
  16. package/dist/core/theme-manager.d.ts +27 -4
  17. package/dist/core/theme-manager.js +107 -0
  18. package/dist/core/variants.js +38 -0
  19. package/dist/create-stoop-internal.d.ts +30 -0
  20. package/dist/create-stoop-internal.js +123 -0
  21. package/dist/create-stoop-ssr.d.ts +10 -0
  22. package/dist/create-stoop-ssr.js +26 -0
  23. package/dist/create-stoop.d.ts +32 -4
  24. package/dist/create-stoop.js +156 -0
  25. package/dist/inject.d.ts +113 -0
  26. package/dist/inject.js +308 -0
  27. package/dist/types/index.d.ts +157 -17
  28. package/dist/types/index.js +5 -0
  29. package/dist/types/react-polymorphic-types.d.ts +15 -8
  30. package/dist/utils/auto-preload.d.ts +45 -0
  31. package/dist/utils/auto-preload.js +167 -0
  32. package/dist/utils/helpers.d.ts +64 -0
  33. package/dist/utils/helpers.js +150 -0
  34. package/dist/utils/storage.d.ts +148 -0
  35. package/dist/utils/storage.js +396 -0
  36. package/dist/utils/{string.d.ts → theme-utils.d.ts} +36 -12
  37. package/dist/utils/theme-utils.js +353 -0
  38. package/dist/utils/theme.d.ts +17 -5
  39. package/dist/utils/theme.js +304 -0
  40. package/package.json +48 -24
  41. package/LICENSE.md +0 -21
  42. package/dist/api/create-theme.d.ts +0 -13
  43. package/dist/api/css.d.ts +0 -16
  44. package/dist/api/keyframes.d.ts +0 -16
  45. package/dist/api/provider.d.ts +0 -19
  46. package/dist/api/use-theme.d.ts +0 -13
  47. package/dist/index.d.ts +0 -6
  48. package/dist/index.js +0 -13
  49. package/dist/inject/browser.d.ts +0 -59
  50. package/dist/inject/dedup.d.ts +0 -29
  51. package/dist/inject/index.d.ts +0 -41
  52. package/dist/inject/ssr.d.ts +0 -28
  53. package/dist/utils/theme-map.d.ts +0 -25
  54. package/dist/utils/theme-validation.d.ts +0 -13
  55. package/dist/utils/type-guards.d.ts +0 -26
  56. package/dist/utils/utilities.d.ts +0 -14
@@ -0,0 +1,396 @@
1
+ /**
2
+ * Storage and theme detection utilities.
3
+ * Provides simplified localStorage and cookie management, plus automatic theme selection.
4
+ * Supports SSR compatibility and error handling.
5
+ */
6
+ import { DEFAULT_COOKIE_MAX_AGE, DEFAULT_COOKIE_PATH } from "../constants";
7
+ import { isBrowser } from "./helpers";
8
+ // ============================================================================
9
+ // Storage Utilities
10
+ // ============================================================================
11
+ /**
12
+ * Parses a JSON value safely.
13
+ *
14
+ * @param value - String value to parse
15
+ * @param fallback - Fallback value if parsing fails
16
+ * @returns Parsed value or fallback
17
+ */
18
+ function safeJsonParse(value, fallback) {
19
+ try {
20
+ return JSON.parse(value);
21
+ }
22
+ catch {
23
+ return fallback;
24
+ }
25
+ }
26
+ /**
27
+ * Safely gets a value from localStorage.
28
+ *
29
+ * @param key - Storage key
30
+ * @returns Storage result
31
+ */
32
+ export function getFromStorage(key) {
33
+ if (!isBrowser()) {
34
+ return { error: "Not in browser environment", success: false, value: null };
35
+ }
36
+ try {
37
+ const value = localStorage.getItem(key);
38
+ return { source: "localStorage", success: true, value };
39
+ }
40
+ catch (error) {
41
+ return {
42
+ error: error instanceof Error ? error.message : "localStorage access failed",
43
+ success: false,
44
+ value: null,
45
+ };
46
+ }
47
+ }
48
+ /**
49
+ * Safely sets a value in localStorage.
50
+ *
51
+ * @param key - Storage key
52
+ * @param value - Value to store
53
+ * @returns Storage result
54
+ */
55
+ export function setInStorage(key, value) {
56
+ if (!isBrowser()) {
57
+ return { error: "Not in browser environment", success: false, value: undefined };
58
+ }
59
+ try {
60
+ localStorage.setItem(key, value);
61
+ return { success: true, value: undefined };
62
+ }
63
+ catch (error) {
64
+ return {
65
+ error: error instanceof Error ? error.message : "localStorage write failed",
66
+ success: false,
67
+ value: undefined,
68
+ };
69
+ }
70
+ }
71
+ /**
72
+ * Safely removes a value from localStorage.
73
+ *
74
+ * @param key - Storage key
75
+ * @returns Storage result
76
+ */
77
+ export function removeFromStorage(key) {
78
+ if (!isBrowser()) {
79
+ return { error: "Not in browser environment", success: false, value: undefined };
80
+ }
81
+ try {
82
+ localStorage.removeItem(key);
83
+ return { success: true, value: undefined };
84
+ }
85
+ catch (error) {
86
+ return {
87
+ error: error instanceof Error ? error.message : "localStorage remove failed",
88
+ success: false,
89
+ value: undefined,
90
+ };
91
+ }
92
+ }
93
+ /**
94
+ * Gets a cookie value.
95
+ *
96
+ * @param name - Cookie name
97
+ * @returns Cookie value or null if not found
98
+ */
99
+ export function getCookie(name) {
100
+ if (!isBrowser())
101
+ return null;
102
+ const value = `; ${document.cookie}`;
103
+ const parts = value.split(`; ${name}=`);
104
+ if (parts.length === 2) {
105
+ return parts.pop()?.split(";").shift() || null;
106
+ }
107
+ return null;
108
+ }
109
+ /**
110
+ * Sets a cookie value.
111
+ *
112
+ * @param name - Cookie name
113
+ * @param value - Cookie value
114
+ * @param options - Cookie options
115
+ * @returns Success status
116
+ */
117
+ export function setCookie(name, value, options = {}) {
118
+ if (!isBrowser())
119
+ return false;
120
+ const { maxAge = DEFAULT_COOKIE_MAX_AGE, path = DEFAULT_COOKIE_PATH, secure = false } = options;
121
+ try {
122
+ document.cookie = `${name}=${value}; path=${path}; max-age=${maxAge}${secure ? "; secure" : ""}`;
123
+ return true;
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ }
129
+ /**
130
+ * Removes a cookie by setting it to expire.
131
+ *
132
+ * @param name - Cookie name
133
+ * @param path - Cookie path
134
+ * @returns Success status
135
+ */
136
+ export function removeCookie(name, path = "/") {
137
+ if (!isBrowser())
138
+ return false;
139
+ try {
140
+ document.cookie = `${name}=; path=${path}; max-age=0`;
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
147
+ /**
148
+ * Unified storage API that works with both localStorage and cookies.
149
+ *
150
+ * @param key - Storage key
151
+ * @param options - Storage options
152
+ * @returns Storage result
153
+ */
154
+ export function getStorage(key, options = {}) {
155
+ const { type = "localStorage" } = options;
156
+ if (type === "cookie") {
157
+ const value = getCookie(key);
158
+ return {
159
+ source: "cookie",
160
+ success: value !== null,
161
+ value,
162
+ };
163
+ }
164
+ return getFromStorage(key);
165
+ }
166
+ /**
167
+ * Unified storage API that works with both localStorage and cookies.
168
+ *
169
+ * @param key - Storage key
170
+ * @param value - Value to store
171
+ * @param options - Storage options
172
+ * @returns Storage result
173
+ */
174
+ export function setStorage(key, value, options = {}) {
175
+ const { type = "localStorage" } = options;
176
+ if (type === "cookie") {
177
+ const success = setCookie(key, value, options);
178
+ return {
179
+ error: success ? undefined : "Cookie write failed",
180
+ success,
181
+ value: undefined,
182
+ };
183
+ }
184
+ return setInStorage(key, value);
185
+ }
186
+ /**
187
+ * Unified storage API that works with both localStorage and cookies.
188
+ *
189
+ * @param key - Storage key
190
+ * @param options - Storage options
191
+ * @returns Storage result
192
+ */
193
+ export function removeStorage(key, options = {}) {
194
+ const { type = "localStorage" } = options;
195
+ if (type === "cookie") {
196
+ const success = removeCookie(key, options.path);
197
+ return {
198
+ error: success ? undefined : "Cookie remove failed",
199
+ success,
200
+ value: undefined,
201
+ };
202
+ }
203
+ return removeFromStorage(key);
204
+ }
205
+ /**
206
+ * Gets a JSON value from storage with automatic parsing.
207
+ *
208
+ * @param key - Storage key
209
+ * @param fallback - Fallback value if parsing fails or key not found
210
+ * @param options - Storage options
211
+ * @returns Parsed JSON value or fallback
212
+ */
213
+ export function getJsonFromStorage(key, fallback, options = {}) {
214
+ const result = getStorage(key, options);
215
+ if (!result.success || result.value === null) {
216
+ return { ...result, value: fallback };
217
+ }
218
+ const parsed = safeJsonParse(result.value, fallback);
219
+ return { ...result, value: parsed };
220
+ }
221
+ /**
222
+ * Sets a JSON value in storage with automatic serialization.
223
+ *
224
+ * @param key - Storage key
225
+ * @param value - Value to serialize and store
226
+ * @param options - Storage options
227
+ * @returns Storage result
228
+ */
229
+ export function setJsonInStorage(key, value, options = {}) {
230
+ try {
231
+ const serialized = JSON.stringify(value);
232
+ return setStorage(key, serialized, options);
233
+ }
234
+ catch (error) {
235
+ return {
236
+ error: error instanceof Error ? error.message : "JSON serialization failed",
237
+ success: false,
238
+ value: undefined,
239
+ };
240
+ }
241
+ }
242
+ /**
243
+ * Creates a typed storage interface for a specific key.
244
+ *
245
+ * @param key - Storage key
246
+ * @param options - Storage options
247
+ * @returns Typed storage interface
248
+ */
249
+ export function createStorage(key, options = {}) {
250
+ return {
251
+ get: () => getStorage(key, options),
252
+ getJson: (fallback) => getJsonFromStorage(key, fallback, options),
253
+ remove: () => removeStorage(key, options),
254
+ set: (value) => setStorage(key, value, options),
255
+ setJson: (value) => setJsonInStorage(key, value, options),
256
+ };
257
+ }
258
+ // ============================================================================
259
+ // Theme Detection Utilities
260
+ // ============================================================================
261
+ /**
262
+ * Gets localStorage value safely (internal helper for theme detection).
263
+ * Uses getFromStorage for consistency.
264
+ *
265
+ * @param key - Storage key
266
+ * @returns Stored value or null if not found or access failed
267
+ */
268
+ function getLocalStorage(key) {
269
+ const result = getFromStorage(key);
270
+ return result.success ? result.value : null;
271
+ }
272
+ /**
273
+ * Detects system color scheme preference.
274
+ *
275
+ * @returns 'dark' or 'light' based on system preference
276
+ */
277
+ function getSystemPreference() {
278
+ if (!isBrowser())
279
+ return null;
280
+ try {
281
+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
282
+ }
283
+ catch {
284
+ return null;
285
+ }
286
+ }
287
+ /**
288
+ * Validates if a theme name exists in available themes.
289
+ *
290
+ * @param themeName - Theme name to validate
291
+ * @param themes - Available themes map
292
+ * @returns True if theme is valid
293
+ */
294
+ function isValidTheme(themeName, themes) {
295
+ return !themes || !!themes[themeName];
296
+ }
297
+ /**
298
+ * Detects the best theme to use based on multiple sources with priority.
299
+ *
300
+ * Priority order (highest to lowest):
301
+ * 1. Explicit localStorage preference
302
+ * 2. Cookie preference (for SSR compatibility)
303
+ * 3. System color scheme preference
304
+ * 4. Default theme
305
+ *
306
+ * @param options - Theme detection options
307
+ * @returns Theme detection result
308
+ */
309
+ export function detectTheme(options = {}) {
310
+ const { cookie: cookieKey, default: defaultTheme = "light", localStorage: storageKey, systemPreference = true, themes, } = options;
311
+ // 1. Check localStorage (highest priority - explicit user choice)
312
+ if (storageKey) {
313
+ const stored = getLocalStorage(storageKey);
314
+ if (stored && isValidTheme(stored, themes)) {
315
+ return {
316
+ confidence: 0.9, // High confidence - explicit user choice
317
+ source: "localStorage",
318
+ theme: stored,
319
+ };
320
+ }
321
+ }
322
+ // 2. Check cookie (for SSR compatibility)
323
+ if (cookieKey) {
324
+ const cookieValue = getCookie(cookieKey);
325
+ if (cookieValue && isValidTheme(cookieValue, themes)) {
326
+ return {
327
+ confidence: 0.8, // High confidence - persisted preference
328
+ source: "cookie",
329
+ theme: cookieValue,
330
+ };
331
+ }
332
+ }
333
+ // 3. Check system preference
334
+ if (systemPreference) {
335
+ const system = getSystemPreference();
336
+ if (system && isValidTheme(system, themes)) {
337
+ return {
338
+ confidence: 0.6, // Medium confidence - system default
339
+ source: "system",
340
+ theme: system,
341
+ };
342
+ }
343
+ }
344
+ // 4. Fall back to default
345
+ return {
346
+ confidence: 0.3, // Low confidence - fallback only
347
+ source: "default",
348
+ theme: defaultTheme,
349
+ };
350
+ }
351
+ /**
352
+ * Creates a theme detector function with pre-configured options.
353
+ *
354
+ * @param options - Theme detection options
355
+ * @returns Theme detection function
356
+ */
357
+ export function createThemeDetector(options) {
358
+ return () => detectTheme(options);
359
+ }
360
+ /**
361
+ * Auto-detects theme for SSR contexts (server-side or during hydration).
362
+ * Uses only cookie and default sources since localStorage isn't available.
363
+ *
364
+ * @param options - Theme detection options
365
+ * @returns Theme name
366
+ */
367
+ export function detectThemeForSSR(options = {}) {
368
+ const { cookie: cookieKey, default: defaultTheme = "light", themes } = options;
369
+ // Only check cookie in SSR context
370
+ if (cookieKey) {
371
+ const cookieValue = getCookie(cookieKey);
372
+ if (cookieValue && isValidTheme(cookieValue, themes)) {
373
+ return cookieValue;
374
+ }
375
+ }
376
+ return defaultTheme;
377
+ }
378
+ /**
379
+ * Listens for system theme changes and calls callback when changed.
380
+ *
381
+ * @param callback - Function to call when system theme changes
382
+ * @returns Cleanup function
383
+ */
384
+ export function onSystemThemeChange(callback) {
385
+ if (!isBrowser()) {
386
+ return () => { }; // No-op in SSR
387
+ }
388
+ const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
389
+ const handleChange = (e) => {
390
+ callback(e.matches ? "dark" : "light");
391
+ };
392
+ mediaQuery.addEventListener("change", handleChange);
393
+ return () => {
394
+ mediaQuery.removeEventListener("change", handleChange);
395
+ };
396
+ }
@@ -1,10 +1,11 @@
1
1
  /**
2
- * String utility functions.
3
- * Provides hashing for class name generation, camelCase to kebab-case conversion,
4
- * and CSS sanitization utilities for security.
2
+ * Theme-related string utilities and property mapping.
3
+ * Provides hashing, CSS sanitization, and theme scale mapping for property-aware token resolution.
5
4
  */
5
+ import type { ThemeScale } from "../types";
6
6
  /**
7
- * Generates a hash string from an input string.
7
+ * Generates a hash string from an input string using FNV-1a algorithm.
8
+ * Includes string length to reduce collision probability.
8
9
  *
9
10
  * @param str - String to hash
10
11
  * @returns Hashed string
@@ -35,6 +36,7 @@ export declare function escapeCSSValue(value: string | number): string;
35
36
  /**
36
37
  * Validates and sanitizes CSS selectors to prevent injection attacks.
37
38
  * Only allows safe selector characters. Returns empty string for invalid selectors.
39
+ * Uses memoization for performance.
38
40
  *
39
41
  * @param selector - Selector to sanitize
40
42
  * @returns Sanitized selector string or empty string if invalid
@@ -43,6 +45,7 @@ export declare function sanitizeCSSSelector(selector: string): string;
43
45
  /**
44
46
  * Validates and sanitizes CSS variable names to prevent injection attacks.
45
47
  * CSS custom properties must start with -- and contain only valid characters.
48
+ * Uses memoization for performance.
46
49
  *
47
50
  * @param name - Variable name to sanitize
48
51
  * @returns Sanitized variable name
@@ -58,18 +61,12 @@ export declare function escapeCSSVariableValue(value: string | number): string;
58
61
  /**
59
62
  * Sanitizes prefix for use in CSS selectors and class names.
60
63
  * Only allows alphanumeric characters, hyphens, and underscores.
64
+ * Defaults to "stoop" if prefix is empty or becomes empty after sanitization.
61
65
  *
62
66
  * @param prefix - Prefix to sanitize
63
- * @returns Sanitized prefix string
67
+ * @returns Sanitized prefix string (never empty, defaults to "stoop")
64
68
  */
65
69
  export declare function sanitizePrefix(prefix: string): string;
66
- /**
67
- * Escapes prefix for use in CSS attribute selectors.
68
- *
69
- * @param prefix - Prefix to escape
70
- * @returns Escaped prefix string
71
- */
72
- export declare function escapePrefixForSelector(prefix: string): string;
73
70
  /**
74
71
  * Sanitizes media query strings to prevent injection attacks.
75
72
  * Only allows safe characters for media queries.
@@ -81,6 +78,7 @@ export declare function sanitizeMediaQuery(mediaQuery: string): string;
81
78
  /**
82
79
  * Sanitizes CSS class names to prevent injection attacks.
83
80
  * Only allows valid CSS class name characters.
81
+ * Uses memoization for performance.
84
82
  *
85
83
  * @param className - Class name(s) to sanitize
86
84
  * @returns Sanitized class name string
@@ -88,6 +86,7 @@ export declare function sanitizeMediaQuery(mediaQuery: string): string;
88
86
  export declare function sanitizeClassName(className: string): string;
89
87
  /**
90
88
  * Sanitizes CSS property names to prevent injection attacks.
89
+ * Uses memoization for performance.
91
90
  *
92
91
  * @param propertyName - Property name to sanitize
93
92
  * @returns Sanitized property name
@@ -100,3 +99,28 @@ export declare function sanitizeCSSPropertyName(propertyName: string): string;
100
99
  * @returns True if key is valid
101
100
  */
102
101
  export declare function validateKeyframeKey(key: string): boolean;
102
+ /**
103
+ * Gets a pre-compiled regex for matching :root CSS selector blocks.
104
+ * Uses caching for performance.
105
+ *
106
+ * @param prefix - Optional prefix (unused, kept for API compatibility)
107
+ * @returns RegExp for matching :root selector blocks
108
+ */
109
+ export declare function getRootRegex(prefix?: string): RegExp;
110
+ /**
111
+ * Auto-detects theme scale from CSS property name using pattern matching.
112
+ * Used as fallback when property is not in DEFAULT_THEME_MAP.
113
+ *
114
+ * @param property - CSS property name
115
+ * @returns Theme scale name or undefined if no pattern matches
116
+ */
117
+ export declare function autoDetectScale(property: string): ThemeScale | undefined;
118
+ /**
119
+ * Gets the theme scale for a CSS property.
120
+ * Checks user themeMap first, then default themeMap, then pattern matching.
121
+ *
122
+ * @param property - CSS property name
123
+ * @param userThemeMap - Optional user-provided themeMap override
124
+ * @returns Theme scale name or undefined if no mapping found
125
+ */
126
+ export declare function getScaleForProperty(property: string, userThemeMap?: Record<string, ThemeScale>): ThemeScale | undefined;