@actuarial-ts/compliance 0.6.0 → 0.7.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.
Files changed (83) hide show
  1. package/README.md +19 -9
  2. package/dist/bundle.d.ts +1 -1
  3. package/dist/bundle.d.ts.map +1 -1
  4. package/dist/bundle.js +163 -21
  5. package/dist/bundle.js.map +1 -1
  6. package/dist/diagnosticArtifactStream.d.ts +30 -0
  7. package/dist/diagnosticArtifactStream.d.ts.map +1 -0
  8. package/dist/diagnosticArtifactStream.js +128 -0
  9. package/dist/diagnosticArtifactStream.js.map +1 -0
  10. package/dist/diagnosticByteSource.d.ts +10 -0
  11. package/dist/diagnosticByteSource.d.ts.map +1 -0
  12. package/dist/diagnosticByteSource.js +70 -0
  13. package/dist/diagnosticByteSource.js.map +1 -0
  14. package/dist/diagnosticByteView.d.ts +3 -0
  15. package/dist/diagnosticByteView.d.ts.map +1 -0
  16. package/dist/diagnosticByteView.js +27 -0
  17. package/dist/diagnosticByteView.js.map +1 -0
  18. package/dist/diagnosticCompactRun.d.ts +43 -0
  19. package/dist/diagnosticCompactRun.d.ts.map +1 -0
  20. package/dist/diagnosticCompactRun.js +253 -0
  21. package/dist/diagnosticCompactRun.js.map +1 -0
  22. package/dist/diagnosticReplayFrames.d.ts +10 -0
  23. package/dist/diagnosticReplayFrames.d.ts.map +1 -0
  24. package/dist/diagnosticReplayFrames.js +99 -0
  25. package/dist/diagnosticReplayFrames.js.map +1 -0
  26. package/dist/diagnosticReplayProtocol.d.ts +17 -0
  27. package/dist/diagnosticReplayProtocol.d.ts.map +1 -0
  28. package/dist/diagnosticReplayProtocol.js +98 -0
  29. package/dist/diagnosticReplayProtocol.js.map +1 -0
  30. package/dist/diagnosticReplayReader.d.ts +41 -0
  31. package/dist/diagnosticReplayReader.d.ts.map +1 -0
  32. package/dist/diagnosticReplayReader.js +346 -0
  33. package/dist/diagnosticReplayReader.js.map +1 -0
  34. package/dist/diagnosticReplayValue.d.ts +34 -0
  35. package/dist/diagnosticReplayValue.d.ts.map +1 -0
  36. package/dist/diagnosticReplayValue.js +269 -0
  37. package/dist/diagnosticReplayValue.js.map +1 -0
  38. package/dist/diagnosticReplayWriter.d.ts +25 -0
  39. package/dist/diagnosticReplayWriter.d.ts.map +1 -0
  40. package/dist/diagnosticReplayWriter.js +148 -0
  41. package/dist/diagnosticReplayWriter.js.map +1 -0
  42. package/dist/diagnosticRun.d.ts +52 -29
  43. package/dist/diagnosticRun.d.ts.map +1 -1
  44. package/dist/diagnosticRun.js +564 -174
  45. package/dist/diagnosticRun.js.map +1 -1
  46. package/dist/diagnosticRunEvidence.d.ts +18 -0
  47. package/dist/diagnosticRunEvidence.d.ts.map +1 -0
  48. package/dist/diagnosticRunEvidence.js +195 -0
  49. package/dist/diagnosticRunEvidence.js.map +1 -0
  50. package/dist/index.d.ts +4 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +4 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/ledger.d.ts.map +1 -1
  55. package/dist/ledger.js +47 -6
  56. package/dist/ledger.js.map +1 -1
  57. package/dist/metadata.d.ts.map +1 -1
  58. package/dist/metadata.js +27 -3
  59. package/dist/metadata.js.map +1 -1
  60. package/dist/sha256Stream.d.ts +6 -0
  61. package/dist/sha256Stream.d.ts.map +1 -0
  62. package/dist/sha256Stream.js +103 -0
  63. package/dist/sha256Stream.js.map +1 -0
  64. package/dist/version.d.ts +1 -1
  65. package/dist/version.js +1 -1
  66. package/package.json +6 -5
  67. package/src/bundle.ts +272 -32
  68. package/src/diagnosticArtifactStream.ts +148 -0
  69. package/src/diagnosticByteSource.ts +82 -0
  70. package/src/diagnosticByteView.ts +27 -0
  71. package/src/diagnosticCompactRun.ts +462 -0
  72. package/src/diagnosticReplayFrames.ts +99 -0
  73. package/src/diagnosticReplayProtocol.ts +99 -0
  74. package/src/diagnosticReplayReader.ts +428 -0
  75. package/src/diagnosticReplayValue.ts +269 -0
  76. package/src/diagnosticReplayWriter.ts +190 -0
  77. package/src/diagnosticRun.ts +1030 -93
  78. package/src/diagnosticRunEvidence.ts +391 -0
  79. package/src/index.ts +10 -0
  80. package/src/ledger.ts +59 -8
  81. package/src/metadata.ts +48 -7
  82. package/src/sha256Stream.ts +108 -0
  83. package/src/version.ts +1 -1
