@hot-updater/plugin-core 1.0.0-rc.15 → 1.0.0-rc.17

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.
Files changed (151) hide show
  1. package/dist/coreApi.d.cts +131 -0
  2. package/dist/coreApi.d.mts +131 -0
  3. package/dist/database/adapter.cjs +46 -0
  4. package/dist/database/adapter.d.cts +183 -0
  5. package/dist/database/adapter.d.mts +183 -0
  6. package/dist/database/adapter.mjs +38 -0
  7. package/dist/{insightsDistinctSummary.mjs → database/distinct.cjs} +25 -11
  8. package/dist/database/distinct.d.cts +16 -0
  9. package/dist/database/distinct.d.mts +16 -0
  10. package/dist/{insightsDistinctSummary.cjs → database/distinct.mjs} +21 -15
  11. package/dist/database/memoryAdapter.cjs +115 -0
  12. package/dist/database/memoryAdapter.d.cts +16 -0
  13. package/dist/database/memoryAdapter.d.mts +16 -0
  14. package/dist/database/memoryAdapter.mjs +115 -0
  15. package/dist/database/values.cjs +110 -0
  16. package/dist/database/values.d.cts +30 -0
  17. package/dist/database/values.d.mts +30 -0
  18. package/dist/database/values.mjs +100 -0
  19. package/dist/database/verifyAdapter.cjs +136 -0
  20. package/dist/database/verifyAdapter.d.cts +29 -0
  21. package/dist/database/verifyAdapter.d.mts +29 -0
  22. package/dist/database/verifyAdapter.mjs +135 -0
  23. package/dist/databaseErrors.cjs +30 -0
  24. package/dist/databaseErrors.d.cts +21 -0
  25. package/dist/databaseErrors.d.mts +21 -0
  26. package/dist/databaseErrors.mjs +28 -0
  27. package/dist/databaseJsonValue.cjs +0 -2
  28. package/dist/databaseJsonValue.d.cts +3 -3
  29. package/dist/databaseJsonValue.d.mts +3 -3
  30. package/dist/databaseJsonValue.mjs +1 -2
  31. package/dist/databaseMetadata.cjs +2 -2
  32. package/dist/databaseMetadata.mjs +1 -1
  33. package/dist/index.cjs +9 -39
  34. package/dist/index.d.cts +13 -19
  35. package/dist/index.d.mts +13 -19
  36. package/dist/index.mjs +7 -14
  37. package/dist/internal.cjs +37 -20
  38. package/dist/internal.d.cts +11 -12
  39. package/dist/internal.d.mts +11 -12
  40. package/dist/internal.mjs +8 -6
  41. package/dist/releaseCatalogCompiler.cjs +1 -1
  42. package/dist/releaseCatalogCompiler.mjs +2 -2
  43. package/dist/releaseCatalogMutation.cjs +0 -292
  44. package/dist/releaseCatalogMutation.d.cts +4 -45
  45. package/dist/releaseCatalogMutation.d.mts +4 -45
  46. package/dist/releaseCatalogMutation.mjs +1 -288
  47. package/dist/releaseManagement.cjs +0 -221
  48. package/dist/releaseManagement.d.cts +4 -28
  49. package/dist/releaseManagement.d.mts +4 -28
  50. package/dist/releaseManagement.mjs +1 -216
  51. package/dist/types/databaseConfig.cjs +5 -0
  52. package/dist/types/databaseConfig.d.cts +61 -0
  53. package/dist/types/databaseConfig.d.mts +61 -0
  54. package/dist/types/databaseConfig.mjs +5 -0
  55. package/dist/types/databaseOperations.d.cts +5 -174
  56. package/dist/types/databaseOperations.d.mts +5 -174
  57. package/dist/types/databaseRows.d.cts +1 -53
  58. package/dist/types/databaseRows.d.mts +1 -53
  59. package/dist/types/index.cjs +2 -0
  60. package/dist/types/index.d.cts +8 -74
  61. package/dist/types/index.d.mts +8 -74
  62. package/dist/types/index.mjs +2 -1
  63. package/dist/types/internal.d.cts +4 -8
  64. package/dist/types/internal.d.mts +4 -8
  65. package/dist/types/models.d.cts +14 -0
  66. package/dist/types/models.d.mts +14 -0
  67. package/dist/types/public.d.cts +4 -3
  68. package/dist/types/public.d.mts +4 -3
  69. package/package.json +1 -1
  70. package/dist/calculatePagination.cjs +0 -25
  71. package/dist/calculatePagination.d.cts +0 -12
  72. package/dist/calculatePagination.d.mts +0 -12
  73. package/dist/calculatePagination.mjs +0 -25
  74. package/dist/createDatabasePlugin.cjs +0 -875
  75. package/dist/createDatabasePlugin.d.cts +0 -28
  76. package/dist/createDatabasePlugin.d.mts +0 -28
  77. package/dist/createDatabasePlugin.mjs +0 -871
  78. package/dist/databaseClient.cjs +0 -117
  79. package/dist/databaseClient.d.cts +0 -32
  80. package/dist/databaseClient.d.mts +0 -32
  81. package/dist/databaseClient.mjs +0 -114
  82. package/dist/databaseClientReads.cjs +0 -115
  83. package/dist/databaseClientReads.mjs +0 -113
  84. package/dist/databaseClientUpdates.cjs +0 -37
  85. package/dist/databaseClientUpdates.d.cts +0 -11
  86. package/dist/databaseClientUpdates.d.mts +0 -11
  87. package/dist/databaseClientUpdates.mjs +0 -35
  88. package/dist/databasePluginCrud.cjs +0 -87
  89. package/dist/databasePluginCrud.d.cts +0 -4
  90. package/dist/databasePluginCrud.d.mts +0 -4
  91. package/dist/databasePluginCrud.mjs +0 -86
  92. package/dist/databasePluginCrudValidation.d.cts +0 -6
  93. package/dist/databasePluginCrudValidation.d.mts +0 -6
  94. package/dist/databasePluginCrudValidationErrors.cjs +0 -11
  95. package/dist/databasePluginCrudValidationErrors.d.cts +0 -9
  96. package/dist/databasePluginCrudValidationErrors.d.mts +0 -9
  97. package/dist/databasePluginCrudValidationErrors.mjs +0 -11
  98. package/dist/databasePluginCrudValidationFields.cjs +0 -284
  99. package/dist/databasePluginCrudValidationFields.d.cts +0 -1
  100. package/dist/databasePluginCrudValidationFields.d.mts +0 -1
  101. package/dist/databasePluginCrudValidationFields.mjs +0 -272
  102. package/dist/databasePluginCrudValidationMutations.cjs +0 -88
  103. package/dist/databasePluginCrudValidationMutations.d.cts +0 -1
  104. package/dist/databasePluginCrudValidationMutations.d.mts +0 -1
  105. package/dist/databasePluginCrudValidationMutations.mjs +0 -82
  106. package/dist/databasePluginCrudValidationQueries.cjs +0 -103
  107. package/dist/databasePluginCrudValidationQueries.d.cts +0 -2
  108. package/dist/databasePluginCrudValidationQueries.d.mts +0 -2
  109. package/dist/databasePluginCrudValidationQueries.mjs +0 -97
  110. package/dist/databasePluginCrudValidationRows.cjs +0 -55
  111. package/dist/databasePluginCrudValidationRows.d.cts +0 -1
  112. package/dist/databasePluginCrudValidationRows.d.mts +0 -1
  113. package/dist/databasePluginCrudValidationRows.mjs +0 -53
  114. package/dist/databasePluginTransaction.cjs +0 -7
  115. package/dist/databasePluginTransaction.mjs +0 -7
  116. package/dist/insightsContract.cjs +0 -192
  117. package/dist/insightsContract.d.cts +0 -9
  118. package/dist/insightsContract.d.mts +0 -9
  119. package/dist/insightsContract.mjs +0 -189
  120. package/dist/insightsDistinctSummary.d.cts +0 -12
  121. package/dist/insightsDistinctSummary.d.mts +0 -12
  122. package/dist/insightsLatestQueries.cjs +0 -53
  123. package/dist/insightsLatestQueries.d.cts +0 -13
  124. package/dist/insightsLatestQueries.d.mts +0 -13
  125. package/dist/insightsLatestQueries.mjs +0 -52
  126. package/dist/insightsOverview.cjs +0 -139
  127. package/dist/insightsOverview.d.cts +0 -40
  128. package/dist/insightsOverview.d.mts +0 -40
  129. package/dist/insightsOverview.mjs +0 -135
  130. package/dist/paginateBundles.cjs +0 -53
  131. package/dist/paginateBundles.d.cts +0 -13
  132. package/dist/paginateBundles.d.mts +0 -13
  133. package/dist/paginateBundles.mjs +0 -53
  134. package/dist/queryBundles.cjs +0 -34
  135. package/dist/queryBundles.d.cts +0 -9
  136. package/dist/queryBundles.d.mts +0 -9
  137. package/dist/queryBundles.mjs +0 -32
  138. package/dist/requestBundleCache.cjs +0 -22
  139. package/dist/requestBundleCache.d.cts +0 -8
  140. package/dist/requestBundleCache.d.mts +0 -8
  141. package/dist/requestBundleCache.mjs +0 -22
  142. package/dist/types/database.d.cts +0 -5
  143. package/dist/types/database.d.mts +0 -5
  144. package/dist/types/databaseFields.cjs +0 -85
  145. package/dist/types/databaseFields.d.cts +0 -12
  146. package/dist/types/databaseFields.d.mts +0 -12
  147. package/dist/types/databaseFields.mjs +0 -85
  148. package/dist/types/databasePlugin.d.cts +0 -388
  149. package/dist/types/databasePlugin.d.mts +0 -388
  150. package/dist/types/databaseQuery.d.cts +0 -46
  151. package/dist/types/databaseQuery.d.mts +0 -46
