@bquery/bquery 1.5.0 → 1.6.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 (106) hide show
  1. package/README.md +586 -546
  2. package/dist/component/component.d.ts +13 -5
  3. package/dist/component/component.d.ts.map +1 -1
  4. package/dist/component/html.d.ts +40 -3
  5. package/dist/component/html.d.ts.map +1 -1
  6. package/dist/component/index.d.ts +2 -2
  7. package/dist/component/index.d.ts.map +1 -1
  8. package/dist/component/library.d.ts.map +1 -1
  9. package/dist/component/types.d.ts +131 -16
  10. package/dist/component/types.d.ts.map +1 -1
  11. package/dist/component-BEQgt5hl.js +600 -0
  12. package/dist/component-BEQgt5hl.js.map +1 -0
  13. package/dist/component.es.mjs +7 -6
  14. package/dist/config-DRmZZno3.js.map +1 -1
  15. package/dist/core-BGQJVw0-.js +35 -0
  16. package/dist/core-BGQJVw0-.js.map +1 -0
  17. package/dist/{core-CK2Mfpf4.js → core-CCEabVHl.js} +2 -2
  18. package/dist/{core-CK2Mfpf4.js.map → core-CCEabVHl.js.map} +1 -1
  19. package/dist/core.es.mjs +1 -1
  20. package/dist/effect-AFRW_Plg.js +84 -0
  21. package/dist/effect-AFRW_Plg.js.map +1 -0
  22. package/dist/full.d.ts +4 -4
  23. package/dist/full.d.ts.map +1 -1
  24. package/dist/full.es.mjs +98 -94
  25. package/dist/full.iife.js +14 -14
  26. package/dist/full.iife.js.map +1 -1
  27. package/dist/full.umd.js +14 -14
  28. package/dist/full.umd.js.map +1 -1
  29. package/dist/index.es.mjs +143 -139
  30. package/dist/{motion-C5DRdPnO.js → motion-D9TcHxOF.js} +1 -1
  31. package/dist/{motion-C5DRdPnO.js.map → motion-D9TcHxOF.js.map} +1 -1
  32. package/dist/motion.es.mjs +1 -1
  33. package/dist/{platform-B7JhGBc7.js → platform-Dr9b6fsq.js} +21 -20
  34. package/dist/platform-Dr9b6fsq.js.map +1 -0
  35. package/dist/platform.es.mjs +1 -1
  36. package/dist/{reactive-BDya-ia8.js → reactive-DSkct0dO.js} +51 -50
  37. package/dist/reactive-DSkct0dO.js.map +1 -0
  38. package/dist/reactive.es.mjs +19 -17
  39. package/dist/{router-CijiICxt.js → router-CbDhl8rS.js} +3 -3
  40. package/dist/{router-CijiICxt.js.map → router-CbDhl8rS.js.map} +1 -1
  41. package/dist/router.es.mjs +1 -1
  42. package/dist/{sanitize-jyJ2ryE2.js → sanitize-Bs2dkMby.js} +94 -83
  43. package/dist/sanitize-Bs2dkMby.js.map +1 -0
  44. package/dist/security/index.d.ts +4 -2
  45. package/dist/security/index.d.ts.map +1 -1
  46. package/dist/security/sanitize.d.ts +4 -1
  47. package/dist/security/sanitize.d.ts.map +1 -1
  48. package/dist/security/trusted-html.d.ts +53 -0
  49. package/dist/security/trusted-html.d.ts.map +1 -0
  50. package/dist/security.es.mjs +10 -9
  51. package/dist/store/define-store.d.ts +1 -1
  52. package/dist/store/define-store.d.ts.map +1 -1
  53. package/dist/store/mapping.d.ts +1 -1
  54. package/dist/store/mapping.d.ts.map +1 -1
  55. package/dist/store/persisted.d.ts +1 -1
  56. package/dist/store/persisted.d.ts.map +1 -1
  57. package/dist/store/types.d.ts +2 -2
  58. package/dist/store/types.d.ts.map +1 -1
  59. package/dist/store/watch.d.ts +1 -1
  60. package/dist/store/watch.d.ts.map +1 -1
  61. package/dist/{store-CPK9E62U.js → store-BwDvI45q.js} +49 -48
  62. package/dist/{store-CPK9E62U.js.map → store-BwDvI45q.js.map} +1 -1
  63. package/dist/store.es.mjs +1 -1
  64. package/dist/storybook/index.d.ts +37 -0
  65. package/dist/storybook/index.d.ts.map +1 -0
  66. package/dist/storybook.es.mjs +151 -0
  67. package/dist/storybook.es.mjs.map +1 -0
  68. package/dist/untrack-B0rVscTc.js +7 -0
  69. package/dist/untrack-B0rVscTc.js.map +1 -0
  70. package/dist/{view-Cdi0g-qo.js → view-C70lA3vf.js} +29 -28
  71. package/dist/{view-Cdi0g-qo.js.map → view-C70lA3vf.js.map} +1 -1
  72. package/dist/view.es.mjs +9 -8
  73. package/package.json +141 -136
  74. package/src/component/component.ts +259 -54
  75. package/src/component/html.ts +153 -53
  76. package/src/component/index.ts +10 -2
  77. package/src/component/library.ts +42 -28
  78. package/src/component/types.ts +184 -19
  79. package/src/full.ts +8 -2
  80. package/src/motion/transition.ts +97 -97
  81. package/src/motion/types.ts +208 -208
  82. package/src/platform/announcer.ts +208 -208
  83. package/src/platform/config.ts +163 -163
  84. package/src/platform/cookies.ts +165 -165
  85. package/src/platform/index.ts +39 -39
  86. package/src/platform/meta.ts +168 -168
  87. package/src/reactive/async-data.ts +486 -486
  88. package/src/reactive/index.ts +37 -37
  89. package/src/reactive/signal.ts +29 -29
  90. package/src/security/constants.ts +211 -211
  91. package/src/security/index.ts +17 -10
  92. package/src/security/sanitize.ts +70 -66
  93. package/src/security/trusted-html.ts +71 -0
  94. package/src/store/define-store.ts +49 -48
  95. package/src/store/mapping.ts +74 -73
  96. package/src/store/persisted.ts +62 -61
  97. package/src/store/types.ts +92 -94
  98. package/src/store/watch.ts +53 -52
  99. package/src/storybook/index.ts +479 -0
  100. package/dist/component-CY5MVoYN.js +0 -531
  101. package/dist/component-CY5MVoYN.js.map +0 -1
  102. package/dist/core-DPdbItcq.js +0 -112
  103. package/dist/core-DPdbItcq.js.map +0 -1
  104. package/dist/platform-B7JhGBc7.js.map +0 -1
  105. package/dist/reactive-BDya-ia8.js.map +0 -1
  106. package/dist/sanitize-jyJ2ryE2.js.map +0 -1