@@ -0,0 +1,148 @@
1
+ import {
2
+ diagnosticJsonPreflight,
3
+ isDiagnosticPlainRecord,
4
+ isDiagnosticToken,
5
+ } from "@actuarial-ts/core";
6
+ import { ComplianceError } from "./errors.js";
7
+ import type { DiagnosticArtifactDigest } from "./diagnosticRun.js";
8
+ import { createSha256 } from "./sha256Stream.js";
9
+ import { diagnosticByteView } from "./diagnosticByteView.js";
10
+ import { consumeDiagnosticByteSource } from "./diagnosticByteSource.js";
11
+
12
+ export interface DiagnosticArtifactStreamMetadata {
13
+ readonly id: string;
14
+ readonly scope: "input" | "preparation";
15
+ /** Optional completeness check; no digest handle is issued on truncation. */
16
+ readonly expectedByteLength?: number;
17
+ /** Caller-selected resource ceiling, at most Number.MAX_SAFE_INTEGER. */
18
+ readonly maximumByteLength?: number;
19
+ }
20
+ declare const computedArtifactDigestBrand: unique symbol;
21
+ export type ComputedDiagnosticArtifactDigest = Extract<
22
+ DiagnosticArtifactDigest,
23
+ { assurance: "sdk-computed" }
24
+ > & { readonly [computedArtifactDigestBrand]: true };
25
+
26
+ const computed = new WeakSet<object>();
27
+ const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")!.get!;
28
+ const throwIfAborted = AbortSignal.prototype.throwIfAborted;
29
+ const COPY_SIZE = 65_536;
30
+
31
+ function invalid(message: string, path = "$"): never {
32
+ throw new ComplianceError("BAD_DIAGNOSTIC_RUN", message, path);
33
+ }
34
+
35
+ function ownedMetadata(value: DiagnosticArtifactStreamMetadata) {
36
+ // Read descriptors once. A Proxy must not pass validation with one property
37
+ // value and supply a different value when the final digest is assembled.
38
+ if (!isDiagnosticPlainRecord(value)) invalid("Artifact metadata must be a plain object");
39
+ const snapshot = Object.create(null) as Record<string, unknown>;
40
+ for (const key of Reflect.ownKeys(value)) {
41
+ if (typeof key !== "string") invalid("Artifact metadata cannot have symbol keys");
42
+ const field = Object.getOwnPropertyDescriptor(value, key);
43
+ if (!field || !("value" in field) || !field.enumerable)
44
+ invalid("Artifact metadata must contain enumerable data properties", `$.${key}`);
45
+ snapshot[key] = field.value;
46
+ }
47
+ value = snapshot as unknown as DiagnosticArtifactStreamMetadata;
48
+ const issues = diagnosticJsonPreflight(value, "input");
49
+ if (issues.length) invalid(issues[0]!.message, issues[0]!.path);
50
+ if (!isDiagnosticPlainRecord(value)) invalid("Artifact metadata must be a plain object");
51
+ for (const key of Object.keys(value))
52
+ if (!["id", "scope", "expectedByteLength", "maximumByteLength"].includes(key))
53
+ invalid("Unknown artifact metadata key", `$.${key}`);
54
+ if (!isDiagnosticToken(value.id)) invalid("Artifact ID must be a valid token", "$.id");
55
+ if (value.scope !== "input" && value.scope !== "preparation")
56
+ invalid("Artifact scope must be input or preparation", "$.scope");
57
+ for (const key of ["expectedByteLength", "maximumByteLength"] as const)
58
+ if (value[key] !== undefined && (!Number.isSafeInteger(value[key]) || value[key]! < 0))
59
+ invalid("Byte length must be a nonnegative safe integer", `$.${key}`);
60
+ const maximumByteLength = value.maximumByteLength ?? Number.MAX_SAFE_INTEGER;
61
+ if (value.expectedByteLength !== undefined && value.expectedByteLength > maximumByteLength)
62
+ invalid("Expected byte length exceeds the resource ceiling", "$.expectedByteLength");
63
+ return {
64
+ id: value.id,
65
+ scope: value.scope,
66
+ expectedByteLength: value.expectedByteLength,
67
+ maximumByteLength,
68
+ };
69
+ }
70
+
71
+ function cancellation(options: { readonly signal?: AbortSignal }): () => void {
72
+ if (!isDiagnosticPlainRecord(options)) invalid("Artifact stream options must be a plain object");
73
+ for (const key of Reflect.ownKeys(options))
74
+ if (key !== "signal") invalid("Unknown artifact stream option");
75
+ const field = Object.getOwnPropertyDescriptor(options, "signal");
76
+ if (field && (!("value" in field) || !field.enumerable))
77
+ invalid("Artifact signal must be supplied as a data property");
78
+ const signal = field?.value;
79
+ if (signal === undefined) return () => {};
80
+ try {
81
+ signalAborted.call(signal);
82
+ } catch {
83
+ invalid("Artifact signal must be an AbortSignal");
84
+ }
85
+ // Capture the genuine signal and intrinsic method before any producer await.
86
+ return () => throwIfAborted.call(signal);
87
+ }
88
+
89
+ /**
90
+ * Hash the bytes actually received, retaining only a bounded chunk copy.
91
+ * The producer owns I/O. A completed handle means SDK-computed content digest,
92
+ * not source authenticity, a signature, or validation of an actuarial run.
93
+ * Shared buffers are refused; bytes are consumed before requesting the next
94
+ * chunk. A changing producer must be checked again against this digest on replay.
95
+ * Cancellation is cooperative between received chunks; the producer should use
96
+ * the same signal to cancel pending I/O. One synchronous chunk is not interrupted.
97
+ */
98
+ export async function digestDiagnosticArtifactChunks(
99
+ metadata: DiagnosticArtifactStreamMetadata,
100
+ chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>,
101
+ options: { readonly signal?: AbortSignal } = {},
102
+ ): Promise<ComputedDiagnosticArtifactDigest> {
103
+ const owned = ownedMetadata(metadata);
104
+ const checkCancellation = cancellation(options);
105
+ checkCancellation();
106
+ const hash = createSha256();
107
+ const copy = new Uint8Array(COPY_SIZE);
108
+ let byteLength = 0;
109
+ try {
110
+ for await (const chunk of consumeDiagnosticByteSource(chunks, checkCancellation)) {
111
+ checkCancellation();
112
+ const view = diagnosticByteView(chunk);
113
+ const size = view.byteLength;
114
+ if (!Number.isSafeInteger(byteLength + size) || byteLength + size > owned.maximumByteLength)
115
+ invalid("Artifact byte length exceeds the resource ceiling", "$.chunks");
116
+ if (owned.expectedByteLength !== undefined && byteLength + size > owned.expectedByteLength)
117
+ invalid("Artifact has more bytes than declared", "$.chunks");
118
+ for (let start = 0; start < size; start += COPY_SIZE) {
119
+ const length = Math.min(COPY_SIZE, size - start);
120
+ copy.set(new Uint8Array(view.buffer, view.byteOffset + start, length));
121
+ hash.update(copy.subarray(0, length));
122
+ }
123
+ byteLength += size;
124
+ }
125
+ checkCancellation();
126
+ if (owned.expectedByteLength !== undefined && byteLength !== owned.expectedByteLength)
127
+ invalid("Artifact ended before its declared byte length", "$.chunks");
128
+ const digest = Object.freeze({
129
+ id: owned.id,
130
+ scope: owned.scope,
131
+ assurance: "sdk-computed" as const,
132
+ algorithm: "sha256" as const,
133
+ value: hash.digest(),
134
+ byteLength,
135
+ }) as ComputedDiagnosticArtifactDigest;
136
+ computed.add(digest);
137
+ return digest;
138
+ } finally {
139
+ copy.fill(0);
140
+ }
141
+ }
142
+
143
+ export function assertComputedDiagnosticArtifactDigest(
144
+ value: unknown,
145
+ ): asserts value is ComputedDiagnosticArtifactDigest {
146
+ if (value === null || typeof value !== "object" || !computed.has(value))
147
+ invalid("Value is not an authentic SDK-computed streamed artifact digest");
148
+ }
@@ -0,0 +1,82 @@
1
+ type DiagnosticByteSource = Iterable<Uint8Array> | AsyncIterable<Uint8Array>;
2
+
3
+ function isObject(value: unknown): value is object {
4
+ return (
5
+ value !== null && (typeof value === "object" || typeof value === "function")
6
+ );
7
+ }
8
+
9
+ /**
10
+ * Own one producer iterator through completion, cancellation or read failure.
11
+ * Unlike a bare for-await loop, a rejected next() also closes the producer.
12
+ * A cleanup failure never replaces the error that caused cleanup. Hosts should
13
+ * pass the same cancellation signal to pending I/O; checks cannot interrupt it.
14
+ */
15
+ export async function* consumeDiagnosticByteSource(
16
+ source: DiagnosticByteSource,
17
+ checkCancellation: () => void = () => {},
18
+ ): AsyncGenerator<Uint8Array> {
19
+ if (!isObject(source))
20
+ throw new TypeError("Diagnostic byte source must be iterable");
21
+ const iterable = source as Partial<
22
+ Iterable<Uint8Array> & AsyncIterable<Uint8Array>
23
+ >;
24
+ const asynchronous = iterable[Symbol.asyncIterator];
25
+ const method = asynchronous ?? iterable[Symbol.iterator];
26
+ if (typeof method !== "function")
27
+ throw new TypeError(
28
+ "Diagnostic byte source must provide an iterator method",
29
+ );
30
+ const iterator: unknown = Reflect.apply(method, source, []);
31
+ if (!isObject(iterator))
32
+ throw new TypeError("Diagnostic byte iterator must be an object");
33
+ const protocol = iterator as { next?: unknown; return?: unknown };
34
+ let completed = false;
35
+ let failed = false;
36
+ try {
37
+ // Capture next once, as the iterator protocol does; never use a producer's
38
+ // potentially overwritten Function.call property.
39
+ const next = protocol.next;
40
+ if (typeof next !== "function")
41
+ throw new TypeError("Diagnostic byte iterator must provide next()");
42
+ for (;;) {
43
+ checkCancellation();
44
+ const result: unknown = await Reflect.apply(next, iterator, []);
45
+ if (!isObject(result))
46
+ throw new TypeError(
47
+ "Diagnostic byte read must return an iterator result",
48
+ );
49
+ const item = result as IteratorResult<Uint8Array>;
50
+ completed = Boolean(item.done);
51
+ checkCancellation();
52
+ if (completed) return;
53
+ // An async generator also observes a rejected value from a synchronous
54
+ // iterator here, so that failure follows the same cleanup path.
55
+ yield item.value;
56
+ }
57
+ } catch (error) {
58
+ failed = true;
59
+ throw error;
60
+ } finally {
61
+ if (!completed) {
62
+ try {
63
+ // Read return only when closing, once, following normal iterator
64
+ // semantics. The generator's finally executes at most once.
65
+ const close = protocol.return;
66
+ if (close !== undefined && close !== null) {
67
+ if (typeof close !== "function")
68
+ throw new TypeError(
69
+ "Diagnostic byte iterator return must be a function",
70
+ );
71
+ const result: unknown = await Reflect.apply(close, iterator, []);
72
+ if (!isObject(result))
73
+ throw new TypeError(
74
+ "Diagnostic byte iterator return must return an iterator result",
75
+ );
76
+ }
77
+ } catch (cleanupError) {
78
+ if (!failed) throw cleanupError;
79
+ }
80
+ }
81
+ }
82
+ }
@@ -0,0 +1,27 @@
1
+ import { ComplianceError } from "./errors.js";
2
+
3
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
4
+ const byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength")!.get!;
5
+ const byteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteOffset")!.get!;
6
+ const bufferOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer")!.get!;
7
+ const arrayBufferLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")!
8
+ .get!;
9
+ const resizable = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "resizable")?.get;
10
+
11
+ /** Borrow a synchronous intrinsic-only view; callers copy before yielding. */
12
+ export function diagnosticByteView(chunk: unknown): Uint8Array<ArrayBuffer> {
13
+ const fail = (message: string): never => {
14
+ throw new ComplianceError("BAD_DIAGNOSTIC_RUN", message, "$.chunks");
15
+ };
16
+ if (!(chunk instanceof Uint8Array) || !ArrayBuffer.isView(chunk))
17
+ fail("Artifact chunks must be Uint8Array values");
18
+ const buffer = bufferOf.call(chunk) as ArrayBuffer;
19
+ try {
20
+ arrayBufferLength.call(buffer);
21
+ } catch {
22
+ fail("Shared artifact buffers cannot provide a stable byte snapshot");
23
+ }
24
+ if (resizable?.call(buffer))
25
+ fail("Resizable artifact buffers cannot provide a stable byte snapshot");
26
+ return new Uint8Array(buffer, byteOffset.call(chunk), byteLength.call(chunk));
27
+ }