@polycode-projects/the-mechanical-code-talker 5.0.46 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,315 @@
1
+ // row-backend-dynamo.mjs — the DynamoDB row backend: the shipped, production
2
+ // storage adapter for the row-backend contract (row-backend.mjs). A consumer
3
+ // builds an @aws-sdk/lib-dynamodb document client with their own credentials
4
+ // and injects it here; this module holds no credentials and builds no
5
+ // client of its own.
6
+ //
7
+ // The AWS SDK loads lazily. Importing this module performs no IO and pulls
8
+ // no AWS code, so installing tmct never requires the SDK. The first storage
9
+ // call runs `await import("@aws-sdk/lib-dynamodb")` once, caches the command
10
+ // constructors, and a consumer who never installed the SDK sees a named
11
+ // error explaining what to add.
12
+ //
13
+ // Table shape, per the contract's recommended key layout: partition key is
14
+ // the session key; sort key is "<rowClass>#<term>#<rowKey>" for a row,
15
+ // "meta#<key>" for a sidecar value. A term-prefix Query is then one line
16
+ // (`begins_with(sk, "fact#<term>#")`), no table change needed later. The
17
+ // sort key alone can't be decoded back into rowClass/term/rowKey (a rowKey
18
+ // can itself carry "#" or "@"), so those travel as their own item attributes
19
+ // too. `attributeNames` remaps only the four storage attribute names — pk,
20
+ // sk, expiresAt, deletedAt; rowKey/rowClass/term/json/value are fixed wire
21
+ // vocabulary and never remap.
22
+ //
23
+ // Deletes arrive as bare rowKeys with no rowClass or term attached (the
24
+ // contract's own shape), so there is no way to build the target sk without
25
+ // first finding the item. `deleteRows`/`deleteAll` both Query the whole
26
+ // session partition, then loop Delete (physical mode) or Update (soft-delete
27
+ // mode, stamping `deletedAt`) over what they found.
28
+
29
+ import {
30
+ BackendRejected, BackendUnavailable, assertValidRow, rowProblems, rowJsonBytes,
31
+ ROW_BACKEND_KIND, ROW_BACKEND_CONTRACT_VERSION,
32
+ } from "./row-backend.mjs";
33
+
34
+ const META_SK_PREFIX = "meta#";
35
+ const SDK_MODULE_SPECIFIER = "@aws-sdk/lib-dynamodb";
36
+
37
+ const DEFAULT_ATTRIBUTE_NAMES = Object.freeze({
38
+ pk: "pk", sk: "sk", expiresAt: "expiresAt", deletedAt: "deletedAt",
39
+ });
40
+
41
+ const nowEpochSeconds = () => Math.floor(Date.now() / 1000);
42
+ const OVERSIZED_ONLY = /over the \d+-byte cap$/;
43
+
44
+ // Cached across every backend instance in this process — the SDK's command
45
+ // constructors never change per session, so there is nothing session-scoped
46
+ // to re-fetch. A failed import is not cached: a consumer who installs the
47
+ // SDK after a first failed call should have their very next call succeed.
48
+ let sdkPromise = null;
49
+ async function loadDynamoCommands() {
50
+ if (!sdkPromise) {
51
+ sdkPromise = import(SDK_MODULE_SPECIFIER).catch((cause) => {
52
+ sdkPromise = null;
53
+ throw new BackendUnavailable(
54
+ `the DynamoDB row backend needs "${SDK_MODULE_SPECIFIER}" (>=3) installed alongside tmct; run \`npm install ${SDK_MODULE_SPECIFIER}\` and retry`,
55
+ { cause },
56
+ );
57
+ });
58
+ }
59
+ return sdkPromise;
60
+ }
61
+
62
+ /** Runs `fn` over `items` with at most `limit` calls in flight at once.
63
+ * `writeConcurrency: Infinity` (the default) runs the whole batch together —
64
+ * batches are 1-5 rows, so that is the natural ceiling; `1` serializes it. */
65
+ async function mapWithConcurrency(items, limit, fn) {
66
+ if (!items.length) return;
67
+ const workerCount = Math.max(1, Math.min(limit, items.length));
68
+ let cursor = 0;
69
+ async function worker() {
70
+ for (;;) {
71
+ const index = cursor++;
72
+ if (index >= items.length) return;
73
+ await fn(items[index], index);
74
+ }
75
+ }
76
+ await Promise.all(Array.from({ length: workerCount }, worker));
77
+ }
78
+
79
+ export function createDynamoRowBackend({
80
+ client,
81
+ tableName,
82
+ sessionKey,
83
+ ttlSeconds = null,
84
+ softDelete = false,
85
+ consistentRead = true,
86
+ writeConcurrency = Infinity,
87
+ onOversizedRow = "throw",
88
+ basePayload = null,
89
+ maxRows = null,
90
+ maxBytes = null,
91
+ attributeNames = DEFAULT_ATTRIBUTE_NAMES,
92
+ } = {}) {
93
+ if (!client) throw new TypeError("createDynamoRowBackend needs a client (an @aws-sdk/lib-dynamodb DynamoDBDocumentClient)");
94
+ if (!tableName) throw new TypeError("createDynamoRowBackend needs a tableName");
95
+ if (!sessionKey) throw new TypeError("createDynamoRowBackend needs a sessionKey");
96
+
97
+ const names = { ...DEFAULT_ATTRIBUTE_NAMES, ...attributeNames };
98
+ let closed = false;
99
+
100
+ const assertOpen = () => {
101
+ if (closed) throw new BackendUnavailable("this row backend was closed and can no longer be used");
102
+ };
103
+
104
+ const primaryKey = (sk) => ({ [names.pk]: sessionKey, [names.sk]: sk });
105
+ const skForRow = (rowClass, term, rowKey) => `${rowClass}#${term}#${rowKey}`;
106
+ const skForMeta = (metaKey) => `${META_SK_PREFIX}${metaKey}`;
107
+ const expiresAtToStamp = () => (ttlSeconds == null ? undefined : nowEpochSeconds() + ttlSeconds);
108
+
109
+ function rowFromItem(item) {
110
+ const row = { rowKey: item.rowKey, rowClass: item.rowClass, term: item.term, json: item.json };
111
+ const expiresAt = item[names.expiresAt];
112
+ if (typeof expiresAt === "number") row.expiresAt = expiresAt;
113
+ return row;
114
+ }
115
+
116
+ /** Wraps every store call so a network failure or a 429/5xx-shaped
117
+ * rejection surfaces as `BackendUnavailable`, never a raw SDK error a
118
+ * consumer would have to string-match. `BackendRejected`/`BackendUnavailable`
119
+ * raised deliberately elsewhere in this module (the SDK-missing error,
120
+ * the size caps) pass through unchanged. */
121
+ async function send(command) {
122
+ try {
123
+ return await client.send(command);
124
+ } catch (error) {
125
+ if (error instanceof BackendRejected || error instanceof BackendUnavailable) throw error;
126
+ throw new BackendUnavailable(`the DynamoDB row backend's store call failed: ${error.message}`, { cause: error });
127
+ }
128
+ }
129
+
130
+ async function query({ keyConditionExpression, filterExpression, expressionAttributeNames, expressionAttributeValues }) {
131
+ const { QueryCommand } = await loadDynamoCommands();
132
+ const items = [];
133
+ let exclusiveStartKey;
134
+ do {
135
+ const result = await send(new QueryCommand({
136
+ TableName: tableName,
137
+ KeyConditionExpression: keyConditionExpression,
138
+ FilterExpression: filterExpression,
139
+ ExpressionAttributeNames: expressionAttributeNames,
140
+ ExpressionAttributeValues: expressionAttributeValues,
141
+ ConsistentRead: consistentRead,
142
+ ExclusiveStartKey: exclusiveStartKey,
143
+ }));
144
+ items.push(...(result.Items || []));
145
+ exclusiveStartKey = result.LastEvaluatedKey;
146
+ } while (exclusiveStartKey);
147
+ return items;
148
+ }
149
+
150
+ /** Every item under this session's partition, row and meta alike,
151
+ * regardless of soft-delete state — the shared read `deleteRows`/
152
+ * `deleteAll` resolve a bare rowKey against, since neither can build the
153
+ * target sk from the rowKey alone. */
154
+ async function queryAllItems() {
155
+ return query({
156
+ keyConditionExpression: "#pk = :pk",
157
+ expressionAttributeNames: { "#pk": names.pk },
158
+ expressionAttributeValues: { ":pk": sessionKey },
159
+ });
160
+ }
161
+
162
+ async function readRows() {
163
+ assertOpen();
164
+ const expressionAttributeNames = { "#pk": names.pk, "#sk": names.sk };
165
+ const filterClauses = ["NOT begins_with(#sk, :metaPrefix)"];
166
+ if (softDelete) {
167
+ filterClauses.push("attribute_not_exists(#deletedAt)");
168
+ expressionAttributeNames["#deletedAt"] = names.deletedAt;
169
+ }
170
+ const items = await query({
171
+ keyConditionExpression: "#pk = :pk",
172
+ filterExpression: filterClauses.join(" AND "),
173
+ expressionAttributeNames,
174
+ expressionAttributeValues: { ":pk": sessionKey, ":metaPrefix": META_SK_PREFIX },
175
+ });
176
+ return items.map(rowFromItem);
177
+ }
178
+
179
+ async function readRowsByTerm(term) {
180
+ assertOpen();
181
+ const expressionAttributeNames = { "#pk": names.pk, "#sk": names.sk };
182
+ let filterExpression;
183
+ if (softDelete) {
184
+ filterExpression = "attribute_not_exists(#deletedAt)";
185
+ expressionAttributeNames["#deletedAt"] = names.deletedAt;
186
+ }
187
+ const items = await query({
188
+ keyConditionExpression: "#pk = :pk AND begins_with(#sk, :skPrefix)",
189
+ filterExpression,
190
+ expressionAttributeNames,
191
+ expressionAttributeValues: { ":pk": sessionKey, ":skPrefix": `fact#${term}#` },
192
+ });
193
+ return items.map(rowFromItem);
194
+ }
195
+
196
+ async function putRows(candidateRows) {
197
+ assertOpen();
198
+ const rows = candidateRows || [];
199
+ if (maxRows != null && rows.length > maxRows) {
200
+ throw new BackendRejected(`putRows carries ${rows.length} rows, over this session's ${maxRows}-row cap`);
201
+ }
202
+ if (maxBytes != null) {
203
+ const totalBytes = rows.reduce((sum, row) => sum + rowJsonBytes(row), 0);
204
+ if (totalBytes > maxBytes) {
205
+ throw new BackendRejected(`putRows carries ${totalBytes} bytes, over this session's ${maxBytes}-byte cap`);
206
+ }
207
+ }
208
+
209
+ const toWrite = [];
210
+ for (const row of rows) {
211
+ const problems = rowProblems(row);
212
+ if (!problems.length) { toWrite.push(row); continue; }
213
+ const oversizedOnly = problems.length === 1 && OVERSIZED_ONLY.test(problems[0]);
214
+ if (oversizedOnly && onOversizedRow === "drop") {
215
+ // The wire row carries no separate provenance field of its own —
216
+ // rowKey is the provenance-derived id (core.mjs's factGroupId
217
+ // model), so it is what a dropped-row log can name.
218
+ console.warn(`tmct memory row backend: dropped oversized row ${JSON.stringify(row?.rowKey ?? null)}`);
219
+ continue;
220
+ }
221
+ assertValidRow(row); // throws BackendRejected naming every problem; aborts the whole batch
222
+ }
223
+
224
+ const { PutCommand } = await loadDynamoCommands();
225
+ const expiresAt = expiresAtToStamp();
226
+ await mapWithConcurrency(toWrite, writeConcurrency, async (row) => {
227
+ const item = {
228
+ ...primaryKey(skForRow(row.rowClass, row.term, row.rowKey)),
229
+ rowKey: row.rowKey, rowClass: row.rowClass, term: row.term, json: row.json,
230
+ ...(expiresAt !== undefined ? { [names.expiresAt]: expiresAt } : {}),
231
+ };
232
+ await send(new PutCommand({ TableName: tableName, Item: item }));
233
+ });
234
+ }
235
+
236
+ async function applyDeletes(items) {
237
+ if (!items.length) return;
238
+ if (softDelete) {
239
+ const { UpdateCommand } = await loadDynamoCommands();
240
+ await Promise.all(items.map((item) => send(new UpdateCommand({
241
+ TableName: tableName,
242
+ Key: primaryKey(item[names.sk]),
243
+ UpdateExpression: "SET #deletedAt = :deletedAt",
244
+ ExpressionAttributeNames: { "#deletedAt": names.deletedAt },
245
+ ExpressionAttributeValues: { ":deletedAt": Date.now() },
246
+ }))));
247
+ return;
248
+ }
249
+ const { DeleteCommand } = await loadDynamoCommands();
250
+ await Promise.all(items.map((item) => send(new DeleteCommand({
251
+ TableName: tableName,
252
+ Key: primaryKey(item[names.sk]),
253
+ }))));
254
+ }
255
+
256
+ async function deleteRows(rowKeys) {
257
+ assertOpen();
258
+ const wanted = new Set(rowKeys || []);
259
+ if (!wanted.size) return;
260
+ const items = await queryAllItems();
261
+ await applyDeletes(items.filter((item) => wanted.has(item.rowKey)));
262
+ }
263
+
264
+ async function deleteAll() {
265
+ assertOpen();
266
+ await applyDeletes(await queryAllItems());
267
+ }
268
+
269
+ async function readMeta(metaKey) {
270
+ assertOpen();
271
+ const { GetCommand } = await loadDynamoCommands();
272
+ const result = await send(new GetCommand({
273
+ TableName: tableName,
274
+ Key: primaryKey(skForMeta(metaKey)),
275
+ ConsistentRead: consistentRead,
276
+ }));
277
+ const item = result.Item;
278
+ if (!item) return null;
279
+ if (softDelete && item[names.deletedAt] !== undefined) return null;
280
+ return typeof item.value === "string" ? item.value : null;
281
+ }
282
+
283
+ async function putMeta(metaKey, value) {
284
+ assertOpen();
285
+ const { PutCommand } = await loadDynamoCommands();
286
+ const expiresAt = expiresAtToStamp();
287
+ const item = {
288
+ ...primaryKey(skForMeta(metaKey)),
289
+ value,
290
+ ...(expiresAt !== undefined ? { [names.expiresAt]: expiresAt } : {}),
291
+ };
292
+ await send(new PutCommand({ TableName: tableName, Item: item }));
293
+ }
294
+
295
+ async function close() {
296
+ closed = true;
297
+ }
298
+
299
+ return {
300
+ kind: ROW_BACKEND_KIND,
301
+ contractVersion: ROW_BACKEND_CONTRACT_VERSION,
302
+ // Not part of the contract: an inert read-only overlay carried for the
303
+ // wrapping layer (§3.4's basePayload mechanics) to assemble beneath this
304
+ // session's own rows once it lands. This backend never reads or writes it.
305
+ basePayload,
306
+ readRows,
307
+ readRowsByTerm,
308
+ putRows,
309
+ deleteRows,
310
+ readMeta,
311
+ putMeta,
312
+ deleteAll,
313
+ close,
314
+ };
315
+ }
@@ -0,0 +1,85 @@
1
+ // row-backend-memory.mjs — the reference implementation of the memory
2
+ // row-backend contract (row-backend.mjs): the simplest complete backend, an
3
+ // in-process Map. It is the working example the contract's own doc-comment
4
+ // describes, the fixture the conformance kit proves itself against
5
+ // (src/tools/memory-backend-conformance.mjs), and the storage the row
6
+ // service's local double runs over.
7
+ //
8
+ // Deletes are physical here: a deleted row's key leaves the map. The
9
+ // contract only promises a deleted row is absent from every later read, so a
10
+ // backend that tombstones instead and filters reads is equally conformant —
11
+ // the kit checks the observable outcome, never which of the two this is.
12
+
13
+ import {
14
+ ROW_BACKEND_KIND, ROW_BACKEND_CONTRACT_VERSION,
15
+ BackendUnavailable, assertValidRow,
16
+ } from "./row-backend.mjs";
17
+
18
+ const nowEpochSeconds = () => Math.floor(Date.now() / 1000);
19
+
20
+ /** A row backend over an in-process Map, scoped to one session by
21
+ * construction (the caller makes a fresh one per session, exactly as every
22
+ * shipped backend does). `clock` is a hook for deterministic TTL tests. */
23
+ export function createRowMemoryBackend({ clock = nowEpochSeconds } = {}) {
24
+ const rows = new Map();
25
+ const meta = new Map();
26
+ let closed = false;
27
+
28
+ const assertOpen = () => {
29
+ if (closed) throw new BackendUnavailable("this row backend was closed and can no longer be used");
30
+ };
31
+
32
+ const liveRows = () => [...rows.values()].filter(
33
+ (row) => row.expiresAt === undefined || row.expiresAt > clock(),
34
+ );
35
+
36
+ return {
37
+ kind: ROW_BACKEND_KIND,
38
+ contractVersion: ROW_BACKEND_CONTRACT_VERSION,
39
+
40
+ async readRows() {
41
+ assertOpen();
42
+ return liveRows().map((row) => ({ ...row }));
43
+ },
44
+
45
+ async readRowsByTerm(term) {
46
+ assertOpen();
47
+ return liveRows().filter((row) => row.term === term).map((row) => ({ ...row }));
48
+ },
49
+
50
+ async putRows(candidateRows) {
51
+ assertOpen();
52
+ // Validate every row before writing any of them: a batch carrying one
53
+ // malformed row is refused whole, so a caller retries with the bad row
54
+ // removed rather than discovering a half-applied write. Earlier,
55
+ // already-durable rows from prior calls are untouched either way.
56
+ const validated = (candidateRows || []).map((row) => assertValidRow(row));
57
+ for (const row of validated) rows.set(row.rowKey, { ...row });
58
+ },
59
+
60
+ async deleteRows(rowKeys) {
61
+ assertOpen();
62
+ for (const key of rowKeys || []) rows.delete(key);
63
+ },
64
+
65
+ async readMeta(key) {
66
+ assertOpen();
67
+ return meta.has(key) ? meta.get(key) : null;
68
+ },
69
+
70
+ async putMeta(key, value) {
71
+ assertOpen();
72
+ meta.set(key, value);
73
+ },
74
+
75
+ async deleteAll() {
76
+ assertOpen();
77
+ rows.clear();
78
+ meta.clear();
79
+ },
80
+
81
+ async close() {
82
+ closed = true;
83
+ },
84
+ };
85
+ }
@@ -0,0 +1,162 @@
1
+ // row-backend.mjs — the published contract for a custom memory backend: a
2
+ // session-scoped async row store the consumer constructs and injects, which
3
+ // tmct binds into the same `memoryDir` token every memory call already threads.
4
+ //
5
+ // A backend is a duck-typed object, and `isRowBackend` is the test:
6
+ //
7
+ // {
8
+ // kind: "tmct-memory-row-backend",
9
+ // contractVersion: 1,
10
+ //
11
+ // readRows(), // → AsyncIterable<row> | Promise<row[]>: every live row
12
+ // putRows(rows), // upsert; per-row atomic; resolves when all rows are durable
13
+ // deleteRows(rowKeys), // the rows are absent from every later read; missing keys are a no-op
14
+ // readRowsByTerm(term), // OPTIONAL: rows whose index term matches
15
+ // readMeta(key), // → string | null
16
+ // putMeta(key, value), // upsert one sidecar value
17
+ // deleteAll(), // every row and meta entry this session key reaches goes absent
18
+ // close(), // release connections; further calls may reject
19
+ // }
20
+ //
21
+ // Read order never carries meaning: what a row means rides its own content, so
22
+ // two backends handing the same rows back in different orders assemble the same
23
+ // payload.
24
+ //
25
+ // Deleting is observable, not physical. The contract promises one thing — a
26
+ // deleted row never appears in a later read. Removing the item and tombstoning
27
+ // it behind a filtered read both satisfy that, so an adapter picks whichever
28
+ // its store makes cheap.
29
+
30
+ // The wire row a backend stores is `{ rowKey, rowClass, term, json }` plus an
31
+ // optional `expiresAt` in epoch seconds. `json` is the serialized record and the
32
+ // only field carrying tmct-shaped content; the other three are what an adapter
33
+ // indexes on, and `expiresAt` is the adapter's own TTL stamp, absent when the
34
+ // consumer set no policy. `rowProblems` below is the shape's one authority.
35
+
36
+ export const ROW_BACKEND_KIND = "tmct-memory-row-backend";
37
+ export const ROW_BACKEND_CONTRACT_VERSION = 1;
38
+
39
+ /** The closed row-class set. `bookkeeping` is the structural gate: a row in
40
+ * that class is internal (a research-queue entry, a researched-term marker)
41
+ * and never composes into a visitor-facing answer, so read paths exclude it by
42
+ * field rather than by matching on its content. */
43
+ export const ROW_CLASSES = Object.freeze([
44
+ "fact", "source", "utterance", "session", "rule", "retraction", "edge-group", "bookkeeping",
45
+ ]);
46
+
47
+ export const BOOKKEEPING_ROW_CLASS = "bookkeeping";
48
+
49
+ /** The per-row size cap. The projection enforces it before any write leaves the
50
+ * process, so an oversized fact fails in the turn that minted it rather than
51
+ * as a store's 400 several hops later. */
52
+ export const MAX_ROW_BYTES = 4096;
53
+
54
+ export const BACKEND_REJECTED_CODE = "TMCT_BACKEND_REJECTED";
55
+ export const BACKEND_UNAVAILABLE_CODE = "TMCT_BACKEND_UNAVAILABLE";
56
+
57
+ /** Both failure classes carry a stable `code`, so a consumer whose turn is
58
+ * itself the last resort catches by class or by code and carries on without
59
+ * persistence. Nothing has to match on an error message. */
60
+ function describeFailure(error, details) {
61
+ if (details?.rowKey) error.rowKey = details.rowKey;
62
+ if (details?.rowClass) error.rowClass = details.rowClass;
63
+ if (details?.provenance) error.provenance = details.provenance;
64
+ if (details?.status) error.status = details.status;
65
+ return error;
66
+ }
67
+
68
+ /** The input was refused: an oversized row, a malformed key, a failed
69
+ * validation. Retrying the same input gets the same answer. */
70
+ export class BackendRejected extends Error {
71
+ constructor(message, details = {}) {
72
+ super(message, details.cause ? { cause: details.cause } : undefined);
73
+ this.name = "BackendRejected";
74
+ this.code = BACKEND_REJECTED_CODE;
75
+ describeFailure(this, details);
76
+ }
77
+ }
78
+
79
+ /** The store could not be reached or refused service: a network failure, a
80
+ * 429/507/5xx. The same input may well succeed later. */
81
+ export class BackendUnavailable extends Error {
82
+ constructor(message, details = {}) {
83
+ super(message, details.cause ? { cause: details.cause } : undefined);
84
+ this.name = "BackendUnavailable";
85
+ this.code = BACKEND_UNAVAILABLE_CODE;
86
+ describeFailure(this, details);
87
+ }
88
+ }
89
+
90
+ const REQUIRED_METHODS = Object.freeze([
91
+ "readRows", "putRows", "deleteRows", "readMeta", "putMeta", "deleteAll", "close",
92
+ ]);
93
+
94
+ /** The one method a backend may leave out. Core's read path does not call it
95
+ * yet; it is in the contract so the index shape is settled and an adapter that
96
+ * implements it needs no table change when core starts issuing term reads. */
97
+ export const OPTIONAL_METHODS = Object.freeze(["readRowsByTerm"]);
98
+
99
+ /** What stops `value` from being a row backend, as a list of plain sentences.
100
+ * Empty means it is one. */
101
+ export function rowBackendProblems(value) {
102
+ const problems = [];
103
+ if (!value || typeof value !== "object") return ["not an object"];
104
+ if (value.kind !== ROW_BACKEND_KIND) problems.push(`kind is ${JSON.stringify(value.kind)}, expected ${JSON.stringify(ROW_BACKEND_KIND)}`);
105
+ if (value.contractVersion !== ROW_BACKEND_CONTRACT_VERSION) {
106
+ problems.push(`contractVersion is ${JSON.stringify(value.contractVersion)}, expected ${ROW_BACKEND_CONTRACT_VERSION}`);
107
+ }
108
+ for (const method of REQUIRED_METHODS) {
109
+ if (typeof value[method] !== "function") problems.push(`${method}() is missing`);
110
+ }
111
+ for (const method of OPTIONAL_METHODS) {
112
+ if (method in value && value[method] != null && typeof value[method] !== "function") {
113
+ problems.push(`${method} is present but not a function`);
114
+ }
115
+ }
116
+ return problems;
117
+ }
118
+
119
+ /** True when `value` is a row backend tmct can bind as a `memoryDir` token. */
120
+ export function isRowBackend(value) {
121
+ return rowBackendProblems(value).length === 0;
122
+ }
123
+
124
+ /** The stored size of a row: its serialized record in UTF-8 bytes. TextEncoder
125
+ * rather than Buffer, because this module runs in the browser too. */
126
+ export function rowJsonBytes(row) {
127
+ return new TextEncoder().encode(String(row?.json ?? "")).length;
128
+ }
129
+
130
+ /** What stops `row` from being a valid wire row, as a list of plain sentences.
131
+ * Empty means it is one. */
132
+ export function rowProblems(row) {
133
+ const problems = [];
134
+ if (!row || typeof row !== "object") return ["not an object"];
135
+ if (typeof row.rowKey !== "string" || !row.rowKey) problems.push("rowKey must be a non-empty string");
136
+ if (!ROW_CLASSES.includes(row.rowClass)) problems.push(`rowClass ${JSON.stringify(row.rowClass)} is outside the closed set (${ROW_CLASSES.join(", ")})`);
137
+ if (typeof row.term !== "string") problems.push("term must be a string, empty when the row has no term read path");
138
+ if (typeof row.json !== "string" || !row.json) problems.push("json must be a non-empty string");
139
+ else {
140
+ const bytes = rowJsonBytes(row);
141
+ if (bytes > MAX_ROW_BYTES) problems.push(`json is ${bytes} bytes, over the ${MAX_ROW_BYTES}-byte cap`);
142
+ }
143
+ if (row.expiresAt !== undefined && !Number.isInteger(row.expiresAt)) {
144
+ problems.push("expiresAt must be epoch seconds as an integer when present");
145
+ }
146
+ return problems;
147
+ }
148
+
149
+ export function isValidRow(row) {
150
+ return rowProblems(row).length === 0;
151
+ }
152
+
153
+ /** Throw a `BackendRejected` naming every problem, or return the row. Adapters
154
+ * call this on the way in so a malformed row never reaches a store. */
155
+ export function assertValidRow(row, details = {}) {
156
+ const problems = rowProblems(row);
157
+ if (!problems.length) return row;
158
+ throw new BackendRejected(
159
+ `invalid memory row ${JSON.stringify(row?.rowKey ?? null)}: ${problems.join("; ")}`,
160
+ { rowKey: typeof row?.rowKey === "string" ? row.rowKey : "", rowClass: row?.rowClass, ...details },
161
+ );
162
+ }