@sygnl/identity-manager 1.0.1

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/dist/index.cjs ADDED
@@ -0,0 +1,252 @@
1
+ 'use strict';
2
+
3
+ // src/types.ts
4
+ var DEFAULT_OPTIONS = {
5
+ anonymousIdCookieName: "_stid",
6
+ sessionIdCookieName: "_session_id",
7
+ anonymousIdTTL: 365,
8
+ sessionIdTTL: 1,
9
+ cookieDomain: void 0,
10
+ cookiePath: "/",
11
+ cookieSameSite: "Lax",
12
+ cookieSecure: true,
13
+ useLocalStorage: true,
14
+ debug: false
15
+ };
16
+
17
+ // src/IdentityManager.ts
18
+ var IdentityManager = class {
19
+ /**
20
+ * Create a new IdentityManager instance
21
+ * @param options - Configuration options (optional)
22
+ */
23
+ constructor(options) {
24
+ this.options = { ...DEFAULT_OPTIONS, ...options };
25
+ this.log("IdentityManager initialized", this.options);
26
+ }
27
+ /**
28
+ * Configure or update options at runtime
29
+ * @param options - Partial options to merge with existing configuration
30
+ */
31
+ configure(options) {
32
+ this.options = { ...this.options, ...options };
33
+ this.log("Configuration updated", this.options);
34
+ }
35
+ // ==================== Cookie Methods ====================
36
+ /**
37
+ * Get a cookie value by name
38
+ * @param name - Cookie name
39
+ * @returns Cookie value or null if not found
40
+ */
41
+ getCookie(name) {
42
+ if (typeof document === "undefined") {
43
+ this.log("getCookie: document is undefined (SSR context)", { name });
44
+ return null;
45
+ }
46
+ try {
47
+ const cookies = document.cookie.split(";");
48
+ const target = name + "=";
49
+ for (let i = 0; i < cookies.length; i++) {
50
+ const c = cookies[i].trim();
51
+ if (c.indexOf(target) === 0) {
52
+ const value = c.substring(target.length);
53
+ this.log("getCookie: hit", { name, value });
54
+ return value;
55
+ }
56
+ }
57
+ this.log("getCookie: miss", { name });
58
+ return null;
59
+ } catch (error) {
60
+ this.log("getCookie: error", { name, error });
61
+ return null;
62
+ }
63
+ }
64
+ /**
65
+ * Set a cookie with configurable options
66
+ * @param name - Cookie name
67
+ * @param value - Cookie value
68
+ * @param days - Time-to-live in days
69
+ */
70
+ setCookie(name, value, days) {
71
+ if (typeof document === "undefined") {
72
+ this.log("setCookie: document is undefined (SSR context)", { name });
73
+ return;
74
+ }
75
+ try {
76
+ const expires = /* @__PURE__ */ new Date();
77
+ expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1e3);
78
+ let cookieString = `${name}=${value}; expires=${expires.toUTCString()}; path=${this.options.cookiePath}; SameSite=${this.options.cookieSameSite}`;
79
+ if (this.options.cookieSecure) {
80
+ cookieString += "; Secure";
81
+ }
82
+ if (this.options.cookieDomain) {
83
+ cookieString += `; Domain=${this.options.cookieDomain}`;
84
+ }
85
+ document.cookie = cookieString;
86
+ this.log("setCookie: success", {
87
+ name,
88
+ value,
89
+ expires: expires.toISOString(),
90
+ ttlSeconds: days * 86400
91
+ });
92
+ } catch (error) {
93
+ this.log("setCookie: error", { name, error });
94
+ }
95
+ }
96
+ // ==================== localStorage Methods ====================
97
+ /**
98
+ * Get a value from localStorage
99
+ * @param key - Storage key
100
+ * @returns Stored value or null
101
+ */
102
+ getLocalStorage(key) {
103
+ if (!this.options.useLocalStorage) {
104
+ return null;
105
+ }
106
+ if (typeof localStorage === "undefined") {
107
+ this.log("getLocalStorage: localStorage is undefined (SSR context)", { key });
108
+ return null;
109
+ }
110
+ try {
111
+ const value = localStorage.getItem(key);
112
+ this.log("getLocalStorage: " + (value ? "hit" : "miss"), { key, value });
113
+ return value;
114
+ } catch (error) {
115
+ this.log("getLocalStorage: error (private browsing?)", { key, error });
116
+ return null;
117
+ }
118
+ }
119
+ /**
120
+ * Set a value in localStorage
121
+ * @param key - Storage key
122
+ * @param value - Value to store
123
+ */
124
+ setLocalStorage(key, value) {
125
+ if (!this.options.useLocalStorage) {
126
+ return;
127
+ }
128
+ if (typeof localStorage === "undefined") {
129
+ this.log("setLocalStorage: localStorage is undefined (SSR context)", { key });
130
+ return;
131
+ }
132
+ try {
133
+ localStorage.setItem(key, value);
134
+ this.log("setLocalStorage: success", { key, value });
135
+ } catch (error) {
136
+ this.log("setLocalStorage: error (quota exceeded?)", { key, error });
137
+ }
138
+ }
139
+ // ==================== UUID Generation ====================
140
+ /**
141
+ * Generate a UUID v4
142
+ * Uses crypto.randomUUID() if available, falls back to Math.random()
143
+ * @returns UUID string
144
+ */
145
+ generateUUID() {
146
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
147
+ try {
148
+ const uuid2 = crypto.randomUUID();
149
+ this.log("generateUUID: crypto.randomUUID()", { uuid: uuid2 });
150
+ return uuid2;
151
+ } catch (error) {
152
+ this.log("generateUUID: crypto.randomUUID() failed, falling back", { error });
153
+ }
154
+ }
155
+ const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
156
+ const r = Math.random() * 16 | 0;
157
+ const v = c === "x" ? r : r & 3 | 8;
158
+ return v.toString(16);
159
+ });
160
+ this.log("generateUUID: Math.random() fallback", { uuid });
161
+ return uuid;
162
+ }
163
+ // ==================== Anonymous ID Methods ====================
164
+ /**
165
+ * Get the current anonymous ID without creating a new one
166
+ * @returns Anonymous ID or null if not found
167
+ */
168
+ getAnonymousId() {
169
+ const cookieValue = this.getCookie(this.options.anonymousIdCookieName);
170
+ if (cookieValue) {
171
+ return cookieValue;
172
+ }
173
+ const storageValue = this.getLocalStorage(this.options.anonymousIdCookieName);
174
+ if (storageValue) {
175
+ this.setCookie(
176
+ this.options.anonymousIdCookieName,
177
+ storageValue,
178
+ this.options.anonymousIdTTL
179
+ );
180
+ return storageValue;
181
+ }
182
+ return null;
183
+ }
184
+ /**
185
+ * Get or create an anonymous ID
186
+ * @returns Anonymous ID (always returns a value)
187
+ */
188
+ ensureAnonymousId() {
189
+ let anonymousId = this.getCookie(this.options.anonymousIdCookieName);
190
+ if (!anonymousId) {
191
+ anonymousId = this.getLocalStorage(this.options.anonymousIdCookieName);
192
+ if (!anonymousId) {
193
+ anonymousId = this.generateUUID();
194
+ this.log("ensureAnonymousId: generated new ID", { anonymousId });
195
+ } else {
196
+ this.log("ensureAnonymousId: restored from localStorage", { anonymousId });
197
+ }
198
+ this.setCookie(
199
+ this.options.anonymousIdCookieName,
200
+ anonymousId,
201
+ this.options.anonymousIdTTL
202
+ );
203
+ this.setLocalStorage(this.options.anonymousIdCookieName, anonymousId);
204
+ } else {
205
+ this.log("ensureAnonymousId: found in cookie", { anonymousId });
206
+ }
207
+ return anonymousId;
208
+ }
209
+ // ==================== Session ID Methods ====================
210
+ /**
211
+ * Get the current session ID without creating a new one
212
+ * @returns Session ID or null if not found
213
+ */
214
+ getSessionId() {
215
+ return this.getCookie(this.options.sessionIdCookieName);
216
+ }
217
+ /**
218
+ * Get or create a session ID
219
+ * @returns Session ID (always returns a value)
220
+ */
221
+ ensureSessionId() {
222
+ let sessionId = this.getCookie(this.options.sessionIdCookieName);
223
+ if (!sessionId) {
224
+ sessionId = `sess_${Date.now()}`;
225
+ this.setCookie(
226
+ this.options.sessionIdCookieName,
227
+ sessionId,
228
+ this.options.sessionIdTTL
229
+ );
230
+ this.log("ensureSessionId: generated new session", { sessionId });
231
+ } else {
232
+ this.log("ensureSessionId: found existing session", { sessionId });
233
+ }
234
+ return sessionId;
235
+ }
236
+ // ==================== Debug Logging ====================
237
+ /**
238
+ * Log debug messages to console if debug mode is enabled
239
+ * @param message - Log message
240
+ * @param data - Additional data to log
241
+ */
242
+ log(message, data) {
243
+ if (this.options.debug && typeof console !== "undefined") {
244
+ console.log(`[IdentityManager] ${message}`, data || "");
245
+ }
246
+ }
247
+ };
248
+
249
+ exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
250
+ exports.IdentityManager = IdentityManager;
251
+ //# sourceMappingURL=index.cjs.map
252
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/IdentityManager.ts"],"names":["uuid"],"mappings":";;;AAyEO,IAAM,eAAA,GAA0C;AAA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;AAAA;AAAA;AAAA;AAAA;AAAA,EASQ,GAAA,CAAI,SAAiB,IAAA,EAAsB;AACjD,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,KAAA,IAAS,OAAO,YAAY,WAAA,EAAa;AACxD,MAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,kBAAA,EAAqB,OAAO,CAAA,CAAA,EAAI,QAAQ,EAAE,CAAA;AAAA,IACxD;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Configuration options for IdentityManager\n */\nexport interface IdentityManagerOptions {\n /**\n * Cookie name for anonymous ID storage\n * @default '_stid'\n */\n anonymousIdCookieName: string;\n\n /**\n * Cookie name for session ID storage\n * @default '_session_id'\n */\n sessionIdCookieName: string;\n\n /**\n * Anonymous ID time-to-live in days\n * @default 365\n */\n anonymousIdTTL: number;\n\n /**\n * Session ID time-to-live in days\n * @default 1\n */\n sessionIdTTL: number;\n\n /**\n * Cookie domain (optional, defaults to current domain)\n * Use '.example.com' for subdomain sharing\n */\n cookieDomain?: string;\n\n /**\n * Cookie path\n * @default '/'\n */\n cookiePath: string;\n\n /**\n * Cookie SameSite attribute\n * @default 'Lax'\n */\n cookieSameSite: 'Strict' | 'Lax' | 'None';\n\n /**\n * Cookie Secure flag (requires HTTPS)\n * @default true\n */\n cookieSecure: boolean;\n\n /**\n * Enable localStorage fallback when cookies fail\n * @default true\n */\n useLocalStorage: boolean;\n\n /**\n * Enable debug logging to console\n * @default false\n */\n debug: boolean;\n}\n\n/**\n * Partial configuration for runtime updates\n */\nexport type PartialIdentityManagerOptions = Partial<IdentityManagerOptions>;\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_OPTIONS: IdentityManagerOptions = {\n anonymousIdCookieName: '_stid',\n sessionIdCookieName: '_session_id',\n anonymousIdTTL: 365,\n sessionIdTTL: 1,\n cookieDomain: undefined,\n cookiePath: '/',\n cookieSameSite: 'Lax',\n cookieSecure: true,\n useLocalStorage: true,\n debug: false,\n};\n","import {\n IdentityManagerOptions,\n PartialIdentityManagerOptions,\n DEFAULT_OPTIONS,\n} from './types';\n\n/**\n * IdentityManager - Manages anonymous user identity and session tracking\n * \n * Features:\n * - Persistent anonymous ID with cookie + localStorage fallback\n * - Temporary session ID management\n * - Configurable TTL for both identity types\n * - SSR-safe (gracefully handles missing document/window)\n * - Zero dependencies\n * \n * @example\n * ```typescript\n * const identity = new IdentityManager({ debug: true });\n * const userId = identity.ensureAnonymousId();\n * const sessionId = identity.ensureSessionId();\n * ```\n */\nexport class IdentityManager {\n private options: IdentityManagerOptions;\n\n /**\n * Create a new IdentityManager instance\n * @param options - Configuration options (optional)\n */\n constructor(options?: PartialIdentityManagerOptions) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n this.log('IdentityManager initialized', this.options);\n }\n\n /**\n * Configure or update options at runtime\n * @param options - Partial options to merge with existing configuration\n */\n public configure(options: PartialIdentityManagerOptions): void {\n this.options = { ...this.options, ...options };\n this.log('Configuration updated', this.options);\n }\n\n // ==================== Cookie Methods ====================\n\n /**\n * Get a cookie value by name\n * @param name - Cookie name\n * @returns Cookie value or null if not found\n */\n public getCookie(name: string): string | null {\n // SSR safety check\n if (typeof document === 'undefined') {\n this.log('getCookie: document is undefined (SSR context)', { name });\n return null;\n }\n\n try {\n const cookies = document.cookie.split(';');\n const target = name + '=';\n \n for (let i = 0; i < cookies.length; i++) {\n const c = cookies[i].trim();\n if (c.indexOf(target) === 0) {\n const value = c.substring(target.length);\n this.log('getCookie: hit', { name, value });\n return value;\n }\n }\n \n this.log('getCookie: miss', { name });\n return null;\n } catch (error) {\n this.log('getCookie: error', { name, error });\n return null;\n }\n }\n\n /**\n * Set a cookie with configurable options\n * @param name - Cookie name\n * @param value - Cookie value\n * @param days - Time-to-live in days\n */\n public setCookie(name: string, value: string, days: number): void {\n // SSR safety check\n if (typeof document === 'undefined') {\n this.log('setCookie: document is undefined (SSR context)', { name });\n return;\n }\n\n try {\n const expires = new Date();\n expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);\n\n let cookieString = `${name}=${value}; expires=${expires.toUTCString()}; path=${this.options.cookiePath}; SameSite=${this.options.cookieSameSite}`;\n\n if (this.options.cookieSecure) {\n cookieString += '; Secure';\n }\n\n if (this.options.cookieDomain) {\n cookieString += `; Domain=${this.options.cookieDomain}`;\n }\n\n document.cookie = cookieString;\n\n this.log('setCookie: success', {\n name,\n value,\n expires: expires.toISOString(),\n ttlSeconds: days * 86400,\n });\n } catch (error) {\n this.log('setCookie: error', { name, error });\n }\n }\n\n // ==================== localStorage Methods ====================\n\n /**\n * Get a value from localStorage\n * @param key - Storage key\n * @returns Stored value or null\n */\n private getLocalStorage(key: string): string | null {\n if (!this.options.useLocalStorage) {\n return null;\n }\n\n // SSR safety check\n if (typeof localStorage === 'undefined') {\n this.log('getLocalStorage: localStorage is undefined (SSR context)', { key });\n return null;\n }\n\n try {\n const value = localStorage.getItem(key);\n this.log('getLocalStorage: ' + (value ? 'hit' : 'miss'), { key, value });\n return value;\n } catch (error) {\n this.log('getLocalStorage: error (private browsing?)', { key, error });\n return null;\n }\n }\n\n /**\n * Set a value in localStorage\n * @param key - Storage key\n * @param value - Value to store\n */\n private setLocalStorage(key: string, value: string): void {\n if (!this.options.useLocalStorage) {\n return;\n }\n\n // SSR safety check\n if (typeof localStorage === 'undefined') {\n this.log('setLocalStorage: localStorage is undefined (SSR context)', { key });\n return;\n }\n\n try {\n localStorage.setItem(key, value);\n this.log('setLocalStorage: success', { key, value });\n } catch (error) {\n this.log('setLocalStorage: error (quota exceeded?)', { key, error });\n }\n }\n\n // ==================== UUID Generation ====================\n\n /**\n * Generate a UUID v4\n * Uses crypto.randomUUID() if available, falls back to Math.random()\n * @returns UUID string\n */\n private generateUUID(): string {\n // Modern browsers with crypto.randomUUID()\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n try {\n const uuid = crypto.randomUUID();\n this.log('generateUUID: crypto.randomUUID()', { uuid });\n return uuid;\n } catch (error) {\n this.log('generateUUID: crypto.randomUUID() failed, falling back', { error });\n }\n }\n\n // Fallback to Math.random() implementation (RFC4122 compliant)\n const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n\n this.log('generateUUID: Math.random() fallback', { uuid });\n return uuid;\n }\n\n // ==================== Anonymous ID Methods ====================\n\n /**\n * Get the current anonymous ID without creating a new one\n * @returns Anonymous ID or null if not found\n */\n public getAnonymousId(): string | null {\n // Try cookie first\n const cookieValue = this.getCookie(this.options.anonymousIdCookieName);\n if (cookieValue) {\n return cookieValue;\n }\n\n // Try localStorage fallback\n const storageValue = this.getLocalStorage(this.options.anonymousIdCookieName);\n if (storageValue) {\n // Restore to cookie if found in localStorage\n this.setCookie(\n this.options.anonymousIdCookieName,\n storageValue,\n this.options.anonymousIdTTL\n );\n return storageValue;\n }\n\n return null;\n }\n\n /**\n * Get or create an anonymous ID\n * @returns Anonymous ID (always returns a value)\n */\n public ensureAnonymousId(): string {\n // Try to get existing ID\n let anonymousId = this.getCookie(this.options.anonymousIdCookieName);\n\n if (!anonymousId) {\n // Try localStorage fallback\n anonymousId = this.getLocalStorage(this.options.anonymousIdCookieName);\n\n if (!anonymousId) {\n // Generate new UUID\n anonymousId = this.generateUUID();\n this.log('ensureAnonymousId: generated new ID', { anonymousId });\n } else {\n this.log('ensureAnonymousId: restored from localStorage', { anonymousId });\n }\n\n // Save to both cookie and localStorage\n this.setCookie(\n this.options.anonymousIdCookieName,\n anonymousId,\n this.options.anonymousIdTTL\n );\n this.setLocalStorage(this.options.anonymousIdCookieName, anonymousId);\n } else {\n this.log('ensureAnonymousId: found in cookie', { anonymousId });\n }\n\n return anonymousId;\n }\n\n // ==================== Session ID Methods ====================\n\n /**\n * Get the current session ID without creating a new one\n * @returns Session ID or null if not found\n */\n public getSessionId(): string | null {\n return this.getCookie(this.options.sessionIdCookieName);\n }\n\n /**\n * Get or create a session ID\n * @returns Session ID (always returns a value)\n */\n public ensureSessionId(): string {\n let sessionId = this.getCookie(this.options.sessionIdCookieName);\n\n if (!sessionId) {\n sessionId = `sess_${Date.now()}`;\n this.setCookie(\n this.options.sessionIdCookieName,\n sessionId,\n this.options.sessionIdTTL\n );\n this.log('ensureSessionId: generated new session', { sessionId });\n } else {\n this.log('ensureSessionId: found existing session', { sessionId });\n }\n\n return sessionId;\n }\n\n // ==================== Debug Logging ====================\n\n /**\n * Log debug messages to console if debug mode is enabled\n * @param message - Log message\n * @param data - Additional data to log\n */\n private log(message: string, data?: unknown): void {\n if (this.options.debug && typeof console !== 'undefined') {\n console.log(`[IdentityManager] ${message}`, data || '');\n }\n }\n}\n"]}
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Configuration options for IdentityManager
3
+ */
4
+ interface IdentityManagerOptions {
5
+ /**
6
+ * Cookie name for anonymous ID storage
7
+ * @default '_stid'
8
+ */
9
+ anonymousIdCookieName: string;
10
+ /**
11
+ * Cookie name for session ID storage
12
+ * @default '_session_id'
13
+ */
14
+ sessionIdCookieName: string;
15
+ /**
16
+ * Anonymous ID time-to-live in days
17
+ * @default 365
18
+ */
19
+ anonymousIdTTL: number;
20
+ /**
21
+ * Session ID time-to-live in days
22
+ * @default 1
23
+ */
24
+ sessionIdTTL: number;
25
+ /**
26
+ * Cookie domain (optional, defaults to current domain)
27
+ * Use '.example.com' for subdomain sharing
28
+ */
29
+ cookieDomain?: string;
30
+ /**
31
+ * Cookie path
32
+ * @default '/'
33
+ */
34
+ cookiePath: string;
35
+ /**
36
+ * Cookie SameSite attribute
37
+ * @default 'Lax'
38
+ */
39
+ cookieSameSite: 'Strict' | 'Lax' | 'None';
40
+ /**
41
+ * Cookie Secure flag (requires HTTPS)
42
+ * @default true
43
+ */
44
+ cookieSecure: boolean;
45
+ /**
46
+ * Enable localStorage fallback when cookies fail
47
+ * @default true
48
+ */
49
+ useLocalStorage: boolean;
50
+ /**
51
+ * Enable debug logging to console
52
+ * @default false
53
+ */
54
+ debug: boolean;
55
+ }
56
+ /**
57
+ * Partial configuration for runtime updates
58
+ */
59
+ type PartialIdentityManagerOptions = Partial<IdentityManagerOptions>;
60
+ /**
61
+ * Default configuration values
62
+ */
63
+ declare const DEFAULT_OPTIONS: IdentityManagerOptions;
64
+
65
+ /**
66
+ * IdentityManager - Manages anonymous user identity and session tracking
67
+ *
68
+ * Features:
69
+ * - Persistent anonymous ID with cookie + localStorage fallback
70
+ * - Temporary session ID management
71
+ * - Configurable TTL for both identity types
72
+ * - SSR-safe (gracefully handles missing document/window)
73
+ * - Zero dependencies
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const identity = new IdentityManager({ debug: true });
78
+ * const userId = identity.ensureAnonymousId();
79
+ * const sessionId = identity.ensureSessionId();
80
+ * ```
81
+ */
82
+ declare class IdentityManager {
83
+ private options;
84
+ /**
85
+ * Create a new IdentityManager instance
86
+ * @param options - Configuration options (optional)
87
+ */
88
+ constructor(options?: PartialIdentityManagerOptions);
89
+ /**
90
+ * Configure or update options at runtime
91
+ * @param options - Partial options to merge with existing configuration
92
+ */
93
+ configure(options: PartialIdentityManagerOptions): void;
94
+ /**
95
+ * Get a cookie value by name
96
+ * @param name - Cookie name
97
+ * @returns Cookie value or null if not found
98
+ */
99
+ getCookie(name: string): string | null;
100
+ /**
101
+ * Set a cookie with configurable options
102
+ * @param name - Cookie name
103
+ * @param value - Cookie value
104
+ * @param days - Time-to-live in days
105
+ */
106
+ setCookie(name: string, value: string, days: number): void;
107
+ /**
108
+ * Get a value from localStorage
109
+ * @param key - Storage key
110
+ * @returns Stored value or null
111
+ */
112
+ private getLocalStorage;
113
+ /**
114
+ * Set a value in localStorage
115
+ * @param key - Storage key
116
+ * @param value - Value to store
117
+ */
118
+ private setLocalStorage;
119
+ /**
120
+ * Generate a UUID v4
121
+ * Uses crypto.randomUUID() if available, falls back to Math.random()
122
+ * @returns UUID string
123
+ */
124
+ private generateUUID;
125
+ /**
126
+ * Get the current anonymous ID without creating a new one
127
+ * @returns Anonymous ID or null if not found
128
+ */
129
+ getAnonymousId(): string | null;
130
+ /**
131
+ * Get or create an anonymous ID
132
+ * @returns Anonymous ID (always returns a value)
133
+ */
134
+ ensureAnonymousId(): string;
135
+ /**
136
+ * Get the current session ID without creating a new one
137
+ * @returns Session ID or null if not found
138
+ */
139
+ getSessionId(): string | null;
140
+ /**
141
+ * Get or create a session ID
142
+ * @returns Session ID (always returns a value)
143
+ */
144
+ ensureSessionId(): string;
145
+ /**
146
+ * Log debug messages to console if debug mode is enabled
147
+ * @param message - Log message
148
+ * @param data - Additional data to log
149
+ */
150
+ private log;
151
+ }
152
+
153
+ export { DEFAULT_OPTIONS, IdentityManager, type IdentityManagerOptions, type PartialIdentityManagerOptions };
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Configuration options for IdentityManager
3
+ */
4
+ interface IdentityManagerOptions {
5
+ /**
6
+ * Cookie name for anonymous ID storage
7
+ * @default '_stid'
8
+ */
9
+ anonymousIdCookieName: string;
10
+ /**
11
+ * Cookie name for session ID storage
12
+ * @default '_session_id'
13
+ */
14
+ sessionIdCookieName: string;
15
+ /**
16
+ * Anonymous ID time-to-live in days
17
+ * @default 365
18
+ */
19
+ anonymousIdTTL: number;
20
+ /**
21
+ * Session ID time-to-live in days
22
+ * @default 1
23
+ */
24
+ sessionIdTTL: number;
25
+ /**
26
+ * Cookie domain (optional, defaults to current domain)
27
+ * Use '.example.com' for subdomain sharing
28
+ */
29
+ cookieDomain?: string;
30
+ /**
31
+ * Cookie path
32
+ * @default '/'
33
+ */
34
+ cookiePath: string;
35
+ /**
36
+ * Cookie SameSite attribute
37
+ * @default 'Lax'
38
+ */
39
+ cookieSameSite: 'Strict' | 'Lax' | 'None';
40
+ /**
41
+ * Cookie Secure flag (requires HTTPS)
42
+ * @default true
43
+ */
44
+ cookieSecure: boolean;
45
+ /**
46
+ * Enable localStorage fallback when cookies fail
47
+ * @default true
48
+ */
49
+ useLocalStorage: boolean;
50
+ /**
51
+ * Enable debug logging to console
52
+ * @default false
53
+ */
54
+ debug: boolean;
55
+ }
56
+ /**
57
+ * Partial configuration for runtime updates
58
+ */
59
+ type PartialIdentityManagerOptions = Partial<IdentityManagerOptions>;
60
+ /**
61
+ * Default configuration values
62
+ */
63
+ declare const DEFAULT_OPTIONS: IdentityManagerOptions;
64
+
65
+ /**
66
+ * IdentityManager - Manages anonymous user identity and session tracking
67
+ *
68
+ * Features:
69
+ * - Persistent anonymous ID with cookie + localStorage fallback
70
+ * - Temporary session ID management
71
+ * - Configurable TTL for both identity types
72
+ * - SSR-safe (gracefully handles missing document/window)
73
+ * - Zero dependencies
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const identity = new IdentityManager({ debug: true });
78
+ * const userId = identity.ensureAnonymousId();
79
+ * const sessionId = identity.ensureSessionId();
80
+ * ```
81
+ */
82
+ declare class IdentityManager {
83
+ private options;
84
+ /**
85
+ * Create a new IdentityManager instance
86
+ * @param options - Configuration options (optional)
87
+ */
88
+ constructor(options?: PartialIdentityManagerOptions);
89
+ /**
90
+ * Configure or update options at runtime
91
+ * @param options - Partial options to merge with existing configuration
92
+ */
93
+ configure(options: PartialIdentityManagerOptions): void;
94
+ /**
95
+ * Get a cookie value by name
96
+ * @param name - Cookie name
97
+ * @returns Cookie value or null if not found
98
+ */
99
+ getCookie(name: string): string | null;
100
+ /**
101
+ * Set a cookie with configurable options
102
+ * @param name - Cookie name
103
+ * @param value - Cookie value
104
+ * @param days - Time-to-live in days
105
+ */
106
+ setCookie(name: string, value: string, days: number): void;
107
+ /**
108
+ * Get a value from localStorage
109
+ * @param key - Storage key
110
+ * @returns Stored value or null
111
+ */
112
+ private getLocalStorage;
113
+ /**
114
+ * Set a value in localStorage
115
+ * @param key - Storage key
116
+ * @param value - Value to store
117
+ */
118
+ private setLocalStorage;
119
+ /**
120
+ * Generate a UUID v4
121
+ * Uses crypto.randomUUID() if available, falls back to Math.random()
122
+ * @returns UUID string
123
+ */
124
+ private generateUUID;
125
+ /**
126
+ * Get the current anonymous ID without creating a new one
127
+ * @returns Anonymous ID or null if not found
128
+ */
129
+ getAnonymousId(): string | null;
130
+ /**
131
+ * Get or create an anonymous ID
132
+ * @returns Anonymous ID (always returns a value)
133
+ */
134
+ ensureAnonymousId(): string;
135
+ /**
136
+ * Get the current session ID without creating a new one
137
+ * @returns Session ID or null if not found
138
+ */
139
+ getSessionId(): string | null;
140
+ /**
141
+ * Get or create a session ID
142
+ * @returns Session ID (always returns a value)
143
+ */
144
+ ensureSessionId(): string;
145
+ /**
146
+ * Log debug messages to console if debug mode is enabled
147
+ * @param message - Log message
148
+ * @param data - Additional data to log
149
+ */
150
+ private log;
151
+ }
152
+
153
+ export { DEFAULT_OPTIONS, IdentityManager, type IdentityManagerOptions, type PartialIdentityManagerOptions };