@innovatorved/code-lab 0.7.1 → 0.7.2

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 (71) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +10 -0
  3. package/README.md +5 -5
  4. package/dist/code-lab-sql.esm.js +2 -2
  5. package/dist/code-lab-sql.umd.js +3 -3
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +918 -884
  9. package/dist/code-lab.js +917 -881
  10. package/dist/extensions/cpp.esm.js +33 -33
  11. package/dist/extensions/cpp.js +33 -33
  12. package/dist/extensions/python.esm.js +79 -49
  13. package/dist/extensions/python.js +79 -49
  14. package/dist/index.d.ts +1 -1
  15. package/dist/logger.d.ts +4 -20
  16. package/dist/modular-kernel.d.ts +0 -1
  17. package/dist/packages/core/src/errors.d.ts +5 -1
  18. package/dist/packages/fs/src/backends.d.ts +0 -27
  19. package/dist/packages/fs/src/index.d.ts +1 -1
  20. package/dist/packages/ui/src/html.d.ts +1 -0
  21. package/dist/packages/ui/src/index.d.ts +1 -0
  22. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -2
  23. package/dist/packages/ui/src/observability.d.ts +1 -1
  24. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  25. package/dist/preview-sw.js +1 -1
  26. package/dist/runtime.d.ts +3 -0
  27. package/dist/runtime.esm.js +2 -2
  28. package/dist/runtime.js +2 -2
  29. package/dist/schemas.d.ts +1 -1
  30. package/dist/shell.esm.js +277 -285
  31. package/dist/shell.js +277 -285
  32. package/dist/terminal.esm.js +2 -2
  33. package/dist/terminal.js +2 -2
  34. package/dist/workbench/editor.d.ts +0 -4
  35. package/dist/workbench/index.d.ts +0 -2
  36. package/dist/workbench/intellisense.d.ts +0 -1
  37. package/dist/workbench/xterm-adapter.d.ts +0 -1
  38. package/package.json +2 -4
  39. package/src/code-lab.css +0 -8086
  40. package/src/csp.ts +0 -590
  41. package/src/diagnostics.ts +0 -287
  42. package/src/extensions/cpp.ts +0 -2371
  43. package/src/extensions/guided-lab.ts +0 -68
  44. package/src/extensions/javascript.ts +0 -54
  45. package/src/extensions/python.ts +0 -1743
  46. package/src/extensions/typescript.ts +0 -85
  47. package/src/extensions/umbrella.ts +0 -5
  48. package/src/html.ts +0 -88
  49. package/src/index.ts +0 -129
  50. package/src/logger.ts +0 -139
  51. package/src/modular-kernel.ts +0 -7
  52. package/src/preview-sw.js +0 -296
  53. package/src/runtime/test-harness.ts +0 -57
  54. package/src/runtime.ts +0 -10565
  55. package/src/sample.html +0 -304
  56. package/src/schemas.ts +0 -366
  57. package/src/scm.ts +0 -2453
  58. package/src/search.ts +0 -433
  59. package/src/shell.ts +0 -10990
  60. package/src/storage.ts +0 -773
  61. package/src/terminal.ts +0 -1402
  62. package/src/workbench/command-palette.ts +0 -101
  63. package/src/workbench/diff-editor.ts +0 -472
  64. package/src/workbench/editor.ts +0 -49
  65. package/src/workbench/icons.ts +0 -255
  66. package/src/workbench/index.ts +0 -29
  67. package/src/workbench/intellisense.ts +0 -1884
  68. package/src/workbench/share.ts +0 -128
  69. package/src/workbench/xterm-adapter.ts +0 -1571
  70. package/src/workbench.ts +0 -21825
  71. package/src/zip.ts +0 -348
