@usebridger/storage-sqlite 0.0.0-stage → 0.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/LICENSE +202 -0
- package/dist/index.d.mts +16 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +373 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +33 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { StoragePort } from "@usebridger/core/adapter";
|
|
2
|
+
//#region src/index.d.ts
|
|
3
|
+
export interface SqliteOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Arquivo do banco (criado, com as pastas, se não existir) ou `':memory:'` para um banco
|
|
6
|
+
* descartado no `close()`.
|
|
7
|
+
*/
|
|
8
|
+
readonly path: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Abre o banco, liga o WAL e aplica as migrations do adapter. Lança se o arquivo não abre ou se
|
|
12
|
+
* foi gravado por uma versão mais nova do adapter.
|
|
13
|
+
*/
|
|
14
|
+
export declare function sqlite(options: SqliteOptions): StoragePort;
|
|
15
|
+
//#endregion
|
|
16
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;iBAQiB;;;;;WAKN;;;;;;wBAOK,OAAO,SAAS,gBAAgB"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { StorageClosedError, normalizeDocument, normalizeIndexes, normalizeQuery, normalizeWhere } from "@usebridger/core/adapter";
|
|
6
|
+
//#region src/schema.ts
|
|
7
|
+
const MIGRATIONS = [`
|
|
8
|
+
CREATE TABLE kv (
|
|
9
|
+
namespace TEXT NOT NULL,
|
|
10
|
+
key TEXT NOT NULL,
|
|
11
|
+
value TEXT NOT NULL,
|
|
12
|
+
PRIMARY KEY (namespace, key)
|
|
13
|
+
) WITHOUT ROWID;
|
|
14
|
+
|
|
15
|
+
CREATE TABLE documents (
|
|
16
|
+
seq INTEGER PRIMARY KEY,
|
|
17
|
+
namespace TEXT NOT NULL,
|
|
18
|
+
collection TEXT NOT NULL,
|
|
19
|
+
id TEXT NOT NULL,
|
|
20
|
+
doc TEXT NOT NULL,
|
|
21
|
+
UNIQUE (namespace, collection, id)
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
CREATE TABLE auth_creds (
|
|
25
|
+
session TEXT PRIMARY KEY,
|
|
26
|
+
creds TEXT NOT NULL
|
|
27
|
+
) WITHOUT ROWID;
|
|
28
|
+
|
|
29
|
+
CREATE TABLE auth_keys (
|
|
30
|
+
session TEXT NOT NULL,
|
|
31
|
+
type TEXT NOT NULL,
|
|
32
|
+
id TEXT NOT NULL,
|
|
33
|
+
value TEXT NOT NULL,
|
|
34
|
+
PRIMARY KEY (session, type, id)
|
|
35
|
+
) WITHOUT ROWID;
|
|
36
|
+
`, `
|
|
37
|
+
CREATE TABLE leases (
|
|
38
|
+
name TEXT PRIMARY KEY,
|
|
39
|
+
owner TEXT NOT NULL,
|
|
40
|
+
expires_at INTEGER NOT NULL
|
|
41
|
+
) WITHOUT ROWID;
|
|
42
|
+
`];
|
|
43
|
+
/** Versão do schema que este adapter conhece (a do `PRAGMA user_version` depois do boot). */
|
|
44
|
+
const SCHEMA_VERSION = MIGRATIONS.length;
|
|
45
|
+
/** Roda `body` numa transação: tudo ou nada, mesmo se ele lançar. */
|
|
46
|
+
function transaction(db, body) {
|
|
47
|
+
db.exec("BEGIN IMMEDIATE");
|
|
48
|
+
try {
|
|
49
|
+
const result = body();
|
|
50
|
+
db.exec("COMMIT");
|
|
51
|
+
return result;
|
|
52
|
+
} catch (error) {
|
|
53
|
+
db.exec("ROLLBACK");
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function migrate(db) {
|
|
58
|
+
const { user_version: current } = db.prepare("PRAGMA user_version").get();
|
|
59
|
+
if (current > SCHEMA_VERSION) throw new Error(`storage-sqlite: o banco está no schema ${current}, mais novo que o deste adapter (${SCHEMA_VERSION}). Atualize o @usebridger/storage-sqlite.`);
|
|
60
|
+
for (let version = current; version < SCHEMA_VERSION; version++) transaction(db, () => {
|
|
61
|
+
db.exec(MIGRATIONS[version]);
|
|
62
|
+
db.exec(`PRAGMA user_version = ${version + 1}`);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function isFilePath(path) {
|
|
66
|
+
return path !== "" && path !== ":memory:" && !path.startsWith("file:");
|
|
67
|
+
}
|
|
68
|
+
/** Abre (ou cria) o banco, liga o WAL e aplica as migrations pendentes. */
|
|
69
|
+
function openDatabase(path) {
|
|
70
|
+
if (isFilePath(path)) mkdirSync(dirname(path), { recursive: true });
|
|
71
|
+
const db = new DatabaseSync(path);
|
|
72
|
+
try {
|
|
73
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
74
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
75
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
76
|
+
migrate(db);
|
|
77
|
+
return db;
|
|
78
|
+
} catch (error) {
|
|
79
|
+
db.close();
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/sql.ts
|
|
85
|
+
/** Expressão de um campo do documento. O índice declarado usa exatamente esta expressão. */
|
|
86
|
+
function fieldValueSql(field) {
|
|
87
|
+
return `json_extract(doc, '$.${field}')`;
|
|
88
|
+
}
|
|
89
|
+
function fieldSql(field) {
|
|
90
|
+
if (field === "id") return {
|
|
91
|
+
value: "id",
|
|
92
|
+
type: "'text'"
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
value: fieldValueSql(field),
|
|
96
|
+
type: `json_type(doc, '$.${field}')`
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
const NUMBER = (type) => `(${type} IS 'integer' OR ${type} IS 'real')`;
|
|
100
|
+
function equals({ value, type }, operand) {
|
|
101
|
+
if (operand === null) return {
|
|
102
|
+
sql: `${value} IS NULL`,
|
|
103
|
+
params: []
|
|
104
|
+
};
|
|
105
|
+
if (typeof operand === "boolean") return {
|
|
106
|
+
sql: `${type} IS '${operand}'`,
|
|
107
|
+
params: []
|
|
108
|
+
};
|
|
109
|
+
if (typeof operand === "number") return {
|
|
110
|
+
sql: `(${NUMBER(type)} AND ${value} IS ?)`,
|
|
111
|
+
params: [operand]
|
|
112
|
+
};
|
|
113
|
+
return {
|
|
114
|
+
sql: `(${type} IS 'text' AND ${value} IS ?)`,
|
|
115
|
+
params: [operand]
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
const COMPARISON = {
|
|
119
|
+
gt: ">",
|
|
120
|
+
gte: ">=",
|
|
121
|
+
lt: "<",
|
|
122
|
+
lte: "<="
|
|
123
|
+
};
|
|
124
|
+
function condition(entry) {
|
|
125
|
+
const field = fieldSql(entry.field);
|
|
126
|
+
switch (entry.op) {
|
|
127
|
+
case "eq": return equals(field, entry.value);
|
|
128
|
+
case "ne": {
|
|
129
|
+
const eq = equals(field, entry.value);
|
|
130
|
+
return {
|
|
131
|
+
sql: `NOT ${eq.sql}`,
|
|
132
|
+
params: eq.params
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
case "in": {
|
|
136
|
+
if (entry.value.length === 0) return {
|
|
137
|
+
sql: "0",
|
|
138
|
+
params: []
|
|
139
|
+
};
|
|
140
|
+
const items = entry.value.map((operand) => equals(field, operand));
|
|
141
|
+
return {
|
|
142
|
+
sql: `(${items.map((item) => item.sql).join(" OR ")})`,
|
|
143
|
+
params: items.flatMap((item) => item.params)
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
default: return {
|
|
147
|
+
sql: `(${typeof entry.value === "number" ? NUMBER(field.type) : `${field.type} IS 'text'`} AND ${field.value} ${COMPARISON[entry.op]} ?)`,
|
|
148
|
+
params: [entry.value]
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/** Condições combinadas com E; lista vazia casa com tudo. */
|
|
153
|
+
function whereSql(conditions) {
|
|
154
|
+
if (conditions.length === 0) return {
|
|
155
|
+
sql: "1",
|
|
156
|
+
params: []
|
|
157
|
+
};
|
|
158
|
+
const parts = conditions.map(condition);
|
|
159
|
+
return {
|
|
160
|
+
sql: parts.map((part) => part.sql).join(" AND "),
|
|
161
|
+
params: parts.flatMap((part) => part.params)
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Ordenação do contrato: primeiro a classe de tipo (null/ausente < booleano < número < texto <
|
|
166
|
+
* array/objeto), depois o valor (arrays e objetos empatam), e o empate cai no `seq` — sempre
|
|
167
|
+
* crescente, também em `desc`.
|
|
168
|
+
*/
|
|
169
|
+
function orderBySql(sorts) {
|
|
170
|
+
return [...sorts.flatMap(({ field, direction }) => {
|
|
171
|
+
const { value, type } = fieldSql(field);
|
|
172
|
+
const dir = direction === "asc" ? "ASC" : "DESC";
|
|
173
|
+
const rank = `CASE WHEN ${value} IS NULL THEN 0 WHEN ${type} IN ('true', 'false') THEN 1 WHEN ${type} IN ('integer', 'real') THEN 2 WHEN ${type} IS 'text' THEN 3 ELSE 4 END`;
|
|
174
|
+
const comparable = `CASE WHEN ${type} IN ('array', 'object') THEN NULL ELSE ${value} END`;
|
|
175
|
+
return [`${rank} ${dir}`, `${comparable} ${dir}`];
|
|
176
|
+
}), "seq ASC"].join(", ");
|
|
177
|
+
}
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region src/storage.ts
|
|
180
|
+
function serialize(value) {
|
|
181
|
+
const text = JSON.stringify(value);
|
|
182
|
+
if (text === void 0) throw new TypeError("Valor não serializável em JSON.");
|
|
183
|
+
return text;
|
|
184
|
+
}
|
|
185
|
+
function parse(text) {
|
|
186
|
+
return JSON.parse(text);
|
|
187
|
+
}
|
|
188
|
+
/** StoragePort sobre `db`, que já deve estar aberto e migrado. Fecha o banco no `close()`. */
|
|
189
|
+
function createSqliteStorage(db) {
|
|
190
|
+
let closed = false;
|
|
191
|
+
const statements = /* @__PURE__ */ new Map();
|
|
192
|
+
const indexes = /* @__PURE__ */ new Set();
|
|
193
|
+
function ensureOpen() {
|
|
194
|
+
if (closed) throw new StorageClosedError();
|
|
195
|
+
}
|
|
196
|
+
function statement(sql) {
|
|
197
|
+
let prepared = statements.get(sql);
|
|
198
|
+
if (prepared === void 0) {
|
|
199
|
+
prepared = db.prepare(sql);
|
|
200
|
+
statements.set(sql, prepared);
|
|
201
|
+
}
|
|
202
|
+
return prepared;
|
|
203
|
+
}
|
|
204
|
+
function ensureIndex(field) {
|
|
205
|
+
if (indexes.has(field)) return;
|
|
206
|
+
const name = `documents_field_${Buffer.from(field).toString("hex")}`;
|
|
207
|
+
db.exec(`CREATE INDEX IF NOT EXISTS ${name} ON documents (namespace, collection, ${fieldValueSql(field)})`);
|
|
208
|
+
indexes.add(field);
|
|
209
|
+
}
|
|
210
|
+
function createKv(namespace) {
|
|
211
|
+
return {
|
|
212
|
+
async get(key) {
|
|
213
|
+
ensureOpen();
|
|
214
|
+
const row = statement("SELECT value FROM kv WHERE namespace = ? AND key = ?").get(namespace, key);
|
|
215
|
+
return row === void 0 ? void 0 : parse(row.value);
|
|
216
|
+
},
|
|
217
|
+
async set(key, value) {
|
|
218
|
+
ensureOpen();
|
|
219
|
+
statement("INSERT INTO kv (namespace, key, value) VALUES (?, ?, ?) ON CONFLICT (namespace, key) DO UPDATE SET value = excluded.value").run(namespace, key, serialize(value));
|
|
220
|
+
},
|
|
221
|
+
async delete(key) {
|
|
222
|
+
ensureOpen();
|
|
223
|
+
const { changes } = statement("DELETE FROM kv WHERE namespace = ? AND key = ?").run(namespace, key);
|
|
224
|
+
return Number(changes) > 0;
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function createCollection(namespace, name, fields) {
|
|
229
|
+
function prepare() {
|
|
230
|
+
ensureOpen();
|
|
231
|
+
for (const field of fields) ensureIndex(field);
|
|
232
|
+
}
|
|
233
|
+
function targetSql(target) {
|
|
234
|
+
if (typeof target === "string") return {
|
|
235
|
+
sql: "id = ?",
|
|
236
|
+
params: [target]
|
|
237
|
+
};
|
|
238
|
+
return whereSql(normalizeWhere(target));
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
async insert(document) {
|
|
242
|
+
prepare();
|
|
243
|
+
const text = serialize(normalizeDocument(document));
|
|
244
|
+
const id = randomUUID();
|
|
245
|
+
statement("INSERT INTO documents (namespace, collection, id, doc) VALUES (?, ?, ?, ?)").run(namespace, name, id, text);
|
|
246
|
+
return id;
|
|
247
|
+
},
|
|
248
|
+
async get(id) {
|
|
249
|
+
prepare();
|
|
250
|
+
const row = statement("SELECT doc FROM documents WHERE namespace = ? AND collection = ? AND id = ?").get(namespace, name, id);
|
|
251
|
+
return row === void 0 ? void 0 : {
|
|
252
|
+
...parse(row.doc),
|
|
253
|
+
id
|
|
254
|
+
};
|
|
255
|
+
},
|
|
256
|
+
async find(query) {
|
|
257
|
+
prepare();
|
|
258
|
+
const { where, orderBy, limit, offset } = normalizeQuery(query);
|
|
259
|
+
const filter = whereSql(where);
|
|
260
|
+
return db.prepare(`SELECT id, doc FROM documents WHERE namespace = ? AND collection = ? AND ${filter.sql} ORDER BY ${orderBySql(orderBy)} LIMIT ? OFFSET ?`).all(namespace, name, ...filter.params, limit ?? -1, offset).map((row) => ({
|
|
261
|
+
...parse(row.doc),
|
|
262
|
+
id: row.id
|
|
263
|
+
}));
|
|
264
|
+
},
|
|
265
|
+
async update(target, patch) {
|
|
266
|
+
prepare();
|
|
267
|
+
const changes = normalizeDocument(patch);
|
|
268
|
+
const filter = targetSql(target);
|
|
269
|
+
return transaction(db, () => {
|
|
270
|
+
const rows = db.prepare("SELECT seq, doc FROM documents WHERE namespace = ? AND collection = ? AND " + filter.sql).all(namespace, name, ...filter.params);
|
|
271
|
+
const write = statement("UPDATE documents SET doc = ? WHERE seq = ?");
|
|
272
|
+
for (const row of rows) write.run(serialize({
|
|
273
|
+
...parse(row.doc),
|
|
274
|
+
...changes
|
|
275
|
+
}), row.seq);
|
|
276
|
+
return rows.length;
|
|
277
|
+
});
|
|
278
|
+
},
|
|
279
|
+
async delete(target) {
|
|
280
|
+
prepare();
|
|
281
|
+
const filter = targetSql(target);
|
|
282
|
+
const { changes } = db.prepare(`DELETE FROM documents WHERE namespace = ? AND collection = ? AND ${filter.sql}`).run(namespace, name, ...filter.params);
|
|
283
|
+
return Number(changes);
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
function createPluginStorage(namespace) {
|
|
288
|
+
return {
|
|
289
|
+
kv: createKv(namespace),
|
|
290
|
+
collection(name, options) {
|
|
291
|
+
return createCollection(namespace, name, normalizeIndexes(options));
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
function createAuthState(session) {
|
|
296
|
+
return {
|
|
297
|
+
async getCreds() {
|
|
298
|
+
ensureOpen();
|
|
299
|
+
const row = statement("SELECT creds FROM auth_creds WHERE session = ?").get(session);
|
|
300
|
+
return row === void 0 ? void 0 : parse(row.creds);
|
|
301
|
+
},
|
|
302
|
+
async setCreds(creds) {
|
|
303
|
+
ensureOpen();
|
|
304
|
+
statement("INSERT INTO auth_creds (session, creds) VALUES (?, ?) ON CONFLICT (session) DO UPDATE SET creds = excluded.creds").run(session, serialize(creds));
|
|
305
|
+
},
|
|
306
|
+
async getKeys(type, ids) {
|
|
307
|
+
ensureOpen();
|
|
308
|
+
const rows = statement("SELECT id, value FROM auth_keys WHERE session = ? AND type = ? AND id IN (SELECT value FROM json_each(?))").all(session, type, JSON.stringify(ids));
|
|
309
|
+
const result = {};
|
|
310
|
+
for (const row of rows) result[row.id] = parse(row.value);
|
|
311
|
+
return result;
|
|
312
|
+
},
|
|
313
|
+
async setKeys(data) {
|
|
314
|
+
ensureOpen();
|
|
315
|
+
const entries = Object.entries(data).flatMap(([type, values]) => Object.entries(values).map(([id, value]) => [
|
|
316
|
+
type,
|
|
317
|
+
id,
|
|
318
|
+
value === null ? null : serialize(value)
|
|
319
|
+
]));
|
|
320
|
+
const write = statement("INSERT INTO auth_keys (session, type, id, value) VALUES (?, ?, ?, ?) ON CONFLICT (session, type, id) DO UPDATE SET value = excluded.value");
|
|
321
|
+
const remove = statement("DELETE FROM auth_keys WHERE session = ? AND type = ? AND id = ?");
|
|
322
|
+
transaction(db, () => {
|
|
323
|
+
for (const [type, id, text] of entries) if (text === null) remove.run(session, type, id);
|
|
324
|
+
else write.run(session, type, id, text);
|
|
325
|
+
});
|
|
326
|
+
},
|
|
327
|
+
async clear() {
|
|
328
|
+
ensureOpen();
|
|
329
|
+
transaction(db, () => {
|
|
330
|
+
statement("DELETE FROM auth_creds WHERE session = ?").run(session);
|
|
331
|
+
statement("DELETE FROM auth_keys WHERE session = ?").run(session);
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
forNamespace(namespace) {
|
|
338
|
+
return createPluginStorage(namespace);
|
|
339
|
+
},
|
|
340
|
+
authState(session) {
|
|
341
|
+
return createAuthState(session);
|
|
342
|
+
},
|
|
343
|
+
async acquireLease(name, owner, ttlMs) {
|
|
344
|
+
ensureOpen();
|
|
345
|
+
const now = Date.now();
|
|
346
|
+
const { changes } = statement("INSERT INTO leases (name, owner, expires_at) VALUES (?, ?, ?) ON CONFLICT (name) DO UPDATE SET owner = excluded.owner, expires_at = excluded.expires_at WHERE leases.owner = excluded.owner OR leases.expires_at <= ?").run(name, owner, now + ttlMs, now);
|
|
347
|
+
return Number(changes) > 0;
|
|
348
|
+
},
|
|
349
|
+
async releaseLease(name, owner) {
|
|
350
|
+
ensureOpen();
|
|
351
|
+
statement("DELETE FROM leases WHERE name = ? AND owner = ?").run(name, owner);
|
|
352
|
+
},
|
|
353
|
+
async close() {
|
|
354
|
+
if (closed) return;
|
|
355
|
+
closed = true;
|
|
356
|
+
statements.clear();
|
|
357
|
+
db.close();
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
//#endregion
|
|
362
|
+
//#region src/index.ts
|
|
363
|
+
/**
|
|
364
|
+
* Abre o banco, liga o WAL e aplica as migrations do adapter. Lança se o arquivo não abre ou se
|
|
365
|
+
* foi gravado por uma versão mais nova do adapter.
|
|
366
|
+
*/
|
|
367
|
+
function sqlite(options) {
|
|
368
|
+
return createSqliteStorage(openDatabase(options.path));
|
|
369
|
+
}
|
|
370
|
+
//#endregion
|
|
371
|
+
export { sqlite };
|
|
372
|
+
|
|
373
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/schema.ts","../src/sql.ts","../src/storage.ts","../src/index.ts"],"sourcesContent":["// Abertura do banco e migrations internas do adapter. O schema é do adapter, não dos plugins\n// (ADR 0015): plugin nenhum cria tabela, então a versão do schema é uma só, guardada no\n// `PRAGMA user_version`, e cada migration roda uma vez, numa transação, no boot.\n\nimport { mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { DatabaseSync } from 'node:sqlite';\n\n// Namespace, coleção e chave em colunas separadas: concatenar (\"ns:chave\") colidiria. O `seq`\n// é a ordem de inserção do contrato (desempate da ordenação); como é a rowid, um update não o\n// muda. Só se acrescenta migration ao fim da lista, nunca se edita uma que já saiu.\nconst MIGRATIONS: readonly string[] = [\n `\n CREATE TABLE kv (\n namespace TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (namespace, key)\n ) WITHOUT ROWID;\n\n CREATE TABLE documents (\n seq INTEGER PRIMARY KEY,\n namespace TEXT NOT NULL,\n collection TEXT NOT NULL,\n id TEXT NOT NULL,\n doc TEXT NOT NULL,\n UNIQUE (namespace, collection, id)\n );\n\n CREATE TABLE auth_creds (\n session TEXT PRIMARY KEY,\n creds TEXT NOT NULL\n ) WITHOUT ROWID;\n\n CREATE TABLE auth_keys (\n session TEXT NOT NULL,\n type TEXT NOT NULL,\n id TEXT NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (session, type, id)\n ) WITHOUT ROWID;\n `,\n // Travas com validade (ADR 0074). `expires_at` em ms desde a época, pelo relógio do processo:\n // quem divide um arquivo SQLite está na mesma máquina.\n `\n CREATE TABLE leases (\n name TEXT PRIMARY KEY,\n owner TEXT NOT NULL,\n expires_at INTEGER NOT NULL\n ) WITHOUT ROWID;\n `,\n];\n\n/** Versão do schema que este adapter conhece (a do `PRAGMA user_version` depois do boot). */\nexport const SCHEMA_VERSION: number = MIGRATIONS.length;\n\n/** Roda `body` numa transação: tudo ou nada, mesmo se ele lançar. */\nexport function transaction<T>(db: DatabaseSync, body: () => T): T {\n db.exec('BEGIN IMMEDIATE');\n try {\n const result = body();\n db.exec('COMMIT');\n return result;\n } catch (error) {\n db.exec('ROLLBACK');\n throw error;\n }\n}\n\nfunction migrate(db: DatabaseSync): void {\n const { user_version: current } = db.prepare('PRAGMA user_version').get() as {\n user_version: number;\n };\n // Banco gravado por uma versão mais nova do adapter: seguir poderia corromper o que ela\n // gravou. Melhor parar no boot com a causa do que falhar depois numa consulta.\n if (current > SCHEMA_VERSION) {\n throw new Error(\n `storage-sqlite: o banco está no schema ${current}, mais novo que o deste adapter ` +\n `(${SCHEMA_VERSION}). Atualize o @usebridger/storage-sqlite.`,\n );\n }\n for (let version = current; version < SCHEMA_VERSION; version++) {\n transaction(db, () => {\n db.exec(MIGRATIONS[version] as string);\n db.exec(`PRAGMA user_version = ${version + 1}`);\n });\n }\n}\n\nfunction isFilePath(path: string): boolean {\n return path !== '' && path !== ':memory:' && !path.startsWith('file:');\n}\n\n/** Abre (ou cria) o banco, liga o WAL e aplica as migrations pendentes. */\nexport function openDatabase(path: string): DatabaseSync {\n // \"Clona e roda\": `data/bot.sqlite` funciona sem criar a pasta antes.\n if (isFilePath(path)) mkdirSync(dirname(path), { recursive: true });\n const db = new DatabaseSync(path);\n try {\n // WAL: leituras não esperam a escrita, e o `synchronous = NORMAL` continua seguro contra\n // queda do processo (só uma queda do SO pode perder a última transação). O `busy_timeout`\n // cobre outro processo (um script de manutenção) segurando o banco por um instante.\n db.exec('PRAGMA journal_mode = WAL');\n db.exec('PRAGMA synchronous = NORMAL');\n db.exec('PRAGMA busy_timeout = 5000');\n migrate(db);\n return db;\n } catch (error) {\n db.close();\n throw error;\n }\n}\n","// Tradução da consulta canônica do core (`normalizeQuery`/`normalizeWhere`) para SQL sobre a\n// coluna `doc` (JSON em texto). O nome de campo já chega validado como identificador simples,\n// então vai interpolado no caminho JSON; valores sempre entram como parâmetro.\n//\n// Cada campo é um par: `value` (o que `json_extract` devolve) e `type` (o `json_type`). O tipo é\n// necessário porque `json_extract` devolve `true` como 1 e arrays/objetos como texto: sem ele,\n// `{ v: 1 }` casaria `true` e `{ v: '[1]' }` casaria um array. Toda comparação usa `IS`, que\n// nunca dá NULL: assim o `ne` pode ser o `NOT` exato do `eq`, inclusive para campo ausente.\n\nimport type { Scalar } from '@usebridger/core';\nimport type { NormalizedCondition, NormalizedSort } from '@usebridger/core/adapter';\n\nexport type SqlParam = string | number;\n\nexport interface SqlFragment {\n readonly sql: string;\n readonly params: readonly SqlParam[];\n}\n\ninterface FieldSql {\n readonly value: string;\n readonly type: string;\n}\n\n/** Expressão de um campo do documento. O índice declarado usa exatamente esta expressão. */\nexport function fieldValueSql(field: string): string {\n return `json_extract(doc, '$.${field}')`;\n}\n\nfunction fieldSql(field: string): FieldSql {\n // O `id` é coluna, sempre texto.\n if (field === 'id') return { value: 'id', type: \"'text'\" };\n return { value: fieldValueSql(field), type: `json_type(doc, '$.${field}')` };\n}\n\nconst NUMBER = (type: string): string => `(${type} IS 'integer' OR ${type} IS 'real')`;\n\nfunction equals({ value, type }: FieldSql, operand: Scalar): SqlFragment {\n // JSON null e campo ausente: `json_extract` devolve NULL nos dois casos (array/objeto não).\n if (operand === null) return { sql: `${value} IS NULL`, params: [] };\n if (typeof operand === 'boolean') return { sql: `${type} IS '${operand}'`, params: [] };\n if (typeof operand === 'number') {\n return { sql: `(${NUMBER(type)} AND ${value} IS ?)`, params: [operand] };\n }\n return { sql: `(${type} IS 'text' AND ${value} IS ?)`, params: [operand] };\n}\n\nconst COMPARISON = { gt: '>', gte: '>=', lt: '<', lte: '<=' } as const;\n\nfunction condition(entry: NormalizedCondition): SqlFragment {\n const field = fieldSql(entry.field);\n switch (entry.op) {\n case 'eq':\n return equals(field, entry.value);\n case 'ne': {\n const eq = equals(field, entry.value);\n return { sql: `NOT ${eq.sql}`, params: eq.params };\n }\n case 'in': {\n if (entry.value.length === 0) return { sql: '0', params: [] };\n const items = entry.value.map((operand) => equals(field, operand));\n return {\n sql: `(${items.map((item) => item.sql).join(' OR ')})`,\n params: items.flatMap((item) => item.params),\n };\n }\n default: {\n // Só casa com o mesmo tipo do operando. Texto compara pela collation BINARY, que no banco\n // UTF-8 é a ordem de code point do contrato.\n const sameType =\n typeof entry.value === 'number' ? NUMBER(field.type) : `${field.type} IS 'text'`;\n return {\n sql: `(${sameType} AND ${field.value} ${COMPARISON[entry.op]} ?)`,\n params: [entry.value],\n };\n }\n }\n}\n\n/** Condições combinadas com E; lista vazia casa com tudo. */\nexport function whereSql(conditions: readonly NormalizedCondition[]): SqlFragment {\n if (conditions.length === 0) return { sql: '1', params: [] };\n const parts = conditions.map(condition);\n return {\n sql: parts.map((part) => part.sql).join(' AND '),\n params: parts.flatMap((part) => part.params),\n };\n}\n\n/**\n * Ordenação do contrato: primeiro a classe de tipo (null/ausente < booleano < número < texto <\n * array/objeto), depois o valor (arrays e objetos empatam), e o empate cai no `seq` — sempre\n * crescente, também em `desc`.\n */\nexport function orderBySql(sorts: readonly NormalizedSort[]): string {\n const terms = sorts.flatMap(({ field, direction }) => {\n const { value, type } = fieldSql(field);\n const dir = direction === 'asc' ? 'ASC' : 'DESC';\n const rank =\n `CASE WHEN ${value} IS NULL THEN 0 WHEN ${type} IN ('true', 'false') THEN 1 ` +\n `WHEN ${type} IN ('integer', 'real') THEN 2 WHEN ${type} IS 'text' THEN 3 ELSE 4 END`;\n const comparable = `CASE WHEN ${type} IN ('array', 'object') THEN NULL ELSE ${value} END`;\n return [`${rank} ${dir}`, `${comparable} ${dir}`];\n });\n return [...terms, 'seq ASC'].join(', ');\n}\n","// StoragePort sobre um banco SQLite (`node:sqlite`, ADR 0051). A validação da entrada vem do\n// core (`normalize*`), então os erros saem iguais aos do adapter em memória; aqui fica só a\n// tradução para SQL. O driver é síncrono: cada método roda a consulta inteira dentro do\n// `async`, e qualquer erro (inclusive o `StorageClosedError`) chega como rejeição.\n\nimport { randomUUID } from 'node:crypto';\nimport type { DatabaseSync, StatementSync } from 'node:sqlite';\nimport type {\n Collection,\n CollectionOptions,\n FindQuery,\n JsonObject,\n JsonValue,\n KeyValueStore,\n Patch,\n PluginStorage,\n Target,\n WithId,\n} from '@usebridger/core';\nimport {\n type AuthKeyData,\n type AuthStateStore,\n normalizeDocument,\n normalizeIndexes,\n normalizeQuery,\n normalizeWhere,\n StorageClosedError,\n type StoragePort,\n} from '@usebridger/core/adapter';\nimport { transaction } from './schema.ts';\nimport { fieldValueSql, orderBySql, type SqlFragment, whereSql } from './sql.ts';\n\ntype Document = { readonly [key: string]: JsonValue };\n\nfunction serialize(value: unknown): string {\n const text = JSON.stringify(value);\n if (text === undefined) throw new TypeError('Valor não serializável em JSON.');\n return text;\n}\n\nfunction parse<T>(text: string): T {\n return JSON.parse(text) as T;\n}\n\n/** StoragePort sobre `db`, que já deve estar aberto e migrado. Fecha o banco no `close()`. */\nexport function createSqliteStorage(db: DatabaseSync): StoragePort {\n let closed = false;\n // Consultas fixas preparadas uma vez. As de `find`/`update`/`delete` por filtro mudam de\n // forma a cada chamada e são preparadas na hora: cachear por texto cresceria sem limite.\n const statements = new Map<string, StatementSync>();\n // Índices já criados neste processo, para não repetir o DDL a cada operação.\n const indexes = new Set<string>();\n\n function ensureOpen(): void {\n if (closed) throw new StorageClosedError();\n }\n\n function statement(sql: string): StatementSync {\n let prepared = statements.get(sql);\n if (prepared === undefined) {\n prepared = db.prepare(sql);\n statements.set(sql, prepared);\n }\n return prepared;\n }\n\n function ensureIndex(field: string): void {\n if (indexes.has(field)) return;\n // Um índice por campo, para todas as coleções: (namespace, collection, valor) serve à\n // consulta de qualquer coleção que filtre ou ordene por ele. O nome vai em hexadecimal\n // porque identificador SQL não diferencia maiúsculas (`fireAt` e `fireat` colidiriam).\n const name = `documents_field_${Buffer.from(field).toString('hex')}`;\n db.exec(\n `CREATE INDEX IF NOT EXISTS ${name} ON documents (namespace, collection, ${fieldValueSql(field)})`,\n );\n indexes.add(field);\n }\n\n function createKv(namespace: string): KeyValueStore {\n return {\n async get<T extends JsonValue = JsonValue>(key: string): Promise<T | undefined> {\n ensureOpen();\n const row = statement('SELECT value FROM kv WHERE namespace = ? AND key = ?').get(\n namespace,\n key,\n ) as { value: string } | undefined;\n return row === undefined ? undefined : parse<T>(row.value);\n },\n async set(key: string, value: JsonValue): Promise<void> {\n ensureOpen();\n statement(\n 'INSERT INTO kv (namespace, key, value) VALUES (?, ?, ?) ' +\n 'ON CONFLICT (namespace, key) DO UPDATE SET value = excluded.value',\n ).run(namespace, key, serialize(value));\n },\n async delete(key: string): Promise<boolean> {\n ensureOpen();\n const { changes } = statement('DELETE FROM kv WHERE namespace = ? AND key = ?').run(\n namespace,\n key,\n );\n return Number(changes) > 0;\n },\n };\n }\n\n function createCollection<T extends Document>(\n namespace: string,\n name: string,\n fields: readonly string[],\n ): Collection<T> {\n function prepare(): void {\n ensureOpen();\n for (const field of fields) ensureIndex(field);\n }\n\n function targetSql(target: Target<T>): SqlFragment {\n if (typeof target === 'string') return { sql: 'id = ?', params: [target] };\n return whereSql(normalizeWhere(target));\n }\n\n return {\n async insert(document: T): Promise<string> {\n prepare();\n const text = serialize(normalizeDocument(document));\n const id = randomUUID();\n statement('INSERT INTO documents (namespace, collection, id, doc) VALUES (?, ?, ?, ?)').run(\n namespace,\n name,\n id,\n text,\n );\n return id;\n },\n async get(id: string): Promise<WithId<T> | undefined> {\n prepare();\n const row = statement(\n 'SELECT doc FROM documents WHERE namespace = ? AND collection = ? AND id = ?',\n ).get(namespace, name, id) as { doc: string } | undefined;\n return row === undefined ? undefined : { ...parse<T>(row.doc), id };\n },\n async find(query?: FindQuery<T>): Promise<WithId<T>[]> {\n prepare();\n const { where, orderBy, limit, offset } = normalizeQuery(query);\n const filter = whereSql(where);\n // `LIMIT -1` é \"sem limite\" no SQLite; OFFSET exige um LIMIT antes.\n const rows = db\n .prepare(\n 'SELECT id, doc FROM documents WHERE namespace = ? AND collection = ? AND ' +\n `${filter.sql} ORDER BY ${orderBySql(orderBy)} LIMIT ? OFFSET ?`,\n )\n .all(namespace, name, ...filter.params, limit ?? -1, offset) as {\n id: string;\n doc: string;\n }[];\n return rows.map((row) => ({ ...parse<T>(row.doc), id: row.id }));\n },\n async update(target: Target<T>, patch: Patch<T>): Promise<number> {\n prepare();\n const changes = normalizeDocument(patch);\n const filter = targetSql(target);\n // Merge raso em JS: o `json_patch` do SQLite mescla objetos aninhados e trata `null`\n // como remoção (RFC 7396), o contrário do patch raso do contrato.\n return transaction(db, () => {\n const rows = db\n .prepare(\n 'SELECT seq, doc FROM documents WHERE namespace = ? AND collection = ? AND ' +\n filter.sql,\n )\n .all(namespace, name, ...filter.params) as { seq: number; doc: string }[];\n const write = statement('UPDATE documents SET doc = ? WHERE seq = ?');\n for (const row of rows) {\n write.run(serialize({ ...parse<JsonObject>(row.doc), ...changes }), row.seq);\n }\n return rows.length;\n });\n },\n async delete(target: Target<T>): Promise<number> {\n prepare();\n const filter = targetSql(target);\n const { changes } = db\n .prepare(`DELETE FROM documents WHERE namespace = ? AND collection = ? AND ${filter.sql}`)\n .run(namespace, name, ...filter.params);\n return Number(changes);\n },\n };\n }\n\n function createPluginStorage(namespace: string): PluginStorage {\n return {\n kv: createKv(namespace),\n collection<T extends Document>(name: string, options?: CollectionOptions): Collection<T> {\n // Valida na hora (o contrato lança aqui), mas só cria o índice na primeira operação:\n // `collection()` é síncrono e não deve fazer I/O nem falhar por causa do banco.\n return createCollection<T>(namespace, name, normalizeIndexes(options));\n },\n };\n }\n\n function createAuthState(session: string): AuthStateStore {\n return {\n async getCreds(): Promise<JsonValue | undefined> {\n ensureOpen();\n const row = statement('SELECT creds FROM auth_creds WHERE session = ?').get(session) as\n | { creds: string }\n | undefined;\n return row === undefined ? undefined : parse(row.creds);\n },\n async setCreds(creds: JsonValue): Promise<void> {\n ensureOpen();\n statement(\n 'INSERT INTO auth_creds (session, creds) VALUES (?, ?) ' +\n 'ON CONFLICT (session) DO UPDATE SET creds = excluded.creds',\n ).run(session, serialize(creds));\n },\n async getKeys(type: string, ids: readonly string[]): Promise<Record<string, JsonValue>> {\n ensureOpen();\n // A lista vai como um array JSON: o Baileys pede centenas de ids de uma vez, e um\n // `IN (?, ?, ...)` por tamanho esbarraria no limite de parâmetros do SQLite.\n const rows = statement(\n 'SELECT id, value FROM auth_keys WHERE session = ? AND type = ? ' +\n 'AND id IN (SELECT value FROM json_each(?))',\n ).all(session, type, JSON.stringify(ids)) as { id: string; value: string }[];\n const result: Record<string, JsonValue> = {};\n for (const row of rows) result[row.id] = parse(row.value);\n return result;\n },\n async setKeys(data: AuthKeyData): Promise<void> {\n ensureOpen();\n // Serializa o lote antes de abrir a transação: um valor inválido não chega a gravar nada.\n const entries = Object.entries(data).flatMap(([type, values]) =>\n Object.entries(values).map(\n ([id, value]) => [type, id, value === null ? null : serialize(value)] as const,\n ),\n );\n const write = statement(\n 'INSERT INTO auth_keys (session, type, id, value) VALUES (?, ?, ?, ?) ' +\n 'ON CONFLICT (session, type, id) DO UPDATE SET value = excluded.value',\n );\n const remove = statement('DELETE FROM auth_keys WHERE session = ? AND type = ? AND id = ?');\n transaction(db, () => {\n for (const [type, id, text] of entries) {\n if (text === null) remove.run(session, type, id);\n else write.run(session, type, id, text);\n }\n });\n },\n async clear(): Promise<void> {\n ensureOpen();\n transaction(db, () => {\n statement('DELETE FROM auth_creds WHERE session = ?').run(session);\n statement('DELETE FROM auth_keys WHERE session = ?').run(session);\n });\n },\n };\n }\n\n return {\n forNamespace(namespace: string): PluginStorage {\n return createPluginStorage(namespace);\n },\n authState(session: string): AuthStateStore {\n return createAuthState(session);\n },\n async acquireLease(name: string, owner: string, ttlMs: number): Promise<boolean> {\n ensureOpen();\n const now = Date.now();\n // Um comando só, então atômico entre conexões: o upsert não toca a linha (0 mudanças) se\n // ela é de outro dono e ainda vale.\n const { changes } = statement(\n 'INSERT INTO leases (name, owner, expires_at) VALUES (?, ?, ?) ' +\n 'ON CONFLICT (name) DO UPDATE SET owner = excluded.owner, expires_at = excluded.expires_at ' +\n 'WHERE leases.owner = excluded.owner OR leases.expires_at <= ?',\n ).run(name, owner, now + ttlMs, now);\n return Number(changes) > 0;\n },\n async releaseLease(name: string, owner: string): Promise<void> {\n ensureOpen();\n statement('DELETE FROM leases WHERE name = ? AND owner = ?').run(name, owner);\n },\n async close(): Promise<void> {\n if (closed) return;\n closed = true;\n statements.clear();\n db.close();\n },\n };\n}\n","// Entry `@usebridger/storage-sqlite`: o adapter de storage padrão, que o app passa em\n// `createBot({ storage })`. Usa o `node:sqlite` do próprio Node (ADR 0051): nada de addon nativo\n// para compilar no `pnpm install`.\n\nimport type { StoragePort } from '@usebridger/core/adapter';\nimport { openDatabase } from './schema.ts';\nimport { createSqliteStorage } from './storage.ts';\n\nexport interface SqliteOptions {\n /**\n * Arquivo do banco (criado, com as pastas, se não existir) ou `':memory:'` para um banco\n * descartado no `close()`.\n */\n readonly path: string;\n}\n\n/**\n * Abre o banco, liga o WAL e aplica as migrations do adapter. Lança se o arquivo não abre ou se\n * foi gravado por uma versão mais nova do adapter.\n */\nexport function sqlite(options: SqliteOptions): StoragePort {\n return createSqliteStorage(openDatabase(options.path));\n}\n"],"mappings":";;;;;;AAWA,MAAM,aAAgC,CACpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgCA;;;;;;GAOF;;AAGA,MAAa,iBAAyB,WAAW;;AAGjD,SAAgB,YAAe,IAAkB,MAAkB;CACjE,GAAG,KAAK,iBAAiB;CACzB,IAAI;EACF,MAAM,SAAS,KAAK;EACpB,GAAG,KAAK,QAAQ;EAChB,OAAO;CACT,SAAS,OAAO;EACd,GAAG,KAAK,UAAU;EAClB,MAAM;CACR;AACF;AAEA,SAAS,QAAQ,IAAwB;CACvC,MAAM,EAAE,cAAc,YAAY,GAAG,QAAQ,qBAAqB,CAAC,CAAC,IAAI;CAKxE,IAAI,UAAU,gBACZ,MAAM,IAAI,MACR,0CAA0C,QAAQ,mCAC5C,eAAe,0CACvB;CAEF,KAAK,IAAI,UAAU,SAAS,UAAU,gBAAgB,WACpD,YAAY,UAAU;EACpB,GAAG,KAAK,WAAW,QAAkB;EACrC,GAAG,KAAK,yBAAyB,UAAU,GAAG;CAChD,CAAC;AAEL;AAEA,SAAS,WAAW,MAAuB;CACzC,OAAO,SAAS,MAAM,SAAS,cAAc,CAAC,KAAK,WAAW,OAAO;AACvE;;AAGA,SAAgB,aAAa,MAA4B;CAEvD,IAAI,WAAW,IAAI,GAAG,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK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5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Storage do Bridger em SQLite (node:sqlite), sem dependência nativa.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/murillous/usebridger.git",
|
|
9
|
+
"directory": "packages/storage-sqlite"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/murillous/usebridger/tree/develop/packages/storage-sqlite/docs#readme",
|
|
12
|
+
"bugs": "https://github.com/murillous/usebridger/issues",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"imports": {
|
|
15
|
+
"#*": "./src/*"
|
|
16
|
+
},
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"@usebridger/source": "./src/index.ts",
|
|
20
|
+
"types": "./dist/index.d.mts",
|
|
21
|
+
"default": "./dist/index.mjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@usebridger/core": "^0.1.0"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsdown"
|
|
35
|
+
}
|
|
6
36
|
}
|
package/README.md
DELETED