blackhole.db 1.0.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.
Binary file
Binary file
package/index.js ADDED
@@ -0,0 +1,321 @@
1
+ /**
2
+ * blackhole/js/index.js
3
+ */
4
+
5
+ const native = require('./index.node');
6
+ 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
+
26
+ // ── SchemaField ───────────────────────────────────────────────────────────────
27
+
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;
50
+ }
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);
65
+ }
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;
109
+ }
110
+
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;
114
+ }
115
+
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;
130
+ }
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;
141
+ }
142
+ }
143
+
144
+ // ── Document ──────────────────────────────────────────────────────────────────
145
+
146
+ class Document {
147
+ 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);
152
+
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;
156
+ }
157
+ }
158
+
159
+ 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);
165
+ return this;
166
+ }
167
+
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);
173
+ }
174
+
175
+ toJSON() {
176
+ const out = { ...this };
177
+ for (const [name, fn] of Object.entries(_model.get(this).schema._virtuals)) {
178
+ out[name] = fn.call(this);
179
+ }
180
+ return out;
181
+ }
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
+ }
192
+
193
+ // ── Model ─────────────────────────────────────────────────────────────────────
194
+
195
+ class Model {
196
+ constructor(name, schema) {
197
+ this.name = name;
198
+ this.schema = schema;
199
+ this._prefix = `${name}/`;
200
+ }
201
+
202
+ _keyFor(id) { return `${this._prefix}${id}`; }
203
+
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
+
222
+ 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();
228
+ }
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
+ }
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
+ }
320
+
321
+ module.exports = { connect, model, Schema, SchemaTypes, Document };
package/index.node ADDED
Binary file
package/package.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "blackhole.db",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "dependencies": {
6
+ "uuid": "^9.0.1"
7
+ }
8
+ }