blackhole.db 1.0.0 → 1.1.0

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/index.js CHANGED
@@ -1,321 +1,226 @@
1
- /**
2
- * blackhole/js/index.js
3
- */
4
-
5
1
  const native = require('./index.node');
6
2
  const { v4: uuidv4 } = require('uuid');
7
- const { inspect } = require('util');
8
-
9
- // ── Private WeakMap storage (completely inaccessible from outside) ────────────
10
- const _key = new WeakMap();
11
- const _id = new WeakMap();
12
- const _model = new WeakMap();
13
-
14
- // ── SchemaTypes ───────────────────────────────────────────────────────────────
15
-
16
- const SchemaTypes = {
17
- String,
18
- Number,
19
- Boolean,
20
- Date,
21
- Array,
22
- Object,
23
- Mixed: null,
24
- };
25
3
 
26
- // ── SchemaField ───────────────────────────────────────────────────────────────
4
+ const _internal = new WeakMap();
27
5
 
28
- class SchemaField {
29
- constructor(def) {
30
- if (def === String || def === Number || def === Boolean ||
31
- def === Date || def === Array || def === Object) {
32
- this.type = def;
33
- this.required = false;
34
- this.default = undefined;
35
- this.enum = null;
36
- this.min = undefined;
37
- this.max = undefined;
38
- } else if (typeof def === 'object' && def !== null && def.type !== undefined) {
39
- this.type = def.type;
40
- this.required = def.required ?? false;
41
- this.default = def.default;
42
- this.enum = def.enum ?? null;
43
- this.min = def.min;
44
- this.max = def.max;
45
- } else {
46
- this.type = null;
47
- this.required = false;
48
- this.default = undefined;
49
- this.enum = null;
6
+ /**
7
+ * 1. GLOBAL BLACKHOLE FUNCTIONS
8
+ */
9
+ const blackhole = {
10
+ models: {},
11
+ connect: async (path = 'blackhole.db') => {
12
+ native.open(path);
13
+ return blackhole.connection;
14
+ },
15
+ createConnection: (path) => blackhole.connect(path),
16
+ disconnect: async () => {},
17
+ model: (name, schema) => {
18
+ if (!schema) return blackhole.models[name];
19
+ return blackhole.models[name] = new Model(name, schema);
20
+ },
21
+ Schema: class Schema {
22
+ constructor(definition, options = {}) {
23
+ this.obj = definition; this.options = options;
24
+ this.methods = {}; this.statics = {}; this.virtuals = {};
25
+ this._hooks = { pre: {}, post: {} };
26
+ this.paths = {};
27
+ if (definition) this.add(definition);
50
28
  }
51
- }
52
- }
53
-
54
- // ── Schema ────────────────────────────────────────────────────────────────────
55
-
56
- class Schema {
57
- constructor(definition, options = {}) {
58
- this.fields = {};
59
- this.options = options;
60
- this._virtuals = {};
61
- this._hooks = { pre: {}, post: {} };
62
-
63
- for (const [key, def] of Object.entries(definition)) {
64
- this.fields[key] = new SchemaField(def);
29
+ add(obj, prefix = '') {
30
+ for (let [k, v] of Object.entries(obj)) this.paths[prefix + k] = v;
65
31
  }
66
- }
67
-
68
- virtual(name, fn) {
69
- this._virtuals[name] = fn;
70
- return this;
71
- }
72
-
73
- pre(event, fn) {
74
- (this._hooks.pre[event] ??= []).push(fn);
75
- return this;
76
- }
77
-
78
- post(event, fn) {
79
- (this._hooks.post[event] ??= []).push(fn);
80
- return this;
81
- }
82
-
83
- validate(doc) {
84
- const out = {};
85
-
86
- for (const [key, field] of Object.entries(this.fields)) {
87
- let value = doc[key];
88
-
89
- if (value === undefined && field.default !== undefined) {
90
- value = typeof field.default === 'function' ? field.default() : field.default;
91
- }
92
-
93
- if (value === undefined || value === null) {
94
- if (field.required) throw new Error(`Field "${key}" is required`);
95
- if (value !== undefined) out[key] = value;
96
- continue;
97
- }
98
-
99
- value = coerce(key, value, field.type);
100
-
101
- if (field.enum && !field.enum.includes(value))
102
- throw new Error(`Field "${key}" must be one of [${field.enum.join(', ')}]`);
103
- if (field.min !== undefined && value < field.min)
104
- throw new Error(`Field "${key}" must be >= ${field.min}`);
105
- if (field.max !== undefined && value > field.max)
106
- throw new Error(`Field "${key}" must be <= ${field.max}`);
107
-
108
- out[key] = value;
32
+ path(p, v) { if (v) this.paths[p] = v; return this.paths[p]; }
33
+ plugin(fn, opts) { fn(this, opts); return this; }
34
+ pre(ev, fn) { (this._hooks.pre[ev] ??= []).push(fn); return this; }
35
+ post(ev, fn) { (this._hooks.post[ev] ??= []).push(fn); return this; }
36
+ virtual(name) {
37
+ return this.virtuals[name] = {
38
+ get(fn) { this.getter = fn; return this; },
39
+ set(fn) { this.setter = fn; return this; }
40
+ };
109
41
  }
42
+ },
43
+ Types: { ObjectId: () => uuidv4() },
44
+ connection: { on: () => {}, once: () => {} },
45
+ set: () => {},
46
+ pluralize: (v) => v
47
+ };
110
48
 
111
- // Pass through extra fields not in schema (Mixed behaviour)
112
- for (const [key, value] of Object.entries(doc)) {
113
- if (!(key in this.fields)) out[key] = value;
49
+ /**
50
+ * 5. QUERY HELPERS (Chainable)
51
+ */
52
+ class Query {
53
+ constructor(model, filter, op) {
54
+ this.model = model; this._filter = filter || {}; this._op = op;
55
+ this._limit = 0; this._skip = 0; this._sort = null; this._isLean = false;
56
+ }
57
+ limit(n) { this._limit = n; return this; }
58
+ skip(n) { this._skip = n; return this; }
59
+ sort(s) { this._sort = s; return this; }
60
+ lean(v = true) { this._isLean = v; return this; }
61
+
62
+ async exec() {
63
+ let raw = JSON.parse(native.scan(this.model._prefix, JSON.stringify(this._filter)));
64
+
65
+ if (this._sort) {
66
+ const k = Object.keys(this._sort)[0], d = this._sort[k];
67
+ raw.sort((a, b) => a[k] > b[k] ? d : -d);
68
+ }
69
+
70
+ if (this._skip || this._limit) {
71
+ raw = raw.slice(this._skip, this._limit ? this._skip + this._limit : undefined);
114
72
  }
115
73
 
116
- return out;
117
- }
118
- }
119
-
120
- // ── Type coercion ─────────────────────────────────────────────────────────────
121
-
122
- function coerce(key, value, type) {
123
- if (type === null) return value;
124
- switch (type) {
125
- case String: return String(value);
126
- case Number: {
127
- const n = Number(value);
128
- if (isNaN(n)) throw new Error(`Field "${key}" must be a Number, got: ${value}`);
129
- return n;
74
+ if (this._op === 'findOne' || this._op === 'findById') {
75
+ const res = raw[0] || null;
76
+ if (!res) return null;
77
+ return this._isLean ? res : this.model._wrap(res);
130
78
  }
131
- case Boolean: return Boolean(value);
132
- case Date: return new Date(value).toISOString();
133
- case Array:
134
- if (!Array.isArray(value)) throw new Error(`Field "${key}" must be an Array`);
135
- return value;
136
- case Object:
137
- if (typeof value !== 'object' || Array.isArray(value))
138
- throw new Error(`Field "${key}" must be an Object`);
139
- return value;
140
- default: return value;
79
+ return this._isLean ? raw : raw.map(r => this.model._wrap(r));
141
80
  }
81
+ then(res, rej) { return this.exec().then(res, rej); }
142
82
  }
143
83
 
144
- // ── Document ──────────────────────────────────────────────────────────────────
145
-
84
+ /**
85
+ * 4. DOCUMENT FUNCTIONS (Instance)
86
+ */
146
87
  class Document {
147
88
  constructor(data, model) {
148
- // Store internals in WeakMaps — not on the object at all
149
- _key.set(this, data._key);
150
- _id.set(this, data._id);
151
- _model.set(this, model);
89
+ const id = data._id || data._key?.split('/')[1] || uuidv4();
90
+ const key = data._key || model._keyFor(id);
91
+
92
+ // Create Proxy first to avoid state binding issues
93
+ const proxy = new Proxy(this, {
94
+ set: (t, p, v) => {
95
+ const state = _internal.get(proxy);
96
+ if (p === 'id' || p === '_id') return true; // Read-only getters
97
+ if (state) state.modified.add(p);
98
+ t[p] = v; return true;
99
+ }
100
+ });
101
+
102
+ _internal.set(proxy, { model, id, key, modified: new Set(), isNew: !data._key });
152
103
 
153
- // Only assign user-facing fields onto the object
154
- for (const [k, v] of Object.entries(data)) {
155
- if (k !== '_key' && k !== '_id') this[k] = v;
104
+ // Initialize values into proxy (filtering out getters)
105
+ for (let [k, v] of Object.entries(data)) {
106
+ if (k !== '_id' && k !== 'id' && k !== '_key') proxy[k] = v;
156
107
  }
108
+
109
+ for (let [n, f] of Object.entries(model.schema.methods)) this[n] = f.bind(proxy);
110
+ return proxy;
157
111
  }
158
112
 
113
+ get id() { return _internal.get(this).id; }
114
+ get _id() { return _internal.get(this).id; }
115
+
159
116
  async save() {
160
- const m = _model.get(this);
161
- await m._runHooks('pre', 'save', this);
162
- const key = _key.get(this) ?? m._keyFor(_id.get(this));
163
- native.put(key, JSON.stringify(this._toStorable()));
164
- await m._runHooks('post', 'save', this);
117
+ const state = _internal.get(this);
118
+ await state.model._runHooks('pre', 'save', this);
119
+ const data = this.toObject();
120
+ data._id = state.id;
121
+ native.put(state.key, JSON.stringify(data));
122
+ state.modified.clear();
123
+ await state.model._runHooks('post', 'save', this);
165
124
  return this;
166
125
  }
167
126
 
168
- async remove() {
169
- const m = _model.get(this);
170
- await m._runHooks('pre', 'remove', this);
171
- native.del(_key.get(this));
172
- await m._runHooks('post', 'remove', this);
127
+ async updateOne(u) { Object.assign(this, u); return this.save(); }
128
+ async deleteOne() { return native.del(_internal.get(this).key); }
129
+ isModified(p) { return _internal.get(this).modified.has(p); }
130
+ markModified(p) { _internal.get(this).modified.add(p); }
131
+ validate() { return true; }
132
+
133
+ toObject() {
134
+ const o = { ...this };
135
+ for (let k in o) if (typeof o[k] === 'function') delete o[k];
136
+ return JSON.parse(JSON.stringify(o));
173
137
  }
174
138
 
175
139
  toJSON() {
176
- const out = { ...this };
177
- for (const [name, fn] of Object.entries(_model.get(this).schema._virtuals)) {
178
- out[name] = fn.call(this);
140
+ const o = this.toObject();
141
+ o.id = this.id;
142
+ const { model } = _internal.get(this);
143
+ for (let [n, v] of Object.entries(model.schema.virtuals)) {
144
+ if (v.getter) o[n] = v.getter.call(this);
179
145
  }
180
- return out;
146
+ return o;
181
147
  }
182
-
183
- _toStorable() {
184
- return { _id: _id.get(this), ...this };
185
- }
186
-
187
- // Internal accessors — for use by Model only
188
- static _getKey(doc) { return _key.get(doc); }
189
- static _getId(doc) { return _id.get(doc); }
190
- static _getModel(doc) { return _model.get(doc); }
191
148
  }
192
149
 
193
- // ── Model ─────────────────────────────────────────────────────────────────────
194
-
150
+ /**
151
+ * 3. MODEL FUNCTIONS (Statics)
152
+ */
195
153
  class Model {
196
154
  constructor(name, schema) {
197
- this.name = name;
198
- this.schema = schema;
199
- this._prefix = `${name}/`;
155
+ this.name = name; this.schema = schema; this._prefix = `${name}/`;
156
+ Object.assign(this, schema.statics);
200
157
  }
201
-
202
158
  _keyFor(id) { return `${this._prefix}${id}`; }
159
+ _wrap(raw) { return new Document(raw, this); }
160
+ async _runHooks(p, e, d) { for (let f of this.schema._hooks[p][e] ?? []) await f.call(d); }
203
161
 
204
- async _runHooks(phase, event, doc) {
205
- for (const fn of this.schema._hooks[phase][event] ?? []) {
206
- await fn.call(doc);
207
- }
208
- }
209
-
210
- _wrap(raw) {
211
- const key = raw._key;
212
- const id = raw._id ?? raw._key?.split('/')[1];
213
- const data = { _key: key, _id: id };
214
- for (const [k, v] of Object.entries(raw)) {
215
- if (k !== '_key' && k !== '_id') data[k] = v;
216
- }
217
- return new Document(data, this);
218
- }
219
-
220
- // ── CRUD ────────────────────────────────────────────────────────────────────
221
-
162
+ // Create
222
163
  async create(data) {
223
- const validated = this.schema.validate(data);
224
-
225
- if (this.schema.options.timestamps) {
226
- validated.createdAt = new Date().toISOString();
227
- validated.updatedAt = new Date().toISOString();
164
+ if (Array.isArray(data)) return Promise.all(data.map(d => this.create(d)));
165
+ const doc = new Document(data, this);
166
+ return doc.save();
167
+ }
168
+ async insertMany(arr) { return this.create(arr); }
169
+
170
+ // Read
171
+ find(f) { return new Query(this, f, 'find'); }
172
+ findOne(f) { return new Query(this, f, 'findOne'); }
173
+ findById(id) { return this.findOne({ _id: id }); }
174
+ async countDocuments(f) { return (await this.find(f)).length; }
175
+ async distinct(field) {
176
+ const all = await this.find({}).lean();
177
+ return [...new Set(all.map(x => x[field]))];
178
+ }
179
+
180
+ // Update
181
+ async updateOne(f, u) {
182
+ const d = await this.findOne(f);
183
+ if (!d) return { matchedCount: 0 };
184
+ Object.assign(d, u); await d.save();
185
+ return { matchedCount: 1 };
186
+ }
187
+ async updateMany(f, u) {
188
+ const ds = await this.find(f);
189
+ for (let d of ds) { Object.assign(d, u); await d.save(); }
190
+ return { matchedCount: ds.length };
191
+ }
192
+ async findOneAndUpdate(f, u, opts = {}) {
193
+ const d = await this.findOne(f);
194
+ if (!d) return opts.upsert ? this.create({ ...f, ...u }) : null;
195
+ Object.assign(d, u); return d.save();
196
+ }
197
+ findByIdAndUpdate(id, u, o) { return this.findOneAndUpdate({ _id: id }, u, o); }
198
+
199
+ // Delete
200
+ async deleteOne(f) {
201
+ const d = await this.findOne(f);
202
+ if (!d) return { deletedCount: 0 };
203
+ await d.deleteOne(); return { deletedCount: 1 };
204
+ }
205
+ async deleteMany(f) {
206
+ const ds = await this.find(f);
207
+ for (let d of ds) await d.deleteOne();
208
+ return { deletedCount: ds.length };
209
+ }
210
+ async findOneAndDelete(f) {
211
+ const d = await this.findOne(f);
212
+ if (d) await d.deleteOne(); return d;
213
+ }
214
+ findByIdAndDelete(id) { return this.findOneAndDelete({ _id: id }); }
215
+
216
+ // Advanced
217
+ async aggregate(p) { return this.find({}).lean(); }
218
+ async bulkWrite(ops) {
219
+ for (let o of ops) {
220
+ if (o.insertOne) await this.create(o.insertOne.document);
221
+ if (o.deleteOne) await this.deleteOne(o.deleteOne.filter);
228
222
  }
229
-
230
- validated._id ??= uuidv4();
231
- const key = this._keyFor(validated._id);
232
-
233
- const doc = new Document({ ...validated, _key: key, _id: validated._id }, this);
234
-
235
- await this._runHooks('pre', 'save', doc);
236
- native.put(key, JSON.stringify(doc._toStorable()));
237
- await this._runHooks('post', 'save', doc);
238
-
239
- return doc;
240
- }
241
-
242
- find(filter = {}) {
243
- const raw = JSON.parse(native.scan(this._prefix, JSON.stringify(filter)));
244
- return raw.map(r => this._wrap(r));
245
- }
246
-
247
- findOne(filter = {}) {
248
- return this.find(filter)[0] ?? null;
249
- }
250
-
251
- findById(id) {
252
- const raw = native.get(this._keyFor(id));
253
- if (!raw) return null;
254
- const parsed = JSON.parse(raw);
255
- return this._wrap({ ...parsed, _key: this._keyFor(id) });
256
223
  }
257
-
258
- findOneAndUpdate(filter, update, opts = {}) {
259
- const doc = this.findOne(filter);
260
- if (!doc) return null;
261
-
262
- const merged = { ...doc._toStorable(), ...update };
263
-
264
- if (this.schema.options.timestamps) {
265
- merged.updatedAt = new Date().toISOString();
266
- }
267
-
268
- const validated = this.schema.validate(merged);
269
- const key = Document._getKey(doc);
270
- native.put(key, JSON.stringify({ _id: Document._getId(doc), ...validated }));
271
- return this._wrap({ ...validated, _key: key, _id: Document._getId(doc) });
272
- }
273
-
274
- findByIdAndUpdate(id, update) {
275
- return this.findOneAndUpdate({ _id: id }, update);
276
- }
277
-
278
- deleteOne(filter) {
279
- const doc = this.findOne(filter);
280
- if (!doc) return { deletedCount: 0 };
281
- native.del(Document._getKey(doc));
282
- return { deletedCount: 1 };
283
- }
284
-
285
- deleteMany(filter) {
286
- const docs = this.find(filter);
287
- for (const doc of docs) native.del(Document._getKey(doc));
288
- return { deletedCount: docs.length };
289
- }
290
-
291
- findByIdAndDelete(id) {
292
- const key = this._keyFor(id);
293
- const existed = native.del(key);
294
- return { deletedCount: existed ? 1 : 0 };
295
- }
296
-
297
- countDocuments(filter = {}) {
298
- return this.find(filter).length;
299
- }
300
-
301
- listKeys() {
302
- return JSON.parse(native.list_keys(this._prefix));
303
- }
304
- }
305
-
306
- // ── Top-level API ─────────────────────────────────────────────────────────────
307
-
308
- const _models = new Map();
309
-
310
- function connect(dbPath) {
311
- native.open(dbPath);
312
- }
313
-
314
- function model(name, schema) {
315
- if (_models.has(name)) return _models.get(name);
316
- const m = new Model(name, schema);
317
- _models.set(name, m);
318
- return m;
319
224
  }
320
225
 
321
- module.exports = { connect, model, Schema, SchemaTypes, Document };
226
+ module.exports = blackhole;
package/index.node CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blackhole.db",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "main": "index.js",
5
5
  "dependencies": {
6
6
  "uuid": "^9.0.1"
Binary file
Binary file