@auditstream/node 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,859 @@
1
+ import { i as getCachedScopePayload, n as MAX_PAYLOAD_BYTES, r as audit$1, t as AuditstreamError } from "./context-pPVY39Lw.mjs";
2
+ // src/transport.ts
3
+ /**
4
+ * Maximum character length of an unpadded base64url actor payload in a trailing SQL comment
5
+ * (`ceil(512 * 4 / 3) = 683` per Auditstream Specification 0.1.0).
6
+ */
7
+ const MAX_ENCODED_COMMENT_CHARS = 683;
8
+ const VALID_ACTOR_TYPES = /* @__PURE__ */ new Set([
9
+ "user",
10
+ "api_key",
11
+ "ai_agent",
12
+ "service",
13
+ "system"
14
+ ]);
15
+ const KNOWN_CONTEXT_KEYS = [
16
+ "requestId",
17
+ "source",
18
+ "ip",
19
+ "userAgent"
20
+ ];
21
+ const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
22
+ const BASE64URL_DECODE_LUT = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
23
+ for (let i = 0; i < 64; i++) BASE64URL_DECODE_LUT[BASE64URL_ALPHABET.codePointAt(i) ?? 0] = i;
24
+ const TRAILING_COMMENT_REGEX = /\/\*([^/]*)\*\/[\s;]*$/;
25
+ const AUDITSTREAM_PREFIX = "auditstream='";
26
+ const COMMA_AUDITSTREAM_PREFIX = ",auditstream='";
27
+ const TAIL_SLICE_CHARS = 4096;
28
+ const utf8Encoder$1 = new TextEncoder();
29
+ const utf8Decoder$1 = new TextDecoder("utf-8", { fatal: true });
30
+ function isPlainObject$2(value) {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32
+ }
33
+ function isNonEmptyString(value) {
34
+ return typeof value === "string" && value.length > 0;
35
+ }
36
+ function isValidOptionalNonEmptyString(obj, key) {
37
+ return !Object.hasOwn(obj, key) || isNonEmptyString(obj[key]);
38
+ }
39
+ function isValidNestedActorObject(value) {
40
+ if (!isPlainObject$2(value)) return false;
41
+ return typeof value.type === "string" && VALID_ACTOR_TYPES.has(value.type) && isNonEmptyString(value.id) && !Object.hasOwn(value, "onBehalfOf") && isValidOptionalNonEmptyString(value, "tenant");
42
+ }
43
+ /** Internal Spec 0.1.0 actor payload validator shared with `history.ts`. */
44
+ function isValidActorObject(value) {
45
+ if (!isPlainObject$2(value)) return false;
46
+ if (typeof value.type !== "string" || !VALID_ACTOR_TYPES.has(value.type) || !isNonEmptyString(value.id) || !isValidOptionalNonEmptyString(value, "tenant")) return false;
47
+ if (Object.hasOwn(value, "onBehalfOf") && !isValidNestedActorObject(value.onBehalfOf)) return false;
48
+ return true;
49
+ }
50
+ /** Internal Spec 0.1.0 context payload validator shared with `history.ts`. */
51
+ function isValidContextObject(value) {
52
+ if (!isPlainObject$2(value)) return false;
53
+ for (const key of KNOWN_CONTEXT_KEYS) if (!isValidOptionalNonEmptyString(value, key)) return false;
54
+ return true;
55
+ }
56
+ /**
57
+ * Internal RFC 4648 unpadded base64url encoder shared with `query.ts` cursors.
58
+ */
59
+ function encodeBase64UrlUnpadded(bytes) {
60
+ let out = "";
61
+ const len = bytes.length;
62
+ let i = 0;
63
+ while (i + 2 < len) {
64
+ const b0 = bytes[i] ?? 0;
65
+ const b1 = bytes[i + 1] ?? 0;
66
+ const b2 = bytes[i + 2] ?? 0;
67
+ const chunk = b0 << 16 | b1 << 8 | b2;
68
+ out += BASE64URL_ALPHABET.charAt(chunk >> 18 & 63) + BASE64URL_ALPHABET.charAt(chunk >> 12 & 63) + BASE64URL_ALPHABET.charAt(chunk >> 6 & 63) + BASE64URL_ALPHABET.charAt(chunk & 63);
69
+ i += 3;
70
+ }
71
+ const remaining = len - i;
72
+ if (remaining === 1) {
73
+ const b0 = bytes[i] ?? 0;
74
+ out += BASE64URL_ALPHABET.charAt(b0 >> 2 & 63) + BASE64URL_ALPHABET.charAt(b0 << 4 & 63);
75
+ } else if (remaining === 2) {
76
+ const b0 = bytes[i] ?? 0;
77
+ const b1 = bytes[i + 1] ?? 0;
78
+ const chunk = b0 << 8 | b1;
79
+ out += BASE64URL_ALPHABET.charAt(chunk >> 10 & 63) + BASE64URL_ALPHABET.charAt(chunk >> 4 & 63) + BASE64URL_ALPHABET.charAt(chunk << 2 & 63);
80
+ }
81
+ return out;
82
+ }
83
+ function decodeBase64UrlChar(encoded, index) {
84
+ const code = encoded.codePointAt(index) ?? 128;
85
+ return code < 128 ? BASE64URL_DECODE_LUT[code] ?? -1 : -1;
86
+ }
87
+ /**
88
+ * Internal RFC 4648 unpadded base64url decoder shared with `query.ts` cursors.
89
+ */
90
+ function decodeBase64UrlUnpadded(encoded, maxLen = 683) {
91
+ const len = encoded.length;
92
+ if (len === 0 || len > maxLen || len % 4 === 1) return null;
93
+ const byteLen = Math.floor(len * 3 / 4);
94
+ const out = new Uint8Array(byteLen);
95
+ const rem = len % 4;
96
+ const fullEnd = len - rem;
97
+ let outIdx = 0;
98
+ for (let i = 0; i < fullEnd; i += 4) {
99
+ const c0 = decodeBase64UrlChar(encoded, i);
100
+ const c1 = decodeBase64UrlChar(encoded, i + 1);
101
+ const c2 = decodeBase64UrlChar(encoded, i + 2);
102
+ const c3 = decodeBase64UrlChar(encoded, i + 3);
103
+ if ((c0 | c1 | c2 | c3) < 0) return null;
104
+ out[outIdx++] = c0 << 2 | c1 >> 4;
105
+ out[outIdx++] = (c1 & 15) << 4 | c2 >> 2;
106
+ out[outIdx++] = (c2 & 3) << 6 | c3;
107
+ }
108
+ if (rem === 2) {
109
+ const c0 = decodeBase64UrlChar(encoded, fullEnd);
110
+ const c1 = decodeBase64UrlChar(encoded, fullEnd + 1);
111
+ if ((c0 | c1) < 0) return null;
112
+ out[outIdx] = c0 << 2 | c1 >> 4;
113
+ } else if (rem === 3) {
114
+ const c0 = decodeBase64UrlChar(encoded, fullEnd);
115
+ const c1 = decodeBase64UrlChar(encoded, fullEnd + 1);
116
+ const c2 = decodeBase64UrlChar(encoded, fullEnd + 2);
117
+ if ((c0 | c1 | c2) < 0) return null;
118
+ out[outIdx++] = c0 << 2 | c1 >> 4;
119
+ out[outIdx] = (c1 & 15) << 4 | c2 >> 2;
120
+ }
121
+ return out;
122
+ }
123
+ function assertNonEmptyString(value, field, code) {
124
+ if (typeof value !== "string" || value.length === 0) throw new AuditstreamError(code, `${field} must be a non-empty string`);
125
+ }
126
+ /**
127
+ * Locale-independent UTF-16 code-unit comparator matching `spec/transport.md` lexicographic
128
+ * key ordering without depending on the host's default locale.
129
+ */
130
+ function compareCodeUnits(a, b) {
131
+ if (a < b) return -1;
132
+ if (a > b) return 1;
133
+ return 0;
134
+ }
135
+ function canonicalizeNestedActor(raw) {
136
+ if (!isPlainObject$2(raw)) throw new AuditstreamError("INVALID_ACTOR", "actor.onBehalfOf must be a JSON object");
137
+ if (typeof raw.type !== "string" || !VALID_ACTOR_TYPES.has(raw.type)) throw new AuditstreamError("INVALID_ACTOR", "actor.onBehalfOf.type must be one of user, api_key, ai_agent, service, system");
138
+ assertNonEmptyString(raw.id, "actor.onBehalfOf.id", "INVALID_ACTOR");
139
+ if ("onBehalfOf" in raw && raw.onBehalfOf !== void 0) throw new AuditstreamError("INVALID_ACTOR", "actor.onBehalfOf must not contain a nested onBehalfOf (max depth is 1)");
140
+ if (raw.tenant !== void 0) assertNonEmptyString(raw.tenant, "actor.onBehalfOf.tenant", "INVALID_ACTOR");
141
+ const ordered = {
142
+ type: raw.type,
143
+ id: raw.id
144
+ };
145
+ if (raw.tenant !== void 0) ordered.tenant = raw.tenant;
146
+ for (const key of Object.keys(raw).sort(compareCodeUnits)) {
147
+ if (key === "type" || key === "id" || key === "tenant" || key === "onBehalfOf") continue;
148
+ if (raw[key] !== void 0) ordered[key] = raw[key];
149
+ }
150
+ return ordered;
151
+ }
152
+ function canonicalizeContext(raw) {
153
+ if (!isPlainObject$2(raw)) throw new AuditstreamError("INVALID_CONTEXT", "context must be a JSON object");
154
+ const ordered = {};
155
+ if (raw.requestId !== void 0) {
156
+ assertNonEmptyString(raw.requestId, "context.requestId", "INVALID_CONTEXT");
157
+ ordered.requestId = raw.requestId;
158
+ }
159
+ if (raw.source !== void 0) {
160
+ assertNonEmptyString(raw.source, "context.source", "INVALID_CONTEXT");
161
+ ordered.source = raw.source;
162
+ }
163
+ if (raw.ip !== void 0) {
164
+ assertNonEmptyString(raw.ip, "context.ip", "INVALID_CONTEXT");
165
+ ordered.ip = raw.ip;
166
+ }
167
+ if (raw.userAgent !== void 0) {
168
+ assertNonEmptyString(raw.userAgent, "context.userAgent", "INVALID_CONTEXT");
169
+ ordered.userAgent = raw.userAgent;
170
+ }
171
+ for (const key of Object.keys(raw).sort(compareCodeUnits)) {
172
+ if (key === "requestId" || key === "source" || key === "ip" || key === "userAgent") continue;
173
+ if (raw[key] !== void 0) ordered[key] = raw[key];
174
+ }
175
+ return ordered;
176
+ }
177
+ function serializeCanonicalPayload(scope) {
178
+ const rawActor = scope.actor;
179
+ if (!isPlainObject$2(rawActor)) throw new AuditstreamError("INVALID_ACTOR", "actor must be a JSON object");
180
+ if (typeof rawActor.type !== "string" || !VALID_ACTOR_TYPES.has(rawActor.type)) throw new AuditstreamError("INVALID_ACTOR", "actor.type must be one of user, api_key, ai_agent, service, system");
181
+ assertNonEmptyString(rawActor.id, "actor.id", "INVALID_ACTOR");
182
+ const nested = rawActor.onBehalfOf !== void 0 ? canonicalizeNestedActor(rawActor.onBehalfOf) : void 0;
183
+ if (rawActor.tenant !== void 0) assertNonEmptyString(rawActor.tenant, "actor.tenant", "INVALID_ACTOR");
184
+ const rawContext = scope.context;
185
+ const canonicalContext = rawContext !== void 0 ? canonicalizeContext(rawContext) : void 0;
186
+ const ordered = {
187
+ type: rawActor.type,
188
+ id: rawActor.id
189
+ };
190
+ if (nested !== void 0) ordered.onBehalfOf = nested;
191
+ if (rawActor.tenant !== void 0) ordered.tenant = rawActor.tenant;
192
+ if (canonicalContext !== void 0) ordered.context = canonicalContext;
193
+ for (const key of Object.keys(rawActor).sort(compareCodeUnits)) {
194
+ if (key === "type" || key === "id" || key === "onBehalfOf" || key === "tenant" || key === "context") continue;
195
+ if (rawActor[key] !== void 0) ordered[key] = rawActor[key];
196
+ }
197
+ const json = JSON.stringify(ordered);
198
+ const bytes = utf8Encoder$1.encode(json);
199
+ if (bytes.byteLength > 512) throw new AuditstreamError("PAYLOAD_TOO_LARGE", `serialized actor payload is ${bytes.byteLength} UTF-8 bytes, exceeding the 512-byte limit`);
200
+ return {
201
+ json,
202
+ bytes
203
+ };
204
+ }
205
+ function getOrEncodeCached(cached) {
206
+ if (cached.encoded === void 0) cached.encoded = encodeBase64UrlUnpadded(cached.bytes);
207
+ return cached.encoded;
208
+ }
209
+ function isAsciiWhitespaceOrSemicolon(code) {
210
+ return code === 32 || code === 59 || code === 10 || code === 13 || code === 9 || code === 12 || code === 11;
211
+ }
212
+ function extractTrailingCommentBody(sql) {
213
+ const len = sql.length;
214
+ const windowStart = Math.max(0, len - TAIL_SLICE_CHARS);
215
+ let end = len - 1;
216
+ while (end >= windowStart) {
217
+ const code = sql.codePointAt(end) ?? 0;
218
+ if (isAsciiWhitespaceOrSemicolon(code)) {
219
+ end--;
220
+ continue;
221
+ }
222
+ if (code > 127) return TRAILING_COMMENT_REGEX.exec(sql.slice(windowStart))?.[1] ?? null;
223
+ break;
224
+ }
225
+ if (end < windowStart + 3 || sql.codePointAt(end) !== 47 || sql.codePointAt(end - 1) !== 42) return null;
226
+ const openSlash = sql.lastIndexOf("/", end - 2);
227
+ if (openSlash < windowStart || openSlash > end - 3 || sql.codePointAt(openSlash + 1) !== 42) return null;
228
+ return sql.slice(openSlash + 2, end - 1);
229
+ }
230
+ function extractAuditstreamTagValue(body) {
231
+ let valueStart;
232
+ if (body.startsWith(AUDITSTREAM_PREFIX)) valueStart = 13;
233
+ else {
234
+ const keyIdx = body.indexOf(COMMA_AUDITSTREAM_PREFIX);
235
+ if (keyIdx === -1) return null;
236
+ valueStart = keyIdx + 14;
237
+ }
238
+ const quoteIdx = body.indexOf("'", valueStart);
239
+ if (quoteIdx === -1) return null;
240
+ return body.slice(valueStart, quoteIdx);
241
+ }
242
+ /**
243
+ * Validates `scope` against Auditstream Specification 0.1.0, serializes it into canonical
244
+ * compact UTF-8 JSON (key order `type`, `id`, `onBehalfOf`, `tenant`, `context`), and
245
+ * returns the RFC 4648 unpadded base64url representation suitable for `/*auditstream='...'*\/`.
246
+ *
247
+ * Uses `TextEncoder` and a self-contained base64url encoder with no `Buffer` dependency so
248
+ * it runs cleanly on Node.js, Bun, Deno, and Cloudflare Workers (`nodejs_als` only).
249
+ *
250
+ * @throws {@link AuditstreamError} if the actor/context is invalid or exceeds 512 UTF-8 bytes.
251
+ */
252
+ function encodeScope(scope) {
253
+ const cached = getCachedScopePayload(scope);
254
+ if (cached !== void 0) return getOrEncodeCached(cached);
255
+ const { bytes } = serializeCanonicalPayload(scope);
256
+ return encodeBase64UrlUnpadded(bytes);
257
+ }
258
+ /**
259
+ * Validates `scope` against Auditstream Specification 0.1.0 and returns the canonical
260
+ * compact UTF-8 JSON string for `SELECT set_config('auditstream.actor', $1, true)`.
261
+ *
262
+ * @throws {@link AuditstreamError} if the actor/context is invalid or exceeds 512 UTF-8 bytes.
263
+ */
264
+ function setConfigValue(scope) {
265
+ const cached = getCachedScopePayload(scope);
266
+ if (cached !== void 0) return cached.json;
267
+ const { json } = serializeCanonicalPayload(scope);
268
+ return json;
269
+ }
270
+ /**
271
+ * Returns `true` if `sql` already ends with a trailing comment containing an `auditstream`
272
+ * sqlcommenter key (with optional trailing ASCII whitespace or semicolons).
273
+ */
274
+ function isTagged(sql) {
275
+ const body = extractTrailingCommentBody(sql);
276
+ if (body === null) return false;
277
+ return extractAuditstreamTagValue(body) !== null;
278
+ }
279
+ /**
280
+ * Appends ` /*auditstream='<base64url>'*\/` to the end of `sql` for the active or supplied
281
+ * {@link AuditScope}.
282
+ *
283
+ * - Defaults `scope` to `audit.current()`.
284
+ * - Returns `sql` unchanged when no scope is active or when `sql` is already tagged.
285
+ * - Never tags a statement twice; appends after any existing SQL comments.
286
+ * - Throws {@link AuditstreamError} before building any SQL text when the scope is invalid
287
+ * or exceeds 512 UTF-8 bytes.
288
+ */
289
+ function tagSql(sql, scope = audit$1.current()) {
290
+ if (scope === void 0) return sql;
291
+ if (isTagged(sql)) return sql;
292
+ const cached = getCachedScopePayload(scope);
293
+ if (cached !== void 0) {
294
+ if (cached.commentSuffix === void 0) cached.commentSuffix = ` /*auditstream='${getOrEncodeCached(cached)}'*/`;
295
+ return `${sql}${cached.commentSuffix}`;
296
+ }
297
+ return `${sql} /*auditstream='${encodeScope(scope)}'*/`;
298
+ }
299
+ /**
300
+ * Decodes a trailing `/*auditstream='...'*\/` SQL comment from `sql` following the exact
301
+ * extraction and validation rules in `spec/transport.md`.
302
+ *
303
+ * - Returns `{ actor: null, context: null, actorSource: null }` when no trailing comment
304
+ * or no `auditstream` key is present.
305
+ * - Returns `{ actor: null, context: null, actorSource: "invalid" }` when an `auditstream`
306
+ * key is present but malformed, oversized (over 512 UTF-8 bytes or 683 chars), padded,
307
+ * invalid UTF-8, non-JSON, or violates the `spec/actor.md` actor/context schema
308
+ * (including the 5-value `type` enum, non-empty `id`/`tenant`, depth-1 `onBehalfOf`,
309
+ * and object `context` with non-empty known fields).
310
+ * - Preserves unknown additive keys in `actor`, `onBehalfOf`, and `context`.
311
+ * - Never throws on malformed input.
312
+ */
313
+ function decodeScope(sql) {
314
+ const body = extractTrailingCommentBody(sql);
315
+ if (body === null) return {
316
+ actor: null,
317
+ context: null,
318
+ actorSource: null
319
+ };
320
+ const rawValue = extractAuditstreamTagValue(body);
321
+ if (rawValue === null) return {
322
+ actor: null,
323
+ context: null,
324
+ actorSource: null
325
+ };
326
+ const bytes = decodeBase64UrlUnpadded(rawValue);
327
+ if (bytes === null || bytes.byteLength > 512) return {
328
+ actor: null,
329
+ context: null,
330
+ actorSource: "invalid"
331
+ };
332
+ let text;
333
+ try {
334
+ text = utf8Decoder$1.decode(bytes);
335
+ } catch {
336
+ return {
337
+ actor: null,
338
+ context: null,
339
+ actorSource: "invalid"
340
+ };
341
+ }
342
+ let parsed;
343
+ try {
344
+ parsed = JSON.parse(text);
345
+ } catch {
346
+ return {
347
+ actor: null,
348
+ context: null,
349
+ actorSource: "invalid"
350
+ };
351
+ }
352
+ if (!isValidActorObject(parsed)) return {
353
+ actor: null,
354
+ context: null,
355
+ actorSource: "invalid"
356
+ };
357
+ const parsedObj = parsed;
358
+ let context = null;
359
+ if (Object.hasOwn(parsedObj, "context")) {
360
+ if (!isValidContextObject(parsedObj.context)) return {
361
+ actor: null,
362
+ context: null,
363
+ actorSource: "invalid"
364
+ };
365
+ context = parsedObj.context;
366
+ }
367
+ const actor = {};
368
+ for (const [key, value] of Object.entries(parsedObj)) {
369
+ if (key === "context") continue;
370
+ actor[key] = value;
371
+ }
372
+ return {
373
+ actor,
374
+ context,
375
+ actorSource: "comment"
376
+ };
377
+ }
378
+ // src/history.ts
379
+ /**
380
+ * Auditstream history schema version supported by Specification 0.1.0.
381
+ */
382
+ const SUPPORTED_SCHEMA_VERSION = 1;
383
+ /**
384
+ * Default row limit applied by `audit.history()` when `limit` is omitted.
385
+ */
386
+ const DEFAULT_HISTORY_LIMIT = 50;
387
+ /**
388
+ * Maximum row limit accepted by `audit.history()`.
389
+ */
390
+ const MAX_HISTORY_LIMIT = 1e3;
391
+ /** Internal schema identifier validation pattern shared with `query.ts`. */
392
+ const VALID_SCHEMA_PATTERN = /^[a-z_][a-z0-9_]*$/;
393
+ const UUID_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
394
+ const RFC3339_UTC_MICROS_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
395
+ const VALID_ACTOR_SOURCES = /* @__PURE__ */ new Set([
396
+ "set_config",
397
+ "comment",
398
+ "jwt",
399
+ "invalid"
400
+ ]);
401
+ const VALID_SOURCES = /* @__PURE__ */ new Set(["db", "app"]);
402
+ /** Internal SQL projection list for the 18 normative history columns shared with `query.ts`. */
403
+ const HISTORY_SELECT_COLUMNS = "id::text AS id, event_id::text AS event_id, pg_catalog.to_char(occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS occurred_at, xact_id::text AS xact_id, source, schema_name, table_name, table_oid, op, record_id, before, after, changed, actor, context, actor_source, db_user, schema_version";
404
+ /** Internal plain-object check shared with `query.ts`. */
405
+ function isPlainObject$1(value) {
406
+ return typeof value === "object" && value !== null && !Array.isArray(value);
407
+ }
408
+ /**
409
+ * Normalizes a JSON decimal literal to `sign|digits|exp` so we can detect whether converting
410
+ * the literal to an IEEE-754 binary64 `number` lost precision.
411
+ */
412
+ function canonicalDecimalKey(raw) {
413
+ const s = raw.trim();
414
+ const negative = s.startsWith("-");
415
+ const unsigned = negative ? s.slice(1) : s.startsWith("+") ? s.slice(1) : s;
416
+ const eIdx = unsigned.search(/[eE]/);
417
+ const mantissa = eIdx >= 0 ? unsigned.slice(0, eIdx) : unsigned;
418
+ const explicitExp = eIdx >= 0 ? Number.parseInt(unsigned.slice(eIdx + 1), 10) : 0;
419
+ if (!Number.isFinite(explicitExp)) return null;
420
+ const dotIdx = mantissa.indexOf(".");
421
+ const intPart = dotIdx >= 0 ? mantissa.slice(0, dotIdx) : mantissa;
422
+ const fracPart = dotIdx >= 0 ? mantissa.slice(dotIdx + 1) : "";
423
+ const combined = intPart + fracPart;
424
+ if (!/^\d+$/.test(combined)) return null;
425
+ const firstNonZero = combined.search(/[1-9]/);
426
+ if (firstNonZero < 0) return "0|0";
427
+ let lastNonZero = combined.length - 1;
428
+ while (lastNonZero > firstNonZero && combined.charAt(lastNonZero) === "0") lastNonZero -= 1;
429
+ const sigDigits = combined.slice(firstNonZero, lastNonZero + 1);
430
+ const trailingZeros = combined.length - 1 - lastNonZero;
431
+ const exp = explicitExp - fracPart.length + trailingZeros;
432
+ return `${negative ? "-" : ""}${sigDigits}e${exp}`;
433
+ }
434
+ function preservesExactNumericValue(value, source) {
435
+ if (!Number.isFinite(value)) return false;
436
+ const srcKey = canonicalDecimalKey(source);
437
+ const valKey = canonicalDecimalKey(String(value));
438
+ return srcKey !== null && valKey !== null && srcKey === valKey;
439
+ }
440
+ function validateNullableString(value, field) {
441
+ if (value === null || value === void 0) return null;
442
+ if (typeof value !== "string" || value.length === 0) throw new AuditstreamError("INVALID_RECORD", `${field} must be a non-empty string or null`);
443
+ return value;
444
+ }
445
+ function validateNullableObject(value, field) {
446
+ if (value === null || value === void 0) return null;
447
+ if (!isPlainObject$1(value)) throw new AuditstreamError("INVALID_RECORD", `${field} must be a JSON object or null`);
448
+ return value;
449
+ }
450
+ function validateNullableStringArray(value, field) {
451
+ if (value === null || value === void 0) return null;
452
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item.length === 0)) throw new AuditstreamError("INVALID_RECORD", `${field} must be an array of non-empty strings or null`);
453
+ return value;
454
+ }
455
+ function validateNullableActor(value) {
456
+ if (value === null || value === void 0) return null;
457
+ if (!isValidActorObject(value)) throw new AuditstreamError("INVALID_RECORD", "actor must be null or conform to Auditstream Specification 0.1.0");
458
+ return value;
459
+ }
460
+ function validateNullableContext(value) {
461
+ if (value === null || value === void 0) return null;
462
+ if (!isValidContextObject(value)) throw new AuditstreamError("INVALID_RECORD", "context must be null or a JSON object with non-empty known fields");
463
+ return value;
464
+ }
465
+ function validateNullableActorSource(value) {
466
+ if (value === null || value === void 0) return null;
467
+ if (typeof value !== "string" || !VALID_ACTOR_SOURCES.has(value)) throw new AuditstreamError("INVALID_RECORD", `actor_source must be one of set_config, comment, jwt, invalid, or null`);
468
+ return value;
469
+ }
470
+ /**
471
+ * Parses and validates a single JSON Lines export record against Auditstream Specification 0.1.0
472
+ * (`spec/export.md` and `spec/schemas/event.schema.json`).
473
+ *
474
+ * - Validates every required field (`event_id`, `occurred_at`, `source`, `op`, `db_user`,
475
+ * `schema_version`) and requires `schema_version === 1`. Throws {@link AuditstreamError}
476
+ * (`INVALID_RECORD`) on malformed JSON, missing fields, invalid types, or unsupported
477
+ * `schema_version`.
478
+ * - Ignores unknown additive fields for forward compatibility.
479
+ * - **Arbitrary-precision `numeric` preservation:** uses ES2025 `JSON.parse` reviver source text
480
+ * access (`context.source`) so PostgreSQL `numeric` values that would lose precision in
481
+ * IEEE-754 binary64 (such as 30-digit decimals or integers beyond `Number.MAX_SAFE_INTEGER`)
482
+ * are returned verbatim as strings rather than rounded doubles.
483
+ * - **Runtime support for `context.source`:** supported on Node.js 22.12+ (all supported Node
484
+ * versions), Deno 2+, Bun 1.2+, and Cloudflare Workers (V8 12.4+). Runtimes without
485
+ * `JSON.parse` source text access fall back to standard JavaScript `number` values.
486
+ */
487
+ function parseExportRecord(line) {
488
+ if (typeof line !== "string" || line.trim().length === 0) throw new AuditstreamError("INVALID_RECORD", "export record line must be a non-empty string");
489
+ let parsed;
490
+ try {
491
+ parsed = (0, JSON.parse)(line, (_key, value, context) => {
492
+ if (typeof value === "number" && context !== void 0 && typeof context.source === "string" && !preservesExactNumericValue(value, context.source)) return context.source;
493
+ return value;
494
+ });
495
+ } catch (err) {
496
+ const detail = err instanceof Error ? err.message : String(err);
497
+ throw new AuditstreamError("INVALID_RECORD", `invalid JSON in export record: ${detail}`);
498
+ }
499
+ if (!isPlainObject$1(parsed)) throw new AuditstreamError("INVALID_RECORD", "export record must be a JSON object");
500
+ if (typeof parsed.event_id !== "string" || !UUID_PATTERN.test(parsed.event_id)) throw new AuditstreamError("INVALID_RECORD", "event_id must be a valid UUID string");
501
+ if (typeof parsed.occurred_at !== "string" || !RFC3339_UTC_MICROS_PATTERN.test(parsed.occurred_at)) throw new AuditstreamError("INVALID_RECORD", "occurred_at must be an RFC 3339 UTC timestamp with 6 fractional digits");
502
+ if (typeof parsed.source !== "string" || !VALID_SOURCES.has(parsed.source)) throw new AuditstreamError("INVALID_RECORD", "source must be \"db\" or \"app\"");
503
+ if (typeof parsed.op !== "string" || parsed.op.length < 1 || parsed.op.length > 64) throw new AuditstreamError("INVALID_RECORD", "op must be a string between 1 and 64 characters");
504
+ if (typeof parsed.db_user !== "string" || parsed.db_user.length === 0) throw new AuditstreamError("INVALID_RECORD", "db_user must be a non-empty string");
505
+ if (parsed.schema_version !== 1) throw new AuditstreamError("INVALID_RECORD", `unsupported schema_version ${String(parsed.schema_version)} (expected 1)`);
506
+ return {
507
+ event_id: parsed.event_id,
508
+ occurred_at: parsed.occurred_at,
509
+ source: parsed.source,
510
+ schema_name: validateNullableString(parsed.schema_name, "schema_name"),
511
+ table_name: validateNullableString(parsed.table_name, "table_name"),
512
+ op: parsed.op,
513
+ record_id: validateNullableObject(parsed.record_id, "record_id"),
514
+ before: validateNullableObject(parsed.before, "before"),
515
+ after: validateNullableObject(parsed.after, "after"),
516
+ changed: validateNullableStringArray(parsed.changed, "changed"),
517
+ actor: validateNullableActor(parsed.actor),
518
+ context: validateNullableContext(parsed.context),
519
+ actor_source: validateNullableActorSource(parsed.actor_source),
520
+ db_user: parsed.db_user,
521
+ schema_version: parsed.schema_version
522
+ };
523
+ }
524
+ function normalizeTimestamp(raw) {
525
+ if (raw instanceof Date) return raw.toISOString();
526
+ if (typeof raw === "string" && raw.length > 0) return raw;
527
+ throw new AuditstreamError("INVALID_RECORD", "history row occurred_at must be a Date or string");
528
+ }
529
+ function normalizeTableOid(raw) {
530
+ if (raw === null || raw === void 0) return null;
531
+ if (typeof raw === "number") return raw;
532
+ if (typeof raw === "string") {
533
+ const num = Number(raw);
534
+ if (Number.isFinite(num)) return num;
535
+ }
536
+ throw new AuditstreamError("INVALID_RECORD", "history row table_oid must be a number or null");
537
+ }
538
+ /** Internal row decoder shared with `query.ts`. */
539
+ function rowToHistoryEntry(row) {
540
+ const id = typeof row.id === "string" ? row.id : typeof row.id === "number" ? String(row.id) : null;
541
+ if (id === null || id.length === 0) throw new AuditstreamError("INVALID_RECORD", "history row missing id");
542
+ const xactId = typeof row.xact_id === "string" ? row.xact_id : typeof row.xact_id === "number" ? String(row.xact_id) : null;
543
+ if (xactId === null || xactId.length === 0) throw new AuditstreamError("INVALID_RECORD", "history row missing xact_id");
544
+ if (typeof row.event_id !== "string" || row.event_id.length === 0) throw new AuditstreamError("INVALID_RECORD", "history row missing event_id");
545
+ if (typeof row.source !== "string" || !VALID_SOURCES.has(row.source)) throw new AuditstreamError("INVALID_RECORD", "history row source must be \"db\" or \"app\"");
546
+ if (typeof row.op !== "string" || row.op.length === 0) throw new AuditstreamError("INVALID_RECORD", "history row missing op");
547
+ if (typeof row.db_user !== "string" || row.db_user.length === 0) throw new AuditstreamError("INVALID_RECORD", "history row missing db_user");
548
+ const schemaVersion = typeof row.schema_version === "number" ? row.schema_version : typeof row.schema_version === "string" ? Number(row.schema_version) : NaN;
549
+ if (!Number.isInteger(schemaVersion) || schemaVersion < 1) throw new AuditstreamError("INVALID_RECORD", "history row has invalid schema_version");
550
+ return {
551
+ id,
552
+ event_id: row.event_id,
553
+ occurred_at: normalizeTimestamp(row.occurred_at),
554
+ xact_id: xactId,
555
+ source: row.source,
556
+ schema_name: validateNullableString(row.schema_name, "schema_name"),
557
+ table_name: validateNullableString(row.table_name, "table_name"),
558
+ table_oid: normalizeTableOid(row.table_oid),
559
+ op: row.op,
560
+ record_id: validateNullableObject(row.record_id, "record_id"),
561
+ before: validateNullableObject(row.before, "before"),
562
+ after: validateNullableObject(row.after, "after"),
563
+ changed: validateNullableStringArray(row.changed, "changed"),
564
+ actor: validateNullableActor(row.actor),
565
+ context: validateNullableContext(row.context),
566
+ actor_source: validateNullableActorSource(row.actor_source),
567
+ db_user: row.db_user,
568
+ schema_version: schemaVersion
569
+ };
570
+ }
571
+ /** Internal shared validation for `exec`, `query`, `schema`, and `limit`. */
572
+ function validateQueryBase(exec, query) {
573
+ if (typeof exec !== "function") throw new AuditstreamError("INVALID_QUERY", "exec must be a function");
574
+ if (!isPlainObject$1(query)) throw new AuditstreamError("INVALID_QUERY", "query must be an object");
575
+ const schema = query.schema ?? "auditstream";
576
+ if (typeof schema !== "string" || !VALID_SCHEMA_PATTERN.test(schema)) throw new AuditstreamError("INVALID_QUERY", `query.schema must match ^[a-z_][a-z0-9_]*$ (got ${JSON.stringify(schema)})`);
577
+ const limit = query.limit ?? 50;
578
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 1e3) throw new AuditstreamError("INVALID_QUERY", `query.limit must be an integer between 1 and ${MAX_HISTORY_LIMIT} (got ${String(limit)})`);
579
+ return {
580
+ schema,
581
+ limit
582
+ };
583
+ }
584
+ /** Internal shared serializer for `query.recordId`. */
585
+ function serializeRecordIdJson(raw) {
586
+ if (!isPlainObject$1(raw)) throw new AuditstreamError("INVALID_QUERY", "query.recordId must be a JSON object");
587
+ try {
588
+ return JSON.stringify(raw);
589
+ } catch (err) {
590
+ const detail = err instanceof Error ? err.message : String(err);
591
+ throw new AuditstreamError("INVALID_QUERY", `query.recordId is not JSON-serializable: ${detail}`);
592
+ }
593
+ }
594
+ /** Internal shared result row extractor accepting both row arrays and `{ rows }` objects. */
595
+ function extractQueryRows(result) {
596
+ return Array.isArray(result) ? result : result.rows;
597
+ }
598
+ /**
599
+ * Reads recorded audit history for a single record from `{schema}.changes`, ordered newest first
600
+ * (`occurred_at DESC, id DESC`).
601
+ *
602
+ * - Sends one parameterized `SELECT` selecting only the 18 normative columns from
603
+ * `spec/history-table.md`, bound as `($1::text, $2::jsonb, $3::int)`.
604
+ * - Validates `schema` against `^[a-z_][a-z0-9_]*$` before sending any SQL and double-quotes
605
+ * the identifier in the query.
606
+ * - Defaults `limit` to `50` and enforces `1..=1000` (values outside `1..=1000` throw
607
+ * {@link AuditstreamError} `INVALID_QUERY`).
608
+ */
609
+ async function readHistory(exec, query) {
610
+ const { schema, limit } = validateQueryBase(exec, query);
611
+ if (typeof query.table !== "string" || query.table.trim().length === 0) throw new AuditstreamError("INVALID_QUERY", "query.table must be a non-empty string");
612
+ const recordIdJson = serializeRecordIdJson(query.recordId);
613
+ return extractQueryRows(await exec(`SELECT ${HISTORY_SELECT_COLUMNS} FROM "${schema}"."changes" WHERE table_name = $1::text AND record_id = $2::jsonb ORDER BY occurred_at DESC, id DESC LIMIT $3::int`, [
614
+ query.table,
615
+ recordIdJson,
616
+ limit
617
+ ])).map(rowToHistoryEntry);
618
+ }
619
+ // src/log.ts
620
+ /**
621
+ * Maximum Unicode code point length of an application event `action` per Auditstream Specification 0.1.0.
622
+ */
623
+ const MAX_ACTION_LENGTH = 64;
624
+ /**
625
+ * Parameterized SQL statement executed by `audit.log()` to record an application event through
626
+ * `auditstream.log_event(text, jsonb, jsonb)`.
627
+ */
628
+ const LOG_EVENT_SQL = "SELECT auditstream.log_event($1::text, $2::jsonb, $3::jsonb)";
629
+ const RESERVED_ACTIONS = /* @__PURE__ */ new Set([
630
+ "INSERT",
631
+ "UPDATE",
632
+ "DELETE",
633
+ "TRUNCATE"
634
+ ]);
635
+ function isPlainObject(value) {
636
+ return typeof value === "object" && value !== null && !Array.isArray(value);
637
+ }
638
+ function validateAction(raw) {
639
+ if (typeof raw !== "string") throw new AuditstreamError("INVALID_EVENT", "event.action must be a string");
640
+ if (raw.trim().length < 1) throw new AuditstreamError("INVALID_EVENT", "event.action must have trimmed length of at least 1 character");
641
+ const codePointLength = [...raw].length;
642
+ if (codePointLength > 64) throw new AuditstreamError("INVALID_EVENT", `event.action is ${codePointLength} characters, exceeding the 64-character limit`);
643
+ if (RESERVED_ACTIONS.has(raw.toUpperCase()) || RESERVED_ACTIONS.has(raw.trim().toUpperCase())) throw new AuditstreamError("INVALID_EVENT", `event.action must not be one of INSERT, UPDATE, DELETE, or TRUNCATE (got ${JSON.stringify(raw)})`);
644
+ return raw;
645
+ }
646
+ function serializeOptionalJsonObject(value, field) {
647
+ if (value === void 0 || value === null) return null;
648
+ if (!isPlainObject(value)) throw new AuditstreamError("INVALID_EVENT", `${field} must be a JSON object or null`);
649
+ let serialized;
650
+ try {
651
+ serialized = JSON.stringify(value);
652
+ } catch (err) {
653
+ const detail = err instanceof Error ? err.message : String(err);
654
+ throw new AuditstreamError("INVALID_EVENT", `${field} is not JSON-serializable: ${detail}`);
655
+ }
656
+ if (typeof serialized !== "string" || !serialized.startsWith("{")) throw new AuditstreamError("INVALID_EVENT", `${field} must serialize to a JSON object`);
657
+ return serialized;
658
+ }
659
+ function buildLogValues(event) {
660
+ if (!isPlainObject(event)) throw new AuditstreamError("INVALID_EVENT", "event must be a JSON object");
661
+ return [
662
+ validateAction(event.action),
663
+ serializeOptionalJsonObject(event.target, "event.target"),
664
+ serializeOptionalJsonObject(event.data, "event.data")
665
+ ];
666
+ }
667
+ /**
668
+ * Validates `event` against Auditstream Specification 0.1.0 and executes
669
+ * `SELECT auditstream.log_event($1::text, $2::jsonb, $3::jsonb)` through `exec`
670
+ * inside the caller's active `AsyncLocalStorage` actor scope.
671
+ *
672
+ * @throws {@link AuditstreamError} if `exec` is not a function or `event` violates Specification 0.1.0.
673
+ */
674
+ async function logEvent(exec, event) {
675
+ if (typeof exec !== "function") throw new AuditstreamError("INVALID_EVENT", "exec must be a function");
676
+ const values = buildLogValues(event);
677
+ await exec(LOG_EVENT_SQL, values);
678
+ }
679
+ // src/query.ts
680
+ /**
681
+ * Maximum number of `op` entries accepted in a single `audit.query()` `op` array filter.
682
+ */
683
+ const MAX_QUERY_OPS = 20;
684
+ const MAX_CURSOR_CHARS = 256;
685
+ const CURSOR_VERSION = 1;
686
+ const CURSOR_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{1,6}Z$/;
687
+ const BIGINT_DECIMAL_PATTERN = /^-?\d+$/;
688
+ const ISO_BOUND_PATTERN = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|[+-]\d{2}:\d{2}))?$/;
689
+ const utf8Encoder = new TextEncoder();
690
+ const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
691
+ function encodeCursor(occurredAt, id) {
692
+ const payload = JSON.stringify({
693
+ v: CURSOR_VERSION,
694
+ t: occurredAt,
695
+ i: id
696
+ });
697
+ return encodeBase64UrlUnpadded(utf8Encoder.encode(payload));
698
+ }
699
+ function decodeCursor(raw) {
700
+ if (typeof raw !== "string" || raw.length === 0) throw new AuditstreamError("INVALID_QUERY", "query.cursor must be a non-empty string");
701
+ const bytes = decodeBase64UrlUnpadded(raw, MAX_CURSOR_CHARS);
702
+ if (bytes === null) throw new AuditstreamError("INVALID_QUERY", "query.cursor is not a valid cursor token");
703
+ let parsed;
704
+ try {
705
+ parsed = JSON.parse(utf8Decoder.decode(bytes));
706
+ } catch {
707
+ throw new AuditstreamError("INVALID_QUERY", "query.cursor is not a valid cursor token");
708
+ }
709
+ if (!isPlainObject$1(parsed) || parsed.v !== CURSOR_VERSION || typeof parsed.t !== "string" || !CURSOR_TIMESTAMP_PATTERN.test(parsed.t) || typeof parsed.i !== "string" || !BIGINT_DECIMAL_PATTERN.test(parsed.i)) throw new AuditstreamError("INVALID_QUERY", "query.cursor payload is invalid");
710
+ return {
711
+ occurredAt: parsed.t,
712
+ id: parsed.i
713
+ };
714
+ }
715
+ function validateCalendarDate(year, month, day) {
716
+ const check = new Date(Date.UTC(year, month - 1, day));
717
+ return check.getUTCFullYear() === year && check.getUTCMonth() === month - 1 && check.getUTCDate() === day;
718
+ }
719
+ function parseTimestampBound(raw, field) {
720
+ if (raw instanceof Date) {
721
+ const ms = raw.getTime();
722
+ if (Number.isNaN(ms)) throw new AuditstreamError("INVALID_QUERY", `${field} must be a valid Date`);
723
+ return {
724
+ sqlValue: raw.toISOString(),
725
+ epochMicros: BigInt(ms) * 1000n
726
+ };
727
+ }
728
+ if (typeof raw !== "string" || raw.trim().length === 0) throw new AuditstreamError("INVALID_QUERY", `${field} must be a valid Date or RFC 3339 timestamp string`);
729
+ const match = ISO_BOUND_PATTERN.exec(raw);
730
+ if (match === null) throw new AuditstreamError("INVALID_QUERY", `${field} must be an RFC 3339 timestamp or YYYY-MM-DD UTC date`);
731
+ if (!validateCalendarDate(Number(match[1]), Number(match[2]), Number(match[3]))) throw new AuditstreamError("INVALID_QUERY", `${field} contains an invalid calendar date`);
732
+ const hourStr = match[4];
733
+ if (hourStr === void 0) {
734
+ const utcDate = `${match[1]}-${match[2]}-${match[3]}T00:00:00Z`;
735
+ return {
736
+ sqlValue: utcDate,
737
+ epochMicros: BigInt(Date.parse(utcDate)) * 1000n
738
+ };
739
+ }
740
+ const minuteStr = match[5] ?? "00";
741
+ const secondStr = match[6] ?? "00";
742
+ const fracStr = match[7] ?? "";
743
+ const tzStr = match[8] ?? "Z";
744
+ const wholeSecIso = `${match[1]}-${match[2]}-${match[3]}T${hourStr}:${minuteStr}:${secondStr}${tzStr}`;
745
+ const wholeSecMs = Date.parse(wholeSecIso);
746
+ if (Number.isNaN(wholeSecMs)) throw new AuditstreamError("INVALID_QUERY", `${field} is not a valid timestamp`);
747
+ const fracMicros = BigInt(fracStr.padEnd(6, "0"));
748
+ return {
749
+ sqlValue: raw,
750
+ epochMicros: BigInt(wholeSecMs) * 1000n + fracMicros
751
+ };
752
+ }
753
+ function validateFilterString(value, field) {
754
+ if (typeof value !== "string" || value.trim().length === 0) throw new AuditstreamError("INVALID_QUERY", `${field} must be a non-empty string`);
755
+ return value;
756
+ }
757
+ function validateOps(raw) {
758
+ if (typeof raw === "string") return [validateFilterString(raw, "query.op")];
759
+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > 20) throw new AuditstreamError("INVALID_QUERY", `query.op must be a non-empty string or an array of 1 to 20 non-empty strings`);
760
+ return raw.map((item) => validateFilterString(item, "query.op[]"));
761
+ }
762
+ function pushOpPredicates(ops, predicates, bind) {
763
+ if (ops.length === 1) {
764
+ const first = ops[0] ?? "";
765
+ predicates.push(`op = ${bind(first)}::text`);
766
+ return;
767
+ }
768
+ const placeholders = ops.map((op) => `${bind(op)}::text`).join(", ");
769
+ predicates.push(`op IN (${placeholders})`);
770
+ }
771
+ function pushTimeAndCursorPredicates(query, predicates, bind) {
772
+ const since = query.since !== void 0 ? parseTimestampBound(query.since, "query.since") : void 0;
773
+ const until = query.until !== void 0 ? parseTimestampBound(query.until, "query.until") : void 0;
774
+ if (since !== void 0 && until !== void 0 && since.epochMicros >= until.epochMicros) throw new AuditstreamError("INVALID_QUERY", "query.until must be strictly after query.since");
775
+ if (since !== void 0) predicates.push(`occurred_at >= ${bind(since.sqlValue)}::timestamptz`);
776
+ if (until !== void 0) predicates.push(`occurred_at < ${bind(until.sqlValue)}::timestamptz`);
777
+ if (query.cursor !== void 0) {
778
+ const cur = decodeCursor(query.cursor);
779
+ const tsParam = bind(cur.occurredAt);
780
+ const idParam = bind(cur.id);
781
+ predicates.push(`occurred_at <= ${tsParam}::timestamptz AND (occurred_at, id) < (${tsParam}::timestamptz, ${idParam}::bigint)`);
782
+ }
783
+ }
784
+ function buildPredicates(query, values) {
785
+ const predicates = [];
786
+ const bind = (value) => {
787
+ values.push(value);
788
+ return `$${values.length}`;
789
+ };
790
+ if (query.schemaName !== void 0) predicates.push(`schema_name = ${bind(validateFilterString(query.schemaName, "query.schemaName"))}::text`);
791
+ if (query.table !== void 0) predicates.push(`table_name = ${bind(validateFilterString(query.table, "query.table"))}::text`);
792
+ if (query.recordId !== void 0) predicates.push(`record_id = ${bind(serializeRecordIdJson(query.recordId))}::jsonb`);
793
+ if (query.actor !== void 0) {
794
+ const p = bind(validateFilterString(query.actor, "query.actor"));
795
+ predicates.push(`(actor->>'id' = ${p}::text OR actor->'onBehalfOf'->>'id' = ${p}::text)`);
796
+ }
797
+ if (query.tenant !== void 0) {
798
+ const p = bind(validateFilterString(query.tenant, "query.tenant"));
799
+ predicates.push(`(actor->>'tenant' = ${p}::text OR actor->'onBehalfOf'->>'tenant' = ${p}::text)`);
800
+ }
801
+ if (query.source !== void 0) {
802
+ if (query.source !== "db" && query.source !== "app") throw new AuditstreamError("INVALID_QUERY", "query.source must be \"db\" or \"app\"");
803
+ predicates.push(`source = ${bind(query.source)}::text`);
804
+ }
805
+ if (query.op !== void 0) pushOpPredicates(validateOps(query.op), predicates, bind);
806
+ if (query.opPrefix !== void 0) {
807
+ const p = bind(validateFilterString(query.opPrefix, "query.opPrefix"));
808
+ predicates.push(`pg_catalog.starts_with(op, ${p}::text)`);
809
+ }
810
+ pushTimeAndCursorPredicates(query, predicates, bind);
811
+ return predicates;
812
+ }
813
+ /**
814
+ * Queries `{schema}.changes` with validated filters and lossless microsecond keyset pagination,
815
+ * ordered newest first (`occurred_at DESC, id DESC`).
816
+ *
817
+ * - Supports both database trigger rows (`source: "db"`) and application events logged via
818
+ * `audit.log()` (`source: "app"`, `table_name IS NULL`).
819
+ * - Requires at least one bounding filter (`recordId`, `since`, or `until`) unless
820
+ * `unbounded: true` is passed explicitly.
821
+ * - Fetches `limit + 1` rows (no `count(*)`) and emits `occurred_at <= $ts::timestamptz AND
822
+ * (occurred_at, id) < ($ts::timestamptz, $id::bigint)` so PostgreSQL prunes monthly partitions.
823
+ * - **Backend-only API:** Enforce authentication and tenant authorization on the server, and
824
+ * project {@link HistoryEntry} rows to an allowlisted client DTO before returning data to browsers.
825
+ */
826
+ async function queryHistory(exec, query) {
827
+ const { schema, limit } = validateQueryBase(exec, query);
828
+ if (query.unbounded !== void 0 && typeof query.unbounded !== "boolean") throw new AuditstreamError("INVALID_QUERY", "query.unbounded must be a boolean");
829
+ if (!(query.recordId !== void 0 || query.since !== void 0 || query.until !== void 0) && query.unbounded !== true) throw new AuditstreamError("INVALID_QUERY", "audit.query() requires at least one bounding filter (recordId, since, or until) or explicit unbounded: true");
830
+ const values = [];
831
+ const predicates = buildPredicates(query, values);
832
+ values.push(limit + 1);
833
+ const limitParam = `$${values.length}`;
834
+ const whereClause = predicates.length > 0 ? ` WHERE ${predicates.join(" AND ")}` : "";
835
+ const rows = extractQueryRows(await exec(`SELECT ${HISTORY_SELECT_COLUMNS} FROM "${schema}"."changes"${whereClause} ORDER BY occurred_at DESC, id DESC LIMIT ${limitParam}::int`, values));
836
+ const hasMore = rows.length > limit;
837
+ const entries = (hasMore ? rows.slice(0, limit) : rows).map(rowToHistoryEntry);
838
+ const last = entries[entries.length - 1];
839
+ return {
840
+ entries,
841
+ nextCursor: hasMore && last !== void 0 ? encodeCursor(last.occurred_at, last.id) : null,
842
+ hasMore
843
+ };
844
+ }
1
845
  // src/index.ts
2
846
  /** Package identifier exported by the workspace skeleton. */
3
847
  const PACKAGE_NAME = "@auditstream/node";
4
- export { PACKAGE_NAME };
848
+ /**
849
+ * Shared Auditstream runtime entry point providing `audit.as()`, `audit.current()`,
850
+ * `audit.log()`, `audit.history()`, and `audit.query()`.
851
+ */
852
+ const audit = Object.freeze({
853
+ as: audit$1.as,
854
+ current: audit$1.current,
855
+ log: logEvent,
856
+ history: readHistory,
857
+ query: queryHistory
858
+ });
859
+ export { AuditstreamError, DEFAULT_HISTORY_LIMIT, LOG_EVENT_SQL, MAX_ACTION_LENGTH, MAX_ENCODED_COMMENT_CHARS, MAX_HISTORY_LIMIT, MAX_PAYLOAD_BYTES, MAX_QUERY_OPS, PACKAGE_NAME, SUPPORTED_SCHEMA_VERSION, audit, decodeScope, encodeScope, isTagged, parseExportRecord, setConfigValue, tagSql };