-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathbrowser-storage.ts
More file actions
299 lines (258 loc) · 7.87 KB
/
browser-storage.ts
File metadata and controls
299 lines (258 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
* Safe localStorage utilities with SSR support
* Provides clean error handling and type safety for browser storage operations
*/
import { createLogger } from '@sim/logger'
const logger = createLogger('BrowserStorage')
/**
* Safe localStorage operations with fallbacks
*/
export class BrowserStorage {
/**
* Safely gets an item from localStorage
* @param key - The storage key
* @param defaultValue - The default value to return if key doesn't exist or access fails
* @returns The stored value or default value
*/
static getItem<T = string>(key: string, defaultValue: T): T {
if (typeof window === 'undefined') {
return defaultValue
}
try {
const item = window.localStorage.getItem(key)
if (item === null) {
return defaultValue
}
try {
return JSON.parse(item) as T
} catch {
return item as T
}
} catch (error) {
logger.warn(`Failed to get localStorage item "${key}":`, error)
return defaultValue
}
}
/**
* Safely sets an item in localStorage
* @param key - The storage key
* @param value - The value to store
* @returns True if successful, false otherwise
*/
static setItem<T>(key: string, value: T): boolean {
if (typeof window === 'undefined') {
return false
}
try {
const serializedValue = typeof value === 'string' ? value : JSON.stringify(value)
window.localStorage.setItem(key, serializedValue)
return true
} catch (error) {
logger.warn(`Failed to set localStorage item "${key}":`, error)
return false
}
}
/**
* Safely removes an item from localStorage
* @param key - The storage key to remove
* @returns True if successful, false otherwise
*/
static removeItem(key: string): boolean {
if (typeof window === 'undefined') {
return false
}
try {
window.localStorage.removeItem(key)
return true
} catch (error) {
logger.warn(`Failed to remove localStorage item "${key}":`, error)
return false
}
}
/**
* Check if localStorage is available
* @returns True if localStorage is available and accessible
*/
static isAvailable(): boolean {
if (typeof window === 'undefined') {
return false
}
try {
const testKey = '__test_localStorage_availability__'
window.localStorage.setItem(testKey, 'test')
window.localStorage.removeItem(testKey)
return true
} catch {
return false
}
}
}
export const STORAGE_KEYS = {
LANDING_PAGE_PROMPT: 'sim_landing_page_prompt',
LANDING_PAGE_WORKFLOW_SEED: 'sim_landing_page_workflow_seed',
WORKSPACE_RECENCY: 'sim_workspace_recency',
} as const
export class WorkspaceRecencyStorage {
private static readonly KEY = STORAGE_KEYS.WORKSPACE_RECENCY
static touch(workspaceId: string): void {
const map = WorkspaceRecencyStorage.getAll()
map[workspaceId] = Date.now()
BrowserStorage.setItem(WorkspaceRecencyStorage.KEY, map)
}
static getAll(): Record<string, number> {
return BrowserStorage.getItem<Record<string, number>>(WorkspaceRecencyStorage.KEY, {})
}
static getMostRecent(): string | null {
const map = WorkspaceRecencyStorage.getAll()
const entries = Object.entries(map)
if (entries.length === 0) return null
entries.sort((a, b) => b[1] - a[1])
return entries[0][0]
}
static remove(workspaceId: string): void {
const map = WorkspaceRecencyStorage.getAll()
delete map[workspaceId]
BrowserStorage.setItem(WorkspaceRecencyStorage.KEY, map)
}
/**
* Removes localStorage entries for workspace IDs not in the provided list.
* Call from effects or event handlers, not during render.
*/
static prune(validIds: Set<string>): void {
const map = WorkspaceRecencyStorage.getAll()
let pruned = false
for (const id of Object.keys(map)) {
if (!validIds.has(id)) {
delete map[id]
pruned = true
}
}
if (pruned) {
BrowserStorage.setItem(WorkspaceRecencyStorage.KEY, map)
}
}
/**
* Sorts workspaces by recency (most recent first).
* Workspaces without a recorded timestamp are placed after tracked ones.
* Pure function safe for use in render-phase computations.
*/
static sortByRecency<T extends { id: string }>(workspaces: T[]): T[] {
const map = WorkspaceRecencyStorage.getAll()
return [...workspaces].sort((a, b) => {
const aTime = map[a.id] ?? 0
const bTime = map[b.id] ?? 0
return bTime - aTime
})
}
}
/**
* Specialized utility for managing the landing page prompt
*/
export class LandingPromptStorage {
private static readonly KEY = STORAGE_KEYS.LANDING_PAGE_PROMPT
/**
* Store a prompt from the landing page
* @param prompt - The prompt text to store
* @returns True if successful, false otherwise
*/
static store(prompt: string): boolean {
if (!prompt || prompt.trim().length === 0) {
return false
}
const data = {
prompt: prompt.trim(),
timestamp: Date.now(),
}
return BrowserStorage.setItem(LandingPromptStorage.KEY, data)
}
/**
* Retrieve and consume the stored prompt
* @param maxAge - Maximum age of the prompt in milliseconds (default: 24 hours)
* @returns The stored prompt or null if not found/expired
*/
static consume(maxAge: number = 24 * 60 * 60 * 1000): string | null {
const data = BrowserStorage.getItem<{ prompt: string; timestamp: number } | null>(
LandingPromptStorage.KEY,
null
)
if (!data || !data.prompt || !data.timestamp) {
return null
}
const age = Date.now() - data.timestamp
if (age > maxAge) {
LandingPromptStorage.clear()
return null
}
LandingPromptStorage.clear()
return data.prompt
}
/**
* Check if there's a stored prompt without consuming it
* @param maxAge - Maximum age of the prompt in milliseconds (default: 24 hours)
* @returns True if there's a valid prompt, false otherwise
*/
static hasPrompt(maxAge: number = 24 * 60 * 60 * 1000): boolean {
const data = BrowserStorage.getItem<{ prompt: string; timestamp: number } | null>(
LandingPromptStorage.KEY,
null
)
if (!data || !data.prompt || !data.timestamp) {
return false
}
const age = Date.now() - data.timestamp
if (age > maxAge) {
LandingPromptStorage.clear()
return false
}
return true
}
/**
* Clear the stored prompt
* @returns True if successful, false otherwise
*/
static clear(): boolean {
return BrowserStorage.removeItem(LandingPromptStorage.KEY)
}
}
export interface LandingWorkflowSeed {
templateId: string
workflowName: string
workflowDescription?: string
color?: string
workflowJson: string
}
/**
* Specialized utility for managing a landing-page workflow seed.
* Stores a workflow export JSON so it can be imported after signup.
*/
export class LandingWorkflowSeedStorage {
private static readonly KEY = STORAGE_KEYS.LANDING_PAGE_WORKFLOW_SEED
static store(seed: LandingWorkflowSeed): boolean {
if (!seed.templateId || !seed.workflowName || !seed.workflowJson) {
return false
}
return BrowserStorage.setItem(LandingWorkflowSeedStorage.KEY, {
...seed,
timestamp: Date.now(),
})
}
static consume(maxAge: number = 24 * 60 * 60 * 1000): LandingWorkflowSeed | null {
const data = BrowserStorage.getItem<(LandingWorkflowSeed & { timestamp: number }) | null>(
LandingWorkflowSeedStorage.KEY,
null
)
if (!data || !data.templateId || !data.workflowName || !data.timestamp || !data.workflowJson) {
return null
}
if (Date.now() - data.timestamp > maxAge) {
LandingWorkflowSeedStorage.clear()
return null
}
LandingWorkflowSeedStorage.clear()
const { timestamp: _timestamp, ...seed } = data
return seed
}
static clear(): boolean {
return BrowserStorage.removeItem(LandingWorkflowSeedStorage.KEY)
}
}