@@ -0,0 +1,30 @@
1
+ import { DatabaseKey, DatabaseKeyValue, DatabaseValue, PhysicalColumn, PhysicalIndex, PhysicalTable, QueryRequest, StoredRow } from "./adapter.mjs";
2
+ //#region src/database/values.d.ts
3
+ declare class DatabaseValueError extends Error {
4
+ readonly name = "DatabaseValueError";
5
+ }
6
+ /** Compares strings in UTF-8 byte order, which is Unicode code point order. */
7
+ declare const compareUtf8: (left: string, right: string) => number;
8
+ /** Orders strings by UTF-8 bytes, numbers numerically, and false before true. */
9
+ declare const compareKeyValues: (left: DatabaseKeyValue, right: DatabaseKeyValue) => number;
10
+ /** Compares tuples element by element; a shorter equal prefix sorts first. */
11
+ declare const compareTuples: (left: readonly DatabaseKeyValue[], right: readonly DatabaseKeyValue[]) => number;
12
+ /** JSON text with object keys sorted, so a value compares equal after a store reorders map keys. */
13
+ declare const canonicalJson: (value: DatabaseValue | undefined) => string;
14
+ declare const isKeyValue: (value: unknown) => value is DatabaseKeyValue;
15
+ /** Every `eq` tuple a row is indexed under; none when an index field is null. */
16
+ declare const indexEntries: (table: PhysicalTable, index: PhysicalIndex, row: StoredRow) => readonly DatabaseKey[];
17
+ /** The row's position in an index read, following `indexOrderColumns`. */
18
+ declare const indexOrderTuple: (table: PhysicalTable, index: PhysicalIndex, row: StoredRow) => DatabaseKey;
19
+ /** Whether a stored row belongs to the result range of a query. */
20
+ declare const matchesQuery: (table: PhysicalTable, index: PhysicalIndex, request: QueryRequest, row: StoredRow) => boolean;
21
+ interface NormalizeOptions {
22
+ /** The backend returns JSON and multi-valued columns as text. */
23
+ readonly jsonText: boolean;
24
+ }
25
+ /** Converts a backend value (int8 text, BigInt, Decimal, 0/1, JSON text) to a stored value. */
26
+ declare const normalizeStoredValue: (column: PhysicalColumn, raw: unknown, options: NormalizeOptions) => DatabaseValue;
27
+ /** Converts every column of a backend row; unknown backend columns are dropped. */
28
+ declare const normalizeStoredRow: (table: PhysicalTable, raw: Readonly<Record<string, unknown>>, options: NormalizeOptions) => StoredRow;
29
+ //#endregion
30
+ export { DatabaseValueError, NormalizeOptions, canonicalJson, compareKeyValues, compareTuples, compareUtf8, indexEntries, indexOrderTuple, isKeyValue, matchesQuery, normalizeStoredRow, normalizeStoredValue };
@@ -0,0 +1,100 @@
1
+ import { findPhysicalColumn, indexOrderColumns } from "./adapter.mjs";
2
+ //#region src/database/values.ts
3
+ var DatabaseValueError = class extends Error {
4
+ name = "DatabaseValueError";
5
+ };
6
+ /** Compares strings in UTF-8 byte order, which is Unicode code point order. */
7
+ const compareUtf8 = (left, right) => {
8
+ let leftIndex = 0;
9
+ let rightIndex = 0;
10
+ while (leftIndex < left.length && rightIndex < right.length) {
11
+ const leftPoint = left.codePointAt(leftIndex);
12
+ const rightPoint = right.codePointAt(rightIndex);
13
+ if (leftPoint !== rightPoint) return leftPoint < rightPoint ? -1 : 1;
14
+ leftIndex += leftPoint > 65535 ? 2 : 1;
15
+ rightIndex += rightPoint > 65535 ? 2 : 1;
16
+ }
17
+ const leftDone = leftIndex >= left.length;
18
+ return leftDone === rightIndex >= right.length ? 0 : leftDone ? -1 : 1;
19
+ };
20
+ /** Orders strings by UTF-8 bytes, numbers numerically, and false before true. */
21
+ const compareKeyValues = (left, right) => {
22
+ if (typeof left === "string" && typeof right === "string") return compareUtf8(left, right);
23
+ if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
24
+ if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
25
+ throw new DatabaseValueError(`Cannot compare ${typeof left} with ${typeof right}.`);
26
+ };
27
+ /** Compares tuples element by element; a shorter equal prefix sorts first. */
28
+ const compareTuples = (left, right) => {
29
+ for (let index = 0; index < Math.min(left.length, right.length); index += 1) {
30
+ const result = compareKeyValues(left[index], right[index]);
31
+ if (result !== 0) return result;
32
+ }
33
+ return left.length - right.length;
34
+ };
35
+ /** JSON text with object keys sorted, so a value compares equal after a store reorders map keys. */
36
+ 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);
37
+ const isKeyValue = (value) => typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
38
+ /** Every `eq` tuple a row is indexed under; none when an index field is null. */
39
+ const indexEntries = (table, index, row) => {
40
+ if (index.sort.some((column) => !isKeyValue(row[column]))) return [];
41
+ let entries = [[]];
42
+ for (const column of index.eq) {
43
+ const value = row[column];
44
+ const values = findPhysicalColumn(table, column).multi ? Array.isArray(value) ? value.filter(isKeyValue) : [] : isKeyValue(value) ? [value] : [];
45
+ if (values.length === 0) return [];
46
+ entries = entries.flatMap((entry) => [...new Set(values)].map((item) => [...entry, item]));
47
+ }
48
+ return entries;
49
+ };
50
+ /** The row's position in an index read, following `indexOrderColumns`. */
51
+ const indexOrderTuple = (table, index, row) => indexOrderColumns(table, index).map((column) => {
52
+ const value = row[column];
53
+ if (!isKeyValue(value)) throw new DatabaseValueError(`${table.name}.${column} is not orderable for index ${index.name}.`);
54
+ return value;
55
+ });
56
+ const satisfiesBound = (tuple, bound, side) => {
57
+ if (bound === void 0) return true;
58
+ const result = compareTuples(tuple.slice(0, bound.values.length), bound.values);
59
+ if (result === 0) return bound.inclusive;
60
+ return side === "lower" ? result > 0 : result < 0;
61
+ };
62
+ /** Whether a stored row belongs to the result range of a query. */
63
+ 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");
64
+ const INTEGER_TEXT = /^-?\d+$/u;
65
+ const NUMBER_TEXT = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/iu;
66
+ const toNumber = (raw, integer) => {
67
+ const text = typeof raw === "bigint" ? raw.toString() : typeof raw === "string" ? raw : typeof raw === "object" && raw !== null && "toString" in raw ? String(raw) : void 0;
68
+ const value = typeof raw === "number" ? raw : text !== void 0 && (integer ? INTEGER_TEXT : NUMBER_TEXT).test(text) ? Number(text) : NaN;
69
+ if (integer ? !Number.isSafeInteger(value) : !Number.isFinite(value)) throw new DatabaseValueError(`Expected a ${integer ? "safe integer" : "finite number"}.`);
70
+ return value;
71
+ };
72
+ const toBoolean = (raw) => {
73
+ if (raw === true || raw === 1 || raw === 1n || raw === "1" || raw === "t") return true;
74
+ if (raw === false || raw === 0 || raw === 0n || raw === "0" || raw === "f") return false;
75
+ if (raw === "true" || raw === "false") return raw === "true";
76
+ throw new DatabaseValueError("Expected a boolean.");
77
+ };
78
+ const toScalar = (column, raw) => {
79
+ switch (column.type) {
80
+ case "string":
81
+ if (typeof raw !== "string") throw new DatabaseValueError(`Expected a string in ${column.name}.`);
82
+ return raw;
83
+ case "integer":
84
+ case "number": return toNumber(raw, column.type === "integer");
85
+ case "boolean": return toBoolean(raw);
86
+ case "json": return raw;
87
+ }
88
+ };
89
+ /** Converts a backend value (int8 text, BigInt, Decimal, 0/1, JSON text) to a stored value. */
90
+ const normalizeStoredValue = (column, raw, options) => {
91
+ if (raw === null || raw === void 0) return null;
92
+ const parsed = options.jsonText && (column.multi || column.type === "json") && typeof raw === "string" ? JSON.parse(raw) : raw;
93
+ if (!column.multi) return toScalar(column, parsed);
94
+ if (!Array.isArray(parsed) || parsed.length > 16) throw new DatabaseValueError(`Expected at most 16 values in ${column.name}.`);
95
+ return parsed.map((item) => toScalar(column, item));
96
+ };
97
+ /** Converts every column of a backend row; unknown backend columns are dropped. */
98
+ const normalizeStoredRow = (table, raw, options) => Object.fromEntries(table.columns.map((column) => [column.name, normalizeStoredValue(column, raw[column.name], options)]));
99
+ //#endregion
100
+ export { DatabaseValueError, canonicalJson, compareKeyValues, compareTuples, compareUtf8, indexEntries, indexOrderTuple, isKeyValue, matchesQuery, normalizeStoredRow, normalizeStoredValue };
@@ -0,0 +1,136 @@
1
+ const require_adapter = require("./adapter.cjs");
2
+ const require_values = require("./values.cjs");
3
+ //#region src/database/verifyAdapter.ts
4
+ var DatabaseAdapterContractError = class extends Error {
5
+ name = "DatabaseAdapterContractError";
6
+ };
7
+ const EMPTY = {
8
+ gets: 0,
9
+ keys: 0,
10
+ queries: 0,
11
+ rows: 0
12
+ };
13
+ const createReadMeter = () => {
14
+ const tables = /* @__PURE__ */ new Map();
15
+ const add = (table, count) => {
16
+ const current = tables.get(table) ?? EMPTY;
17
+ tables.set(table, {
18
+ gets: current.gets + (count.gets ?? 0),
19
+ keys: current.keys + (count.keys ?? 0),
20
+ queries: current.queries + (count.queries ?? 0),
21
+ rows: current.rows + (count.rows ?? 0)
22
+ });
23
+ };
24
+ return {
25
+ add,
26
+ meter: {
27
+ total: () => [...tables.values()].reduce((sum, count) => ({
28
+ gets: sum.gets + count.gets,
29
+ keys: sum.keys + count.keys,
30
+ queries: sum.queries + count.queries,
31
+ rows: sum.rows + count.rows
32
+ }), EMPTY),
33
+ byTable: (table) => tables.get(table) ?? EMPTY,
34
+ reset: () => tables.clear()
35
+ }
36
+ };
37
+ };
38
+ const fail = (message) => {
39
+ throw new DatabaseAdapterContractError(message);
40
+ };
41
+ const sameKey = (left, right) => left.length === right.length && require_values.compareTuples(left, right) === 0;
42
+ const verifyRequest = (table, request) => {
43
+ const index = require_adapter.findPhysicalIndex(table, request.index);
44
+ if (!Number.isSafeInteger(request.limit) || request.limit < 1 || request.limit > 500) fail(`query limit must be 1–500.`);
45
+ 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.`);
46
+ return index;
47
+ };
48
+ const verifyRows = (table, request, rows) => {
49
+ const index = require_adapter.findPhysicalIndex(table, request.index);
50
+ if (rows.length > request.limit) fail(`${table.name}.${index.name} returned more than ${request.limit} rows.`);
51
+ let previous;
52
+ for (const row of rows) {
53
+ if (!require_values.matchesQuery(table, index, request, row)) fail(`${table.name}.${index.name} returned a row outside the request.`);
54
+ const tuple = require_values.indexOrderTuple(table, index, row);
55
+ if (previous !== void 0) {
56
+ const order = require_values.compareTuples(previous, tuple);
57
+ if (request.order === "asc" ? order >= 0 : order <= 0) fail(`${table.name}.${index.name} returned rows out of order.`);
58
+ }
59
+ previous = tuple;
60
+ }
61
+ return previous;
62
+ };
63
+ const verifyWrite = (adapter, ops) => {
64
+ if (ops.length === 0) fail("write needs at least one op.");
65
+ const seen = /* @__PURE__ */ new Set();
66
+ for (const op of ops) {
67
+ const key = op.type === "insert" ? require_adapter.rowKey(op.table, op.row) : op.key;
68
+ const id = JSON.stringify([op.table.name, key]);
69
+ if (seen.has(id)) fail(`write touches ${op.table.name} ${id} twice.`);
70
+ seen.add(id);
71
+ if (op.type === "insert" && typeof op.row["_v"] !== "number") fail(`insert into ${op.table.name} must set _v.`);
72
+ 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.`);
73
+ }
74
+ if (!adapter.fits(ops)) fail("write does not fit in one atomic write.");
75
+ };
76
+ /** Wraps an adapter to check the contract at its boundary and count reads. */
77
+ const verifyAdapter = (adapter, options = {}) => {
78
+ const { add, meter } = createReadMeter();
79
+ return {
80
+ ...adapter,
81
+ id: adapter.id,
82
+ reads: meter,
83
+ fits: (ops) => adapter.fits(ops),
84
+ async get(table, keys) {
85
+ const rows = await adapter.get(table, keys);
86
+ add(table.name, {
87
+ gets: 1,
88
+ keys: keys.length
89
+ });
90
+ if (rows.length !== keys.length) fail(`${table.name} get returned ${rows.length} rows for ${keys.length} keys.`);
91
+ rows.forEach((row, position) => {
92
+ if (row !== null && !sameKey(require_adapter.rowKey(table, row), keys[position])) fail(`${table.name} get returned a row for another key.`);
93
+ });
94
+ return rows;
95
+ },
96
+ async query(table, request) {
97
+ const index = verifyRequest(table, request);
98
+ const rows = await adapter.query(table, request);
99
+ add(table.name, {
100
+ queries: 1,
101
+ rows: rows.length
102
+ });
103
+ const last = verifyRows(table, request, rows);
104
+ if (options.probeShortPages && last !== void 0 && rows.length < request.limit) {
105
+ const bound = {
106
+ values: last,
107
+ inclusive: false
108
+ };
109
+ if ((await adapter.query(table, {
110
+ ...request,
111
+ limit: 1,
112
+ ...request.order === "asc" ? { lower: bound } : { upper: bound }
113
+ })).length > 0) fail(`${table.name}.${index.name} returned a short page before the range ended.`);
114
+ }
115
+ return rows;
116
+ },
117
+ ...adapter.prune && { async prune(table, before, limit) {
118
+ if (table.retention === void 0) fail(`${table.name} has no retention to prune by.`);
119
+ if (!Number.isSafeInteger(limit) || limit < 1) fail("prune limit must be a positive integer.");
120
+ const deleted = await adapter.prune(table, before, limit);
121
+ if (!Number.isSafeInteger(deleted) || deleted < 0 || deleted > limit) fail(`${table.name} prune reported ${deleted} rows for ${limit}.`);
122
+ return deleted;
123
+ } },
124
+ async write(ops) {
125
+ verifyWrite(adapter, ops);
126
+ const result = await adapter.write(ops);
127
+ if (!result.ok && "failedOp" in result) {
128
+ if (!Number.isSafeInteger(result.failedOp) || result.failedOp < 0 || result.failedOp >= ops.length) fail(`write reported failedOp ${result.failedOp} for ${ops.length} ops.`);
129
+ }
130
+ return result;
131
+ }
132
+ };
133
+ };
134
+ //#endregion
135
+ exports.DatabaseAdapterContractError = DatabaseAdapterContractError;
136
+ exports.verifyAdapter = verifyAdapter;
@@ -0,0 +1,29 @@
1
+ import { DatabaseAdapter } from "./adapter.cjs";
2
+ //#region src/database/verifyAdapter.d.ts
3
+ declare class DatabaseAdapterContractError extends Error {
4
+ readonly name = "DatabaseAdapterContractError";
5
+ }
6
+ interface DatabaseReadCount {
7
+ /** `get` calls and the keys they asked for, found or not. */
8
+ readonly gets: number;
9
+ readonly keys: number;
10
+ /** `query` calls, zero-row calls included, and the rows they returned. */
11
+ readonly queries: number;
12
+ readonly rows: number;
13
+ }
14
+ interface DatabaseReadMeter {
15
+ total(): DatabaseReadCount;
16
+ byTable(table: string): DatabaseReadCount;
17
+ reset(): void;
18
+ }
19
+ interface VerifiedDatabaseAdapter extends DatabaseAdapter {
20
+ readonly reads: DatabaseReadMeter;
21
+ }
22
+ interface VerifyAdapterOptions {
23
+ /** After a short page, probe once past its last row to prove the range ended. */
24
+ readonly probeShortPages?: boolean;
25
+ }
26
+ /** Wraps an adapter to check the contract at its boundary and count reads. */
27
+ declare const verifyAdapter: (adapter: DatabaseAdapter, options?: VerifyAdapterOptions) => VerifiedDatabaseAdapter;
28
+ //#endregion
29
+ export { DatabaseAdapterContractError, DatabaseReadCount, DatabaseReadMeter, VerifiedDatabaseAdapter, VerifyAdapterOptions, verifyAdapter };
@@ -0,0 +1,29 @@
1
+ import { DatabaseAdapter } from "./adapter.mjs";
2
+ //#region src/database/verifyAdapter.d.ts
3
+ declare class DatabaseAdapterContractError extends Error {
4
+ readonly name = "DatabaseAdapterContractError";
5
+ }
6
+ interface DatabaseReadCount {
7
+ /** `get` calls and the keys they asked for, found or not. */
8
+ readonly gets: number;
9
+ readonly keys: number;
10
+ /** `query` calls, zero-row calls included, and the rows they returned. */
11
+ readonly queries: number;
12
+ readonly rows: number;
13
+ }
14
+ interface DatabaseReadMeter {
15
+ total(): DatabaseReadCount;
16
+ byTable(table: string): DatabaseReadCount;
17
+ reset(): void;
18
+ }
19
+ interface VerifiedDatabaseAdapter extends DatabaseAdapter {
20
+ readonly reads: DatabaseReadMeter;
21
+ }
22
+ interface VerifyAdapterOptions {
23
+ /** After a short page, probe once past its last row to prove the range ended. */
24
+ readonly probeShortPages?: boolean;
25
+ }
26
+ /** Wraps an adapter to check the contract at its boundary and count reads. */
27
+ declare const verifyAdapter: (adapter: DatabaseAdapter, options?: VerifyAdapterOptions) => VerifiedDatabaseAdapter;
28
+ //#endregion
29
+ export { DatabaseAdapterContractError, DatabaseReadCount, DatabaseReadMeter, VerifiedDatabaseAdapter, VerifyAdapterOptions, verifyAdapter };
@@ -0,0 +1,135 @@
1
+ import { findPhysicalIndex, rowKey } from "./adapter.mjs";
2
+ import { compareTuples, indexOrderTuple, isKeyValue, matchesQuery } from "./values.mjs";
3
+ //#region src/database/verifyAdapter.ts
4
+ var DatabaseAdapterContractError = class extends Error {
5
+ name = "DatabaseAdapterContractError";
6
+ };
7
+ const EMPTY = {
8
+ gets: 0,
9
+ keys: 0,
10
+ queries: 0,
11
+ rows: 0
12
+ };
13
+ const createReadMeter = () => {
14
+ const tables = /* @__PURE__ */ new Map();
15
+ const add = (table, count) => {
16
+ const current = tables.get(table) ?? EMPTY;
17
+ tables.set(table, {
18
+ gets: current.gets + (count.gets ?? 0),
19
+ keys: current.keys + (count.keys ?? 0),
20
+ queries: current.queries + (count.queries ?? 0),
21
+ rows: current.rows + (count.rows ?? 0)
22
+ });
23
+ };
24
+ return {
25
+ add,
26
+ meter: {
27
+ total: () => [...tables.values()].reduce((sum, count) => ({
28
+ gets: sum.gets + count.gets,
29
+ keys: sum.keys + count.keys,
30
+ queries: sum.queries + count.queries,
31
+ rows: sum.rows + count.rows
32
+ }), EMPTY),
33
+ byTable: (table) => tables.get(table) ?? EMPTY,
34
+ reset: () => tables.clear()
35
+ }
36
+ };
37
+ };
38
+ const fail = (message) => {
39
+ throw new DatabaseAdapterContractError(message);
40
+ };
41
+ const sameKey = (left, right) => left.length === right.length && compareTuples(left, right) === 0;
42
+ const verifyRequest = (table, request) => {
43
+ const index = findPhysicalIndex(table, request.index);
44
+ if (!Number.isSafeInteger(request.limit) || request.limit < 1 || request.limit > 500) fail(`query limit must be 1–500.`);
45
+ if (request.eq.length !== index.eq.length || !request.eq.every(isKeyValue)) fail(`query on ${table.name}.${index.name} must bind every eq column.`);
46
+ return index;
47
+ };
48
+ const verifyRows = (table, request, rows) => {
49
+ const index = findPhysicalIndex(table, request.index);
50
+ if (rows.length > request.limit) fail(`${table.name}.${index.name} returned more than ${request.limit} rows.`);
51
+ let previous;
52
+ for (const row of rows) {
53
+ if (!matchesQuery(table, index, request, row)) fail(`${table.name}.${index.name} returned a row outside the request.`);
54
+ const tuple = indexOrderTuple(table, index, row);
55
+ if (previous !== void 0) {
56
+ const order = compareTuples(previous, tuple);
57
+ if (request.order === "asc" ? order >= 0 : order <= 0) fail(`${table.name}.${index.name} returned rows out of order.`);
58
+ }
59
+ previous = tuple;
60
+ }
61
+ return previous;
62
+ };
63
+ const verifyWrite = (adapter, ops) => {
64
+ if (ops.length === 0) fail("write needs at least one op.");
65
+ const seen = /* @__PURE__ */ new Set();
66
+ for (const op of ops) {
67
+ const key = op.type === "insert" ? rowKey(op.table, op.row) : op.key;
68
+ const id = JSON.stringify([op.table.name, key]);
69
+ if (seen.has(id)) fail(`write touches ${op.table.name} ${id} twice.`);
70
+ seen.add(id);
71
+ if (op.type === "insert" && typeof op.row["_v"] !== "number") fail(`insert into ${op.table.name} must set _v.`);
72
+ 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.`);
73
+ }
74
+ if (!adapter.fits(ops)) fail("write does not fit in one atomic write.");
75
+ };
76
+ /** Wraps an adapter to check the contract at its boundary and count reads. */
77
+ const verifyAdapter = (adapter, options = {}) => {
78
+ const { add, meter } = createReadMeter();
79
+ return {
80
+ ...adapter,
81
+ id: adapter.id,
82
+ reads: meter,
83
+ fits: (ops) => adapter.fits(ops),
84
+ async get(table, keys) {
85
+ const rows = await adapter.get(table, keys);
86
+ add(table.name, {
87
+ gets: 1,
88
+ keys: keys.length
89
+ });
90
+ if (rows.length !== keys.length) fail(`${table.name} get returned ${rows.length} rows for ${keys.length} keys.`);
91
+ rows.forEach((row, position) => {
92
+ if (row !== null && !sameKey(rowKey(table, row), keys[position])) fail(`${table.name} get returned a row for another key.`);
93
+ });
94
+ return rows;
95
+ },
96
+ async query(table, request) {
97
+ const index = verifyRequest(table, request);
98
+ const rows = await adapter.query(table, request);
99
+ add(table.name, {
100
+ queries: 1,
101
+ rows: rows.length
102
+ });
103
+ const last = verifyRows(table, request, rows);
104
+ if (options.probeShortPages && last !== void 0 && rows.length < request.limit) {
105
+ const bound = {
106
+ values: last,
107
+ inclusive: false
108
+ };
109
+ if ((await adapter.query(table, {
110
+ ...request,
111
+ limit: 1,
112
+ ...request.order === "asc" ? { lower: bound } : { upper: bound }
113
+ })).length > 0) fail(`${table.name}.${index.name} returned a short page before the range ended.`);
114
+ }
115
+ return rows;
116
+ },
117
+ ...adapter.prune && { async prune(table, before, limit) {
118
+ if (table.retention === void 0) fail(`${table.name} has no retention to prune by.`);
119
+ if (!Number.isSafeInteger(limit) || limit < 1) fail("prune limit must be a positive integer.");
120
+ const deleted = await adapter.prune(table, before, limit);
121
+ if (!Number.isSafeInteger(deleted) || deleted < 0 || deleted > limit) fail(`${table.name} prune reported ${deleted} rows for ${limit}.`);
122
+ return deleted;
123
+ } },
124
+ async write(ops) {
125
+ verifyWrite(adapter, ops);
126
+ const result = await adapter.write(ops);
127
+ if (!result.ok && "failedOp" in result) {
128
+ if (!Number.isSafeInteger(result.failedOp) || result.failedOp < 0 || result.failedOp >= ops.length) fail(`write reported failedOp ${result.failedOp} for ${ops.length} ops.`);
129
+ }
130
+ return result;
131
+ }
132
+ };
133
+ };
134
+ //#endregion
135
+ export { DatabaseAdapterContractError, verifyAdapter };
@@ -0,0 +1,30 @@
1
+ //#region src/databaseErrors.ts
2
+ /** A bundle an operation names is not stored. */
3
+ var DatabaseBundleNotFoundError = class extends Error {
4
+ bundleId;
5
+ name = "DatabaseBundleNotFoundError";
6
+ constructor(bundleId) {
7
+ super(`Bundle "${bundleId}" was not found.`);
8
+ this.bundleId = bundleId;
9
+ }
10
+ };
11
+ /** A row a delete names is still referenced, such as a bundle a release uses. */
12
+ var DatabaseRowReferencedError = class extends Error {
13
+ name = "DatabaseRowReferencedError";
14
+ constructor() {
15
+ super("The database row is still referenced.");
16
+ }
17
+ };
18
+ /** Input a database operation refuses before touching storage. */
19
+ var DatabasePluginInputError = class extends Error {
20
+ code;
21
+ name = "DatabasePluginInputError";
22
+ constructor(code) {
23
+ super(`Invalid database plugin input: ${code}`);
24
+ this.code = code;
25
+ }
26
+ };
27
+ //#endregion
28
+ exports.DatabaseBundleNotFoundError = DatabaseBundleNotFoundError;
29
+ exports.DatabasePluginInputError = DatabasePluginInputError;
30
+ exports.DatabaseRowReferencedError = DatabaseRowReferencedError;
@@ -0,0 +1,21 @@
1
+ //#region src/databaseErrors.d.ts
2
+ /** A bundle an operation names is not stored. */
3
+ declare class DatabaseBundleNotFoundError extends Error {
4
+ readonly bundleId: string;
5
+ readonly name = "DatabaseBundleNotFoundError";
6
+ constructor(bundleId: string);
7
+ }
8
+ /** A row a delete names is still referenced, such as a bundle a release uses. */
9
+ declare class DatabaseRowReferencedError extends Error {
10
+ readonly name = "DatabaseRowReferencedError";
11
+ constructor();
12
+ }
13
+ type DatabasePluginInputErrorCode = "invalid-data" | "invalid-field" | "invalid-pagination" | "invalid-query" | "invalid-result";
14
+ /** Input a database operation refuses before touching storage. */
15
+ declare class DatabasePluginInputError extends Error {
16
+ readonly code: DatabasePluginInputErrorCode;
17
+ readonly name = "DatabasePluginInputError";
18
+ constructor(code: DatabasePluginInputErrorCode);
19
+ }
20
+ //#endregion
21
+ export { DatabaseBundleNotFoundError, DatabasePluginInputError, DatabasePluginInputErrorCode, DatabaseRowReferencedError };
@@ -0,0 +1,21 @@
1
+ //#region src/databaseErrors.d.ts
2
+ /** A bundle an operation names is not stored. */
3
+ declare class DatabaseBundleNotFoundError extends Error {
4
+ readonly bundleId: string;
5
+ readonly name = "DatabaseBundleNotFoundError";
6
+ constructor(bundleId: string);
7
+ }
8
+ /** A row a delete names is still referenced, such as a bundle a release uses. */
9
+ declare class DatabaseRowReferencedError extends Error {
10
+ readonly name = "DatabaseRowReferencedError";
11
+ constructor();
12
+ }
13
+ type DatabasePluginInputErrorCode = "invalid-data" | "invalid-field" | "invalid-pagination" | "invalid-query" | "invalid-result";
14
+ /** Input a database operation refuses before touching storage. */
15
+ declare class DatabasePluginInputError extends Error {
16
+ readonly code: DatabasePluginInputErrorCode;
17
+ readonly name = "DatabasePluginInputError";
18
+ constructor(code: DatabasePluginInputErrorCode);
19
+ }
20
+ //#endregion
21
+ export { DatabaseBundleNotFoundError, DatabasePluginInputError, DatabasePluginInputErrorCode, DatabaseRowReferencedError };
@@ -0,0 +1,28 @@
1
+ //#region src/databaseErrors.ts
2
+ /** A bundle an operation names is not stored. */
3
+ var DatabaseBundleNotFoundError = class extends Error {
4
+ bundleId;
5
+ name = "DatabaseBundleNotFoundError";
6
+ constructor(bundleId) {
7
+ super(`Bundle "${bundleId}" was not found.`);
8
+ this.bundleId = bundleId;
9
+ }
10
+ };
11
+ /** A row a delete names is still referenced, such as a bundle a release uses. */
12
+ var DatabaseRowReferencedError = class extends Error {
13
+ name = "DatabaseRowReferencedError";
14
+ constructor() {
15
+ super("The database row is still referenced.");
16
+ }
17
+ };
18
+ /** Input a database operation refuses before touching storage. */
19
+ var DatabasePluginInputError = class extends Error {
20
+ code;
21
+ name = "DatabasePluginInputError";
22
+ constructor(code) {
23
+ super(`Invalid database plugin input: ${code}`);
24
+ this.code = code;
25
+ }
26
+ };
27
+ //#endregion
28
+ export { DatabaseBundleNotFoundError, DatabasePluginInputError, DatabaseRowReferencedError };
@@ -33,9 +33,7 @@ const isDatabaseJsonValue = (value) => {
33
33
  };
34
34
  const isDatabaseJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && isDatabaseJsonValue(value);
35
35
  const isDatabaseMetadataObject = (value) => isDatabaseJsonObject(value) && (!Object.hasOwn(value, "app_version") || typeof value["app_version"] === "string");
36
- const isDatabaseBundleEventMetadata = (value) => isDatabaseJsonObject(value) && (value.username === null || typeof value.username === "string") && typeof value.cohort === "string" && (value.update_strategy === null || value.update_strategy === "fingerprint" || value.update_strategy === "appVersion") && (value.fingerprint_hash === null || typeof value.fingerprint_hash === "string") && (value.sdk_version === null || typeof value.sdk_version === "string");
37
36
  //#endregion
38
- exports.isDatabaseBundleEventMetadata = isDatabaseBundleEventMetadata;
39
37
  exports.isDatabaseJsonObject = isDatabaseJsonObject;
40
38
  exports.isDatabaseJsonValue = isDatabaseJsonValue;
41
39
  exports.isDatabaseMetadataObject = isDatabaseMetadataObject;
@@ -1,7 +1,7 @@
1
- import { DatabaseBundleEventMetadata, DatabaseBundleMetadata } from "./types/databaseRows.cjs";
1
+ import { DatabaseBundleMetadata, DatabaseJsonObject } from "./types/databaseRows.cjs";
2
2
  import "./types/index.cjs";
3
3
  //#region src/databaseJsonValue.d.ts
4
+ declare const isDatabaseJsonObject: (value: unknown) => value is DatabaseJsonObject;
4
5
  declare const isDatabaseMetadataObject: (value: unknown) => value is DatabaseBundleMetadata;
5
- declare const isDatabaseBundleEventMetadata: (value: unknown) => value is DatabaseBundleEventMetadata;
6
6
  //#endregion
7
- export { isDatabaseBundleEventMetadata, isDatabaseMetadataObject };
7
+ export { isDatabaseJsonObject, isDatabaseMetadataObject };
@@ -1,7 +1,7 @@
1
- import { DatabaseBundleEventMetadata, DatabaseBundleMetadata } from "./types/databaseRows.mjs";
1
+ import { DatabaseBundleMetadata, DatabaseJsonObject } from "./types/databaseRows.mjs";
2
2
  import "./types/index.mjs";
3
3
  //#region src/databaseJsonValue.d.ts
4
+ declare const isDatabaseJsonObject: (value: unknown) => value is DatabaseJsonObject;
4
5
  declare const isDatabaseMetadataObject: (value: unknown) => value is DatabaseBundleMetadata;
5
- declare const isDatabaseBundleEventMetadata: (value: unknown) => value is DatabaseBundleEventMetadata;
6
6
  //#endregion
7
- export { isDatabaseBundleEventMetadata, isDatabaseMetadataObject };
7
+ export { isDatabaseJsonObject, isDatabaseMetadataObject };
@@ -33,6 +33,5 @@ const isDatabaseJsonValue = (value) => {
33
33
  };
34
34
  const isDatabaseJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && isDatabaseJsonValue(value);
35
35
  const isDatabaseMetadataObject = (value) => isDatabaseJsonObject(value) && (!Object.hasOwn(value, "app_version") || typeof value["app_version"] === "string");
36
- const isDatabaseBundleEventMetadata = (value) => isDatabaseJsonObject(value) && (value.username === null || typeof value.username === "string") && typeof value.cohort === "string" && (value.update_strategy === null || value.update_strategy === "fingerprint" || value.update_strategy === "appVersion") && (value.fingerprint_hash === null || typeof value.fingerprint_hash === "string") && (value.sdk_version === null || typeof value.sdk_version === "string");
37
36
  //#endregion
38
- export { isDatabaseBundleEventMetadata, isDatabaseJsonObject, isDatabaseJsonValue, isDatabaseMetadataObject };
37
+ export { isDatabaseJsonObject, isDatabaseJsonValue, isDatabaseMetadataObject };
@@ -1,11 +1,11 @@
1
- const require_databasePluginCrudValidationErrors = require("./databasePluginCrudValidationErrors.cjs");
1
+ const require_databaseErrors = require("./databaseErrors.cjs");
2
2
  const require_databaseJsonValue = require("./databaseJsonValue.cjs");
3
3
  let _hot_updater_core = require("@hot-updater/core");
4
4
  //#region src/databaseMetadata.ts
5
5
  const bundleMetadataToRow = (metadata) => {
6
6
  const value = (0, _hot_updater_core.stripBundleArtifactMetadata)(metadata);
7
7
  if (value === void 0) return {};
8
- if (!require_databaseJsonValue.isDatabaseMetadataObject(value)) throw new require_databasePluginCrudValidationErrors.DatabasePluginInputError("invalid-data");
8
+ if (!require_databaseJsonValue.isDatabaseMetadataObject(value)) throw new require_databaseErrors.DatabasePluginInputError("invalid-data");
9
9
  return value;
10
10
  };
11
11
  //#endregion
@@ -1,4 +1,4 @@
1
- import { DatabasePluginInputError } from "./databasePluginCrudValidationErrors.mjs";
1
+ import { DatabasePluginInputError } from "./databaseErrors.mjs";
2
2
  import { isDatabaseMetadataObject } from "./databaseJsonValue.mjs";
3
3
  import { stripBundleArtifactMetadata } from "@hot-updater/core";
4
4
  //#region src/databaseMetadata.ts