package/src/storage.ts DELETED
@@ -1,773 +0,0 @@
1
- /**
2
- * @innovatorved/code-lab — Cascading Multi-Project Durable Workspace Storage
3
- * ============================================================================
4
- * Provides durable multi-project workspace persistence with automatic tiered
5
- * fallback:
6
- * 1. IndexedDB (`indexeddb`) — high-capacity asynchronous browser store
7
- * 2. LocalStorage (`localstorage`) — synchronous key-value fallback
8
- * 3. In-Memory Map (`memory`) — guaranteed zero-dependency fallback for
9
- * headless tests, SSR, or restricted/incognito sandboxes
10
- *
11
- * Strict leaf module: fully typed, zero explicit any, zero empty catches.
12
- */
13
-
14
- export type StorageBackendType = 'indexeddb' | 'localstorage' | 'memory';
15
-
16
- export interface StoredProject {
17
- id: string;
18
- name: string;
19
- files: Record<string, string>;
20
- binaryFiles?: Record<string, Uint8Array | string>;
21
- gitFiles?: Record<string, Uint8Array | string>;
22
- gitMeta?: Record<string, unknown>;
23
- updatedAt: number;
24
- createdAt?: number;
25
- entry?: string;
26
- testEntry?: string;
27
- version?: number;
28
- }
29
-
30
- export interface ProjectSummary {
31
- id: string;
32
- name: string;
33
- updatedAt: number;
34
- fileCount: number;
35
- }
36
-
37
- export interface WorkspaceStorageOptions {
38
- dbName?: string;
39
- storeName?: string;
40
- storagePrefix?: string;
41
- preferredBackend?: StorageBackendType;
42
- }
43
-
44
- export type WorkspaceKind = 'blank' | 'repo' | 'demo' | 'custom';
45
-
46
- export interface WorkspaceMeta {
47
- labId: string;
48
- title: string;
49
- kind: WorkspaceKind;
50
- repo?: string;
51
- updatedAt: number;
52
- fileCount?: number;
53
- }
54
-
55
- export const WORKSPACE_REGISTRY_KEY = 'codelab:workspace-registry:v1';
56
-
57
- const DEFAULT_DB_NAME = 'codelab_workspace_db';
58
- const DEFAULT_STORE_NAME = 'projects';
59
- const DEFAULT_LS_PREFIX = 'codelab:project:';
60
- const WORKBENCH_STATE_PREFIX = 'sd-codelab-v1:';
61
- const LEGACY_WORKBENCH_PREFIX = 'codelab_';
62
-
63
- const memoryRegistry: Map<string, WorkspaceMeta> = new Map();
64
- const memoryOrIdbNonEmptyProjects: Set<string> = new Set();
65
- let registryWriteFailed = false;
66
- let lastBlankTs = 0;
67
- let blankSeq = 0;
68
-
69
- function getSafeLocalStorage(): Storage | null {
70
- try {
71
- if (typeof globalThis === 'undefined' || !('localStorage' in globalThis)) {
72
- return null;
73
- }
74
- const ls = globalThis.localStorage;
75
- if (
76
- !ls ||
77
- typeof ls.getItem !== 'function' ||
78
- typeof ls.setItem !== 'function' ||
79
- typeof ls.removeItem !== 'function'
80
- ) {
81
- return null;
82
- }
83
- return ls;
84
- } catch (err) {
85
- const _ignored = err;
86
- void _ignored;
87
- return null;
88
- }
89
- }
90
-
91
- function isPlainRecord(val: unknown): val is Record<string, unknown> {
92
- return Boolean(val && typeof val === 'object' && !Array.isArray(val));
93
- }
94
-
95
- function normalizeWorkspaceMeta(raw: unknown, existing?: WorkspaceMeta): WorkspaceMeta | null {
96
- if (!isPlainRecord(raw)) return null;
97
- const labId = typeof raw.labId === 'string' ? raw.labId.trim() : '';
98
- if (!labId) return null;
99
-
100
- const rawKind = raw.kind;
101
- const kind: WorkspaceKind =
102
- rawKind === 'blank' || rawKind === 'repo' || rawKind === 'demo' || rawKind === 'custom'
103
- ? rawKind
104
- : (existing?.kind ?? 'custom');
105
-
106
- const title =
107
- typeof raw.title === 'string' && raw.title.trim()
108
- ? raw.title.trim()
109
- : (existing?.title || labId);
110
-
111
- const updatedAt =
112
- typeof raw.updatedAt === 'number' && Number.isFinite(raw.updatedAt)
113
- ? raw.updatedAt
114
- : Date.now();
115
-
116
- const repo =
117
- typeof raw.repo === 'string'
118
- ? (raw.repo.trim() || undefined)
119
- : existing?.repo;
120
-
121
- const fileCount =
122
- typeof raw.fileCount === 'number' && Number.isFinite(raw.fileCount) && raw.fileCount >= 0
123
- ? Math.floor(raw.fileCount)
124
- : existing?.fileCount;
125
-
126
- return {
127
- labId,
128
- title,
129
- kind,
130
- updatedAt,
131
- ...(repo !== undefined ? { repo } : {}),
132
- ...(fileCount !== undefined ? { fileCount } : {})
133
- };
134
- }
135
-
136
- function readRegistryEntries(): Map<string, WorkspaceMeta> {
137
- const ls = getSafeLocalStorage();
138
- if (ls && !registryWriteFailed) {
139
- try {
140
- const raw = ls.getItem(WORKSPACE_REGISTRY_KEY);
141
- if (raw === null) {
142
- memoryRegistry.clear();
143
- return new Map();
144
- }
145
- const parsed = JSON.parse(raw) as unknown;
146
- if (!Array.isArray(parsed)) {
147
- return new Map();
148
- }
149
- const map = new Map<string, WorkspaceMeta>();
150
- for (const entry of parsed) {
151
- const normalized = normalizeWorkspaceMeta(entry);
152
- if (!normalized) continue;
153
- const prev = map.get(normalized.labId);
154
- if (!prev || normalized.updatedAt >= prev.updatedAt) {
155
- map.set(normalized.labId, normalized);
156
- }
157
- }
158
- memoryRegistry.clear();
159
- for (const [k, v] of map.entries()) {
160
- memoryRegistry.set(k, { ...v });
161
- }
162
- return map;
163
- } catch (err) {
164
- const _ignored = err;
165
- void _ignored;
166
- return new Map();
167
- }
168
- }
169
-
170
- const out = new Map<string, WorkspaceMeta>();
171
- for (const [k, v] of memoryRegistry.entries()) {
172
- out.set(k, { ...v });
173
- }
174
- return out;
175
- }
176
-
177
- function persistRegistryEntries(map: Map<string, WorkspaceMeta>): void {
178
- const sorted = Array.from(map.values()).sort((a, b) => b.updatedAt - a.updatedAt);
179
- memoryRegistry.clear();
180
- for (const item of sorted) {
181
- memoryRegistry.set(item.labId, { ...item });
182
- }
183
- const ls = getSafeLocalStorage();
184
- if (ls) {
185
- try {
186
- ls.setItem(WORKSPACE_REGISTRY_KEY, JSON.stringify(sorted));
187
- registryWriteFailed = false;
188
- } catch (err) {
189
- const _ignored = err;
190
- void _ignored;
191
- registryWriteFailed = true;
192
- }
193
- }
194
- }
195
-
196
- export function listWorkspaces(): WorkspaceMeta[] {
197
- return Array.from(readRegistryEntries().values()).sort((a, b) => b.updatedAt - a.updatedAt);
198
- }
199
-
200
- export function getWorkspaceMeta(labId: string): WorkspaceMeta | null {
201
- if (typeof labId !== 'string') return null;
202
- const trimmed = labId.trim();
203
- if (!trimmed) return null;
204
- const found = readRegistryEntries().get(trimmed);
205
- return found ? { ...found } : null;
206
- }
207
-
208
- export function upsertWorkspaceMeta(meta: WorkspaceMeta): void {
209
- if (!isPlainRecord(meta)) return;
210
- const trimmedId = typeof meta.labId === 'string' ? meta.labId.trim() : '';
211
- if (!trimmedId) return;
212
- const map = readRegistryEntries();
213
- const normalized = normalizeWorkspaceMeta(meta, map.get(trimmedId));
214
- if (!normalized) return;
215
- map.set(normalized.labId, normalized);
216
- persistRegistryEntries(map);
217
- }
218
-
219
- export function removeWorkspaceMeta(labId: string): void {
220
- if (typeof labId !== 'string') return;
221
- const trimmed = labId.trim();
222
- if (!trimmed) return;
223
- const map = readRegistryEntries();
224
- if (map.delete(trimmed)) {
225
- persistRegistryEntries(map);
226
- } else {
227
- memoryRegistry.delete(trimmed);
228
- }
229
- }
230
-
231
- function payloadHasSavedFiles(rawJson: string | null): boolean {
232
- if (!rawJson) return false;
233
- try {
234
- const parsed = JSON.parse(rawJson) as unknown;
235
- if (!isPlainRecord(parsed)) return false;
236
-
237
- if (isPlainRecord(parsed.files) && Object.keys(parsed.files).length > 0) {
238
- return true;
239
- }
240
-
241
- if (isPlainRecord(parsed.customFiles)) {
242
- for (const val of Object.values(parsed.customFiles)) {
243
- if (typeof val === 'string') {
244
- return true;
245
- }
246
- if (isPlainRecord(val) && Object.keys(val).length > 0) {
247
- return true;
248
- }
249
- }
250
- }
251
- } catch (err) {
252
- const _ignored = err;
253
- void _ignored;
254
- }
255
- return false;
256
- }
257
-
258
- function checkHasWorkspaceData(
259
- labId: string,
260
- extraPrefix?: string,
261
- instanceMemory?: ReadonlyMap<string, StoredProject>
262
- ): boolean {
263
- if (typeof labId !== 'string') return false;
264
- const trimmed = labId.trim();
265
- if (!trimmed) return false;
266
-
267
- if (instanceMemory) {
268
- const proj = instanceMemory.get(trimmed);
269
- if (proj && isPlainRecord(proj.files) && Object.keys(proj.files).length > 0) {
270
- return true;
271
- }
272
- }
273
-
274
- if (memoryOrIdbNonEmptyProjects.has(trimmed)) {
275
- return true;
276
- }
277
-
278
- const ls = getSafeLocalStorage();
279
- if (ls) {
280
- try {
281
- if (payloadHasSavedFiles(ls.getItem(`${WORKBENCH_STATE_PREFIX}${trimmed}`))) {
282
- return true;
283
- }
284
- if (payloadHasSavedFiles(ls.getItem(`${LEGACY_WORKBENCH_PREFIX}${trimmed}`))) {
285
- return true;
286
- }
287
- if (payloadHasSavedFiles(ls.getItem(`${DEFAULT_LS_PREFIX}${trimmed}`))) {
288
- return true;
289
- }
290
- if (
291
- typeof extraPrefix === 'string' &&
292
- extraPrefix &&
293
- extraPrefix !== DEFAULT_LS_PREFIX &&
294
- payloadHasSavedFiles(ls.getItem(`${extraPrefix}${trimmed}`))
295
- ) {
296
- return true;
297
- }
298
- } catch (err) {
299
- const _ignored = err;
300
- void _ignored;
301
- }
302
- }
303
-
304
- return false;
305
- }
306
-
307
- export function hasWorkspaceData(labId: string): boolean {
308
- return checkHasWorkspaceData(labId);
309
- }
310
-
311
- export function createBlankWorkspaceId(): string {
312
- const now = Date.now();
313
- if (now === lastBlankTs) {
314
- blankSeq += 1;
315
- } else {
316
- lastBlankTs = now;
317
- blankSeq = 0;
318
- }
319
- const rand = Math.random().toString(36).slice(2, 6).padEnd(4, '0');
320
- const suffix = blankSeq > 0 ? `${blankSeq.toString(36)}${rand}` : rand;
321
- return `blank-workspace-${now}-${suffix}`;
322
- }
323
-
324
- export function encodeBase64Bytes(bytes: Uint8Array): string {
325
- if (typeof Buffer !== 'undefined') {
326
- return Buffer.from(bytes).toString('base64');
327
- }
328
- let binary = '';
329
- const chunk = 0x8000;
330
- for (let i = 0; i < bytes.length; i += chunk) {
331
- binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
332
- }
333
- return typeof btoa === 'function' ? btoa(binary) : binary;
334
- }
335
-
336
- export function decodeBase64Bytes(b64: string): Uint8Array {
337
- if (typeof Buffer !== 'undefined') {
338
- const buf = Buffer.from(b64, 'base64');
339
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
340
- }
341
- if (typeof atob === 'function') {
342
- const bin = atob(b64);
343
- const out = new Uint8Array(bin.length);
344
- for (let i = 0; i < bin.length; i++) {
345
- out[i] = bin.charCodeAt(i);
346
- }
347
- return out;
348
- }
349
- return new Uint8Array(0);
350
- }
351
-
352
- function cloneByteMap(
353
- map: Record<string, Uint8Array | string> | undefined,
354
- serializeBase64 = false
355
- ): Record<string, Uint8Array | string> | undefined {
356
- if (!map || typeof map !== 'object') return undefined;
357
- const out: Record<string, Uint8Array | string> = {};
358
- let count = 0;
359
- for (const [k, v] of Object.entries(map)) {
360
- if (v instanceof Uint8Array) {
361
- out[k] = serializeBase64 ? encodeBase64Bytes(v) : new Uint8Array(v);
362
- count++;
363
- } else if (ArrayBuffer.isView(v)) {
364
- const view = new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
365
- out[k] = serializeBase64 ? encodeBase64Bytes(view) : new Uint8Array(view);
366
- count++;
367
- } else if (typeof v === 'string') {
368
- out[k] = serializeBase64 ? v : decodeBase64Bytes(v);
369
- count++;
370
- }
371
- }
372
- return count > 0 ? out : undefined;
373
- }
374
-
375
- function cloneProject(project: StoredProject, serializeBase64 = false): StoredProject {
376
- const filesCopy: Record<string, string> = {};
377
- if (project.files && typeof project.files === 'object') {
378
- for (const [k, v] of Object.entries(project.files)) {
379
- filesCopy[k] = String(v);
380
- }
381
- }
382
- const binaryCopy = cloneByteMap(project.binaryFiles, serializeBase64);
383
- const gitCopy = cloneByteMap(project.gitFiles, serializeBase64);
384
- const gitMetaCopy = isPlainRecord(project.gitMeta) ? { ...project.gitMeta } : undefined;
385
- return {
386
- id: String(project.id),
387
- name: String(project.name || project.id),
388
- files: filesCopy,
389
- ...(binaryCopy ? { binaryFiles: binaryCopy } : {}),
390
- ...(gitCopy ? { gitFiles: gitCopy } : {}),
391
- ...(gitMetaCopy ? { gitMeta: gitMetaCopy } : {}),
392
- updatedAt: typeof project.updatedAt === 'number' ? project.updatedAt : Date.now(),
393
- ...(project.createdAt !== undefined ? { createdAt: project.createdAt } : {}),
394
- ...(project.entry !== undefined ? { entry: project.entry } : {}),
395
- ...(project.testEntry !== undefined ? { testEntry: project.testEntry } : {}),
396
- ...(project.version !== undefined ? { version: project.version } : {})
397
- };
398
- }
399
-
400
- function isLocalStorageAvailable(prefix: string): boolean {
401
- try {
402
- if (typeof globalThis === 'undefined' || !('localStorage' in globalThis)) {
403
- return false;
404
- }
405
- const ls = globalThis.localStorage;
406
- if (!ls || typeof ls.getItem !== 'function' || typeof ls.setItem !== 'function') {
407
- return false;
408
- }
409
- const probeKey = `${prefix}__probe__`;
410
- ls.setItem(probeKey, '1');
411
- ls.removeItem(probeKey);
412
- return true;
413
- } catch (err) {
414
- const _ignored = err;
415
- void _ignored;
416
- return false;
417
- }
418
- }
419
-
420
- function isIndexedDbAvailable(): boolean {
421
- try {
422
- if (typeof globalThis === 'undefined' || !('indexedDB' in globalThis)) {
423
- return false;
424
- }
425
- return Boolean(globalThis.indexedDB && typeof globalThis.indexedDB.open === 'function');
426
- } catch (err) {
427
- const _ignored = err;
428
- void _ignored;
429
- return false;
430
- }
431
- }
432
-
433
- export class WorkspaceStorage {
434
- public static readonly WORKSPACE_REGISTRY_KEY = WORKSPACE_REGISTRY_KEY;
435
- public static readonly listWorkspaces = listWorkspaces;
436
- public static readonly getWorkspaceMeta = getWorkspaceMeta;
437
- public static readonly upsertWorkspaceMeta = upsertWorkspaceMeta;
438
- public static readonly removeWorkspaceMeta = removeWorkspaceMeta;
439
- public static readonly hasWorkspaceData = hasWorkspaceData;
440
- public static readonly createBlankWorkspaceId = createBlankWorkspaceId;
441
-
442
- private readonly dbName: string;
443
- private readonly storeName: string;
444
- private readonly storagePrefix: string;
445
- private backendType: StorageBackendType;
446
- private readonly memoryStore: Map<string, StoredProject> = new Map();
447
- private dbPromise: Promise<IDBDatabase | null> | null = null;
448
-
449
- constructor(options: WorkspaceStorageOptions = {}) {
450
- this.dbName = options.dbName || DEFAULT_DB_NAME;
451
- this.storeName = options.storeName || DEFAULT_STORE_NAME;
452
- this.storagePrefix = options.storagePrefix || DEFAULT_LS_PREFIX;
453
-
454
- if (options.preferredBackend) {
455
- this.backendType = options.preferredBackend;
456
- } else if (isIndexedDbAvailable()) {
457
- this.backendType = 'indexeddb';
458
- } else if (isLocalStorageAvailable(this.storagePrefix)) {
459
- this.backendType = 'localstorage';
460
- } else {
461
- this.backendType = 'memory';
462
- }
463
- }
464
-
465
- public getBackendType(): StorageBackendType {
466
- return this.backendType;
467
- }
468
-
469
- private openIdb(): Promise<IDBDatabase | null> {
470
- if (this.dbPromise) return this.dbPromise;
471
- this.dbPromise = new Promise<IDBDatabase | null>((resolve) => {
472
- try {
473
- const req = globalThis.indexedDB.open(this.dbName, 1);
474
- req.onupgradeneeded = () => {
475
- const db = req.result;
476
- if (!db.objectStoreNames.contains(this.storeName)) {
477
- db.createObjectStore(this.storeName, { keyPath: 'id' });
478
- }
479
- };
480
- req.onsuccess = () => {
481
- resolve(req.result);
482
- };
483
- req.onerror = () => {
484
- resolve(null);
485
- };
486
- } catch (err) {
487
- const _ignored = err;
488
- void _ignored;
489
- resolve(null);
490
- }
491
- });
492
- return this.dbPromise;
493
- }
494
-
495
- private downgradeFromIdb(): void {
496
- if (isLocalStorageAvailable(this.storagePrefix)) {
497
- this.backendType = 'localstorage';
498
- } else {
499
- this.backendType = 'memory';
500
- }
501
- }
502
-
503
- public async saveProject(project: StoredProject): Promise<boolean> {
504
- if (!project || typeof project.id !== 'string' || !project.id.trim()) {
505
- return false;
506
- }
507
- const normalized = cloneProject(project);
508
- const hasFiles = Object.keys(normalized.files).length > 0;
509
- // Always keep memory mirror hot for resilience
510
- this.memoryStore.set(normalized.id, normalized);
511
-
512
- if (this.backendType === 'indexeddb') {
513
- const db = await this.openIdb();
514
- if (!db) {
515
- this.downgradeFromIdb();
516
- } else {
517
- const ok = await new Promise<boolean>((resolve) => {
518
- try {
519
- const tx = db.transaction(this.storeName, 'readwrite');
520
- const store = tx.objectStore(this.storeName);
521
- const req = store.put(normalized);
522
- req.onsuccess = () => resolve(true);
523
- req.onerror = () => resolve(false);
524
- } catch (err) {
525
- const _ignored = err;
526
- void _ignored;
527
- resolve(false);
528
- }
529
- });
530
- if (ok) {
531
- if (hasFiles) memoryOrIdbNonEmptyProjects.add(normalized.id);
532
- else memoryOrIdbNonEmptyProjects.delete(normalized.id);
533
- return true;
534
- }
535
- this.downgradeFromIdb();
536
- }
537
- }
538
-
539
- if (this.backendType === 'localstorage') {
540
- try {
541
- const key = `${this.storagePrefix}${normalized.id}`;
542
- const serializable = cloneProject(normalized, true);
543
- globalThis.localStorage.setItem(key, JSON.stringify(serializable));
544
- memoryOrIdbNonEmptyProjects.delete(normalized.id);
545
- return true;
546
- } catch (err) {
547
- // QuotaExceededError or disabled storage -> fallback to memory
548
- const _ignored = err;
549
- void _ignored;
550
- this.backendType = 'memory';
551
- }
552
- }
553
-
554
- if (hasFiles) memoryOrIdbNonEmptyProjects.add(normalized.id);
555
- else memoryOrIdbNonEmptyProjects.delete(normalized.id);
556
- return true;
557
- }
558
-
559
- public async loadProject(id: string): Promise<StoredProject | null> {
560
- if (!id || typeof id !== 'string') return null;
561
-
562
- if (this.backendType === 'indexeddb') {
563
- const db = await this.openIdb();
564
- if (!db) {
565
- this.downgradeFromIdb();
566
- } else {
567
- const found = await new Promise<StoredProject | null>((resolve) => {
568
- try {
569
- const tx = db.transaction(this.storeName, 'readonly');
570
- const store = tx.objectStore(this.storeName);
571
- const req = store.get(id);
572
- req.onsuccess = () => {
573
- const res = req.result as StoredProject | undefined;
574
- resolve(res ? cloneProject(res) : null);
575
- };
576
- req.onerror = () => resolve(null);
577
- } catch (err) {
578
- const _ignored = err;
579
- void _ignored;
580
- resolve(null);
581
- }
582
- });
583
- if (found) return found;
584
- }
585
- }
586
-
587
- if (this.backendType === 'localstorage') {
588
- try {
589
- const raw = globalThis.localStorage.getItem(`${this.storagePrefix}${id}`);
590
- if (raw) {
591
- const parsed = JSON.parse(raw) as StoredProject;
592
- if (parsed && typeof parsed.id === 'string' && parsed.files && typeof parsed.files === 'object') {
593
- return cloneProject(parsed);
594
- }
595
- }
596
- } catch (err) {
597
- // Corrupted JSON entry in localStorage: remove corrupt key and check memory
598
- const _ignored = err;
599
- void _ignored;
600
- }
601
- }
602
-
603
- const fromMem = this.memoryStore.get(id);
604
- return fromMem ? cloneProject(fromMem) : null;
605
- }
606
-
607
- public async listProjects(): Promise<ProjectSummary[]> {
608
- const byId = new Map<string, ProjectSummary>();
609
-
610
- const recordSummary = (proj: StoredProject): void => {
611
- if (!proj || typeof proj.id !== 'string') return;
612
- byId.set(proj.id, {
613
- id: proj.id,
614
- name: proj.name || proj.id,
615
- updatedAt: typeof proj.updatedAt === 'number' ? proj.updatedAt : Date.now(),
616
- fileCount: proj.files && typeof proj.files === 'object' ? Object.keys(proj.files).length : 0
617
- });
618
- };
619
-
620
- for (const p of this.memoryStore.values()) {
621
- recordSummary(p);
622
- }
623
-
624
- if (this.backendType === 'indexeddb') {
625
- const db = await this.openIdb();
626
- if (db) {
627
- await new Promise<void>((resolve) => {
628
- try {
629
- const tx = db.transaction(this.storeName, 'readonly');
630
- const store = tx.objectStore(this.storeName);
631
- const req = store.getAll();
632
- req.onsuccess = () => {
633
- const items = Array.isArray(req.result) ? (req.result as StoredProject[]) : [];
634
- for (const item of items) {
635
- recordSummary(item);
636
- }
637
- resolve();
638
- };
639
- req.onerror = () => resolve();
640
- } catch (err) {
641
- const _ignored = err;
642
- void _ignored;
643
- resolve();
644
- }
645
- });
646
- }
647
- } else if (this.backendType === 'localstorage') {
648
- try {
649
- const ls = globalThis.localStorage;
650
- for (let i = 0; i < ls.length; i++) {
651
- const key = ls.key(i);
652
- if (key && key.startsWith(this.storagePrefix)) {
653
- const raw = ls.getItem(key);
654
- if (raw) {
655
- try {
656
- const parsed = JSON.parse(raw) as StoredProject;
657
- recordSummary(parsed);
658
- } catch (parseErr) {
659
- const _ignored = parseErr;
660
- void _ignored;
661
- }
662
- }
663
- }
664
- }
665
- } catch (err) {
666
- const _ignored = err;
667
- void _ignored;
668
- }
669
- }
670
-
671
- return Array.from(byId.values()).sort((a, b) => b.updatedAt - a.updatedAt);
672
- }
673
-
674
- public async deleteProject(id: string): Promise<boolean> {
675
- if (!id || typeof id !== 'string') return false;
676
- memoryOrIdbNonEmptyProjects.delete(id);
677
- let existed = this.memoryStore.delete(id);
678
-
679
- if (this.backendType === 'indexeddb') {
680
- const db = await this.openIdb();
681
- if (db) {
682
- const idbDeleted = await new Promise<boolean>((resolve) => {
683
- try {
684
- const tx = db.transaction(this.storeName, 'readwrite');
685
- const store = tx.objectStore(this.storeName);
686
- const checkReq = store.get(id);
687
- checkReq.onsuccess = () => {
688
- if (!checkReq.result) {
689
- resolve(false);
690
- return;
691
- }
692
- const delReq = store.delete(id);
693
- delReq.onsuccess = () => resolve(true);
694
- delReq.onerror = () => resolve(false);
695
- };
696
- checkReq.onerror = () => resolve(false);
697
- } catch (err) {
698
- const _ignored = err;
699
- void _ignored;
700
- resolve(false);
701
- }
702
- });
703
- existed = existed || idbDeleted;
704
- }
705
- }
706
-
707
- if (this.backendType === 'localstorage') {
708
- try {
709
- const key = `${this.storagePrefix}${id}`;
710
- if (globalThis.localStorage.getItem(key) !== null) {
711
- globalThis.localStorage.removeItem(key);
712
- existed = true;
713
- }
714
- } catch (err) {
715
- const _ignored = err;
716
- void _ignored;
717
- }
718
- }
719
-
720
- return existed;
721
- }
722
-
723
- public listWorkspaces(): WorkspaceMeta[] {
724
- return listWorkspaces();
725
- }
726
-
727
- public getWorkspaceMeta(labId: string): WorkspaceMeta | null {
728
- return getWorkspaceMeta(labId);
729
- }
730
-
731
- public upsertWorkspaceMeta(meta: WorkspaceMeta): void {
732
- upsertWorkspaceMeta(meta);
733
- }
734
-
735
- public removeWorkspaceMeta(labId: string): void {
736
- removeWorkspaceMeta(labId);
737
- }
738
-
739
- public hasWorkspaceData(labId: string): boolean {
740
- return checkHasWorkspaceData(labId, this.storagePrefix, this.memoryStore);
741
- }
742
-
743
- public createBlankWorkspaceId(): string {
744
- return createBlankWorkspaceId();
745
- }
746
- }
747
-
748
- export function createWorkspaceStorage(options: WorkspaceStorageOptions = {}): WorkspaceStorage {
749
- return new WorkspaceStorage(options);
750
- }
751
-
752
- export const CodeLabWorkspaceStorage = {
753
- WORKSPACE_REGISTRY_KEY,
754
- WorkspaceStorage,
755
- createWorkspaceStorage,
756
- listWorkspaces,
757
- getWorkspaceMeta,
758
- upsertWorkspaceMeta,
759
- removeWorkspaceMeta,
760
- hasWorkspaceData,
761
- createBlankWorkspaceId,
762
- encodeBase64Bytes,
763
- decodeBase64Bytes
764
- };
765
-
766
- if (typeof globalThis !== 'undefined') {
767
- const g = globalThis as unknown as Record<string, unknown>;
768
- g.CodeLabWorkspaceStorage = CodeLabWorkspaceStorage;
769
- }
770
-
771
- export default {
772
- ...CodeLabWorkspaceStorage
773
- };