@jucie.io/engine-database 1.0.15 → 1.0.16
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/main.js +7 -7
- package/dist/main.js.map +4 -4
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).filter(
|
|
3
|
-
`).filter(
|
|
4
|
-
`;i.
|
|
5
|
-
`).map(
|
|
6
|
-
`).map(r=>JSON.parse(r))}catch(t){return console.error("Error reading WAL entries:",t),[]}},_getWALEntryCount:()=>{try{return i.
|
|
7
|
-
`).filter(r=>r.trim()!=="").length:0}catch(t){return console.error("Error counting WAL entries:",t),0}}}:{}}};
|
|
1
|
+
var y="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import E from"crypto";var T=128,l,u,F=a=>{!l||l.length<a?(l=Buffer.allocUnsafe(a*T),E.randomFillSync(l),u=0):u+a>l.length&&(E.randomFillSync(l),u=0),u+=a},v=a=>(F(a|=0),l.subarray(u-a,u)),D=(a,e,t)=>{let r=(2<<31-Math.clz32(a.length-1|1))-1,s=Math.ceil(1.6*r*e/a.length);return(n=e)=>{let o="";for(;;){let c=t(s),h=s;for(;h--;)if(o+=a[c[h]&r]||"",o.length===n)return o}}},W=(a,e=21)=>D(a,e,v),b=(a=21)=>{F(a|=0);let e="";for(let t=u-a;t<u;t++)e+=y[l[t]&63];return e};var m=class a{static create(e,t=null){return new a(e,t)}constructor(e,t=null){this.state=e,this.database=t}add(e){try{let t=b();return this.state.set([t],e),t}catch(t){return console.error("Error adding value to database:",t),null}}set(...e){try{let[t,r]=e;return this.state.set(t,r),!0}catch(t){console.error("Error setting value in database:",t);return}}get(e=[]){try{return this.state.get(e)}catch(t){console.error("Error getting value from database:",t);return}}has(e){try{return this.state.has(e)}catch(t){return console.error("Error checking if key exists in database:",t),!1}}remove(e){try{return this.state.remove(e)}catch(t){return console.error("Error removing from database:",t),this}}update(e,t){try{return this.state.update(e,t)}catch(r){console.error("Error updating value in database:",r);return}}keys(e=[]){try{return this.state.keys(e)}catch(t){return console.error("Error getting keys from database:",t),[]}}findWhere(e,t,r){try{let s=this.state.findWhere(e,t,r);if(s.length===0)return null;let[n]=s;return this.state.get([n])}catch(s){return console.error("Error finding value in database:",s),null}}findAllWhere(e,t,r){try{return this.state.findAllWhere(e,t,r).map(n=>{let[o]=n;return this.state.get([o])})}catch(s){return console.error("Error finding all values in database:",s),[]}}typeof(e){try{return this.state.typeof(e)}catch(t){return console.error("Error getting type of value in database:",t),null}}collection(e){return a.create(this.state.ref(e),this.database)}batch(e){if(!this.database)return this.state.batch(e);this.database._beginBatch();try{return this.state.batch(e)}finally{this.database._endBatch()}}};function k(a){return typeof setImmediate<"u"?setImmediate(a):typeof process<"u"&&process.nextTick?process.nextTick(a):setTimeout(a,0)}function w(a){typeof clearImmediate<"u"?clearImmediate(a):clearTimeout(a)}import{ServiceProvider as A}from"@jucie.io/engine";import S from"path";import i from"fs";import{promises as g}from"fs";import{createState as P}from"@jucie.io/state";import{OnChange as C}from"/Users/adrianmiller/Development/jucie.io/state/plugins/on-change/src/main.js";var p=new Set,I=!1,x=class extends A{#n=!1;#t=null;#r=null;#h=null;#s=0;#f=100;#p=1e3;#l=new Set;#e=null;#o=!1;#a=null;#y=Date.now();#m=5e3;#d=!1;#i=0;static manifest={name:"Database",dependencies:[],namespace:"database",defaults:{debug:!1,dbPath:"./",dbName:".db",walPath:"./",walName:".wal",checkpointThreshold:100,forceThreshold:1e3,checkpointInterval:5e3}};initialize(e,t){let r=e("state");r||(r=P().install(C)),this.#e=r,this.#f=t.checkpointThreshold,this.#p=t.forceThreshold,this.#m=t.checkpointInterval,p.add(this),this.#g()}#g(){if(I)return;I=!0;let e=async t=>{console.log(`Received ${t}, performing final checkpoint on all databases...`);for(let r of p)try{r.#a&&w(r.#a),r.#n&&r.#s>0&&(await r.#c(),console.log(`Checkpoint completed for database at ${r.#r}`))}catch(s){console.error(`Error checkpointing database ${r.#r}:`,s)}};process.on("SIGINT",async()=>{await e("SIGINT"),process.exit(0)}),process.on("SIGTERM",async()=>{await e("SIGTERM"),process.exit(0)}),process.on("exit",()=>{for(let t of p)t.#n&&t.#s>0&&console.warn(`Emergency: Database ${t.#r} has ${t.#s} uncommitted changes in WAL`)})}actions(e,t){return{isInitialized:()=>this.#n,beginBatch:()=>{this.#i++},endBatch:()=>{this.#i=Math.max(0,this.#i-1),this.#i===0&&this.#o&&this.#u()},initializeDb:async(r={})=>{t={...t,...r};try{if(this.#r=S.join(t.dbPath,t.dbName),this.#t=S.join(t.walPath,t.walName),this.#h=this.#e.onChange.addListener(this.#b),!i.existsSync(this.#r)){let n=await this.#e.export();i.mkdirSync(t.dbPath,{recursive:!0}),i.writeFileSync(this.#r,n)}let s=i.readFileSync(this.#r,"utf8");if(await this.#e.import(s),i.existsSync(this.#t)){let o=i.readFileSync(this.#t,"utf8").trim().split(`
|
|
2
|
+
`).filter(c=>c.trim());for(let c of o){if(!c)continue;let[h,d,f]=JSON.parse(c);d.method==="set"||d.method==="update"?this.#e.set(d.path,d.to):d.method==="remove"&&this.#e.remove(d.path)}await this.#w()}return this.#v(),this.#n=!0,this.#n}catch(s){return console.error("Error initializing database:",s),this.#n}},backup:async(r="./backup.json")=>{try{let s=await this.#e.export();return i.existsSync(r)||i.mkdirSync(S.dirname(r),{recursive:!0}),i.writeFileSync(r,s),r}catch(s){return console.error("Error backing up database:",s),null}},restore:async(r="./backup.json")=>{try{if(!i.existsSync(r))throw new Error("Backup file not found");let s=i.readFileSync(r,"utf8");return await this.#e.import(s),!0}catch(s){return console.error("Error restoring database:",s),!1}},restoreFromBackup:async()=>{try{let r=`${this.#r}.backup`,s=`${this.#t}.backup`;if(!i.existsSync(r))throw new Error("No backup files found");let n=i.readFileSync(r,"utf8");if(await this.#e.import(n),i.existsSync(s)){let c=i.readFileSync(s,"utf8").trim().split(`
|
|
3
|
+
`).filter(h=>h.trim());for(let h of c){if(!h)continue;let[d,f,L]=JSON.parse(h);f.method==="set"||f.method==="update"?this.#e.set(f.path,f.to):f.method==="remove"&&this.#e.remove(f.path)}}return console.log("Successfully restored from backup"),!0}catch(r){return console.error("Error restoring from backup:",r),!1}},checkpoint:async()=>this.#i>0?(this.#o=!0,!1):(await this.#c(),!0),close:async()=>{try{return this.#a&&(w(this.#a),this.#a=null),this.#s>0&&await this.#c(),this.#h&&(this.#h(),this.#h=null),p.delete(this),this.#n=!1,!0}catch(r){return console.error("Error closing database:",r),!1}},destroy:()=>{try{return this.#h(),this.#a&&(w(this.#a),this.#a=null),this.#I(),this.#h=null,this.#e.reset(),p.delete(this),!0}catch(r){return console.error("Error destroying database:",r),!1}},collection:r=>m.create(this.#e.ref(r),this),_beginBatch:()=>{this.#i++},_endBatch:()=>{this.#i=Math.max(0,this.#i-1),this.#i===0&&this.#o&&this.#u()},batch:r=>{this.#i++;try{return this.#e.batch(r)}finally{this.#i=Math.max(0,this.#i-1),this.#i===0&&this.#o&&this.#u()}},...this.#T(this.config.debug)}}#b=async e=>{this.#s+=e.length,this.#E(e);let t=Date.now()-this.#y;if(this.#s>=this.#p){console.warn(`Force checkpoint triggered at ${this.#s} changes`),this.#s=0,await this.#c();return}(this.#s>=this.#f||t>=this.#m)&&(this.#u(),this.#s=0),this.#k()};#k=()=>{this.#l.size!==0&&(this.#l.forEach(e=>e()),this.#l.clear())};#u=()=>{this.#o&&this.#a||(this.#o=!0,!(this.#i>0)&&(this.#a=k(async()=>{await this.#c()})))};#c=async()=>{if(this.#i>0){this.#a=k(async()=>{await this.#c()});return}if(!this.#d)try{this.#d=!0,await this.#S(),await this.#w(),await this.#D(),this.#y=Date.now()}catch(e){console.error("Error during checkpoint:",e)}finally{this.#d=!1,this.#o=!1,this.#a=null}};#S=async()=>{let e=`${this.#r}.backup`,t=`${this.#t}.backup`;try{i.existsSync(this.#r)&&await g.copyFile(this.#r,e),i.existsSync(this.#t)&&await g.copyFile(this.#t,t)}catch(r){console.error("Error backing up files:",r)}};#w=async()=>{let e=await this.#e.export();await g.writeFile(this.#r,e,"utf8")};#x=()=>{i.existsSync(this.#r)&&i.unlinkSync(this.#r)};#E=e=>{let t="";for(let r of e)t+=JSON.stringify(r)+`
|
|
4
|
+
`;i.appendFileSync(this.#t,t)};#F=()=>{i.existsSync(this.#t)&&i.unlinkSync(this.#t)};#v=()=>{i.existsSync(this.#t)&&i.writeFileSync(this.#t,"")};#D=async()=>{i.existsSync(this.#t)&&await g.writeFile(this.#t,"","utf8")};#I=()=>{this.#F(),this.#x()};#T(e=!1){return e?{_afterWrite:()=>new Promise(t=>this.#l.add(t)),_clearDatabase:()=>{try{return this.#e.reset(),i.existsSync(this.#r)&&i.unlinkSync(this.#r),!0}catch(t){return console.error("Error clearing database:",t),!1}},_clearChanges:()=>{try{return this.#s=0,!0}catch(t){return console.error("Error clearing changes:",t),!1}},_getChangeCount:()=>this.#s,_clearWAL:()=>{try{return i.existsSync(this.#t)&&i.writeFileSync(this.#t,""),!0}catch(t){return console.error("Error clearing WAL:",t),!1}},_applyWAL:async()=>{try{if(!i.existsSync(this.#t))return!1;let r=i.readFileSync(this.#t,"utf8").trim().split(`
|
|
5
|
+
`).map(s=>JSON.parse(s));return this.#e.apply(r),i.writeFileSync(this.#t,""),!0}catch(t){return console.error("Error applying WAL:",t),!1}},_checkpoint:async()=>{try{return await new Promise(t=>setTimeout(t,10)),await new Promise(t=>{this.#l.size===0?t():this.#l.add(t)}),await this.#c(),!0}catch(t){return console.error("Error during checkpoint:",t),!1}},_getWALEntries:()=>{try{if(!i.existsSync(this.#t))return[];let t=i.readFileSync(this.#t,"utf8");return t.trim().length===0?[]:t.trim().split(`
|
|
6
|
+
`).map(r=>JSON.parse(r))}catch(t){return console.error("Error reading WAL entries:",t),[]}},_getWALEntryCount:()=>{try{return i.existsSync(this.#t)?i.readFileSync(this.#t,"utf8").trim().split(`
|
|
7
|
+
`).filter(r=>r.trim()!=="").length:0}catch(t){return console.error("Error counting WAL entries:",t),0}}}:{}}};export{x as Database};
|
|
8
8
|
//# sourceMappingURL=main.js.map
|
package/dist/main.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["
|
|
4
|
-
"sourcesContent": ["export { Database } from './Database.js';", "import { ServiceProvider } from '@jucie.io/engine';\nimport path from 'path';\nimport fs from 'fs';\nimport { promises as fsPromises } from 'fs';\nimport { Collection } from './Collection.js';\nimport { nodeIdleTick, cancelIdleTick } from './nodeIdleTick.js';\nimport { createState } from '@jucie.io/state';\nimport { OnChange } from '@jucie.io/state-on-change';\n\n// Track all database instances for shutdown\nconst databaseInstances = new Set();\nlet shutdownHandlersRegistered = false;\n\nexport class Database extends ServiceProvider {\n #initialized = false;\n #walFilePath = null;\n #dbFilePath = null;\n #removeListener = null;\n #changeCount = 0;\n #checkpointThreshold = 100; // Soft limit - defer to idle\n #forceThreshold = 1000; // Hard limit - force immediate checkpoint\n #promises = new Set();\n #state = null;\n #checkpointScheduled = false;\n #checkpointTimerId = null;\n #lastCheckpoint = Date.now();\n #checkpointInterval = 5000; // 5 seconds\n #isCheckpointing = false;\n #activeBatches = 0;\n\n static manifest = {\n name: 'Database',\n dependencies: [],\n namespace: 'database',\n defaults: {\n debug: false,\n dbPath: './',\n dbName: '.db',\n walPath: './',\n walName: '.wal',\n checkpointThreshold: 100, // Soft limit - defer checkpoint to idle\n forceThreshold: 1000, // Hard limit - force immediate checkpoint\n checkpointInterval: 5000 // Max ms between checkpoints\n }\n }\n\n initialize(useContext, config) {\n let state = useContext('state');\n if (!state) {\n state = createState().install(OnChange);\n }\n this.#state = state;\n this.#checkpointThreshold = config.checkpointThreshold;\n this.#forceThreshold = config.forceThreshold;\n this.#checkpointInterval = config.checkpointInterval;\n \n // Track this instance\n databaseInstances.add(this);\n \n // Register shutdown handlers (once for all instances)\n this.#registerShutdownHandlers();\n }\n \n #registerShutdownHandlers() {\n // Only register once globally\n if (shutdownHandlersRegistered) {\n return;\n }\n \n shutdownHandlersRegistered = true;\n \n const shutdown = async (signal) => {\n console.log(`Received ${signal}, performing final checkpoint on all databases...`);\n \n // Checkpoint all database instances\n for (const db of databaseInstances) {\n try {\n // Cancel any pending checkpoint\n if (db.#checkpointTimerId) {\n cancelIdleTick(db.#checkpointTimerId);\n }\n \n // Force immediate checkpoint to save all data\n if (db.#initialized && db.#changeCount > 0) {\n await db.#performCheckpoint();\n console.log(`Checkpoint completed for database at ${db.#dbFilePath}`);\n }\n } catch (error) {\n console.error(`Error checkpointing database ${db.#dbFilePath}:`, error);\n }\n }\n };\n \n // Handle various exit signals\n process.on('SIGINT', async () => {\n await shutdown('SIGINT');\n process.exit(0);\n });\n \n process.on('SIGTERM', async () => {\n await shutdown('SIGTERM');\n process.exit(0);\n });\n \n process.on('exit', () => {\n // Synchronous only - warn about potential data in WAL\n for (const db of databaseInstances) {\n if (db.#initialized && db.#changeCount > 0) {\n console.warn(`Emergency: Database ${db.#dbFilePath} has ${db.#changeCount} uncommitted changes in WAL`);\n }\n }\n });\n }\n\n actions(useContext, config) {\n return {\n isInitialized: () => this.#initialized,\n beginBatch: () => {\n this.#activeBatches++;\n },\n endBatch: () => {\n this.#activeBatches = Math.max(0, this.#activeBatches - 1);\n // If batch ended and checkpoint was deferred, schedule it now\n if (this.#activeBatches === 0 && this.#checkpointScheduled) {\n this.#scheduleCheckpoint();\n }\n },\n initializeDb: async (newConfig = {}) => {\n config = {...config, ...newConfig};\n try {\n this.#dbFilePath = path.join(config.dbPath, config.dbName);\n this.#walFilePath = path.join(config.walPath, config.walName);\n this.#removeListener = this.#state.onChange.addListener(this.#changeListener);\n\n if (!fs.existsSync(this.#dbFilePath)) {\n const exportedData = await this.#state.export();\n fs.mkdirSync(config.dbPath, { recursive: true });\n fs.writeFileSync(this.#dbFilePath, exportedData);\n }\n\n const exportedData = fs.readFileSync(this.#dbFilePath, 'utf8');\n await this.#state.import(exportedData); \n\n if (fs.existsSync(this.#walFilePath)) {\n const walData = fs.readFileSync(this.#walFilePath, 'utf8');\n const walEntries = walData.trim().split('\\n').filter(line => line.trim());\n\n for (const entry of walEntries) {\n if (!entry) continue;\n const [pathId, change, ledgerEntry] = JSON.parse(entry);\n \n if (change.method === 'set' || change.method === 'update') {\n this.#state.set(change.path, change.to);\n } else if (change.method === 'remove') {\n this.#state.remove(change.path);\n }\n }\n\n await this.#writeToDb();\n }\n\n this.#clearWalFile();\n\n this.#initialized = true;\n return this.#initialized;\n \n } catch (error) {\n console.error('Error initializing database:', error);\n return this.#initialized;\n }\n },\n backup: async (filePath = './backup.json') => {\n try {\n const exportedData = await this.#state.export();\n if (!fs.existsSync(filePath)) {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n }\n fs.writeFileSync(filePath, exportedData);\n return filePath;\n\n } catch (error) {\n console.error('Error backing up database:', error);\n return null;\n }\n },\n restore: async (filePath = './backup.json') => {\n try {\n if (!fs.existsSync(filePath)) {\n throw new Error('Backup file not found');\n }\n const exportedData = fs.readFileSync(filePath, 'utf8');\n await this.#state.import(exportedData);\n return true;\n } catch (error) {\n console.error('Error restoring database:', error);\n return false;\n }\n },\n restoreFromBackup: async () => {\n try {\n const dbBackupPath = `${this.#dbFilePath}.backup`;\n const walBackupPath = `${this.#walFilePath}.backup`;\n\n if (!fs.existsSync(dbBackupPath)) {\n throw new Error('No backup files found');\n }\n\n // Load backup DB\n const exportedData = fs.readFileSync(dbBackupPath, 'utf8');\n await this.#state.import(exportedData);\n\n // Replay backup WAL if it exists\n if (fs.existsSync(walBackupPath)) {\n const walData = fs.readFileSync(walBackupPath, 'utf8');\n const walEntries = walData.trim().split('\\n').filter(line => line.trim());\n\n for (const entry of walEntries) {\n if (!entry) continue;\n const [pathId, change, ledgerEntry] = JSON.parse(entry);\n \n if (change.method === 'set' || change.method === 'update') {\n this.#state.set(change.path, change.to);\n } else if (change.method === 'remove') {\n this.#state.remove(change.path);\n }\n }\n }\n\n console.log('Successfully restored from backup');\n return true;\n } catch (error) {\n console.error('Error restoring from backup:', error);\n return false;\n }\n },\n checkpoint: async () => {\n // Force an immediate checkpoint (respects batching)\n if (this.#activeBatches > 0) {\n // Can't checkpoint during batch, just mark as scheduled\n this.#checkpointScheduled = true;\n return false;\n }\n await this.#performCheckpoint();\n return true;\n },\n close: async () => {\n // Graceful shutdown - checkpoint and clean up\n try {\n // Cancel any pending checkpoint\n if (this.#checkpointTimerId) {\n cancelIdleTick(this.#checkpointTimerId);\n this.#checkpointTimerId = null;\n }\n \n // Final checkpoint if there are pending changes\n if (this.#changeCount > 0) {\n await this.#performCheckpoint();\n }\n \n // Remove change listener\n if (this.#removeListener) {\n this.#removeListener();\n this.#removeListener = null;\n }\n \n // Remove from tracked instances\n databaseInstances.delete(this);\n \n this.#initialized = false;\n return true;\n } catch (error) {\n console.error('Error closing database:', error);\n return false;\n }\n },\n destroy: () => {\n try {\n this.#removeListener();\n \n // Cancel any pending checkpoint\n if (this.#checkpointTimerId) {\n cancelIdleTick(this.#checkpointTimerId);\n this.#checkpointTimerId = null;\n }\n \n this.#unlinkAllFiles();\n this.#removeListener = null;\n this.#state.reset();\n \n // Remove from tracked instances\n databaseInstances.delete(this);\n \n return true;\n } catch (error) {\n console.error('Error destroying database:', error);\n return false;\n }\n },\n collection: (name) => {\n return Collection.create(this.#state.ref(name), this);\n },\n _beginBatch: () => {\n this.#activeBatches++;\n },\n _endBatch: () => {\n this.#activeBatches = Math.max(0, this.#activeBatches - 1);\n // If batch ended and checkpoint was deferred, schedule it now\n if (this.#activeBatches === 0 && this.#checkpointScheduled) {\n this.#scheduleCheckpoint();\n }\n },\n batch: (fn) => {\n this.#activeBatches++;\n try {\n return this.#state.batch(fn);\n } finally {\n this.#activeBatches = Math.max(0, this.#activeBatches - 1);\n // If batch ended and checkpoint was deferred, schedule it now\n if (this.#activeBatches === 0 && this.#checkpointScheduled) {\n this.#scheduleCheckpoint();\n }\n }\n },\n ...this.#debugFunctions(this.config.debug)\n }\n }\n\n\n // Set up change listener for future changes\n #changeListener = async (changeEntries) => {\n this.#changeCount += changeEntries.length;\n this.#writeToWal(changeEntries); // Synchronous WAL write (fast, durable)\n\n const timeSinceCheckpoint = Date.now() - this.#lastCheckpoint;\n \n // Check if we hit the FORCE threshold - immediate checkpoint required\n if (this.#changeCount >= this.#forceThreshold) {\n console.warn(`Force checkpoint triggered at ${this.#changeCount} changes`);\n this.#changeCount = 0;\n await this.#performCheckpoint();\n return;\n }\n\n // Check if we should schedule a deferred checkpoint\n const shouldSchedule = \n this.#changeCount >= this.#checkpointThreshold || \n timeSinceCheckpoint >= this.#checkpointInterval;\n\n if (shouldSchedule) {\n this.#scheduleCheckpoint();\n this.#changeCount = 0;\n }\n this.#resolvePromises();\n }\n\n #resolvePromises = () => {\n if (this.#promises.size === 0) return;\n this.#promises.forEach((resolve) => resolve());\n this.#promises.clear();\n }\n\n #scheduleCheckpoint = () => {\n // If already scheduled, don't schedule again\n if (this.#checkpointScheduled && this.#checkpointTimerId) {\n return;\n }\n\n // Mark as scheduled\n this.#checkpointScheduled = true;\n\n // If there are active batches/transactions, defer until they complete\n if (this.#activeBatches > 0) {\n return; // Will be scheduled when endBatch() is called\n }\n\n // Schedule checkpoint for next idle tick\n this.#checkpointTimerId = nodeIdleTick(async () => {\n await this.#performCheckpoint();\n });\n }\n\n #performCheckpoint = async () => {\n // Double-check no batches started since scheduling\n if (this.#activeBatches > 0) {\n // Reschedule for later\n this.#checkpointTimerId = nodeIdleTick(async () => {\n await this.#performCheckpoint();\n });\n return;\n }\n\n // Prevent concurrent checkpoints\n if (this.#isCheckpointing) {\n return;\n }\n\n try {\n this.#isCheckpointing = true;\n \n // Backup current DB and WAL before checkpoint\n await this.#backupCurrentFiles();\n \n // Write new checkpoint\n await this.#writeToDb();\n await this.#clearWalFileAsync();\n this.#lastCheckpoint = Date.now();\n } catch (error) {\n console.error('Error during checkpoint:', error);\n // On error, backup files still exist for recovery\n } finally {\n this.#isCheckpointing = false;\n this.#checkpointScheduled = false;\n this.#checkpointTimerId = null;\n }\n }\n\n #backupCurrentFiles = async () => {\n const dbBackupPath = `${this.#dbFilePath}.backup`;\n const walBackupPath = `${this.#walFilePath}.backup`;\n\n try {\n // Backup DB file if it exists\n if (fs.existsSync(this.#dbFilePath)) {\n await fsPromises.copyFile(this.#dbFilePath, dbBackupPath);\n }\n\n // Backup WAL file if it exists\n if (fs.existsSync(this.#walFilePath)) {\n await fsPromises.copyFile(this.#walFilePath, walBackupPath);\n }\n } catch (error) {\n console.error('Error backing up files:', error);\n // Continue anyway - backup is best effort\n }\n }\n\n #writeToDb = async () => {\n const exportedData = await this.#state.export();\n // Use async write to avoid blocking event loop\n await fsPromises.writeFile(this.#dbFilePath, exportedData, 'utf8');\n }\n\n #unlinkDbFile = () => {\n if (fs.existsSync(this.#dbFilePath)) {\n fs.unlinkSync(this.#dbFilePath);\n }\n }\n\n #writeToWal = (changeEntries) => {\n let wallData = '';\n for (const changeEntry of changeEntries) {\n wallData += JSON.stringify(changeEntry) + '\\n';\n }\n fs.appendFileSync(this.#walFilePath, wallData);\n }\n\n #unlinkWalFile = () => {\n if (fs.existsSync(this.#walFilePath)) {\n fs.unlinkSync(this.#walFilePath);\n }\n }\n\n #clearWalFile = () => {\n if (fs.existsSync(this.#walFilePath)) {\n fs.writeFileSync(this.#walFilePath, '');\n }\n }\n\n #clearWalFileAsync = async () => {\n if (fs.existsSync(this.#walFilePath)) {\n await fsPromises.writeFile(this.#walFilePath, '', 'utf8');\n }\n }\n\n #unlinkAllFiles = () => {\n this.#unlinkWalFile();\n this.#unlinkDbFile();\n }\n\n #debugFunctions (debug = false) {\n return (debug ? {\n _afterWrite: () => {\n return new Promise((resolve) => this.#promises.add(resolve));\n },\n _clearDatabase: () => {\n try {\n this.#state.reset();\n if (fs.existsSync(this.#dbFilePath)) {\n fs.unlinkSync(this.#dbFilePath);\n }\n return true;\n } catch (error) {\n console.error('Error clearing database:', error);\n return false;\n }\n },\n _clearChanges: () => {\n try {\n this.#changeCount = 0;\n return true;\n } catch (error) {\n console.error('Error clearing changes:', error);\n return false;\n }\n },\n _getChangeCount: () => {\n return this.#changeCount;\n },\n _clearWAL: () => {\n try {\n if (fs.existsSync(this.#walFilePath)) {\n fs.writeFileSync(this.#walFilePath, '');\n }\n return true;\n } catch (error) {\n console.error('Error clearing WAL:', error);\n return false;\n }\n },\n _applyWAL: async () => {\n try {\n if (!fs.existsSync(this.#walFilePath)) {\n return false;\n }\n const walData = fs.readFileSync(this.#walFilePath, 'utf8');\n const walEntries = walData.trim().split('\\n').map(line => JSON.parse(line));\n this.#state.apply(walEntries);\n fs.writeFileSync(this.#walFilePath, '');\n return true;\n } catch (error) {\n console.error('Error applying WAL:', error);\n return false;\n }\n },\n _checkpoint: async () => {\n try {\n // Give engine time to process all queued changes\n await new Promise(resolve => setTimeout(resolve, 10));\n \n // Wait for any pending changes to complete first\n await new Promise(resolve => {\n if (this.#promises.size === 0) {\n resolve();\n } else {\n this.#promises.add(resolve);\n }\n });\n \n // Use the new checkpoint mechanism\n await this.#performCheckpoint();\n return true;\n } catch (error) {\n console.error('Error during checkpoint:', error);\n return false;\n }\n },\n _getWALEntries: () => {\n try {\n if (!fs.existsSync(this.#walFilePath)) {\n return [];\n }\n const walData = fs.readFileSync(this.#walFilePath, 'utf8');\n if (walData.trim().length === 0) {\n return [];\n }\n return walData.trim().split('\\n').map(line => JSON.parse(line));\n } catch (error) {\n console.error('Error reading WAL entries:', error);\n return [];\n }\n },\n _getWALEntryCount: () => {\n try {\n if (!fs.existsSync(this.#walFilePath)) {\n return 0;\n }\n const walData = fs.readFileSync(this.#walFilePath, 'utf8');\n return walData.trim().split('\\n').filter(line => line.trim() !== '').length;\n } catch (error) {\n console.error('Error counting WAL entries:', error);\n return 0;\n }\n }\n } : {})\n }\n}", "import crypto from 'crypto'\nimport { urlAlphabet } from './url-alphabet/index.js'\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\nlet fillPool = bytes => {\n if (!pool || pool.length < bytes) {\n pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n crypto.randomFillSync(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.randomFillSync(pool)\n poolOffset = 0\n }\n poolOffset += bytes\n}\nlet random = bytes => {\n fillPool((bytes |= 0))\n return pool.subarray(poolOffset - bytes, poolOffset)\n}\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1\n let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let i = step\n while (i--) {\n id += alphabet[bytes[i] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) => {\n fillPool((size |= 0))\n let id = ''\n for (let i = poolOffset - size; i < poolOffset; i++) {\n id += urlAlphabet[pool[i] & 63]\n }\n return id\n}\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n", "let urlAlphabet =\n 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'\nexport { urlAlphabet }\n", "import { nanoid } from 'nanoid'; // Will be bundled\n\n\nexport class Collection {\n static create(state, database = null) {\n return new Collection(state, database);\n }\n\n constructor(state, database = null) {\n this.state = state;\n this.database = database;\n }\n\n add(value) {\n try {\n const id = nanoid();\n this.state.set([id], value);\n return id\n } catch (error) {\n console.error('Error adding value to database:', error);\n return null;\n }\n }\n\n set(...args) {\n try {\n const [key, value] = args;\n this.state.set(key, value);\n return true;\n } catch (error) {\n console.error('Error setting value in database:', error);\n return undefined;\n }\n }\n\n get(path = []) {\n try {\n return this.state.get(path);\n } catch (error) {\n console.error('Error getting value from database:', error);\n return undefined;\n }\n }\n\n has(path) {\n try {\n return this.state.has(path);\n } catch (error) {\n console.error('Error checking if key exists in database:', error);\n return false;\n }\n }\n\n remove(path) {\n try {\n return this.state.remove(path);\n } catch (error) {\n console.error('Error removing from database:', error);\n return this;\n }\n }\n\n update(path, fn) {\n try {\n return this.state.update(path, fn);\n } catch (error) {\n console.error('Error updating value in database:', error);\n return undefined;\n }\n }\n\n keys(path = []) {\n try {\n return this.state.keys(path);\n } catch (error) {\n console.error('Error getting keys from database:', error);\n return [];\n }\n }\n\n findWhere(key, matcher, value) {\n try {\n const path = this.state.findWhere(key, matcher, value);\n if (path.length === 0) return null;\n const [id] = path;\n return this.state.get([id]);\n } catch (error) {\n console.error('Error finding value in database:', error);\n return null;\n }\n }\n\n findAllWhere(key, matcher, value) {\n try {\n const paths = this.state.findAllWhere(key, matcher, value);\n return paths.map(path => {\n const [id] = path;\n return this.state.get([id]);\n });\n } catch (error) {\n console.error('Error finding all values in database:', error);\n return [];\n }\n }\n\n typeof(path) {\n try {\n return this.state.typeof(path);\n } catch (error) {\n console.error('Error getting type of value in database:', error);\n return null;\n }\n }\n\n collection(name) {\n return Collection.create(this.state.ref(name), this.database);\n }\n\n batch(fn) {\n if (!this.database) {\n // No database context, just execute directly\n return this.state.batch(fn);\n }\n\n // Use database's batch tracking to defer checkpoints\n this.database._beginBatch();\n try {\n return this.state.batch(fn);\n } finally {\n this.database._endBatch();\n }\n }\n}", "/**\n * Node.js idle tick scheduler\n * \n * Defers execution to the next event loop cycle when the system is less busy.\n * Unlike browser's requestIdleCallback, this uses setImmediate for the next tick.\n */\n\nexport function nodeIdleTick(callback) {\n if (typeof setImmediate !== 'undefined') {\n return setImmediate(callback);\n }\n \n // Fallback to process.nextTick (executes before I/O)\n if (typeof process !== 'undefined' && process.nextTick) {\n return process.nextTick(callback);\n }\n \n // Final fallback\n return setTimeout(callback, 0);\n}\n\n/**\n * Cancels a scheduled idle tick callback\n */\nexport function cancelIdleTick(id) {\n if (typeof clearImmediate !== 'undefined') {\n clearImmediate(id);\n } else {\n clearTimeout(id);\n }\n}\n\n"],
|
|
5
|
-
"mappings": "6iBAAA,IAA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EACnC,EACT,CACH,EACD,YAAa,SAAY,CACvB,GAAI,CAEF,aAAM,IAAI,QAAQ2B,GAAW,WAAWA,EAAS,EAAE,CAAC,EAGpD,MAAM,IAAI,QAAQA,GAAW,CACvB,KAAK5C,GAAU,OAAS,EAC1B4C,EAAQ,EAER,KAAK5C,GAAU,IAAI4C,CAAO,CAE9B,CAAC,EAGD,MAAM,KAAK5B,GAAmB,EACvB,EACT,OAASC,EAAO,CACd,eAAQ,MAAM,2BAA4BA,CAAK,EACxC,EACT,CACF,EACA,eAAgB,IAAM,CACpB,GAAI,CACF,GAAI,CAAC,EAAAK,QAAG,WAAW,KAAK5B,EAAY,EAClC,MAAO,CAAC,EAEV,IAAM4D,EAAU,EAAAhC,QAAG,aAAa,KAAK5B,GAAc,MAAM,EACzD,OAAI4D,EAAQ,KAAK,EAAE,SAAW,EACrB,CAAC,EAEHA,EAAQ,KAAK,EAAE,MAAM;AAAA,CAAI,EAAE,IAAI7B,GAAQ,KAAK,MAAMA,CAAI,CAAC,CAChE,OAASR,EAAO,CACd,eAAQ,MAAM,6BAA8BA,CAAK,EAC1C,CAAC,CACV,CACF,EACA,kBAAmB,IAAM,CACvB,GAAI,CACF,OAAK,EAAAK,QAAG,WAAW,KAAK5B,EAAY,EAGpB,EAAA4B,QAAG,aAAa,KAAK5B,GAAc,MAAM,EAC1C,KAAK,EAAE,MAAM;AAAA,CAAI,EAAE,OAAO+B,GAAQA,EAAK,KAAK,IAAM,EAAE,EAAE,OAH5D,CAIX,OAASR,EAAO,CACd,eAAQ,MAAM,8BAA+BA,CAAK,EAC3C,CACT,CACF,CACF,EAAI,CAAC,CACP,CACF",
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../../../node_modules/nanoid/url-alphabet/index.js", "../../../node_modules/nanoid/index.js", "../src/Collection.js", "../src/nodeIdleTick.js", "../src/Database.js"],
|
|
4
|
+
"sourcesContent": ["let urlAlphabet =\n 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'\nexport { urlAlphabet }\n", "import crypto from 'crypto'\nimport { urlAlphabet } from './url-alphabet/index.js'\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\nlet fillPool = bytes => {\n if (!pool || pool.length < bytes) {\n pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n crypto.randomFillSync(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.randomFillSync(pool)\n poolOffset = 0\n }\n poolOffset += bytes\n}\nlet random = bytes => {\n fillPool((bytes |= 0))\n return pool.subarray(poolOffset - bytes, poolOffset)\n}\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1\n let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let i = step\n while (i--) {\n id += alphabet[bytes[i] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) => {\n fillPool((size |= 0))\n let id = ''\n for (let i = poolOffset - size; i < poolOffset; i++) {\n id += urlAlphabet[pool[i] & 63]\n }\n return id\n}\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n", "import { nanoid } from 'nanoid'; // Will be bundled\n\n\nexport class Collection {\n static create(state, database = null) {\n return new Collection(state, database);\n }\n\n constructor(state, database = null) {\n this.state = state;\n this.database = database;\n }\n\n add(value) {\n try {\n const id = nanoid();\n this.state.set([id], value);\n return id\n } catch (error) {\n console.error('Error adding value to database:', error);\n return null;\n }\n }\n\n set(...args) {\n try {\n const [key, value] = args;\n this.state.set(key, value);\n return true;\n } catch (error) {\n console.error('Error setting value in database:', error);\n return undefined;\n }\n }\n\n get(path = []) {\n try {\n return this.state.get(path);\n } catch (error) {\n console.error('Error getting value from database:', error);\n return undefined;\n }\n }\n\n has(path) {\n try {\n return this.state.has(path);\n } catch (error) {\n console.error('Error checking if key exists in database:', error);\n return false;\n }\n }\n\n remove(path) {\n try {\n return this.state.remove(path);\n } catch (error) {\n console.error('Error removing from database:', error);\n return this;\n }\n }\n\n update(path, fn) {\n try {\n return this.state.update(path, fn);\n } catch (error) {\n console.error('Error updating value in database:', error);\n return undefined;\n }\n }\n\n keys(path = []) {\n try {\n return this.state.keys(path);\n } catch (error) {\n console.error('Error getting keys from database:', error);\n return [];\n }\n }\n\n findWhere(key, matcher, value) {\n try {\n const path = this.state.findWhere(key, matcher, value);\n if (path.length === 0) return null;\n const [id] = path;\n return this.state.get([id]);\n } catch (error) {\n console.error('Error finding value in database:', error);\n return null;\n }\n }\n\n findAllWhere(key, matcher, value) {\n try {\n const paths = this.state.findAllWhere(key, matcher, value);\n return paths.map(path => {\n const [id] = path;\n return this.state.get([id]);\n });\n } catch (error) {\n console.error('Error finding all values in database:', error);\n return [];\n }\n }\n\n typeof(path) {\n try {\n return this.state.typeof(path);\n } catch (error) {\n console.error('Error getting type of value in database:', error);\n return null;\n }\n }\n\n collection(name) {\n return Collection.create(this.state.ref(name), this.database);\n }\n\n batch(fn) {\n if (!this.database) {\n // No database context, just execute directly\n return this.state.batch(fn);\n }\n\n // Use database's batch tracking to defer checkpoints\n this.database._beginBatch();\n try {\n return this.state.batch(fn);\n } finally {\n this.database._endBatch();\n }\n }\n}", "/**\n * Node.js idle tick scheduler\n * \n * Defers execution to the next event loop cycle when the system is less busy.\n * Unlike browser's requestIdleCallback, this uses setImmediate for the next tick.\n */\n\nexport function nodeIdleTick(callback) {\n if (typeof setImmediate !== 'undefined') {\n return setImmediate(callback);\n }\n \n // Fallback to process.nextTick (executes before I/O)\n if (typeof process !== 'undefined' && process.nextTick) {\n return process.nextTick(callback);\n }\n \n // Final fallback\n return setTimeout(callback, 0);\n}\n\n/**\n * Cancels a scheduled idle tick callback\n */\nexport function cancelIdleTick(id) {\n if (typeof clearImmediate !== 'undefined') {\n clearImmediate(id);\n } else {\n clearTimeout(id);\n }\n}\n\n", "import { ServiceProvider } from '@jucie.io/engine';\nimport path from 'path';\nimport fs from 'fs';\nimport { promises as fsPromises } from 'fs';\nimport { Collection } from './Collection.js';\nimport { nodeIdleTick, cancelIdleTick } from './nodeIdleTick.js';\nimport { createState } from '@jucie.io/state';\nimport { OnChange } from '@jucie.io/state-on-change';\n\n// Track all database instances for shutdown\nconst databaseInstances = new Set();\nlet shutdownHandlersRegistered = false;\n\nexport class Database extends ServiceProvider {\n #initialized = false;\n #walFilePath = null;\n #dbFilePath = null;\n #removeListener = null;\n #changeCount = 0;\n #checkpointThreshold = 100; // Soft limit - defer to idle\n #forceThreshold = 1000; // Hard limit - force immediate checkpoint\n #promises = new Set();\n #state = null;\n #checkpointScheduled = false;\n #checkpointTimerId = null;\n #lastCheckpoint = Date.now();\n #checkpointInterval = 5000; // 5 seconds\n #isCheckpointing = false;\n #activeBatches = 0;\n\n static manifest = {\n name: 'Database',\n dependencies: [],\n namespace: 'database',\n defaults: {\n debug: false,\n dbPath: './',\n dbName: '.db',\n walPath: './',\n walName: '.wal',\n checkpointThreshold: 100, // Soft limit - defer checkpoint to idle\n forceThreshold: 1000, // Hard limit - force immediate checkpoint\n checkpointInterval: 5000 // Max ms between checkpoints\n }\n }\n\n initialize(useContext, config) {\n let state = useContext('state');\n if (!state) {\n state = createState().install(OnChange);\n }\n this.#state = state;\n this.#checkpointThreshold = config.checkpointThreshold;\n this.#forceThreshold = config.forceThreshold;\n this.#checkpointInterval = config.checkpointInterval;\n \n // Track this instance\n databaseInstances.add(this);\n \n // Register shutdown handlers (once for all instances)\n this.#registerShutdownHandlers();\n }\n \n #registerShutdownHandlers() {\n // Only register once globally\n if (shutdownHandlersRegistered) {\n return;\n }\n \n shutdownHandlersRegistered = true;\n \n const shutdown = async (signal) => {\n console.log(`Received ${signal}, performing final checkpoint on all databases...`);\n \n // Checkpoint all database instances\n for (const db of databaseInstances) {\n try {\n // Cancel any pending checkpoint\n if (db.#checkpointTimerId) {\n cancelIdleTick(db.#checkpointTimerId);\n }\n \n // Force immediate checkpoint to save all data\n if (db.#initialized && db.#changeCount > 0) {\n await db.#performCheckpoint();\n console.log(`Checkpoint completed for database at ${db.#dbFilePath}`);\n }\n } catch (error) {\n console.error(`Error checkpointing database ${db.#dbFilePath}:`, error);\n }\n }\n };\n \n // Handle various exit signals\n process.on('SIGINT', async () => {\n await shutdown('SIGINT');\n process.exit(0);\n });\n \n process.on('SIGTERM', async () => {\n await shutdown('SIGTERM');\n process.exit(0);\n });\n \n process.on('exit', () => {\n // Synchronous only - warn about potential data in WAL\n for (const db of databaseInstances) {\n if (db.#initialized && db.#changeCount > 0) {\n console.warn(`Emergency: Database ${db.#dbFilePath} has ${db.#changeCount} uncommitted changes in WAL`);\n }\n }\n });\n }\n\n actions(useContext, config) {\n return {\n isInitialized: () => this.#initialized,\n beginBatch: () => {\n this.#activeBatches++;\n },\n endBatch: () => {\n this.#activeBatches = Math.max(0, this.#activeBatches - 1);\n // If batch ended and checkpoint was deferred, schedule it now\n if (this.#activeBatches === 0 && this.#checkpointScheduled) {\n this.#scheduleCheckpoint();\n }\n },\n initializeDb: async (newConfig = {}) => {\n config = {...config, ...newConfig};\n try {\n this.#dbFilePath = path.join(config.dbPath, config.dbName);\n this.#walFilePath = path.join(config.walPath, config.walName);\n this.#removeListener = this.#state.onChange.addListener(this.#changeListener);\n\n if (!fs.existsSync(this.#dbFilePath)) {\n const exportedData = await this.#state.export();\n fs.mkdirSync(config.dbPath, { recursive: true });\n fs.writeFileSync(this.#dbFilePath, exportedData);\n }\n\n const exportedData = fs.readFileSync(this.#dbFilePath, 'utf8');\n await this.#state.import(exportedData); \n\n if (fs.existsSync(this.#walFilePath)) {\n const walData = fs.readFileSync(this.#walFilePath, 'utf8');\n const walEntries = walData.trim().split('\\n').filter(line => line.trim());\n\n for (const entry of walEntries) {\n if (!entry) continue;\n const [pathId, change, ledgerEntry] = JSON.parse(entry);\n \n if (change.method === 'set' || change.method === 'update') {\n this.#state.set(change.path, change.to);\n } else if (change.method === 'remove') {\n this.#state.remove(change.path);\n }\n }\n\n await this.#writeToDb();\n }\n\n this.#clearWalFile();\n\n this.#initialized = true;\n return this.#initialized;\n \n } catch (error) {\n console.error('Error initializing database:', error);\n return this.#initialized;\n }\n },\n backup: async (filePath = './backup.json') => {\n try {\n const exportedData = await this.#state.export();\n if (!fs.existsSync(filePath)) {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n }\n fs.writeFileSync(filePath, exportedData);\n return filePath;\n\n } catch (error) {\n console.error('Error backing up database:', error);\n return null;\n }\n },\n restore: async (filePath = './backup.json') => {\n try {\n if (!fs.existsSync(filePath)) {\n throw new Error('Backup file not found');\n }\n const exportedData = fs.readFileSync(filePath, 'utf8');\n await this.#state.import(exportedData);\n return true;\n } catch (error) {\n console.error('Error restoring database:', error);\n return false;\n }\n },\n restoreFromBackup: async () => {\n try {\n const dbBackupPath = `${this.#dbFilePath}.backup`;\n const walBackupPath = `${this.#walFilePath}.backup`;\n\n if (!fs.existsSync(dbBackupPath)) {\n throw new Error('No backup files found');\n }\n\n // Load backup DB\n const exportedData = fs.readFileSync(dbBackupPath, 'utf8');\n await this.#state.import(exportedData);\n\n // Replay backup WAL if it exists\n if (fs.existsSync(walBackupPath)) {\n const walData = fs.readFileSync(walBackupPath, 'utf8');\n const walEntries = walData.trim().split('\\n').filter(line => line.trim());\n\n for (const entry of walEntries) {\n if (!entry) continue;\n const [pathId, change, ledgerEntry] = JSON.parse(entry);\n \n if (change.method === 'set' || change.method === 'update') {\n this.#state.set(change.path, change.to);\n } else if (change.method === 'remove') {\n this.#state.remove(change.path);\n }\n }\n }\n\n console.log('Successfully restored from backup');\n return true;\n } catch (error) {\n console.error('Error restoring from backup:', error);\n return false;\n }\n },\n checkpoint: async () => {\n // Force an immediate checkpoint (respects batching)\n if (this.#activeBatches > 0) {\n // Can't checkpoint during batch, just mark as scheduled\n this.#checkpointScheduled = true;\n return false;\n }\n await this.#performCheckpoint();\n return true;\n },\n close: async () => {\n // Graceful shutdown - checkpoint and clean up\n try {\n // Cancel any pending checkpoint\n if (this.#checkpointTimerId) {\n cancelIdleTick(this.#checkpointTimerId);\n this.#checkpointTimerId = null;\n }\n \n // Final checkpoint if there are pending changes\n if (this.#changeCount > 0) {\n await this.#performCheckpoint();\n }\n \n // Remove change listener\n if (this.#removeListener) {\n this.#removeListener();\n this.#removeListener = null;\n }\n \n // Remove from tracked instances\n databaseInstances.delete(this);\n \n this.#initialized = false;\n return true;\n } catch (error) {\n console.error('Error closing database:', error);\n return false;\n }\n },\n destroy: () => {\n try {\n this.#removeListener();\n \n // Cancel any pending checkpoint\n if (this.#checkpointTimerId) {\n cancelIdleTick(this.#checkpointTimerId);\n this.#checkpointTimerId = null;\n }\n \n this.#unlinkAllFiles();\n this.#removeListener = null;\n this.#state.reset();\n \n // Remove from tracked instances\n databaseInstances.delete(this);\n \n return true;\n } catch (error) {\n console.error('Error destroying database:', error);\n return false;\n }\n },\n collection: (name) => {\n return Collection.create(this.#state.ref(name), this);\n },\n _beginBatch: () => {\n this.#activeBatches++;\n },\n _endBatch: () => {\n this.#activeBatches = Math.max(0, this.#activeBatches - 1);\n // If batch ended and checkpoint was deferred, schedule it now\n if (this.#activeBatches === 0 && this.#checkpointScheduled) {\n this.#scheduleCheckpoint();\n }\n },\n batch: (fn) => {\n this.#activeBatches++;\n try {\n return this.#state.batch(fn);\n } finally {\n this.#activeBatches = Math.max(0, this.#activeBatches - 1);\n // If batch ended and checkpoint was deferred, schedule it now\n if (this.#activeBatches === 0 && this.#checkpointScheduled) {\n this.#scheduleCheckpoint();\n }\n }\n },\n ...this.#debugFunctions(this.config.debug)\n }\n }\n\n\n // Set up change listener for future changes\n #changeListener = async (changeEntries) => {\n this.#changeCount += changeEntries.length;\n this.#writeToWal(changeEntries); // Synchronous WAL write (fast, durable)\n\n const timeSinceCheckpoint = Date.now() - this.#lastCheckpoint;\n \n // Check if we hit the FORCE threshold - immediate checkpoint required\n if (this.#changeCount >= this.#forceThreshold) {\n console.warn(`Force checkpoint triggered at ${this.#changeCount} changes`);\n this.#changeCount = 0;\n await this.#performCheckpoint();\n return;\n }\n\n // Check if we should schedule a deferred checkpoint\n const shouldSchedule = \n this.#changeCount >= this.#checkpointThreshold || \n timeSinceCheckpoint >= this.#checkpointInterval;\n\n if (shouldSchedule) {\n this.#scheduleCheckpoint();\n this.#changeCount = 0;\n }\n this.#resolvePromises();\n }\n\n #resolvePromises = () => {\n if (this.#promises.size === 0) return;\n this.#promises.forEach((resolve) => resolve());\n this.#promises.clear();\n }\n\n #scheduleCheckpoint = () => {\n // If already scheduled, don't schedule again\n if (this.#checkpointScheduled && this.#checkpointTimerId) {\n return;\n }\n\n // Mark as scheduled\n this.#checkpointScheduled = true;\n\n // If there are active batches/transactions, defer until they complete\n if (this.#activeBatches > 0) {\n return; // Will be scheduled when endBatch() is called\n }\n\n // Schedule checkpoint for next idle tick\n this.#checkpointTimerId = nodeIdleTick(async () => {\n await this.#performCheckpoint();\n });\n }\n\n #performCheckpoint = async () => {\n // Double-check no batches started since scheduling\n if (this.#activeBatches > 0) {\n // Reschedule for later\n this.#checkpointTimerId = nodeIdleTick(async () => {\n await this.#performCheckpoint();\n });\n return;\n }\n\n // Prevent concurrent checkpoints\n if (this.#isCheckpointing) {\n return;\n }\n\n try {\n this.#isCheckpointing = true;\n \n // Backup current DB and WAL before checkpoint\n await this.#backupCurrentFiles();\n \n // Write new checkpoint\n await this.#writeToDb();\n await this.#clearWalFileAsync();\n this.#lastCheckpoint = Date.now();\n } catch (error) {\n console.error('Error during checkpoint:', error);\n // On error, backup files still exist for recovery\n } finally {\n this.#isCheckpointing = false;\n this.#checkpointScheduled = false;\n this.#checkpointTimerId = null;\n }\n }\n\n #backupCurrentFiles = async () => {\n const dbBackupPath = `${this.#dbFilePath}.backup`;\n const walBackupPath = `${this.#walFilePath}.backup`;\n\n try {\n // Backup DB file if it exists\n if (fs.existsSync(this.#dbFilePath)) {\n await fsPromises.copyFile(this.#dbFilePath, dbBackupPath);\n }\n\n // Backup WAL file if it exists\n if (fs.existsSync(this.#walFilePath)) {\n await fsPromises.copyFile(this.#walFilePath, walBackupPath);\n }\n } catch (error) {\n console.error('Error backing up files:', error);\n // Continue anyway - backup is best effort\n }\n }\n\n #writeToDb = async () => {\n const exportedData = await this.#state.export();\n // Use async write to avoid blocking event loop\n await fsPromises.writeFile(this.#dbFilePath, exportedData, 'utf8');\n }\n\n #unlinkDbFile = () => {\n if (fs.existsSync(this.#dbFilePath)) {\n fs.unlinkSync(this.#dbFilePath);\n }\n }\n\n #writeToWal = (changeEntries) => {\n let wallData = '';\n for (const changeEntry of changeEntries) {\n wallData += JSON.stringify(changeEntry) + '\\n';\n }\n fs.appendFileSync(this.#walFilePath, wallData);\n }\n\n #unlinkWalFile = () => {\n if (fs.existsSync(this.#walFilePath)) {\n fs.unlinkSync(this.#walFilePath);\n }\n }\n\n #clearWalFile = () => {\n if (fs.existsSync(this.#walFilePath)) {\n fs.writeFileSync(this.#walFilePath, '');\n }\n }\n\n #clearWalFileAsync = async () => {\n if (fs.existsSync(this.#walFilePath)) {\n await fsPromises.writeFile(this.#walFilePath, '', 'utf8');\n }\n }\n\n #unlinkAllFiles = () => {\n this.#unlinkWalFile();\n this.#unlinkDbFile();\n }\n\n #debugFunctions (debug = false) {\n return (debug ? {\n _afterWrite: () => {\n return new Promise((resolve) => this.#promises.add(resolve));\n },\n _clearDatabase: () => {\n try {\n this.#state.reset();\n if (fs.existsSync(this.#dbFilePath)) {\n fs.unlinkSync(this.#dbFilePath);\n }\n return true;\n } catch (error) {\n console.error('Error clearing database:', error);\n return false;\n }\n },\n _clearChanges: () => {\n try {\n this.#changeCount = 0;\n return true;\n } catch (error) {\n console.error('Error clearing changes:', error);\n return false;\n }\n },\n _getChangeCount: () => {\n return this.#changeCount;\n },\n _clearWAL: () => {\n try {\n if (fs.existsSync(this.#walFilePath)) {\n fs.writeFileSync(this.#walFilePath, '');\n }\n return true;\n } catch (error) {\n console.error('Error clearing WAL:', error);\n return false;\n }\n },\n _applyWAL: async () => {\n try {\n if (!fs.existsSync(this.#walFilePath)) {\n return false;\n }\n const walData = fs.readFileSync(this.#walFilePath, 'utf8');\n const walEntries = walData.trim().split('\\n').map(line => JSON.parse(line));\n this.#state.apply(walEntries);\n fs.writeFileSync(this.#walFilePath, '');\n return true;\n } catch (error) {\n console.error('Error applying WAL:', error);\n return false;\n }\n },\n _checkpoint: async () => {\n try {\n // Give engine time to process all queued changes\n await new Promise(resolve => setTimeout(resolve, 10));\n \n // Wait for any pending changes to complete first\n await new Promise(resolve => {\n if (this.#promises.size === 0) {\n resolve();\n } else {\n this.#promises.add(resolve);\n }\n });\n \n // Use the new checkpoint mechanism\n await this.#performCheckpoint();\n return true;\n } catch (error) {\n console.error('Error during checkpoint:', error);\n return false;\n }\n },\n _getWALEntries: () => {\n try {\n if (!fs.existsSync(this.#walFilePath)) {\n return [];\n }\n const walData = fs.readFileSync(this.#walFilePath, 'utf8');\n if (walData.trim().length === 0) {\n return [];\n }\n return walData.trim().split('\\n').map(line => JSON.parse(line));\n } catch (error) {\n console.error('Error reading WAL entries:', error);\n return [];\n }\n },\n _getWALEntryCount: () => {\n try {\n if (!fs.existsSync(this.#walFilePath)) {\n return 0;\n }\n const walData = fs.readFileSync(this.#walFilePath, 'utf8');\n return walData.trim().split('\\n').filter(line => line.trim() !== '').length;\n } catch (error) {\n console.error('Error counting WAL entries:', error);\n return 0;\n }\n }\n } : {})\n }\n}"],
|
|
5
|
+
"mappings": "AAAA,IAAIA,EACF,mECDF,OAAOC,MAAY,SAEnB,IAAMC,EAAuB,IACzBC,EAAMC,EACNC,EAAWC,GAAS,CAClB,CAACH,GAAQA,EAAK,OAASG,GACzBH,EAAO,OAAO,YAAYG,EAAQJ,CAAoB,EACtDD,EAAO,eAAeE,CAAI,EAC1BC,EAAa,GACJA,EAAaE,EAAQH,EAAK,SACnCF,EAAO,eAAeE,CAAI,EAC1BC,EAAa,GAEf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BAAuBA,CAAK,EACnC,EACT,CACH,EACD,YAAa,SAAY,CACvB,GAAI,CAEF,aAAM,IAAI,QAAQyB,GAAW,WAAWA,EAAS,EAAE,CAAC,EAGpD,MAAM,IAAI,QAAQA,GAAW,CACvB,KAAK1C,GAAU,OAAS,EAC1B0C,EAAQ,EAER,KAAK1C,GAAU,IAAI0C,CAAO,CAE9B,CAAC,EAGD,MAAM,KAAK1B,GAAmB,EACvB,EACT,OAASC,EAAO,CACd,eAAQ,MAAM,2BAA4BA,CAAK,EACxC,EACT,CACF,EACA,eAAgB,IAAM,CACpB,GAAI,CACF,GAAI,CAAC/B,EAAG,WAAW,KAAKQ,EAAY,EAClC,MAAO,CAAC,EAEV,IAAMyD,EAAUjE,EAAG,aAAa,KAAKQ,GAAc,MAAM,EACzD,OAAIyD,EAAQ,KAAK,EAAE,SAAW,EACrB,CAAC,EAEHA,EAAQ,KAAK,EAAE,MAAM;AAAA,CAAI,EAAE,IAAI5B,GAAQ,KAAK,MAAMA,CAAI,CAAC,CAChE,OAASN,EAAO,CACd,eAAQ,MAAM,6BAA8BA,CAAK,EAC1C,CAAC,CACV,CACF,EACA,kBAAmB,IAAM,CACvB,GAAI,CACF,OAAK/B,EAAG,WAAW,KAAKQ,EAAY,EAGpBR,EAAG,aAAa,KAAKQ,GAAc,MAAM,EAC1C,KAAK,EAAE,MAAM;AAAA,CAAI,EAAE,OAAO6B,GAAQA,EAAK,KAAK,IAAM,EAAE,EAAE,OAH5D,CAIX,OAASN,EAAO,CACd,eAAQ,MAAM,8BAA+BA,CAAK,EAC3C,CACT,CACF,CACF,EAAI,CAAC,CACP,CACF",
|
|
6
|
+
"names": ["urlAlphabet", "crypto", "POOL_SIZE_MULTIPLIER", "pool", "poolOffset", "fillPool", "bytes", "random", "customRandom", "alphabet", "defaultSize", "getRandom", "mask", "step", "size", "id", "i", "customAlphabet", "nanoid", "urlAlphabet", "Collection", "_Collection", "state", "database", "value", "id", "nanoid", "error", "args", "key", "path", "fn", "matcher", "name", "nodeIdleTick", "callback", "cancelIdleTick", "id", "ServiceProvider", "path", "fs", "fsPromises", "createState", "OnChange", "databaseInstances", "shutdownHandlersRegistered", "Database", "#initialized", "#walFilePath", "#dbFilePath", "#removeListener", "#changeCount", "#checkpointThreshold", "#forceThreshold", "#promises", "#state", "#checkpointScheduled", "#checkpointTimerId", "#lastCheckpoint", "#checkpointInterval", "#isCheckpointing", "#activeBatches", "useContext", "config", "state", "#registerShutdownHandlers", "shutdown", "signal", "db", "cancelIdleTick", "#performCheckpoint", "error", "#scheduleCheckpoint", "newConfig", "#changeListener", "exportedData", "walEntries", "line", "entry", "pathId", "change", "ledgerEntry", "#writeToDb", "#clearWalFile", "filePath", "dbBackupPath", "walBackupPath", "#unlinkAllFiles", "name", "Collection", "fn", "#debugFunctions", "changeEntries", "#writeToWal", "timeSinceCheckpoint", "#resolvePromises", "resolve", "nodeIdleTick", "#backupCurrentFiles", "#clearWalFileAsync", "#unlinkDbFile", "wallData", "changeEntry", "#unlinkWalFile", "debug", "walData"]
|
|
7
7
|
}
|