@hot-updater/plugin-core 1.0.0-rc.3 → 1.0.0-rc.35
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/README.md +33 -0
- package/dist/baseCandidateKey.cjs +50 -0
- package/dist/baseCandidateKey.d.cts +27 -0
- package/dist/baseCandidateKey.d.mts +27 -0
- package/dist/baseCandidateKey.mjs +49 -0
- package/dist/bundleStorageLayout.cjs +7 -0
- package/dist/bundleStorageLayout.d.cts +5 -1
- package/dist/bundleStorageLayout.d.mts +5 -1
- package/dist/bundleStorageLayout.mjs +7 -1
- package/dist/contentType.cjs +9 -0
- package/dist/contentType.d.cts +4 -0
- package/dist/contentType.d.mts +4 -0
- package/dist/contentType.mjs +7 -0
- package/dist/coreApi.d.cts +131 -0
- package/dist/coreApi.d.mts +131 -0
- package/dist/createStorageAdapter.cjs +8 -0
- package/dist/createStorageAdapter.d.cts +9 -0
- package/dist/createStorageAdapter.d.mts +9 -0
- package/dist/createStorageAdapter.mjs +7 -0
- package/dist/database/adapter.cjs +61 -0
- package/dist/database/adapter.d.cts +200 -0
- package/dist/database/adapter.d.mts +200 -0
- package/dist/database/adapter.mjs +55 -0
- package/dist/database/distinct.cjs +88 -0
- package/dist/database/distinct.d.cts +18 -0
- package/dist/database/distinct.d.mts +18 -0
- package/dist/database/distinct.mjs +85 -0
- package/dist/database/memoryAdapter.cjs +107 -0
- package/dist/database/memoryAdapter.d.cts +14 -0
- package/dist/database/memoryAdapter.d.mts +14 -0
- package/dist/database/memoryAdapter.mjs +107 -0
- package/dist/database/values.cjs +114 -0
- package/dist/database/values.d.cts +17 -0
- package/dist/database/values.d.mts +17 -0
- package/dist/database/values.mjs +104 -0
- package/dist/database/verifyAdapter.cjs +137 -0
- package/dist/database/verifyAdapter.d.cts +37 -0
- package/dist/database/verifyAdapter.d.mts +37 -0
- package/dist/database/verifyAdapter.mjs +136 -0
- package/dist/databaseErrors.cjs +30 -0
- package/dist/databaseErrors.d.cts +21 -0
- package/dist/databaseErrors.d.mts +21 -0
- package/dist/databaseErrors.mjs +28 -0
- package/dist/databaseJsonValue.cjs +6 -0
- package/dist/databaseJsonValue.d.cts +9 -2
- package/dist/databaseJsonValue.d.mts +9 -2
- package/dist/databaseJsonValue.mjs +6 -0
- package/dist/databaseMetadata.cjs +4 -4
- package/dist/databaseMetadata.mjs +3 -3
- package/dist/databaseRows.cjs +6 -12
- package/dist/databaseRows.d.cts +1 -1
- package/dist/databaseRows.d.mts +1 -1
- package/dist/databaseRows.mjs +1 -7
- package/dist/engine/core/schema.cjs +279 -0
- package/dist/engine/core/schema.d.cts +312 -0
- package/dist/engine/core/schema.d.mts +312 -0
- package/dist/engine/core/schema.mjs +277 -0
- package/dist/engine/createEngine.cjs +72 -0
- package/dist/engine/createEngine.d.cts +45 -0
- package/dist/engine/createEngine.d.mts +45 -0
- package/dist/engine/createEngine.mjs +72 -0
- package/dist/engine/database/aggregateBatching.cjs +627 -0
- package/dist/engine/database/aggregateBatching.mjs +626 -0
- package/dist/engine/database/cursor.cjs +42 -0
- package/dist/engine/database/cursor.mjs +38 -0
- package/dist/engine/database/database.cjs +68 -0
- package/dist/engine/database/database.mjs +68 -0
- package/dist/engine/database/engine.cjs +37 -0
- package/dist/engine/database/engine.mjs +37 -0
- package/dist/engine/database/engineAggregates.cjs +120 -0
- package/dist/engine/database/engineAggregates.mjs +117 -0
- package/dist/engine/database/engineReads.cjs +182 -0
- package/dist/engine/database/engineReads.d.cts +10 -0
- package/dist/engine/database/engineReads.d.mts +10 -0
- package/dist/engine/database/engineReads.mjs +181 -0
- package/dist/engine/database/engineTransaction.cjs +399 -0
- package/dist/engine/database/engineTransaction.d.cts +18 -0
- package/dist/engine/database/engineTransaction.d.mts +18 -0
- package/dist/engine/database/engineTransaction.mjs +398 -0
- package/dist/engine/database/fence.cjs +156 -0
- package/dist/engine/database/fence.d.cts +41 -0
- package/dist/engine/database/fence.d.mts +41 -0
- package/dist/engine/database/fence.mjs +149 -0
- package/dist/engine/database/kv/kvAdapter.cjs +293 -0
- package/dist/engine/database/kv/kvAdapter.d.cts +116 -0
- package/dist/engine/database/kv/kvAdapter.d.mts +116 -0
- package/dist/engine/database/kv/kvAdapter.mjs +292 -0
- package/dist/engine/database/readMeter.cjs +80 -0
- package/dist/engine/database/readMeter.d.cts +34 -0
- package/dist/engine/database/readMeter.d.mts +34 -0
- package/dist/engine/database/readMeter.mjs +79 -0
- package/dist/engine/database/resolveSchema.cjs +197 -0
- package/dist/engine/database/resolveSchema.d.cts +35 -0
- package/dist/engine/database/resolveSchema.d.mts +35 -0
- package/dist/engine/database/resolveSchema.mjs +195 -0
- package/dist/engine/database/retention.cjs +100 -0
- package/dist/engine/database/retention.mjs +98 -0
- package/dist/engine/database/sql/sqlAdapter.cjs +290 -0
- package/dist/engine/database/sql/sqlAdapter.d.cts +45 -0
- package/dist/engine/database/sql/sqlAdapter.d.mts +45 -0
- package/dist/engine/database/sql/sqlAdapter.mjs +288 -0
- package/dist/engine/database/sql/sqlSchema.cjs +175 -0
- package/dist/engine/database/sql/sqlSchema.d.cts +45 -0
- package/dist/engine/database/sql/sqlSchema.d.mts +45 -0
- package/dist/engine/database/sql/sqlSchema.mjs +169 -0
- package/dist/engine/db/coreDatabase.cjs +94 -0
- package/dist/engine/db/coreDatabase.d.cts +78 -0
- package/dist/engine/db/coreDatabase.d.mts +78 -0
- package/dist/engine/db/coreDatabase.mjs +86 -0
- package/dist/engine/db/engineMigrator.cjs +53 -0
- package/dist/engine/db/engineMigrator.mjs +53 -0
- package/dist/engine/db/engineSql.cjs +26 -0
- package/dist/engine/db/engineSql.d.cts +16 -0
- package/dist/engine/db/engineSql.d.mts +16 -0
- package/dist/engine/db/engineSql.mjs +25 -0
- package/dist/engine/db/engineSqlMigrator.cjs +67 -0
- package/dist/engine/db/engineSqlMigrator.d.cts +21 -0
- package/dist/engine/db/engineSqlMigrator.d.mts +21 -0
- package/dist/engine/db/engineSqlMigrator.mjs +67 -0
- package/dist/engine/db/fixedMigratorShared.cjs +12 -0
- package/dist/engine/db/fixedMigratorShared.mjs +11 -0
- package/dist/engine/db/schemaSettings.cjs +63 -0
- package/dist/engine/db/schemaSettings.d.cts +7 -0
- package/dist/engine/db/schemaSettings.d.mts +7 -0
- package/dist/engine/db/schemaSettings.mjs +62 -0
- package/dist/engine/db/settingsMigrator.cjs +94 -0
- package/dist/engine/db/settingsMigrator.d.cts +25 -0
- package/dist/engine/db/settingsMigrator.d.mts +25 -0
- package/dist/engine/db/settingsMigrator.mjs +91 -0
- package/dist/engine/db/types.d.cts +78 -0
- package/dist/engine/db/types.d.mts +78 -0
- package/dist/index.cjs +97 -49
- package/dist/index.d.cts +46 -22
- package/dist/index.d.mts +46 -22
- package/dist/index.mjs +32 -17
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/comparison-DenM3wCn.cjs +0 -5
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/comparison-DenM3wCn.mjs +1 -5
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/range-DvX-Y6iv.cjs +8 -0
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/range-DvX-Y6iv.mjs +9 -2
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/set-CC5YeoYX.cjs +4 -0
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/set-CC5YeoYX.mjs +4 -1
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/version-CQ98ZBpL.cjs +0 -5
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/version-CQ98ZBpL.mjs +2 -6
- package/dist/releaseCatalogCompiler.cjs +27 -26
- package/dist/releaseCatalogCompiler.d.cts +1 -2
- package/dist/releaseCatalogCompiler.d.mts +2 -3
- package/dist/releaseCatalogCompiler.mjs +5 -9
- package/dist/releaseCatalogMutation.cjs +0 -292
- package/dist/releaseCatalogMutation.d.cts +4 -45
- package/dist/releaseCatalogMutation.d.mts +4 -45
- package/dist/releaseCatalogMutation.mjs +1 -288
- package/dist/releaseManagement.cjs +0 -221
- package/dist/releaseManagement.d.cts +4 -28
- package/dist/releaseManagement.d.mts +4 -28
- package/dist/releaseManagement.mjs +1 -216
- package/dist/remoteBundleSigning.d.cts +2 -2
- package/dist/remoteBundleSigning.d.mts +2 -2
- package/dist/serverPlugin/busy.cjs +36 -0
- package/dist/serverPlugin/busy.d.cts +12 -0
- package/dist/serverPlugin/busy.d.mts +12 -0
- package/dist/serverPlugin/busy.mjs +36 -0
- package/dist/serverPlugin/configError.cjs +7 -0
- package/dist/serverPlugin/configError.d.cts +7 -0
- package/dist/serverPlugin/configError.d.mts +7 -0
- package/dist/serverPlugin/configError.mjs +7 -0
- package/dist/serverPlugin/coreReads.d.cts +48 -0
- package/dist/serverPlugin/coreReads.d.mts +48 -0
- package/dist/serverPlugin/databaseHandle.d.cts +105 -0
- package/dist/serverPlugin/databaseHandle.d.mts +105 -0
- package/dist/serverPlugin/definePlugin.cjs +5 -0
- package/dist/serverPlugin/definePlugin.d.cts +130 -0
- package/dist/serverPlugin/definePlugin.d.mts +130 -0
- package/dist/serverPlugin/definePlugin.mjs +5 -0
- package/dist/serverPlugin/definitions.d.cts +76 -0
- package/dist/serverPlugin/definitions.d.mts +76 -0
- package/dist/serverPlugin/errors.cjs +37 -0
- package/dist/serverPlugin/errors.d.cts +29 -0
- package/dist/serverPlugin/errors.d.mts +29 -0
- package/dist/serverPlugin/errors.mjs +32 -0
- package/dist/serverPlugin/schema.cjs +24 -0
- package/dist/serverPlugin/schema.d.cts +90 -0
- package/dist/serverPlugin/schema.d.mts +90 -0
- package/dist/serverPlugin/schema.mjs +23 -0
- package/dist/types/databaseConfig.cjs +5 -0
- package/dist/types/databaseConfig.d.cts +68 -0
- package/dist/types/databaseConfig.d.mts +68 -0
- package/dist/types/databaseConfig.mjs +5 -0
- package/dist/types/databaseOperations.d.cts +5 -180
- package/dist/types/databaseOperations.d.mts +5 -180
- package/dist/types/databaseRows.d.cts +5 -56
- package/dist/types/databaseRows.d.mts +5 -56
- package/dist/types/index.cjs +2 -0
- package/dist/types/index.d.cts +31 -97
- package/dist/types/index.d.mts +31 -97
- package/dist/types/index.mjs +2 -1
- package/dist/types/models.d.cts +14 -0
- package/dist/types/models.d.mts +14 -0
- package/dist/types/public.d.cts +4 -3
- package/dist/types/public.d.mts +4 -3
- package/dist/uuidv7.cjs +3 -3
- package/dist/uuidv7.d.cts +1 -1
- package/dist/uuidv7.d.mts +1 -1
- package/dist/uuidv7.mjs +1 -1
- package/package.json +10 -7
- package/dist/calculatePagination.cjs +0 -25
- package/dist/calculatePagination.d.cts +0 -12
- package/dist/calculatePagination.d.mts +0 -12
- package/dist/calculatePagination.mjs +0 -25
- package/dist/compressionFormat.cjs +0 -62
- package/dist/compressionFormat.d.cts +0 -33
- package/dist/compressionFormat.d.mts +0 -33
- package/dist/compressionFormat.mjs +0 -58
- package/dist/createDatabasePlugin.cjs +0 -920
- package/dist/createDatabasePlugin.d.cts +0 -28
- package/dist/createDatabasePlugin.d.mts +0 -28
- package/dist/createDatabasePlugin.mjs +0 -916
- package/dist/createStoragePlugin.cjs +0 -8
- package/dist/createStoragePlugin.d.cts +0 -9
- package/dist/createStoragePlugin.d.mts +0 -9
- package/dist/createStoragePlugin.mjs +0 -7
- package/dist/databaseClient.cjs +0 -117
- package/dist/databaseClient.d.cts +0 -32
- package/dist/databaseClient.d.mts +0 -32
- package/dist/databaseClient.mjs +0 -114
- package/dist/databaseClientReads.cjs +0 -115
- package/dist/databaseClientReads.mjs +0 -113
- package/dist/databaseClientUpdates.cjs +0 -40
- package/dist/databaseClientUpdates.d.cts +0 -11
- package/dist/databaseClientUpdates.d.mts +0 -11
- package/dist/databaseClientUpdates.mjs +0 -38
- package/dist/databasePluginCrud.cjs +0 -88
- package/dist/databasePluginCrud.d.cts +0 -4
- package/dist/databasePluginCrud.d.mts +0 -4
- package/dist/databasePluginCrud.mjs +0 -87
- package/dist/databasePluginCrudValidation.d.cts +0 -6
- package/dist/databasePluginCrudValidation.d.mts +0 -6
- package/dist/databasePluginCrudValidationErrors.cjs +0 -11
- package/dist/databasePluginCrudValidationErrors.d.cts +0 -9
- package/dist/databasePluginCrudValidationErrors.d.mts +0 -9
- package/dist/databasePluginCrudValidationErrors.mjs +0 -11
- package/dist/databasePluginCrudValidationFields.cjs +0 -321
- package/dist/databasePluginCrudValidationFields.d.cts +0 -1
- package/dist/databasePluginCrudValidationFields.d.mts +0 -1
- package/dist/databasePluginCrudValidationFields.mjs +0 -309
- package/dist/databasePluginCrudValidationMutations.cjs +0 -107
- package/dist/databasePluginCrudValidationMutations.d.cts +0 -1
- package/dist/databasePluginCrudValidationMutations.d.mts +0 -1
- package/dist/databasePluginCrudValidationMutations.mjs +0 -100
- package/dist/databasePluginCrudValidationQueries.cjs +0 -103
- package/dist/databasePluginCrudValidationQueries.d.cts +0 -2
- package/dist/databasePluginCrudValidationQueries.d.mts +0 -2
- package/dist/databasePluginCrudValidationQueries.mjs +0 -97
- package/dist/databasePluginCrudValidationRows.cjs +0 -55
- package/dist/databasePluginCrudValidationRows.d.cts +0 -1
- package/dist/databasePluginCrudValidationRows.d.mts +0 -1
- package/dist/databasePluginCrudValidationRows.mjs +0 -53
- package/dist/databasePluginTransaction.cjs +0 -7
- package/dist/databasePluginTransaction.mjs +0 -7
- package/dist/insightsContract.cjs +0 -157
- package/dist/insightsContract.d.cts +0 -11
- package/dist/insightsContract.d.mts +0 -11
- package/dist/insightsContract.mjs +0 -153
- package/dist/internal.cjs +0 -6
- package/dist/internal.d.cts +0 -10
- package/dist/internal.d.mts +0 -10
- package/dist/internal.mjs +0 -3
- package/dist/paginateBundles.cjs +0 -53
- package/dist/paginateBundles.d.cts +0 -13
- package/dist/paginateBundles.d.mts +0 -13
- package/dist/paginateBundles.mjs +0 -53
- package/dist/queryBundles.cjs +0 -34
- package/dist/queryBundles.d.cts +0 -9
- package/dist/queryBundles.d.mts +0 -9
- package/dist/queryBundles.mjs +0 -32
- package/dist/requestBundleCache.cjs +0 -22
- package/dist/requestBundleCache.d.cts +0 -8
- package/dist/requestBundleCache.d.mts +0 -8
- package/dist/requestBundleCache.mjs +0 -22
- package/dist/types/database.d.cts +0 -5
- package/dist/types/database.d.mts +0 -5
- package/dist/types/databaseFields.cjs +0 -105
- package/dist/types/databaseFields.d.cts +0 -13
- package/dist/types/databaseFields.d.mts +0 -13
- package/dist/types/databaseFields.mjs +0 -105
- package/dist/types/databasePlugin.d.cts +0 -298
- package/dist/types/databasePlugin.d.mts +0 -298
- package/dist/types/databaseQuery.d.cts +0 -46
- package/dist/types/databaseQuery.d.mts +0 -46
- package/dist/types/internal.d.cts +0 -8
- package/dist/types/internal.d.mts +0 -8
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
const require_adapter = require("./adapter.cjs");
|
|
2
|
+
const require_values = require("./values.cjs");
|
|
3
|
+
//#region src/database/memoryAdapter.ts
|
|
4
|
+
const keyId = (key) => JSON.stringify(key);
|
|
5
|
+
const numberOf = (value) => typeof value === "number" ? value : 0;
|
|
6
|
+
const violatesUnique = (table, rows, id, row) => table.indexes.some((index) => {
|
|
7
|
+
if (!index.unique) return false;
|
|
8
|
+
const entries = require_values.indexEntries(table, index, row);
|
|
9
|
+
return entries.length > 0 && [...rows].some(([otherId, other]) => otherId !== id && require_values.indexEntries(table, index, other).some((entry) => entries.some((candidate) => require_values.compareTuples(entry, candidate) === 0)));
|
|
10
|
+
});
|
|
11
|
+
const putRow = (table, rows, id, row) => {
|
|
12
|
+
if (violatesUnique(table, rows, id, row)) return false;
|
|
13
|
+
rows.set(id, row);
|
|
14
|
+
return true;
|
|
15
|
+
};
|
|
16
|
+
/** Applies one op to a draft; false means its guard or a constraint failed. */
|
|
17
|
+
const applyOp = (rows, op) => {
|
|
18
|
+
const id = keyId(op.type === "insert" ? require_adapter.rowKey(op.table, op.row) : op.key);
|
|
19
|
+
const current = rows.get(id);
|
|
20
|
+
const version = numberOf(current?.["_v"]);
|
|
21
|
+
switch (op.type) {
|
|
22
|
+
case "insert": return current === void 0 && putRow(op.table, rows, id, structuredClone(op.row));
|
|
23
|
+
case "patch": return current !== void 0 && version === op.guard.v && putRow(op.table, rows, id, {
|
|
24
|
+
...current,
|
|
25
|
+
...structuredClone(op.set),
|
|
26
|
+
["_v"]: version + 1
|
|
27
|
+
});
|
|
28
|
+
case "delete": return current !== void 0 && version === op.guard.v && rows.delete(id);
|
|
29
|
+
case "increment": {
|
|
30
|
+
const base = current ?? op.init;
|
|
31
|
+
if (base === void 0 || op.guard !== void 0 && (current === void 0 || version !== op.guard.v)) return false;
|
|
32
|
+
const next = structuredClone(base);
|
|
33
|
+
for (const [column, delta] of Object.entries(op.by)) next[column] = numberOf(base[column]) + delta;
|
|
34
|
+
next["_v"] = numberOf(base["_v"]) + 1;
|
|
35
|
+
return putRow(op.table, rows, id, next);
|
|
36
|
+
}
|
|
37
|
+
case "check": return current !== void 0 && version === op.guard.v;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* The reference adapter: every read is a consistent snapshot and every write
|
|
42
|
+
* applies to a copy that replaces the state only when all ops succeed.
|
|
43
|
+
*/
|
|
44
|
+
const createMemoryAdapter = (options = {}) => {
|
|
45
|
+
const prefix = options.tablePrefix ?? "";
|
|
46
|
+
let state = /* @__PURE__ */ new Map();
|
|
47
|
+
const rowsOf = (table) => state.get(prefix + table.name) ?? /* @__PURE__ */ new Map();
|
|
48
|
+
return {
|
|
49
|
+
id: "memory",
|
|
50
|
+
fits: () => true,
|
|
51
|
+
async get(table, keys) {
|
|
52
|
+
const rows = rowsOf(table);
|
|
53
|
+
return keys.map((key) => {
|
|
54
|
+
const row = rows.get(keyId(key));
|
|
55
|
+
return row === void 0 ? null : structuredClone(row);
|
|
56
|
+
});
|
|
57
|
+
},
|
|
58
|
+
async query(table, request) {
|
|
59
|
+
const index = require_adapter.findPhysicalIndex(table, request.index);
|
|
60
|
+
const direction = request.order === "asc" ? 1 : -1;
|
|
61
|
+
return [...rowsOf(table).values()].filter((row) => require_values.matchesQuery(table, index, request, row)).sort((left, right) => direction * require_values.compareTuples(require_values.indexOrderTuple(table, index, left), require_values.indexOrderTuple(table, index, right))).slice(0, request.limit).map((row) => structuredClone(row));
|
|
62
|
+
},
|
|
63
|
+
async write(ops) {
|
|
64
|
+
const draft = new Map(state);
|
|
65
|
+
const copied = /* @__PURE__ */ new Set();
|
|
66
|
+
for (const [position, op] of ops.entries()) {
|
|
67
|
+
const name = prefix + op.table.name;
|
|
68
|
+
if (!copied.has(name)) {
|
|
69
|
+
draft.set(name, new Map(draft.get(name)));
|
|
70
|
+
copied.add(name);
|
|
71
|
+
}
|
|
72
|
+
if (!applyOp(draft.get(name), op)) return {
|
|
73
|
+
ok: false,
|
|
74
|
+
failedOp: position
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
state = draft;
|
|
78
|
+
return { ok: true };
|
|
79
|
+
},
|
|
80
|
+
async prune(table, before, limit) {
|
|
81
|
+
const column = table.retention?.column ?? "";
|
|
82
|
+
/** Oldest first; the key breaks a tie. */
|
|
83
|
+
const order = (row) => [row[column], ...require_adapter.rowKey(table, row)];
|
|
84
|
+
const doomed = [...rowsOf(table)].filter(([, row]) => {
|
|
85
|
+
const time = row[column];
|
|
86
|
+
return typeof time === "number" && time <= before;
|
|
87
|
+
}).sort(([, left], [, right]) => require_values.compareTuples(order(left), order(right))).slice(0, limit);
|
|
88
|
+
const rows = new Map(rowsOf(table));
|
|
89
|
+
for (const [id] of doomed) rows.delete(id);
|
|
90
|
+
state = new Map(state).set(prefix + table.name, rows);
|
|
91
|
+
return doomed.length;
|
|
92
|
+
},
|
|
93
|
+
migrations: { async apply(tables) {
|
|
94
|
+
const next = new Map(state);
|
|
95
|
+
for (const table of tables) {
|
|
96
|
+
const name = prefix + table.name;
|
|
97
|
+
next.set(name, next.get(name) ?? /* @__PURE__ */ new Map());
|
|
98
|
+
}
|
|
99
|
+
state = next;
|
|
100
|
+
} },
|
|
101
|
+
async dispose() {
|
|
102
|
+
state = /* @__PURE__ */ new Map();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
//#endregion
|
|
107
|
+
exports.createMemoryAdapter = createMemoryAdapter;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { DatabaseAdapter } from "./adapter.cjs";
|
|
2
|
+
//#region src/database/memoryAdapter.d.ts
|
|
3
|
+
/** `createMemoryAdapter`'s options. */
|
|
4
|
+
interface MemoryAdapterOptions {
|
|
5
|
+
/** Prefixes every table's name, so several servers can share one store. */
|
|
6
|
+
readonly tablePrefix?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The reference adapter: every read is a consistent snapshot and every write
|
|
10
|
+
* applies to a copy that replaces the state only when all ops succeed.
|
|
11
|
+
*/
|
|
12
|
+
declare const createMemoryAdapter: (options?: MemoryAdapterOptions) => DatabaseAdapter;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { MemoryAdapterOptions, createMemoryAdapter };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { DatabaseAdapter } from "./adapter.mjs";
|
|
2
|
+
//#region src/database/memoryAdapter.d.ts
|
|
3
|
+
/** `createMemoryAdapter`'s options. */
|
|
4
|
+
interface MemoryAdapterOptions {
|
|
5
|
+
/** Prefixes every table's name, so several servers can share one store. */
|
|
6
|
+
readonly tablePrefix?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The reference adapter: every read is a consistent snapshot and every write
|
|
10
|
+
* applies to a copy that replaces the state only when all ops succeed.
|
|
11
|
+
*/
|
|
12
|
+
declare const createMemoryAdapter: (options?: MemoryAdapterOptions) => DatabaseAdapter;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { MemoryAdapterOptions, createMemoryAdapter };
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { findPhysicalIndex, rowKey } from "./adapter.mjs";
|
|
2
|
+
import { compareTuples, indexEntries, indexOrderTuple, matchesQuery } from "./values.mjs";
|
|
3
|
+
//#region src/database/memoryAdapter.ts
|
|
4
|
+
const keyId = (key) => JSON.stringify(key);
|
|
5
|
+
const numberOf = (value) => typeof value === "number" ? value : 0;
|
|
6
|
+
const violatesUnique = (table, rows, id, row) => table.indexes.some((index) => {
|
|
7
|
+
if (!index.unique) return false;
|
|
8
|
+
const entries = indexEntries(table, index, row);
|
|
9
|
+
return entries.length > 0 && [...rows].some(([otherId, other]) => otherId !== id && indexEntries(table, index, other).some((entry) => entries.some((candidate) => compareTuples(entry, candidate) === 0)));
|
|
10
|
+
});
|
|
11
|
+
const putRow = (table, rows, id, row) => {
|
|
12
|
+
if (violatesUnique(table, rows, id, row)) return false;
|
|
13
|
+
rows.set(id, row);
|
|
14
|
+
return true;
|
|
15
|
+
};
|
|
16
|
+
/** Applies one op to a draft; false means its guard or a constraint failed. */
|
|
17
|
+
const applyOp = (rows, op) => {
|
|
18
|
+
const id = keyId(op.type === "insert" ? rowKey(op.table, op.row) : op.key);
|
|
19
|
+
const current = rows.get(id);
|
|
20
|
+
const version = numberOf(current?.["_v"]);
|
|
21
|
+
switch (op.type) {
|
|
22
|
+
case "insert": return current === void 0 && putRow(op.table, rows, id, structuredClone(op.row));
|
|
23
|
+
case "patch": return current !== void 0 && version === op.guard.v && putRow(op.table, rows, id, {
|
|
24
|
+
...current,
|
|
25
|
+
...structuredClone(op.set),
|
|
26
|
+
["_v"]: version + 1
|
|
27
|
+
});
|
|
28
|
+
case "delete": return current !== void 0 && version === op.guard.v && rows.delete(id);
|
|
29
|
+
case "increment": {
|
|
30
|
+
const base = current ?? op.init;
|
|
31
|
+
if (base === void 0 || op.guard !== void 0 && (current === void 0 || version !== op.guard.v)) return false;
|
|
32
|
+
const next = structuredClone(base);
|
|
33
|
+
for (const [column, delta] of Object.entries(op.by)) next[column] = numberOf(base[column]) + delta;
|
|
34
|
+
next["_v"] = numberOf(base["_v"]) + 1;
|
|
35
|
+
return putRow(op.table, rows, id, next);
|
|
36
|
+
}
|
|
37
|
+
case "check": return current !== void 0 && version === op.guard.v;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* The reference adapter: every read is a consistent snapshot and every write
|
|
42
|
+
* applies to a copy that replaces the state only when all ops succeed.
|
|
43
|
+
*/
|
|
44
|
+
const createMemoryAdapter = (options = {}) => {
|
|
45
|
+
const prefix = options.tablePrefix ?? "";
|
|
46
|
+
let state = /* @__PURE__ */ new Map();
|
|
47
|
+
const rowsOf = (table) => state.get(prefix + table.name) ?? /* @__PURE__ */ new Map();
|
|
48
|
+
return {
|
|
49
|
+
id: "memory",
|
|
50
|
+
fits: () => true,
|
|
51
|
+
async get(table, keys) {
|
|
52
|
+
const rows = rowsOf(table);
|
|
53
|
+
return keys.map((key) => {
|
|
54
|
+
const row = rows.get(keyId(key));
|
|
55
|
+
return row === void 0 ? null : structuredClone(row);
|
|
56
|
+
});
|
|
57
|
+
},
|
|
58
|
+
async query(table, request) {
|
|
59
|
+
const index = findPhysicalIndex(table, request.index);
|
|
60
|
+
const direction = request.order === "asc" ? 1 : -1;
|
|
61
|
+
return [...rowsOf(table).values()].filter((row) => matchesQuery(table, index, request, row)).sort((left, right) => direction * compareTuples(indexOrderTuple(table, index, left), indexOrderTuple(table, index, right))).slice(0, request.limit).map((row) => structuredClone(row));
|
|
62
|
+
},
|
|
63
|
+
async write(ops) {
|
|
64
|
+
const draft = new Map(state);
|
|
65
|
+
const copied = /* @__PURE__ */ new Set();
|
|
66
|
+
for (const [position, op] of ops.entries()) {
|
|
67
|
+
const name = prefix + op.table.name;
|
|
68
|
+
if (!copied.has(name)) {
|
|
69
|
+
draft.set(name, new Map(draft.get(name)));
|
|
70
|
+
copied.add(name);
|
|
71
|
+
}
|
|
72
|
+
if (!applyOp(draft.get(name), op)) return {
|
|
73
|
+
ok: false,
|
|
74
|
+
failedOp: position
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
state = draft;
|
|
78
|
+
return { ok: true };
|
|
79
|
+
},
|
|
80
|
+
async prune(table, before, limit) {
|
|
81
|
+
const column = table.retention?.column ?? "";
|
|
82
|
+
/** Oldest first; the key breaks a tie. */
|
|
83
|
+
const order = (row) => [row[column], ...rowKey(table, row)];
|
|
84
|
+
const doomed = [...rowsOf(table)].filter(([, row]) => {
|
|
85
|
+
const time = row[column];
|
|
86
|
+
return typeof time === "number" && time <= before;
|
|
87
|
+
}).sort(([, left], [, right]) => compareTuples(order(left), order(right))).slice(0, limit);
|
|
88
|
+
const rows = new Map(rowsOf(table));
|
|
89
|
+
for (const [id] of doomed) rows.delete(id);
|
|
90
|
+
state = new Map(state).set(prefix + table.name, rows);
|
|
91
|
+
return doomed.length;
|
|
92
|
+
},
|
|
93
|
+
migrations: { async apply(tables) {
|
|
94
|
+
const next = new Map(state);
|
|
95
|
+
for (const table of tables) {
|
|
96
|
+
const name = prefix + table.name;
|
|
97
|
+
next.set(name, next.get(name) ?? /* @__PURE__ */ new Map());
|
|
98
|
+
}
|
|
99
|
+
state = next;
|
|
100
|
+
} },
|
|
101
|
+
async dispose() {
|
|
102
|
+
state = /* @__PURE__ */ new Map();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
//#endregion
|
|
107
|
+
export { createMemoryAdapter };
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
const require_adapter = require("./adapter.cjs");
|
|
2
|
+
//#region src/database/values.ts
|
|
3
|
+
var DatabaseValueError = class extends Error {
|
|
4
|
+
name = "DatabaseValueError";
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Compares strings in UTF-8 byte order, which is Unicode code point order:
|
|
8
|
+
* the order the engine sorts string keys in. A plugin that merges rows from
|
|
9
|
+
* several reads, as Insights does, keeps that order with it.
|
|
10
|
+
*/
|
|
11
|
+
const compareUtf8 = (left, right) => {
|
|
12
|
+
let leftIndex = 0;
|
|
13
|
+
let rightIndex = 0;
|
|
14
|
+
while (leftIndex < left.length && rightIndex < right.length) {
|
|
15
|
+
const leftPoint = left.codePointAt(leftIndex);
|
|
16
|
+
const rightPoint = right.codePointAt(rightIndex);
|
|
17
|
+
if (leftPoint !== rightPoint) return leftPoint < rightPoint ? -1 : 1;
|
|
18
|
+
leftIndex += leftPoint > 65535 ? 2 : 1;
|
|
19
|
+
rightIndex += rightPoint > 65535 ? 2 : 1;
|
|
20
|
+
}
|
|
21
|
+
const leftDone = leftIndex >= left.length;
|
|
22
|
+
return leftDone === rightIndex >= right.length ? 0 : leftDone ? -1 : 1;
|
|
23
|
+
};
|
|
24
|
+
/** Orders strings by UTF-8 bytes, numbers numerically, and false before true. */
|
|
25
|
+
const compareKeyValues = (left, right) => {
|
|
26
|
+
if (typeof left === "string" && typeof right === "string") return compareUtf8(left, right);
|
|
27
|
+
if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
|
|
28
|
+
if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
|
|
29
|
+
throw new DatabaseValueError(`Cannot compare ${typeof left} with ${typeof right}.`);
|
|
30
|
+
};
|
|
31
|
+
/** Compares tuples element by element; a shorter equal prefix sorts first. */
|
|
32
|
+
const compareTuples = (left, right) => {
|
|
33
|
+
for (let index = 0; index < Math.min(left.length, right.length); index += 1) {
|
|
34
|
+
const result = compareKeyValues(left[index], right[index]);
|
|
35
|
+
if (result !== 0) return result;
|
|
36
|
+
}
|
|
37
|
+
return left.length - right.length;
|
|
38
|
+
};
|
|
39
|
+
/** JSON text with object keys sorted, so a value compares equal after a store reorders map keys. */
|
|
40
|
+
const canonicalJson = (value) => JSON.stringify(value ?? null, (_, inner) => inner !== null && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.entries(inner).sort(([left], [right]) => compareUtf8(left, right))) : inner);
|
|
41
|
+
const isKeyValue = (value) => typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
42
|
+
/** Every `eq` tuple a row is indexed under; none when an index field is null. */
|
|
43
|
+
const indexEntries = (table, index, row) => {
|
|
44
|
+
if (index.sort.some((column) => !isKeyValue(row[column]))) return [];
|
|
45
|
+
let entries = [[]];
|
|
46
|
+
for (const column of index.eq) {
|
|
47
|
+
const value = row[column];
|
|
48
|
+
const values = require_adapter.findPhysicalColumn(table, column).multi ? Array.isArray(value) ? value.filter(isKeyValue) : [] : isKeyValue(value) ? [value] : [];
|
|
49
|
+
if (values.length === 0) return [];
|
|
50
|
+
entries = entries.flatMap((entry) => [...new Set(values)].map((item) => [...entry, item]));
|
|
51
|
+
}
|
|
52
|
+
return entries;
|
|
53
|
+
};
|
|
54
|
+
/** The row's position in an index read, following `indexOrderColumns`. */
|
|
55
|
+
const indexOrderTuple = (table, index, row) => require_adapter.indexOrderColumns(table, index).map((column) => {
|
|
56
|
+
const value = row[column];
|
|
57
|
+
if (!isKeyValue(value)) throw new DatabaseValueError(`${table.name}.${column} is not orderable for index ${index.name}.`);
|
|
58
|
+
return value;
|
|
59
|
+
});
|
|
60
|
+
const satisfiesBound = (tuple, bound, side) => {
|
|
61
|
+
if (bound === void 0) return true;
|
|
62
|
+
const result = compareTuples(tuple.slice(0, bound.values.length), bound.values);
|
|
63
|
+
if (result === 0) return bound.inclusive;
|
|
64
|
+
return side === "lower" ? result > 0 : result < 0;
|
|
65
|
+
};
|
|
66
|
+
/** Whether a stored row belongs to the result range of a query. */
|
|
67
|
+
const matchesQuery = (table, index, request, row) => indexEntries(table, index, row).some((entry) => compareTuples(entry, request.eq) === 0) && satisfiesBound(indexOrderTuple(table, index, row), request.lower, "lower") && satisfiesBound(indexOrderTuple(table, index, row), request.upper, "upper");
|
|
68
|
+
const INTEGER_TEXT = /^-?\d+$/u;
|
|
69
|
+
const NUMBER_TEXT = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/iu;
|
|
70
|
+
const toNumber = (raw, integer) => {
|
|
71
|
+
const text = typeof raw === "bigint" ? raw.toString() : typeof raw === "string" ? raw : typeof raw === "object" && raw !== null && "toString" in raw ? String(raw) : void 0;
|
|
72
|
+
const value = typeof raw === "number" ? raw : text !== void 0 && (integer ? INTEGER_TEXT : NUMBER_TEXT).test(text) ? Number(text) : NaN;
|
|
73
|
+
if (integer ? !Number.isSafeInteger(value) : !Number.isFinite(value)) throw new DatabaseValueError(`Expected a ${integer ? "safe integer" : "finite number"}.`);
|
|
74
|
+
return value;
|
|
75
|
+
};
|
|
76
|
+
const toBoolean = (raw) => {
|
|
77
|
+
if (raw === true || raw === 1 || raw === 1n || raw === "1" || raw === "t") return true;
|
|
78
|
+
if (raw === false || raw === 0 || raw === 0n || raw === "0" || raw === "f") return false;
|
|
79
|
+
if (raw === "true" || raw === "false") return raw === "true";
|
|
80
|
+
throw new DatabaseValueError("Expected a boolean.");
|
|
81
|
+
};
|
|
82
|
+
const toScalar = (column, raw) => {
|
|
83
|
+
switch (column.type) {
|
|
84
|
+
case "string":
|
|
85
|
+
if (typeof raw !== "string") throw new DatabaseValueError(`Expected a string in ${column.name}.`);
|
|
86
|
+
return raw;
|
|
87
|
+
case "integer":
|
|
88
|
+
case "number": return toNumber(raw, column.type === "integer");
|
|
89
|
+
case "boolean": return toBoolean(raw);
|
|
90
|
+
case "json": return raw;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
/** Converts a backend value (int8 text, BigInt, Decimal, 0/1, JSON text) to a stored value. */
|
|
94
|
+
const normalizeStoredValue = (column, raw, options) => {
|
|
95
|
+
if (raw === null || raw === void 0) return null;
|
|
96
|
+
const parsed = options.jsonText && (column.multi || column.type === "json") && typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
97
|
+
if (!column.multi) return toScalar(column, parsed);
|
|
98
|
+
if (!Array.isArray(parsed) || parsed.length > 16) throw new DatabaseValueError(`Expected at most 16 values in ${column.name}.`);
|
|
99
|
+
return parsed.map((item) => toScalar(column, item));
|
|
100
|
+
};
|
|
101
|
+
/** Converts every column of a backend row; unknown backend columns are dropped. */
|
|
102
|
+
const normalizeStoredRow = (table, raw, options) => Object.fromEntries(table.columns.map((column) => [column.name, normalizeStoredValue(column, raw[column.name], options)]));
|
|
103
|
+
//#endregion
|
|
104
|
+
exports.DatabaseValueError = DatabaseValueError;
|
|
105
|
+
exports.canonicalJson = canonicalJson;
|
|
106
|
+
exports.compareKeyValues = compareKeyValues;
|
|
107
|
+
exports.compareTuples = compareTuples;
|
|
108
|
+
exports.compareUtf8 = compareUtf8;
|
|
109
|
+
exports.indexEntries = indexEntries;
|
|
110
|
+
exports.indexOrderTuple = indexOrderTuple;
|
|
111
|
+
exports.isKeyValue = isKeyValue;
|
|
112
|
+
exports.matchesQuery = matchesQuery;
|
|
113
|
+
exports.normalizeStoredRow = normalizeStoredRow;
|
|
114
|
+
exports.normalizeStoredValue = normalizeStoredValue;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { PhysicalTable, StoredRow } from "./adapter.cjs";
|
|
2
|
+
//#region src/database/values.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Compares strings in UTF-8 byte order, which is Unicode code point order:
|
|
5
|
+
* the order the engine sorts string keys in. A plugin that merges rows from
|
|
6
|
+
* several reads, as Insights does, keeps that order with it.
|
|
7
|
+
*/
|
|
8
|
+
declare const compareUtf8: (left: string, right: string) => number;
|
|
9
|
+
/** `normalizeStoredRow`'s options. */
|
|
10
|
+
interface NormalizeOptions {
|
|
11
|
+
/** The backend returns JSON and multi-valued columns as text. */
|
|
12
|
+
readonly jsonText: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** Converts every column of a backend row; unknown backend columns are dropped. */
|
|
15
|
+
declare const normalizeStoredRow: (table: PhysicalTable, raw: Readonly<Record<string, unknown>>, options: NormalizeOptions) => StoredRow;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { NormalizeOptions, compareUtf8, normalizeStoredRow };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { PhysicalTable, StoredRow } from "./adapter.mjs";
|
|
2
|
+
//#region src/database/values.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Compares strings in UTF-8 byte order, which is Unicode code point order:
|
|
5
|
+
* the order the engine sorts string keys in. A plugin that merges rows from
|
|
6
|
+
* several reads, as Insights does, keeps that order with it.
|
|
7
|
+
*/
|
|
8
|
+
declare const compareUtf8: (left: string, right: string) => number;
|
|
9
|
+
/** `normalizeStoredRow`'s options. */
|
|
10
|
+
interface NormalizeOptions {
|
|
11
|
+
/** The backend returns JSON and multi-valued columns as text. */
|
|
12
|
+
readonly jsonText: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** Converts every column of a backend row; unknown backend columns are dropped. */
|
|
15
|
+
declare const normalizeStoredRow: (table: PhysicalTable, raw: Readonly<Record<string, unknown>>, options: NormalizeOptions) => StoredRow;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { NormalizeOptions, compareUtf8, normalizeStoredRow };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { findPhysicalColumn, indexOrderColumns } from "./adapter.mjs";
|
|
2
|
+
//#region src/database/values.ts
|
|
3
|
+
var DatabaseValueError = class extends Error {
|
|
4
|
+
name = "DatabaseValueError";
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Compares strings in UTF-8 byte order, which is Unicode code point order:
|
|
8
|
+
* the order the engine sorts string keys in. A plugin that merges rows from
|
|
9
|
+
* several reads, as Insights does, keeps that order with it.
|
|
10
|
+
*/
|
|
11
|
+
const compareUtf8 = (left, right) => {
|
|
12
|
+
let leftIndex = 0;
|
|
13
|
+
let rightIndex = 0;
|
|
14
|
+
while (leftIndex < left.length && rightIndex < right.length) {
|
|
15
|
+
const leftPoint = left.codePointAt(leftIndex);
|
|
16
|
+
const rightPoint = right.codePointAt(rightIndex);
|
|
17
|
+
if (leftPoint !== rightPoint) return leftPoint < rightPoint ? -1 : 1;
|
|
18
|
+
leftIndex += leftPoint > 65535 ? 2 : 1;
|
|
19
|
+
rightIndex += rightPoint > 65535 ? 2 : 1;
|
|
20
|
+
}
|
|
21
|
+
const leftDone = leftIndex >= left.length;
|
|
22
|
+
return leftDone === rightIndex >= right.length ? 0 : leftDone ? -1 : 1;
|
|
23
|
+
};
|
|
24
|
+
/** Orders strings by UTF-8 bytes, numbers numerically, and false before true. */
|
|
25
|
+
const compareKeyValues = (left, right) => {
|
|
26
|
+
if (typeof left === "string" && typeof right === "string") return compareUtf8(left, right);
|
|
27
|
+
if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
|
|
28
|
+
if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
|
|
29
|
+
throw new DatabaseValueError(`Cannot compare ${typeof left} with ${typeof right}.`);
|
|
30
|
+
};
|
|
31
|
+
/** Compares tuples element by element; a shorter equal prefix sorts first. */
|
|
32
|
+
const compareTuples = (left, right) => {
|
|
33
|
+
for (let index = 0; index < Math.min(left.length, right.length); index += 1) {
|
|
34
|
+
const result = compareKeyValues(left[index], right[index]);
|
|
35
|
+
if (result !== 0) return result;
|
|
36
|
+
}
|
|
37
|
+
return left.length - right.length;
|
|
38
|
+
};
|
|
39
|
+
/** JSON text with object keys sorted, so a value compares equal after a store reorders map keys. */
|
|
40
|
+
const canonicalJson = (value) => JSON.stringify(value ?? null, (_, inner) => inner !== null && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.entries(inner).sort(([left], [right]) => compareUtf8(left, right))) : inner);
|
|
41
|
+
const isKeyValue = (value) => typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
42
|
+
/** Every `eq` tuple a row is indexed under; none when an index field is null. */
|
|
43
|
+
const indexEntries = (table, index, row) => {
|
|
44
|
+
if (index.sort.some((column) => !isKeyValue(row[column]))) return [];
|
|
45
|
+
let entries = [[]];
|
|
46
|
+
for (const column of index.eq) {
|
|
47
|
+
const value = row[column];
|
|
48
|
+
const values = findPhysicalColumn(table, column).multi ? Array.isArray(value) ? value.filter(isKeyValue) : [] : isKeyValue(value) ? [value] : [];
|
|
49
|
+
if (values.length === 0) return [];
|
|
50
|
+
entries = entries.flatMap((entry) => [...new Set(values)].map((item) => [...entry, item]));
|
|
51
|
+
}
|
|
52
|
+
return entries;
|
|
53
|
+
};
|
|
54
|
+
/** The row's position in an index read, following `indexOrderColumns`. */
|
|
55
|
+
const indexOrderTuple = (table, index, row) => indexOrderColumns(table, index).map((column) => {
|
|
56
|
+
const value = row[column];
|
|
57
|
+
if (!isKeyValue(value)) throw new DatabaseValueError(`${table.name}.${column} is not orderable for index ${index.name}.`);
|
|
58
|
+
return value;
|
|
59
|
+
});
|
|
60
|
+
const satisfiesBound = (tuple, bound, side) => {
|
|
61
|
+
if (bound === void 0) return true;
|
|
62
|
+
const result = compareTuples(tuple.slice(0, bound.values.length), bound.values);
|
|
63
|
+
if (result === 0) return bound.inclusive;
|
|
64
|
+
return side === "lower" ? result > 0 : result < 0;
|
|
65
|
+
};
|
|
66
|
+
/** Whether a stored row belongs to the result range of a query. */
|
|
67
|
+
const matchesQuery = (table, index, request, row) => indexEntries(table, index, row).some((entry) => compareTuples(entry, request.eq) === 0) && satisfiesBound(indexOrderTuple(table, index, row), request.lower, "lower") && satisfiesBound(indexOrderTuple(table, index, row), request.upper, "upper");
|
|
68
|
+
const INTEGER_TEXT = /^-?\d+$/u;
|
|
69
|
+
const NUMBER_TEXT = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/iu;
|
|
70
|
+
const toNumber = (raw, integer) => {
|
|
71
|
+
const text = typeof raw === "bigint" ? raw.toString() : typeof raw === "string" ? raw : typeof raw === "object" && raw !== null && "toString" in raw ? String(raw) : void 0;
|
|
72
|
+
const value = typeof raw === "number" ? raw : text !== void 0 && (integer ? INTEGER_TEXT : NUMBER_TEXT).test(text) ? Number(text) : NaN;
|
|
73
|
+
if (integer ? !Number.isSafeInteger(value) : !Number.isFinite(value)) throw new DatabaseValueError(`Expected a ${integer ? "safe integer" : "finite number"}.`);
|
|
74
|
+
return value;
|
|
75
|
+
};
|
|
76
|
+
const toBoolean = (raw) => {
|
|
77
|
+
if (raw === true || raw === 1 || raw === 1n || raw === "1" || raw === "t") return true;
|
|
78
|
+
if (raw === false || raw === 0 || raw === 0n || raw === "0" || raw === "f") return false;
|
|
79
|
+
if (raw === "true" || raw === "false") return raw === "true";
|
|
80
|
+
throw new DatabaseValueError("Expected a boolean.");
|
|
81
|
+
};
|
|
82
|
+
const toScalar = (column, raw) => {
|
|
83
|
+
switch (column.type) {
|
|
84
|
+
case "string":
|
|
85
|
+
if (typeof raw !== "string") throw new DatabaseValueError(`Expected a string in ${column.name}.`);
|
|
86
|
+
return raw;
|
|
87
|
+
case "integer":
|
|
88
|
+
case "number": return toNumber(raw, column.type === "integer");
|
|
89
|
+
case "boolean": return toBoolean(raw);
|
|
90
|
+
case "json": return raw;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
/** Converts a backend value (int8 text, BigInt, Decimal, 0/1, JSON text) to a stored value. */
|
|
94
|
+
const normalizeStoredValue = (column, raw, options) => {
|
|
95
|
+
if (raw === null || raw === void 0) return null;
|
|
96
|
+
const parsed = options.jsonText && (column.multi || column.type === "json") && typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
97
|
+
if (!column.multi) return toScalar(column, parsed);
|
|
98
|
+
if (!Array.isArray(parsed) || parsed.length > 16) throw new DatabaseValueError(`Expected at most 16 values in ${column.name}.`);
|
|
99
|
+
return parsed.map((item) => toScalar(column, item));
|
|
100
|
+
};
|
|
101
|
+
/** Converts every column of a backend row; unknown backend columns are dropped. */
|
|
102
|
+
const normalizeStoredRow = (table, raw, options) => Object.fromEntries(table.columns.map((column) => [column.name, normalizeStoredValue(column, raw[column.name], options)]));
|
|
103
|
+
//#endregion
|
|
104
|
+
export { DatabaseValueError, canonicalJson, compareKeyValues, compareTuples, compareUtf8, indexEntries, indexOrderTuple, isKeyValue, matchesQuery, normalizeStoredRow, normalizeStoredValue };
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
const require_adapter = require("./adapter.cjs");
|
|
2
|
+
const require_values = require("./values.cjs");
|
|
3
|
+
//#region src/database/verifyAdapter.ts
|
|
4
|
+
/** What `verifyAdapter` throws when an adapter call breaks the adapter contract. */
|
|
5
|
+
var DatabaseAdapterContractError = class extends Error {
|
|
6
|
+
name = "DatabaseAdapterContractError";
|
|
7
|
+
};
|
|
8
|
+
const EMPTY = {
|
|
9
|
+
gets: 0,
|
|
10
|
+
keys: 0,
|
|
11
|
+
queries: 0,
|
|
12
|
+
rows: 0
|
|
13
|
+
};
|
|
14
|
+
const createReadMeter = () => {
|
|
15
|
+
const tables = /* @__PURE__ */ new Map();
|
|
16
|
+
const add = (table, count) => {
|
|
17
|
+
const current = tables.get(table) ?? EMPTY;
|
|
18
|
+
tables.set(table, {
|
|
19
|
+
gets: current.gets + (count.gets ?? 0),
|
|
20
|
+
keys: current.keys + (count.keys ?? 0),
|
|
21
|
+
queries: current.queries + (count.queries ?? 0),
|
|
22
|
+
rows: current.rows + (count.rows ?? 0)
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
add,
|
|
27
|
+
meter: {
|
|
28
|
+
total: () => [...tables.values()].reduce((sum, count) => ({
|
|
29
|
+
gets: sum.gets + count.gets,
|
|
30
|
+
keys: sum.keys + count.keys,
|
|
31
|
+
queries: sum.queries + count.queries,
|
|
32
|
+
rows: sum.rows + count.rows
|
|
33
|
+
}), EMPTY),
|
|
34
|
+
byTable: (table) => tables.get(table) ?? EMPTY,
|
|
35
|
+
reset: () => tables.clear()
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const fail = (message) => {
|
|
40
|
+
throw new DatabaseAdapterContractError(message);
|
|
41
|
+
};
|
|
42
|
+
const sameKey = (left, right) => left.length === right.length && require_values.compareTuples(left, right) === 0;
|
|
43
|
+
const verifyRequest = (table, request) => {
|
|
44
|
+
const index = require_adapter.findPhysicalIndex(table, request.index);
|
|
45
|
+
if (!Number.isSafeInteger(request.limit) || request.limit < 1 || request.limit > 500) fail(`query limit must be 1–500.`);
|
|
46
|
+
if (request.eq.length !== index.eq.length || !request.eq.every(require_values.isKeyValue)) fail(`query on ${table.name}.${index.name} must bind every eq column.`);
|
|
47
|
+
return index;
|
|
48
|
+
};
|
|
49
|
+
const verifyRows = (table, request, rows) => {
|
|
50
|
+
const index = require_adapter.findPhysicalIndex(table, request.index);
|
|
51
|
+
if (rows.length > request.limit) fail(`${table.name}.${index.name} returned more than ${request.limit} rows.`);
|
|
52
|
+
let previous;
|
|
53
|
+
for (const row of rows) {
|
|
54
|
+
if (!require_values.matchesQuery(table, index, request, row)) fail(`${table.name}.${index.name} returned a row outside the request.`);
|
|
55
|
+
const tuple = require_values.indexOrderTuple(table, index, row);
|
|
56
|
+
if (previous !== void 0) {
|
|
57
|
+
const order = require_values.compareTuples(previous, tuple);
|
|
58
|
+
if (request.order === "asc" ? order >= 0 : order <= 0) fail(`${table.name}.${index.name} returned rows out of order.`);
|
|
59
|
+
}
|
|
60
|
+
previous = tuple;
|
|
61
|
+
}
|
|
62
|
+
return previous;
|
|
63
|
+
};
|
|
64
|
+
const verifyWrite = (adapter, ops) => {
|
|
65
|
+
if (ops.length === 0) fail("write needs at least one op.");
|
|
66
|
+
const seen = /* @__PURE__ */ new Set();
|
|
67
|
+
for (const op of ops) {
|
|
68
|
+
const key = op.type === "insert" ? require_adapter.rowKey(op.table, op.row) : op.key;
|
|
69
|
+
const id = JSON.stringify([op.table.name, key]);
|
|
70
|
+
if (seen.has(id)) fail(`write touches ${op.table.name} ${id} twice.`);
|
|
71
|
+
seen.add(id);
|
|
72
|
+
if (op.type === "insert" && typeof op.row["_v"] !== "number") fail(`insert into ${op.table.name} must set _v.`);
|
|
73
|
+
if (op.type === "patch" && Object.keys(op.set).some((column) => column === "_v" || op.table.key.includes(column))) fail(`patch of ${op.table.name} may not set key columns or _v.`);
|
|
74
|
+
}
|
|
75
|
+
if (!adapter.fits(ops)) fail("write does not fit in one atomic write.");
|
|
76
|
+
};
|
|
77
|
+
/** Wraps an adapter to check the contract at its boundary and count reads. */
|
|
78
|
+
const verifyAdapter = (adapter, options = {}) => {
|
|
79
|
+
const { add, meter } = createReadMeter();
|
|
80
|
+
return {
|
|
81
|
+
...adapter,
|
|
82
|
+
id: adapter.id,
|
|
83
|
+
reads: meter,
|
|
84
|
+
fits: (ops) => adapter.fits(ops),
|
|
85
|
+
async get(table, keys) {
|
|
86
|
+
const rows = await adapter.get(table, keys);
|
|
87
|
+
add(table.name, {
|
|
88
|
+
gets: 1,
|
|
89
|
+
keys: keys.length
|
|
90
|
+
});
|
|
91
|
+
if (rows.length !== keys.length) fail(`${table.name} get returned ${rows.length} rows for ${keys.length} keys.`);
|
|
92
|
+
rows.forEach((row, position) => {
|
|
93
|
+
if (row !== null && !sameKey(require_adapter.rowKey(table, row), keys[position])) fail(`${table.name} get returned a row for another key.`);
|
|
94
|
+
});
|
|
95
|
+
return rows;
|
|
96
|
+
},
|
|
97
|
+
async query(table, request) {
|
|
98
|
+
const index = verifyRequest(table, request);
|
|
99
|
+
const rows = await adapter.query(table, request);
|
|
100
|
+
add(table.name, {
|
|
101
|
+
queries: 1,
|
|
102
|
+
rows: rows.length
|
|
103
|
+
});
|
|
104
|
+
const last = verifyRows(table, request, rows);
|
|
105
|
+
if (options.probeShortPages && last !== void 0 && rows.length < request.limit) {
|
|
106
|
+
const bound = {
|
|
107
|
+
values: last,
|
|
108
|
+
inclusive: false
|
|
109
|
+
};
|
|
110
|
+
if ((await adapter.query(table, {
|
|
111
|
+
...request,
|
|
112
|
+
limit: 1,
|
|
113
|
+
...request.order === "asc" ? { lower: bound } : { upper: bound }
|
|
114
|
+
})).length > 0) fail(`${table.name}.${index.name} returned a short page before the range ended.`);
|
|
115
|
+
}
|
|
116
|
+
return rows;
|
|
117
|
+
},
|
|
118
|
+
...adapter.prune && { async prune(table, before, limit) {
|
|
119
|
+
if (table.retention === void 0) fail(`${table.name} has no retention to prune by.`);
|
|
120
|
+
if (!Number.isSafeInteger(limit) || limit < 1) fail("prune limit must be a positive integer.");
|
|
121
|
+
const deleted = await adapter.prune(table, before, limit);
|
|
122
|
+
if (!Number.isSafeInteger(deleted) || deleted < 0 || deleted > limit) fail(`${table.name} prune reported ${deleted} rows for ${limit}.`);
|
|
123
|
+
return deleted;
|
|
124
|
+
} },
|
|
125
|
+
async write(ops) {
|
|
126
|
+
verifyWrite(adapter, ops);
|
|
127
|
+
const result = await adapter.write(ops);
|
|
128
|
+
if (!result.ok && "failedOp" in result) {
|
|
129
|
+
if (!Number.isSafeInteger(result.failedOp) || result.failedOp < 0 || result.failedOp >= ops.length) fail(`write reported failedOp ${result.failedOp} for ${ops.length} ops.`);
|
|
130
|
+
}
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
//#endregion
|
|
136
|
+
exports.DatabaseAdapterContractError = DatabaseAdapterContractError;
|
|
137
|
+
exports.verifyAdapter = verifyAdapter;
|