@@ -1,163 +1,163 @@
1
- /**
2
- * Global bQuery configuration helpers.
3
- *
4
- * @module bquery/platform
5
- */
6
-
7
- import { isPlainObject, merge } from '../core/utils/object';
8
-
9
- /** Supported response parsing strategies for fetch composables. */
10
- export type BqueryFetchParseAs = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData' | 'response';
11
-
12
- /** Global fetch defaults used by useFetch(). */
13
- export interface BqueryFetchConfig {
14
- /** Optional base URL prepended to relative request URLs. */
15
- baseUrl?: string;
16
- /** Default request headers. */
17
- headers?: HeadersInit;
18
- /** Default response parser. */
19
- parseAs?: BqueryFetchParseAs;
20
- }
21
-
22
- /** Global cookie defaults used by useCookie(). */
23
- export interface BqueryCookieConfig {
24
- /** Default cookie path. */
25
- path?: string;
26
- /** Default SameSite mode. */
27
- sameSite?: 'Strict' | 'Lax' | 'None';
28
- /** Whether cookies should be marked secure by default. */
29
- secure?: boolean;
30
- }
31
-
32
- /** Global announcer defaults used by useAnnouncer(). */
33
- export interface BqueryAnnouncerConfig {
34
- /** Default politeness level. */
35
- politeness?: 'polite' | 'assertive';
36
- /** Whether announcements should be treated atomically. */
37
- atomic?: boolean;
38
- /** Delay before writing the message into the live region. */
39
- delay?: number;
40
- /** Delay after which the live region is cleared automatically. */
41
- clearDelay?: number;
42
- }
43
-
44
- /** Global page meta defaults used by definePageMeta(). */
45
- export interface BqueryPageMetaConfig {
46
- /** Optional title template function. */
47
- titleTemplate?: (title: string) => string;
48
- }
49
-
50
- /** Global motion defaults used by transition(). */
51
- export interface BqueryTransitionConfig {
52
- /** Skip transitions when reduced motion is preferred. */
53
- skipOnReducedMotion?: boolean;
54
- /** Classes applied to the root element during transitions. */
55
- classes?: string[];
56
- /** Transition type identifiers added when supported by the browser. */
57
- types?: string[];
58
- }
59
-
60
- /** Global default component library configuration. */
61
- export interface BqueryComponentLibraryConfig {
62
- /** Prefix used by registerDefaultComponents(). */
63
- prefix?: string;
64
- }
65
-
66
- /** Complete global bQuery configuration object. */
67
- export interface BqueryConfig {
68
- /** Fetch composable defaults. */
69
- fetch?: BqueryFetchConfig;
70
- /** Cookie composable defaults. */
71
- cookies?: BqueryCookieConfig;
72
- /** Announcer composable defaults. */
73
- announcer?: BqueryAnnouncerConfig;
74
- /** Page metadata defaults. */
75
- pageMeta?: BqueryPageMetaConfig;
76
- /** View transition defaults. */
77
- transitions?: BqueryTransitionConfig;
78
- /** Default component library options. */
79
- components?: BqueryComponentLibraryConfig;
80
- }
81
-
82
- const defaultConfig: BqueryConfig = {
83
- fetch: {
84
- headers: {},
85
- parseAs: 'json',
86
- },
87
- cookies: {
88
- path: '/',
89
- sameSite: 'Lax',
90
- secure: false,
91
- },
92
- announcer: {
93
- politeness: 'polite',
94
- atomic: true,
95
- delay: 16,
96
- clearDelay: 1000,
97
- },
98
- pageMeta: {},
99
- transitions: {
100
- skipOnReducedMotion: false,
101
- classes: [],
102
- types: [],
103
- },
104
- components: {
105
- prefix: 'bq',
106
- },
107
- };
108
-
109
- const cloneConfigValue = <T>(value: T): T => {
110
- if (typeof Headers !== 'undefined' && value instanceof Headers) {
111
- return new Headers(value) as T;
112
- }
113
-
114
- if (Array.isArray(value)) {
115
- return value.map((entry) => cloneConfigValue(entry)) as T;
116
- }
117
-
118
- if (isPlainObject(value)) {
119
- const result: Record<string, unknown> = {};
120
- for (const [key, entry] of Object.entries(value)) {
121
- result[key] = cloneConfigValue(entry);
122
- }
123
- return result as T;
124
- }
125
-
126
- return value;
127
- };
128
-
129
- let currentConfig: BqueryConfig = cloneConfigValue(defaultConfig);
130
-
131
- /**
132
- * Define or extend the global bQuery configuration.
133
- *
134
- * @param config - Partial configuration values to merge into the current config
135
- * @returns The resolved configuration after merging
136
- *
137
- * @example
138
- * ```ts
139
- * defineBqueryConfig({
140
- * fetch: { baseUrl: 'https://api.example.com' },
141
- * components: { prefix: 'ui' },
142
- * });
143
- * ```
144
- */
145
- export const defineBqueryConfig = (config: BqueryConfig): BqueryConfig => {
146
- currentConfig = cloneConfigValue(
147
- merge(
148
- defaultConfig as Record<string, unknown>,
149
- currentConfig as Record<string, unknown>,
150
- config as Record<string, unknown>
151
- ) as BqueryConfig
152
- );
153
- return getBqueryConfig();
154
- };
155
-
156
- /**
157
- * Get the currently resolved bQuery configuration.
158
- *
159
- * @returns A cloned snapshot of the active configuration
160
- */
161
- export const getBqueryConfig = (): BqueryConfig => {
162
- return cloneConfigValue(currentConfig);
163
- };
1
+ /**
2
+ * Global bQuery configuration helpers.
3
+ *
4
+ * @module bquery/platform
5
+ */
6
+
7
+ import { isPlainObject, merge } from '../core/utils/object';
8
+
9
+ /** Supported response parsing strategies for fetch composables. */
10
+ export type BqueryFetchParseAs = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData' | 'response';
11
+
12
+ /** Global fetch defaults used by useFetch(). */
13
+ export interface BqueryFetchConfig {
14
+ /** Optional base URL prepended to relative request URLs. */
15
+ baseUrl?: string;
16
+ /** Default request headers. */
17
+ headers?: HeadersInit;
18
+ /** Default response parser. */
19
+ parseAs?: BqueryFetchParseAs;
20
+ }
21
+
22
+ /** Global cookie defaults used by useCookie(). */
23
+ export interface BqueryCookieConfig {
24
+ /** Default cookie path. */
25
+ path?: string;
26
+ /** Default SameSite mode. */
27
+ sameSite?: 'Strict' | 'Lax' | 'None';
28
+ /** Whether cookies should be marked secure by default. */
29
+ secure?: boolean;
30
+ }
31
+
32
+ /** Global announcer defaults used by useAnnouncer(). */
33
+ export interface BqueryAnnouncerConfig {
34
+ /** Default politeness level. */
35
+ politeness?: 'polite' | 'assertive';
36
+ /** Whether announcements should be treated atomically. */
37
+ atomic?: boolean;
38
+ /** Delay before writing the message into the live region. */
39
+ delay?: number;
40
+ /** Delay after which the live region is cleared automatically. */
41
+ clearDelay?: number;
42
+ }
43
+
44
+ /** Global page meta defaults used by definePageMeta(). */
45
+ export interface BqueryPageMetaConfig {
46
+ /** Optional title template function. */
47
+ titleTemplate?: (title: string) => string;
48
+ }
49
+
50
+ /** Global motion defaults used by transition(). */
51
+ export interface BqueryTransitionConfig {
52
+ /** Skip transitions when reduced motion is preferred. */
53
+ skipOnReducedMotion?: boolean;
54
+ /** Classes applied to the root element during transitions. */
55
+ classes?: string[];
56
+ /** Transition type identifiers added when supported by the browser. */
57
+ types?: string[];
58
+ }
59
+
60
+ /** Global default component library configuration. */
61
+ export interface BqueryComponentLibraryConfig {
62
+ /** Prefix used by registerDefaultComponents(). */
63
+ prefix?: string;
64
+ }
65
+
66
+ /** Complete global bQuery configuration object. */
67
+ export interface BqueryConfig {
68
+ /** Fetch composable defaults. */
69
+ fetch?: BqueryFetchConfig;
70
+ /** Cookie composable defaults. */
71
+ cookies?: BqueryCookieConfig;
72
+ /** Announcer composable defaults. */
73
+ announcer?: BqueryAnnouncerConfig;
74
+ /** Page metadata defaults. */
75
+ pageMeta?: BqueryPageMetaConfig;
76
+ /** View transition defaults. */
77
+ transitions?: BqueryTransitionConfig;
78
+ /** Default component library options. */
79
+ components?: BqueryComponentLibraryConfig;
80
+ }
81
+
82
+ const defaultConfig: BqueryConfig = {
83
+ fetch: {
84
+ headers: {},
85
+ parseAs: 'json',
86
+ },
87
+ cookies: {
88
+ path: '/',
89
+ sameSite: 'Lax',
90
+ secure: false,
91
+ },
92
+ announcer: {
93
+ politeness: 'polite',
94
+ atomic: true,
95
+ delay: 16,
96
+ clearDelay: 1000,
97
+ },
98
+ pageMeta: {},
99
+ transitions: {
100
+ skipOnReducedMotion: false,
101
+ classes: [],
102
+ types: [],
103
+ },
104
+ components: {
105
+ prefix: 'bq',
106
+ },
107
+ };
108
+
109
+ const cloneConfigValue = <T>(value: T): T => {
110
+ if (typeof Headers !== 'undefined' && value instanceof Headers) {
111
+ return new Headers(value) as T;
112
+ }
113
+
114
+ if (Array.isArray(value)) {
115
+ return value.map((entry) => cloneConfigValue(entry)) as T;
116
+ }
117
+
118
+ if (isPlainObject(value)) {
119
+ const result: Record<string, unknown> = {};
120
+ for (const [key, entry] of Object.entries(value)) {
121
+ result[key] = cloneConfigValue(entry);
122
+ }
123
+ return result as T;
124
+ }
125
+
126
+ return value;
127
+ };
128
+
129
+ let currentConfig: BqueryConfig = cloneConfigValue(defaultConfig);
130
+
131
+ /**
132
+ * Define or extend the global bQuery configuration.
133
+ *
134
+ * @param config - Partial configuration values to merge into the current config
135
+ * @returns The resolved configuration after merging
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * defineBqueryConfig({
140
+ * fetch: { baseUrl: 'https://api.example.com' },
141
+ * components: { prefix: 'ui' },
142
+ * });
143
+ * ```
144
+ */
145
+ export const defineBqueryConfig = (config: BqueryConfig): BqueryConfig => {
146
+ currentConfig = cloneConfigValue(
147
+ merge(
148
+ defaultConfig as Record<string, unknown>,
149
+ currentConfig as Record<string, unknown>,
150
+ config as Record<string, unknown>
151
+ ) as BqueryConfig
152
+ );
153
+ return getBqueryConfig();
154
+ };
155
+
156
+ /**
157
+ * Get the currently resolved bQuery configuration.
158
+ *
159
+ * @returns A cloned snapshot of the active configuration
160
+ */
161
+ export const getBqueryConfig = (): BqueryConfig => {
162
+ return cloneConfigValue(currentConfig);
163
+ };
@@ -1,165 +1,165 @@
1
- /**
2
- * Reactive cookie helpers.
3
- *
4
- * @module bquery/platform
5
- */
6
-
7
- import { effect, signal, type Signal } from '../reactive/signal';
8
- import { getBqueryConfig } from './config';
9
-
10
- /** Options for useCookie(). */
11
- export interface UseCookieOptions<T> {
12
- /** Default value when the cookie is not present. */
13
- defaultValue?: T;
14
- /** Cookie path. Defaults to the global config or `/`. */
15
- path?: string;
16
- /** Optional cookie domain. */
17
- domain?: string;
18
- /** Cookie SameSite attribute. */
19
- sameSite?: 'Strict' | 'Lax' | 'None';
20
- /** Whether the cookie should be marked secure. */
21
- secure?: boolean;
22
- /** Cookie expiry date. */
23
- expires?: Date;
24
- /** Cookie max-age in seconds. */
25
- maxAge?: number;
26
- /** Automatically persist signal updates back to document.cookie. */
27
- watch?: boolean;
28
- /** Serialize a value before writing it into the cookie. */
29
- serialize?: (value: T) => string;
30
- /** Deserialize a cookie string into a typed value. */
31
- deserialize?: (value: string) => T;
32
- }
33
-
34
- const readCookie = (name: string): string | null => {
35
- if (typeof document === 'undefined') return null;
36
-
37
- const prefix = `${encodeURIComponent(name)}=`;
38
- const segments = document.cookie ? document.cookie.split(';') : [];
39
-
40
- for (const segment of segments) {
41
- const normalizedSegment = segment.trim();
42
- if (normalizedSegment.startsWith(prefix)) {
43
- const rawValue = normalizedSegment.slice(prefix.length);
44
- try {
45
- return decodeURIComponent(rawValue);
46
- } catch {
47
- return rawValue;
48
- }
49
- }
50
- }
51
-
52
- return null;
53
- };
54
-
55
- const requiresJsonParsing = (value: string): boolean => {
56
- const normalized = value.trim();
57
- return normalized.startsWith('{') || normalized.startsWith('[') || normalized.startsWith('"');
58
- };
59
-
60
- const removeCookie = (
61
- name: string,
62
- options: Pick<UseCookieOptions<unknown>, 'path' | 'domain' | 'sameSite' | 'secure'>
63
- ): void => {
64
- if (typeof document === 'undefined') return;
65
-
66
- const segments = [`${encodeURIComponent(name)}=`, 'Expires=Thu, 01 Jan 1970 00:00:00 GMT'];
67
-
68
- if (options.path) segments.push(`Path=${options.path}`);
69
- if (options.domain) segments.push(`Domain=${options.domain}`);
70
- if (options.sameSite) segments.push(`SameSite=${options.sameSite}`);
71
- if (options.secure) segments.push('Secure');
72
-
73
- document.cookie = segments.join('; ');
74
- };
75
-
76
- const writeCookie = <T>(name: string, value: T, options: UseCookieOptions<T>): void => {
77
- if (typeof document === 'undefined') return;
78
-
79
- const serialized = options.serialize
80
- ? options.serialize(value)
81
- : typeof value === 'string'
82
- ? value
83
- : JSON.stringify(value);
84
-
85
- const segments = [`${encodeURIComponent(name)}=${encodeURIComponent(serialized)}`];
86
-
87
- if (options.path) segments.push(`Path=${options.path}`);
88
- if (options.domain) segments.push(`Domain=${options.domain}`);
89
- if (typeof options.maxAge === 'number') segments.push(`Max-Age=${options.maxAge}`);
90
- if (options.expires) segments.push(`Expires=${options.expires.toUTCString()}`);
91
- if (options.sameSite) segments.push(`SameSite=${options.sameSite}`);
92
- if (options.secure) segments.push('Secure');
93
-
94
- document.cookie = segments.join('; ');
95
- };
96
-
97
- /**
98
- * Create a reactive cookie signal.
99
- *
100
- * @template T - Cookie value type
101
- * @param name - Cookie name
102
- * @param options - Read/write configuration for the cookie
103
- * @returns Reactive signal representing the cookie value
104
- *
105
- * @example
106
- * ```ts
107
- * const theme = useCookie('theme', { defaultValue: 'light' });
108
- * theme.value = 'dark';
109
- * ```
110
- */
111
- export const useCookie = <T>(name: string, options: UseCookieOptions<T> = {}): Signal<T | null> => {
112
- const cookieConfig = getBqueryConfig().cookies;
113
- const resolvedOptions: UseCookieOptions<T> = {
114
- path: cookieConfig?.path ?? '/',
115
- sameSite: cookieConfig?.sameSite ?? 'Lax',
116
- secure: cookieConfig?.secure ?? false,
117
- watch: true,
118
- ...options,
119
- };
120
-
121
- if (resolvedOptions.sameSite === 'None') {
122
- resolvedOptions.secure = true;
123
- }
124
-
125
- const raw = readCookie(name);
126
- let initialValue = (resolvedOptions.defaultValue ?? null) as T | null;
127
-
128
- if (raw !== null) {
129
- try {
130
- initialValue = resolvedOptions.deserialize
131
- ? resolvedOptions.deserialize(raw)
132
- : requiresJsonParsing(raw)
133
- ? (JSON.parse(raw) as T)
134
- : ((raw as T) ?? initialValue);
135
- } catch (error) {
136
- console.warn(`bQuery: Failed to deserialize cookie "${name}", using raw string value`, error);
137
- initialValue = (raw as T) ?? initialValue;
138
- }
139
- }
140
-
141
- const cookie = signal<T | null>(initialValue);
142
-
143
- if (typeof document === 'undefined' || resolvedOptions.watch === false) {
144
- return cookie;
145
- }
146
-
147
- let initialized = false;
148
- effect(() => {
149
- const nextValue = cookie.value;
150
-
151
- if (!initialized) {
152
- initialized = true;
153
- return;
154
- }
155
-
156
- if (nextValue == null) {
157
- removeCookie(name, resolvedOptions);
158
- return;
159
- }
160
-
161
- writeCookie(name, nextValue, resolvedOptions);
162
- });
163
-
164
- return cookie;
165
- };
1
+ /**
2
+ * Reactive cookie helpers.
3
+ *
4
+ * @module bquery/platform
5
+ */
6
+
7
+ import { effect, signal, type Signal } from '../reactive/signal';
8
+ import { getBqueryConfig } from './config';
9
+
10
+ /** Options for useCookie(). */
11
+ export interface UseCookieOptions<T> {
12
+ /** Default value when the cookie is not present. */
13
+ defaultValue?: T;
14
+ /** Cookie path. Defaults to the global config or `/`. */
15
+ path?: string;
16
+ /** Optional cookie domain. */
17
+ domain?: string;
18
+ /** Cookie SameSite attribute. */
19
+ sameSite?: 'Strict' | 'Lax' | 'None';
20
+ /** Whether the cookie should be marked secure. */
21
+ secure?: boolean;
22
+ /** Cookie expiry date. */
23
+ expires?: Date;
24
+ /** Cookie max-age in seconds. */
25
+ maxAge?: number;
26
+ /** Automatically persist signal updates back to document.cookie. */
27
+ watch?: boolean;
28
+ /** Serialize a value before writing it into the cookie. */
29
+ serialize?: (value: T) => string;
30
+ /** Deserialize a cookie string into a typed value. */
31
+ deserialize?: (value: string) => T;
32
+ }
33
+
34
+ const readCookie = (name: string): string | null => {
35
+ if (typeof document === 'undefined') return null;
36
+
37
+ const prefix = `${encodeURIComponent(name)}=`;
38
+ const segments = document.cookie ? document.cookie.split(';') : [];
39
+
40
+ for (const segment of segments) {
41
+ const normalizedSegment = segment.trim();
42
+ if (normalizedSegment.startsWith(prefix)) {
43
+ const rawValue = normalizedSegment.slice(prefix.length);
44
+ try {
45
+ return decodeURIComponent(rawValue);
46
+ } catch {
47
+ return rawValue;
48
+ }
49
+ }
50
+ }
51
+
52
+ return null;
53
+ };
54
+
55
+ const requiresJsonParsing = (value: string): boolean => {
56
+ const normalized = value.trim();
57
+ return normalized.startsWith('{') || normalized.startsWith('[') || normalized.startsWith('"');
58
+ };
59
+
60
+ const removeCookie = (
61
+ name: string,
62
+ options: Pick<UseCookieOptions<unknown>, 'path' | 'domain' | 'sameSite' | 'secure'>
63
+ ): void => {
64
+ if (typeof document === 'undefined') return;
65
+
66
+ const segments = [`${encodeURIComponent(name)}=`, 'Expires=Thu, 01 Jan 1970 00:00:00 GMT'];
67
+
68
+ if (options.path) segments.push(`Path=${options.path}`);
69
+ if (options.domain) segments.push(`Domain=${options.domain}`);
70
+ if (options.sameSite) segments.push(`SameSite=${options.sameSite}`);
71
+ if (options.secure) segments.push('Secure');
72
+
73
+ document.cookie = segments.join('; ');
74
+ };
75
+
76
+ const writeCookie = <T>(name: string, value: T, options: UseCookieOptions<T>): void => {
77
+ if (typeof document === 'undefined') return;
78
+
79
+ const serialized = options.serialize
80
+ ? options.serialize(value)
81
+ : typeof value === 'string'
82
+ ? value
83
+ : JSON.stringify(value);
84
+
85
+ const segments = [`${encodeURIComponent(name)}=${encodeURIComponent(serialized)}`];
86
+
87
+ if (options.path) segments.push(`Path=${options.path}`);
88
+ if (options.domain) segments.push(`Domain=${options.domain}`);
89
+ if (typeof options.maxAge === 'number') segments.push(`Max-Age=${options.maxAge}`);
90
+ if (options.expires) segments.push(`Expires=${options.expires.toUTCString()}`);
91
+ if (options.sameSite) segments.push(`SameSite=${options.sameSite}`);
92
+ if (options.secure) segments.push('Secure');
93
+
94
+ document.cookie = segments.join('; ');
95
+ };
96
+
97
+ /**
98
+ * Create a reactive cookie signal.
99
+ *
100
+ * @template T - Cookie value type
101
+ * @param name - Cookie name
102
+ * @param options - Read/write configuration for the cookie
103
+ * @returns Reactive signal representing the cookie value
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * const theme = useCookie('theme', { defaultValue: 'light' });
108
+ * theme.value = 'dark';
109
+ * ```
110
+ */
111
+ export const useCookie = <T>(name: string, options: UseCookieOptions<T> = {}): Signal<T | null> => {
112
+ const cookieConfig = getBqueryConfig().cookies;
113
+ const resolvedOptions: UseCookieOptions<T> = {
114
+ path: cookieConfig?.path ?? '/',
115
+ sameSite: cookieConfig?.sameSite ?? 'Lax',
116
+ secure: cookieConfig?.secure ?? false,
117
+ watch: true,
118
+ ...options,
119
+ };
120
+
121
+ if (resolvedOptions.sameSite === 'None') {
122
+ resolvedOptions.secure = true;
123
+ }
124
+
125
+ const raw = readCookie(name);
126
+ let initialValue = (resolvedOptions.defaultValue ?? null) as T | null;
127
+
128
+ if (raw !== null) {
129
+ try {
130
+ initialValue = resolvedOptions.deserialize
131
+ ? resolvedOptions.deserialize(raw)
132
+ : requiresJsonParsing(raw)
133
+ ? (JSON.parse(raw) as T)
134
+ : ((raw as T) ?? initialValue);
135
+ } catch (error) {
136
+ console.warn(`bQuery: Failed to deserialize cookie "${name}", using raw string value`, error);
137
+ initialValue = (raw as T) ?? initialValue;
138
+ }
139
+ }
140
+
141
+ const cookie = signal<T | null>(initialValue);
142
+
143
+ if (typeof document === 'undefined' || resolvedOptions.watch === false) {
144
+ return cookie;
145
+ }
146
+
147
+ let initialized = false;
148
+ effect(() => {
149
+ const nextValue = cookie.value;
150
+
151
+ if (!initialized) {
152
+ initialized = true;
153
+ return;
154
+ }
155
+
156
+ if (nextValue == null) {
157
+ removeCookie(name, resolvedOptions);
158
+ return;
159
+ }
160
+
161
+ writeCookie(name, nextValue, resolvedOptions);
162
+ });
163
+
164
+ return cookie;
165
+ };