tapirus 1.0.1 → 1.0.5

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,82 +1,153 @@
1
- /**
2
- * TapirusDB Node.js & TypeScript SDK
3
- * Dual-Mode: Native NAPI-RS Safe-Rust binding with In-Memory Quad-Model Fallback
4
- */
5
-
6
1
  'use strict';
2
+ // Shared native loader source. scripts/sync-node-sdk.js copies this API to both npm packages.
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ let binding;
7
6
 
8
- const path = require('path');
9
- const fs = require('fs');
10
-
11
- // Attempt to load native NAPI-RS prebuilt binary if present
12
- let nativeBinding = null;
13
- const possibleBindings = [
14
- path.join(__dirname, 'tapirus.node'),
15
- path.join(__dirname, 'build', 'Release', 'tapirus.node'),
16
- ];
17
-
18
- for (const p of possibleBindings) {
19
- if (fs.existsSync(p)) {
7
+ function loadBinding() {
8
+ if (binding) return binding;
9
+ const candidates = process.env.TAPIRUS_NATIVE_PATH
10
+ ? [path.resolve(process.env.TAPIRUS_NATIVE_PATH)]
11
+ : [path.join(__dirname, 'tapirus.node'), path.join(__dirname, 'build', 'Release', 'tapirus.node'),
12
+ ...fs.readdirSync(__dirname).filter(file => /^tapirus\..+\.node$/.test(file)).map(file => path.join(__dirname, file))];
13
+ const failures = [];
14
+ for (const file of candidates) {
15
+ if (!fs.existsSync(file)) continue;
20
16
  try {
21
- nativeBinding = require(p);
22
- break;
23
- } catch (_) {}
17
+ const native = { exports: {} };
18
+ process.dlopen(native, file);
19
+ if (typeof native.exports.TapirusClient !== 'function') throw new Error('Missing TapirusClient export');
20
+ binding = native.exports;
21
+ return binding;
22
+ } catch (error) { failures.push(`${path.basename(file)}: ${error.message}`); }
24
23
  }
24
+ throw new Error(`TapirusDB native engine is unavailable for ${process.platform}/${process.arch}. Install a package containing the matching .node binary or set TAPIRUS_NATIVE_PATH for a local build.${failures.length ? '\n' + failures.join('\n') : ''}`);
25
25
  }
26
26
 
27
- // Fallback to pure in-memory quad-model engine
28
- const { TapirusDatabase } = require('./engine.js');
29
-
30
- class TapirusConnectionWrapper {
31
- constructor(db) {
32
- this._db = db;
33
- }
27
+ function paramsJson(params) {
28
+ if (!Array.isArray(params)) throw new TypeError('Parameters must be an array');
29
+ return JSON.stringify(params, (_key, value) => {
30
+ if (typeof value === 'bigint') return { $integer: value.toString() };
31
+ if (value instanceof Uint8Array || (value && value.type === 'Buffer' && Array.isArray(value.data))) return { $blob: Array.from(value.data || value) };
32
+ if (typeof value === 'number' && (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value)))) throw new TypeError('Use finite numbers and bigint for integers outside the safe JS range');
33
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') throw new TypeError('Unsupported SQL parameter');
34
+ return value;
35
+ });
36
+ }
37
+ function identifier(value) {
38
+ if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) throw new TypeError('Invalid SQL identifier');
39
+ return value;
40
+ }
41
+ function limitValue(value) {
42
+ if (!Number.isSafeInteger(value) || value < 0) throw new TypeError('Limit must be a nonnegative safe integer');
43
+ return value;
44
+ }
34
45
 
