diff --git a/src/registerSQLWorker.js b/src/registerSQLWorker.js index 890e1762..16068b3f 100644 --- a/src/registerSQLWorker.js +++ b/src/registerSQLWorker.js @@ -1,3 +1,38 @@ +// **WORKER-COMPATIBLE ENVIRONMENT SETUP**: Must be at the very top +// This prevents "window is not defined" errors when sql.js tries to access window.crypto +if (typeof window === 'undefined') { + // We're in a worker context - provide minimal polyfills + globalThis.window = globalThis; + + // Enhanced crypto polyfill + if (typeof crypto === 'undefined') { + globalThis.crypto = { + getRandomValues: (array) => { + // Simple fallback for worker context + for (let i = 0; i < array.length; i++) { + array[i] = Math.floor(Math.random() * 256); + } + return array; + }, + subtle: { + generateKey: async () => ({ type: 'secret' }), + sign: async () => new Uint8Array(32), + verify: async () => true, + digest: async () => new Uint8Array(32) + } + }; + } else if (!crypto.getRandomValues) { + // Crypto exists but doesn't have getRandomValues - extend it + crypto.getRandomValues = (array) => { + // Simple fallback for worker context + for (let i = 0; i < array.length; i++) { + array[i] = Math.floor(Math.random() * 256); + } + return array; + }; + } +} + /** * SQL Worker Thread Handler for TimeSafari Web Platform * diff --git a/src/services/AbsurdSqlDatabaseService.ts b/src/services/AbsurdSqlDatabaseService.ts index fb7ffe7b..6389ff04 100644 --- a/src/services/AbsurdSqlDatabaseService.ts +++ b/src/services/AbsurdSqlDatabaseService.ts @@ -1,3 +1,17 @@ +// **WORKER-COMPATIBLE CRYPTO POLYFILL**: Must be at the very top +// This prevents "crypto is not defined" errors when running in worker context +if (typeof window === 'undefined' && typeof crypto === 'undefined') { + (globalThis as any).crypto = { + getRandomValues: (array: any) => { + // Simple fallback for worker context + for (let i = 0; i < array.length; i++) { + array[i] = Math.floor(Math.random() * 256); + } + return array; + } + }; +} + import initSqlJs from "@jlongster/sql.js"; import { SQLiteFS } from "absurd-sql"; import IndexedDBBackend from "absurd-sql/dist/indexeddb-backend";