35
- execute(sql, params = []) {
36
- // Synchronous-compatible bridge for test suites and scripts
37
- const res = this._db.execute(sql, params);
38
- if (res && typeof res.then === 'function') {
39
- let done = false;
40
- let val = 0;
41
- res.then(v => { val = v; done = true; });
42
- return val;
46
+ function memoryPayload(value) {
47
+ const names = { sessionId: 'session_id', externalId: 'external_id', sourceVersion: 'source_version', exceptSourceVersion: 'except_source_version', embeddingModel: 'embedding_model', expiresAt: 'expires_at', ttlSeconds: 'ttl_seconds', expectedRevision: 'expected_revision', candidateLimit: 'candidate_limit', rrfK: 'rrf_k', vectorWeight: 'vector_weight', lexicalWeight: 'lexical_weight', recencyWeight: 'recency_weight', importanceWeight: 'importance_weight', halfLifeSeconds: 'half_life_seconds', minScore: 'min_score', maxDocuments: 'max_documents', maxEstimatedBytes: 'max_estimated_bytes', maxDocumentBytes: 'max_document_bytes', maxVectorDimensions: 'max_vector_dimensions', maxVectorSpaces: 'max_vector_spaces', maxBatchDocuments: 'max_batch_documents', maxCandidates: 'max_candidates', hnswM: 'hnsw_m', efConstruction: 'ef_construction', efSearch: 'ef_search' };
48
+ const normalize = item => {
49
+ if (typeof item === 'number' && (!Number.isFinite(item) || (Number.isInteger(item) && !Number.isSafeInteger(item)))) throw new TypeError('Memory values require finite numbers and exact integer parameters');
50
+ if (Array.isArray(item)) return item.map(normalize);
51
+ if (item && typeof item === 'object') {
52
+ const output = Object.create(null);
53
+ for (const [key, entry] of Object.entries(item)) {
54
+ const name = names[key] || key;
55
+ if (Object.hasOwn(output, name)) throw new TypeError(`Duplicate memory field: ${name}`);
56
+ output[name] = normalize(entry);
57
+ }
58
+ return output;
43
59
  }
44
- return res;
45
- }
60
+ return item;
61
+ };
62
+ return JSON.stringify(normalize(value));
63
+ }
46
64
 
47
- query(sql, params = []) {
48
- // Synchronous query execution bridge
49
- let rows = [];
50
- const res = this._db.query(sql, params);
51
- if (res && typeof res.then === 'function') {
52
- res.then(r => { rows = r; });
53
- } else {
54
- rows = res || [];
55
- }
56
- return rows;
65
+ class TapirusDatabase {
66
+ constructor(filePath = ':memory:', options = {}) {
67
+ const nativeOptions = { dbPath: filePath };
68
+ if (options.passphrase !== undefined) nativeOptions.passphrase = options.passphrase;
69
+ if (options.memory !== undefined) nativeOptions.memoryConfigJson = memoryPayload(options.memory);
70
+ this._db = new (loadBinding().TapirusClient)(nativeOptions);
71
+ this.isNative = true;
72
+ this.isOpen = true;
73
+ this.path = filePath;
57
74
  }
58
-
59
- vectorSearch(table, vectorCol, queryVec, limit = 5) {
60
- const sql = `SELECT * FROM ${table} VECTOR NEAR ${vectorCol} = [${queryVec.join(',')}] TOP ${limit};`;
61
- return this.query(sql);
75
+ static open(filePath = ':memory:', options = {}) { return new TapirusDatabase(filePath, options); }
76
+ static openInMemory(options = {}) { return new TapirusDatabase(':memory:', options); }
77
+ static version() { return loadBinding().version(); }
78
+ execute(sql, params = []) { return this._db.execute(sql, paramsJson(params)); }
79
+ query(sql, params = []) { return this._db.query(sql, paramsJson(params)); }
80
+ vectorSearch(table, column, vector, limit = 5) {
81
+ return this.query(`SELECT * FROM ${identifier(table)} VECTOR NEAR ${identifier(column)} = ? TOP ${limitValue(limit)};`, [vector]);
62
82
  }
63
-
64
- graphAlgorithm(algo, _options = {}) {
65
- return { algorithm: algo, status: 'converged', iterations: 20 };
83
+ graphAlgorithm(algorithm) { return this.query(`GRAPH ALGORITHM ${identifier(algorithm)};`); }
84
+ tapClassifyDetailed(text, candidates) { return JSON.parse(this._db.tapClassifyJson(text, candidates)); }
85
+ tapClassify(text, candidates) { return this.tapClassifyDetailed(text, candidates).top_choice; }
86
+ tapVerify(premise, hypothesis, threshold = 0.5) { return this._db.tapVerify(premise, hypothesis, threshold); }
87
+ tapScore(text, criteria) { return this._db.tapScore(text, criteria); }
88
+ tapRoute(state, routes) { return this._db.tapRoute(state, routes); }
89
+ remember(text, importance = 0.5, tags = []) { return this._db.remember(text, importance, tags); }
90
+ storeMemory(document) { return this._db.storeMemoryJson(memoryPayload(document)); }
91
+ searchMemories(search) { return JSON.parse(this._db.searchMemoriesJson(memoryPayload(search))); }
92
+ _memoryRequest(operation, payload = {}) { return JSON.parse(this._db.memoryRequestJson(operation, memoryPayload(payload))); }
93
+ upsertMemory(document) { return this._memoryRequest('upsert', document); }
94
+ storeMemoryBatch(documents) { return this._memoryRequest('store_batch', documents); }
95
+ upsertMemoryBatch(documents) { return this._memoryRequest('upsert_batch', documents); }
96
+ searchMemoriesDetailed(search) { return this._memoryRequest('search_detailed', search); }
97
+ configureMemory(config) { return this._memoryRequest('configure', config); }
98
+ memoryStats() { return this._memoryRequest('stats'); }
99
+ storageHealth() { return this._memoryRequest('storage_health'); }
100
+ prepareMemoryIndexes() { return this._memoryRequest('prepare'); }
101
+ purgeExpiredMemories() { return this._memoryRequest('purge_expired'); }
102
+ deleteMemories(scope) { return this._memoryRequest('delete', scope); }
103
+ forgetMemory(id) {
104
+ if (!Number.isSafeInteger(id) || id < 1) throw new TypeError('Memory ID must be a positive safe integer');
105
+ return this._db.forgetMemory(String(id));
66
106
  }
67
-
68
- close() {
69
- this._db.close();
107
+ recall(query, limit = 5) { return JSON.parse(this._db.recallJson(query, limitValue(limit))); }
108
+ recallPrompt(query, limit = 5) { return this._db.recallPrompt(query, limitValue(limit)); }
109
+ graphRagQuery({ query, limit = 5 }) { return JSON.parse(this._db.graphRagJson(query, limitValue(limit))); }
110
+ subscribe(table, listener) {
111
+ const key = identifier(table).toLowerCase();
112
+ const id = this._db.subscribe(key, (error, json) => {
113
+ if (error) throw error;
114
+ listener(JSON.parse(json));
115
+ });
116
+ return { unsubscribe: () => this._db.unsubscribe(id) };
70
117
  }
118
+ checkpoint() { return this._db.checkpoint(); }
119
+ vacuumInto(targetPath) { return this.execute('VACUUM INTO ?;', [targetPath]); }
120
+ close() { this._db.close(); this.isOpen = false; }
71
121
  }
72
-
73
- function open(filePath = ':memory:', options = {}) {
74
- const db = new TapirusDatabase(filePath, options);
75
- return new TapirusConnectionWrapper(db);
122
+ class TapirusSessionDatabase {
123
+ constructor(filePath = ':memory:', options = {}) {
124
+ this._db = new (loadBinding().SessionDatabaseClient)({ dbPath: filePath, passphrase: options.passphrase, memoryConfigJson: options.memory === undefined ? undefined : memoryPayload(options.memory) });
125
+ }
126
+ session({ busyTimeoutMs = 0 } = {}) {
127
+ if (!Number.isInteger(busyTimeoutMs) || busyTimeoutMs < 0 || busyTimeoutMs > 0xffffffff) throw new TypeError('Invalid session busyTimeoutMs');
128
+ return new TapirusSession(this._db.session(busyTimeoutMs));
129
+ }
130
+ close() { this._db.close(); }
76
131
  }
77
-
78
- module.exports = {
79
- open,
80
- Tapirus: TapirusConnectionWrapper,
81
- TapirusDatabase,
82
- };
132
+ class TapirusSession {
133
+ constructor(native) { this._db = native; }
134
+ execute(sql, params = []) { return this._db.execute(sql, paramsJson(params)); }
135
+ query(sql, params = []) { return this._db.query(sql, paramsJson(params)); }
136
+ begin() { this.execute('BEGIN'); }
137
+ commit() { this.execute('COMMIT'); }
138
+ rollback() { this.execute('ROLLBACK'); }
139
+ transaction(callback) {
140
+ this.begin();
141
+ try {
142
+ const result = callback(this);
143
+ if (result && typeof result.then === 'function') throw new TypeError('Session transaction callbacks must be synchronous');
144
+ this.commit(); return result;
145
+ } catch (error) { try { this.rollback(); } catch (rollback) { error.rollbackError = rollback; } throw error; }
146
+ }
147
+ checkpoint() { return this._db.checkpoint(); }
148
+ close() { this._db.close(); }
149
+ }
150
+ for (const name of ['_memoryRequest', 'storeMemory', 'searchMemories', 'upsertMemory', 'storeMemoryBatch', 'upsertMemoryBatch', 'searchMemoriesDetailed', 'configureMemory', 'memoryStats', 'storageHealth', 'prepareMemoryIndexes', 'purgeExpiredMemories', 'deleteMemories', 'forgetMemory']) {
151
+ Object.defineProperty(TapirusSession.prototype, name, { value: TapirusDatabase.prototype[name] });
152
+ }
153
+ module.exports = { open: TapirusDatabase.open, Tapirus: TapirusDatabase, TapirusDatabase, TapirusSessionDatabase, version: TapirusDatabase.version };
package/package.json CHANGED
@@ -1,45 +1,54 @@
1
- {
2
- "name": "tapirus",
3
- "version": "1.0.1",
4
- "description": "Official Node.js & TypeScript SDK for TapirusDB — Embedded Safe-Rust Quad-Model Database",
5
- "main": "index.js",
6
- "types": "index.d.ts",
7
- "napi": {
8
- "name": "tapirus",
9
- "triples": {
10
- "additional": [
11
- "x86_64-apple-darwin",
12
- "aarch64-apple-darwin",
13
- "x86_64-pc-windows-msvc",
14
- "aarch64-pc-windows-msvc",
15
- "x86_64-unknown-linux-gnu",
16
- "aarch64-unknown-linux-gnu"
17
- ]
18
- }
19
- },
20
- "scripts": {
21
- "build": "napi build --platform --release",
22
- "build:debug": "napi build --platform",
23
- "test": "node test.js"
24
- },
25
- "devDependencies": {
26
- "@napi-rs/cli": "^2.18.3"
27
- },
28
- "keywords": [
29
- "tapirus",
30
- "tapirusdb",
31
- "embedded",
32
- "database",
33
- "sqlite",
34
- "vector",
35
- "ai",
36
- "rag",
37
- "graph"
38
- ],
39
- "author": "TapirusDB Contributors <contact@tapirusdb.com>",
40
- "license": "MIT",
41
- "repository": {
42
- "type": "git",
43
- "url": "git+https://github.com/tapiruslab/TapirusDB.git"
44
- }
45
- }
1
+ {
2
+ "name": "tapirus",
3
+ "version": "1.0.5",
4
+ "description": "Official Node.js and TypeScript SDK for TapirusDB's embedded database APIs",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "files": [
11
+ "index.js",
12
+ "index.d.ts",
13
+ "CORE_LICENSE",
14
+ "LICENSE",
15
+ "NOTICE",
16
+ "*.node"
17
+ ],
18
+ "napi": {
19
+ "name": "tapirus",
20
+ "triples": {
21
+ "additional": [
22
+ "x86_64-apple-darwin",
23
+ "aarch64-apple-darwin",
24
+ "x86_64-pc-windows-msvc",
25
+ "x86_64-unknown-linux-gnu",
26
+ "aarch64-unknown-linux-gnu"
27
+ ]
28
+ }
29
+ },
30
+ "scripts": {
31
+ "build": "node ../../scripts/build-node-sdk.js",
32
+ "build:debug": "node ../../scripts/build-node-sdk.js --debug",
33
+ "test": "node test.js",
34
+ "test:package": "node ../../scripts/test-node-package.js",
35
+ "prepack": "node verify-native.js"
36
+ },
37
+ "keywords": [
38
+ "tapirus",
39
+ "tapirusdb",
40
+ "embedded",
41
+ "database",
42
+ "sqlite",
43
+ "vector",
44
+ "ai",
45
+ "rag",
46
+ "graph"
47
+ ],
48
+ "author": "TapirusDB Contributors <contact@tapirusdb.com>",
49
+ "license": "MIT AND BUSL-1.1",
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/tapiruslab/TapirusDB.git"
53
+ }
54
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
package/Cargo.toml DELETED
@@ -1,15 +0,0 @@
1
- [package]
2
- name = "tapirus-nodejs"
3
- version = "1.0.1"
4
- edition = "2021"
5
-
6
- [lib]
7
- crate-type = ["cdylib"]
8
-
9
- [dependencies]
10
- napi = { version = "2.16.4", default-features = false, features = ["napi4"] }
11
- napi-derive = "2.16.2"
12
- tapirus = { path = "../.." }
13
-
14
- [build-dependencies]
15
- napi-build = "2.1.3"
package/build.rs DELETED
@@ -1,5 +0,0 @@
1
- extern crate napi_build;
2
-
3
- fn main() {
4
- napi_build::setup();
5
- }