@plasius/gpu-shader 0.1.2 → 0.1.4

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.js CHANGED
@@ -43,68 +43,275 @@ function assertImmutableAssetVersion(value) {
43
43
  }
44
44
 
45
45
  // src/canonical-json.ts
46
- function isPlainObject(value) {
47
- const prototype = Object.getPrototypeOf(value);
48
- return prototype === Object.prototype || prototype === null;
46
+ var GPU_CONTRACT_SNAPSHOT_LIMITS = Object.freeze({
47
+ maximumDepth: 64,
48
+ maximumNodes: 262144,
49
+ maximumProperties: 131072,
50
+ maximumElements: 131072,
51
+ maximumArrayLength: 1e5,
52
+ maximumStringBytes: 1024 * 1024,
53
+ maximumAggregateStringBytes: 8 * 1024 * 1024,
54
+ maximumAggregateBytes: 16 * 1024 * 1024,
55
+ maximumInputBytes: 16 * 1024 * 1024
56
+ });
57
+ var QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS = Object.freeze({
58
+ maximumDepth: 96,
59
+ maximumNodes: 4e6,
60
+ maximumProperties: 2e6,
61
+ maximumElements: 2e6,
62
+ maximumArrayLength: 25e4,
63
+ maximumStringBytes: 4 * 1024 * 1024,
64
+ maximumAggregateStringBytes: 128 * 1024 * 1024,
65
+ maximumAggregateBytes: 256 * 1024 * 1024,
66
+ maximumInputBytes: 256 * 1024 * 1024
67
+ });
68
+ var FAILURE_MESSAGES = Object.freeze({
69
+ "aggregate-bytes": "GPU contract snapshot exceeds the aggregate byte limit.",
70
+ "aggregate-string-bytes": "GPU contract snapshot exceeds the aggregate string byte limit.",
71
+ "array-length": "GPU contract snapshot exceeds the single-array element limit.",
72
+ cycle: "GPU contract snapshot contains a circular reference.",
73
+ depth: "GPU contract snapshot exceeds the nesting-depth limit.",
74
+ elements: "GPU contract snapshot exceeds the total element limit.",
75
+ inspection: "GPU contract snapshot rejected unsafe object inspection.",
76
+ nodes: "GPU contract snapshot exceeds the total node limit.",
77
+ "non-finite": "GPU contract snapshot contains a non-finite number.",
78
+ properties: "GPU contract snapshot exceeds the total property limit.",
79
+ shape: "GPU contract snapshot requires plain JSON objects with own enumerable data properties and dense arrays.",
80
+ "string-bytes": "GPU contract snapshot exceeds the individual string byte limit.",
81
+ unicode: "GPU contract snapshot contains an invalid Unicode scalar string or unpaired UTF-16 surrogate.",
82
+ value: "GPU contract snapshot contains undefined or another value that JSON cannot represent."
83
+ });
84
+ var GpuContractSnapshotError = class extends TypeError {
85
+ code;
86
+ constructor(code) {
87
+ super(FAILURE_MESSAGES[code]);
88
+ this.name = "GpuContractSnapshotError";
89
+ this.code = code;
90
+ }
91
+ };
92
+ var TYPED_ARRAY_PROTOTYPE = Reflect.getPrototypeOf(Uint8Array.prototype);
93
+ var TYPED_ARRAY_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(
94
+ TYPED_ARRAY_PROTOTYPE,
95
+ "byteLength"
96
+ )?.get;
97
+ var TYPED_ARRAY_TAG = Reflect.getOwnPropertyDescriptor(
98
+ TYPED_ARRAY_PROTOTYPE,
99
+ Symbol.toStringTag
100
+ )?.get;
101
+ var UINT8_ARRAY_SET = Uint8Array.prototype.set;
102
+ function snapshotUint8Array(value, maximumBytes) {
103
+ if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0) {
104
+ throw new TypeError("GPU contract byte limit must be a non-negative safe integer.");
105
+ }
106
+ let byteLength;
107
+ let tag;
108
+ try {
109
+ if (!TYPED_ARRAY_BYTE_LENGTH || !TYPED_ARRAY_TAG) throw new TypeError();
110
+ byteLength = Reflect.apply(TYPED_ARRAY_BYTE_LENGTH, value, []);
111
+ tag = Reflect.apply(TYPED_ARRAY_TAG, value, []);
112
+ } catch {
113
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
114
+ }
115
+ if (tag !== "Uint8Array" || !Number.isSafeInteger(byteLength) || byteLength > maximumBytes) {
116
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
117
+ }
118
+ const output = new Uint8Array(byteLength);
119
+ try {
120
+ Reflect.apply(UINT8_ARRAY_SET, output, [value]);
121
+ } catch {
122
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
123
+ }
124
+ return output;
125
+ }
126
+ function fail(reason) {
127
+ throw new GpuContractSnapshotError(reason);
128
+ }
129
+ function inspected(operation) {
130
+ try {
131
+ return operation();
132
+ } catch {
133
+ return fail("inspection");
134
+ }
49
135
  }
50
- function assertUnicodeScalarString(value, path) {
136
+ function assertLimit(value, maximum, reason) {
137
+ if (!Number.isSafeInteger(value) || value > maximum) fail(reason);
138
+ }
139
+ function utf8ByteLength(value, maximum) {
140
+ let bytes = 0;
51
141
  for (let index = 0; index < value.length; index += 1) {
52
142
  const code = value.charCodeAt(index);
53
- if (code >= 55296 && code <= 56319) {
143
+ if (code <= 127) bytes += 1;
144
+ else if (code <= 2047) bytes += 2;
145
+ else if (code >= 55296 && code <= 56319) {
54
146
  const next = value.charCodeAt(index + 1);
55
- if (!(next >= 56320 && next <= 57343)) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);
147
+ if (!(next >= 56320 && next <= 57343)) fail("unicode");
148
+ bytes += 4;
56
149
  index += 1;
57
- } else if (code >= 56320 && code <= 57343) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);
150
+ } else if (code >= 56320 && code <= 57343) fail("unicode");
151
+ else bytes += 3;
152
+ if (bytes > maximum) fail("string-bytes");
58
153
  }
154
+ return bytes;
59
155
  }
60
- function canonicalizeGpuContract(value) {
156
+ function quotedJsonByteLength(value, maximum) {
157
+ let raw = 0;
158
+ let quoted = 2;
159
+ for (let index = 0; index < value.length; index += 1) {
160
+ const code = value.charCodeAt(index);
161
+ if (code <= 127) {
162
+ raw += 1;
163
+ if (code <= 31) quoted += code === 8 || code === 9 || code === 10 || code === 12 || code === 13 ? 2 : 6;
164
+ else quoted += code === 34 || code === 92 ? 2 : 1;
165
+ } else if (code <= 2047) {
166
+ raw += 2;
167
+ quoted += 2;
168
+ } else if (code >= 55296 && code <= 56319) {
169
+ const next = value.charCodeAt(index + 1);
170
+ if (!(next >= 56320 && next <= 57343)) fail("unicode");
171
+ raw += 4;
172
+ quoted += 4;
173
+ index += 1;
174
+ } else if (code >= 56320 && code <= 57343) fail("unicode");
175
+ else {
176
+ raw += 3;
177
+ quoted += 3;
178
+ }
179
+ if (raw > maximum) fail("string-bytes");
180
+ }
181
+ return { raw, quoted };
182
+ }
183
+ function assertLimits(limits) {
184
+ for (const value of Object.values(limits)) {
185
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError("GPU contract snapshot limits must be positive safe integers.");
186
+ }
187
+ }
188
+ function snapshotGpuContract(value, limits = GPU_CONTRACT_SNAPSHOT_LIMITS) {
189
+ assertLimits(limits);
61
190
  const ancestors = /* @__PURE__ */ new Set();
62
- const visit = (current, path) => {
63
- if (current === null) return "null";
64
- if (typeof current === "string" || typeof current === "boolean") {
65
- if (typeof current === "string") assertUnicodeScalarString(current, path);
66
- return JSON.stringify(current);
191
+ let nodes = 0;
192
+ let properties = 0;
193
+ let elements = 0;
194
+ let aggregateStringBytes = 0;
195
+ let aggregateBytes = 0;
196
+ const addAggregate = (bytes) => {
197
+ aggregateBytes += bytes;
198
+ assertLimit(aggregateBytes, limits.maximumAggregateBytes, "aggregate-bytes");
199
+ };
200
+ const addString = (text2) => {
201
+ const measured = quotedJsonByteLength(text2, limits.maximumStringBytes);
202
+ aggregateStringBytes += measured.raw;
203
+ assertLimit(aggregateStringBytes, limits.maximumAggregateStringBytes, "aggregate-string-bytes");
204
+ return measured.quoted;
205
+ };
206
+ const visit = (current, depth) => {
207
+ if (depth > limits.maximumDepth) fail("depth");
208
+ nodes += 1;
209
+ assertLimit(nodes, limits.maximumNodes, "nodes");
210
+ if (current === null) {
211
+ addAggregate(4);
212
+ return null;
67
213
  }
68
- if (typeof current === "number") {
69
- if (!Number.isFinite(current)) {
70
- throw new TypeError(`${path} contains a non-finite number.`);
71
- }
72
- return Object.is(current, -0) ? "0" : JSON.stringify(current);
214
+ if (typeof current === "string") {
215
+ addAggregate(addString(current));
216
+ return current;
73
217
  }
74
- if (typeof current !== "object") {
75
- throw new TypeError(`${path} contains a value that JSON cannot represent.`);
218
+ if (typeof current === "boolean") {
219
+ addAggregate(current ? 4 : 5);
220
+ return current;
76
221
  }
77
- if (ancestors.has(current)) {
78
- throw new TypeError(`${path} contains a circular reference.`);
222
+ if (typeof current === "number") {
223
+ if (!Number.isFinite(current)) fail("non-finite");
224
+ const normalized = Object.is(current, -0) ? 0 : current;
225
+ addAggregate(JSON.stringify(normalized).length);
226
+ return normalized;
79
227
  }
228
+ if (typeof current !== "object") fail("value");
229
+ if (ancestors.has(current)) fail("cycle");
230
+ const isArray = inspected(() => Array.isArray(current));
231
+ const prototype = inspected(() => Reflect.getPrototypeOf(current));
232
+ if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) fail("shape");
80
233
  ancestors.add(current);
81
234
  try {
82
- if (Array.isArray(current)) {
83
- return `[${current.map((item, index) => visit(item, `${path}[${index}]`)).join(",")}]`;
235
+ if (isArray) {
236
+ const lengthDescriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, "length"));
237
+ if (!lengthDescriptor || !Object.hasOwn(lengthDescriptor, "value") || lengthDescriptor.enumerable || typeof lengthDescriptor.value !== "number" || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0) fail("shape");
238
+ const length = lengthDescriptor.value;
239
+ assertLimit(length, limits.maximumArrayLength, "array-length");
240
+ elements += length;
241
+ assertLimit(elements, limits.maximumElements, "elements");
242
+ const ownKeys2 = inspected(() => Reflect.ownKeys(current));
243
+ if (ownKeys2.some((key) => typeof key !== "string")) fail("shape");
244
+ if (ownKeys2.length !== length + 1) fail("shape");
245
+ const keySet = new Set(ownKeys2);
246
+ if (!keySet.delete("length")) fail("shape");
247
+ const output2 = new Array(length);
248
+ addAggregate(2 + Math.max(0, length - 1));
249
+ for (let index = 0; index < length; index += 1) {
250
+ const key = String(index);
251
+ if (!keySet.delete(key)) fail("shape");
252
+ const descriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, key));
253
+ if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) fail("shape");
254
+ Object.defineProperty(output2, key, {
255
+ configurable: true,
256
+ enumerable: true,
257
+ value: visit(descriptor.value, depth + 1),
258
+ writable: true
259
+ });
260
+ }
261
+ if (keySet.size !== 0) fail("shape");
262
+ return output2;
84
263
  }
85
- if (!isPlainObject(current)) {
86
- throw new TypeError(`${path} must contain only plain JSON objects.`);
264
+ const ownKeys = inspected(() => Reflect.ownKeys(current));
265
+ if (ownKeys.some((key) => typeof key !== "string")) fail("shape");
266
+ properties += ownKeys.length;
267
+ assertLimit(properties, limits.maximumProperties, "properties");
268
+ addAggregate(2 + Math.max(0, ownKeys.length - 1) + ownKeys.length);
269
+ const output = {};
270
+ for (const key of ownKeys) {
271
+ addAggregate(addString(key));
272
+ const descriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, key));
273
+ if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) fail("shape");
274
+ Object.defineProperty(output, key, {
275
+ configurable: true,
276
+ enumerable: true,
277
+ value: visit(descriptor.value, depth + 1),
278
+ writable: true
279
+ });
87
280
  }
88
- const keys = Object.keys(current).sort();
89
- const properties = keys.map((key) => {
90
- assertUnicodeScalarString(key, `${path} key`);
91
- const member = current[key];
92
- if (member === void 0) {
93
- throw new TypeError(`${path}.${key} is undefined.`);
94
- }
95
- return `${JSON.stringify(key)}:${visit(member, `${path}.${key}`)}`;
96
- });
97
- return `{${properties.join(",")}}`;
281
+ return output;
98
282
  } finally {
99
283
  ancestors.delete(current);
100
284
  }
101
285
  };
102
- return visit(value, "$root");
286
+ return visit(value, 0);
287
+ }
288
+ function serializeSnapshot(value) {
289
+ if (value === null) return "null";
290
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
291
+ if (typeof value === "number") return JSON.stringify(value);
292
+ if (Array.isArray(value)) return `[${value.map(serializeSnapshot).join(",")}]`;
293
+ const input = value;
294
+ return `{${Object.keys(input).sort().map((key) => `${JSON.stringify(key)}:${serializeSnapshot(input[key])}`).join(",")}}`;
295
+ }
296
+ function canonicalizeGpuContract(value) {
297
+ return serializeSnapshot(snapshotGpuContract(value));
103
298
  }
104
299
  function parseCanonicalJson(value) {
105
- const parsed = JSON.parse(value);
106
- if (canonicalizeGpuContract(parsed) !== value) throw new TypeError("JSON input is valid but not in canonical form.");
107
- return parsed;
300
+ if (typeof value !== "string") throw new TypeError("Canonical GPU contract JSON must be a string.");
301
+ try {
302
+ utf8ByteLength(value, GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes);
303
+ } catch {
304
+ throw new TypeError("Canonical GPU contract JSON is invalid or exceeds its input bound.");
305
+ }
306
+ let parsed;
307
+ try {
308
+ parsed = JSON.parse(value);
309
+ } catch {
310
+ throw new TypeError("Canonical GPU contract JSON is invalid or exceeds its input bound.");
311
+ }
312
+ const snapshot = snapshotGpuContract(parsed);
313
+ if (serializeSnapshot(snapshot) !== value) throw new TypeError("JSON input is valid but not in canonical form.");
314
+ return snapshot;
108
315
  }
109
316
 
110
317
  // src/hash.ts
@@ -186,39 +393,41 @@ function modelProjection(manifest) {
186
393
  };
187
394
  }
188
395
  async function computeGpuAbiHash(input) {
189
- if (input.kind === "model") {
396
+ const snapshot = snapshotGpuContract(input);
397
+ if (snapshot.kind === "model") {
190
398
  return computeSha256(
191
399
  `plasius.gpu.model-abi/v1
192
- ${canonicalizeGpuContract(modelProjection(input.interface))}`
400
+ ${canonicalizeGpuContract(modelProjection(snapshot.interface))}`
193
401
  );
194
402
  }
195
- if (input.kind === "interface") {
403
+ if (snapshot.kind === "interface") {
196
404
  return computeSha256(
197
405
  `plasius.gpu.interface-abi/v1
198
- ${canonicalizeGpuContract(interfaceProjection(input.interface))}`
406
+ ${canonicalizeGpuContract(interfaceProjection(snapshot.interface))}`
199
407
  );
200
408
  }
201
409
  const pipelines = sorted(
202
- input.pipelines,
410
+ snapshot.pipelines,
203
411
  (left, right) => compareString(left.pipelineId, right.pipelineId)
204
412
  );
205
413
  const requirements = {
206
- semantics: [...input.requirements.semantics].sort(),
207
- features: [...input.requirements.features].sort(),
208
- limits: sorted(input.requirements.limits, (left, right) => compareString(left.name, right.name)),
209
- formats: [...input.requirements.formats].sort()
414
+ semantics: [...snapshot.requirements.semantics].sort(),
415
+ features: [...snapshot.requirements.features].sort(),
416
+ limits: sorted(snapshot.requirements.limits, (left, right) => compareString(left.name, right.name)),
417
+ formats: [...snapshot.requirements.formats].sort()
210
418
  };
211
419
  return computeSha256(
212
420
  `plasius.gpu.shader-abi/v1
213
421
  ${canonicalizeGpuContract({
214
- interface: interfaceProjection(input.interface),
422
+ interface: interfaceProjection(snapshot.interface),
215
423
  pipelines,
216
424
  requirements
217
425
  })}`
218
426
  );
219
427
  }
220
428
  async function computeShaderManifestCoreSha256(manifest) {
221
- const core = Object.fromEntries(Object.entries(manifest).filter(
429
+ const snapshot = snapshotGpuContract(manifest);
430
+ const core = Object.fromEntries(Object.entries(snapshot).filter(
222
431
  ([key]) => key !== "validationEvidence" && key !== "additionalValidationEvidence"
223
432
  ));
224
433
  return computeSha256(
@@ -855,11 +1064,10 @@ var stages = ["vertex", "fragment", "compute"];
855
1064
  var roles = ["material", "lighting", "outline", "shadow", "post-processing"];
856
1065
  function detachedJson(value, path) {
857
1066
  try {
858
- return JSON.parse(canonicalizeGpuContract(value));
1067
+ return snapshotGpuContract(value);
859
1068
  } catch (cause) {
860
- const detail = cause instanceof Error ? cause.message : "Contract snapshot failed.";
861
- const boundedDetail = [...detail].slice(0, 512).join("");
862
- throw new TypeError(`${path} must contain detached JSON contract data: ${boundedDetail}`, { cause });
1069
+ const detail = cause instanceof GpuContractSnapshotError ? ` ${cause.message}` : "";
1070
+ throw new TypeError(`${path} must contain bounded detached JSON contract data.${detail}`);
863
1071
  }
864
1072
  }
865
1073
  function object(value, path) {
@@ -869,7 +1077,7 @@ function object(value, path) {
869
1077
  function exact(value, keys, path) {
870
1078
  const allowed = new Set(keys);
871
1079
  for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError(`${path}.${key} is not part of this contract version.`);
872
- for (const key of keys) if (!(key in value)) throw new TypeError(`${path}.${key} is required.`);
1080
+ for (const key of keys) if (!Object.hasOwn(value, key)) throw new TypeError(`${path}.${key} is required.`);
873
1081
  }
874
1082
  function text(value, path, maximum = 512) {
875
1083
  if (typeof value !== "string" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 31)) {
@@ -885,11 +1093,8 @@ function token(value, path) {
885
1093
  function immutableVersion(value, path) {
886
1094
  try {
887
1095
  return assertImmutableAssetVersion(value);
888
- } catch (cause) {
889
- throw new TypeError(
890
- `${path} must be an immutable asset version: exact token required; mutable aliases, ranges, wildcards, and URLs are not allowed.`,
891
- { cause }
892
- );
1096
+ } catch {
1097
+ throw new TypeError(`${path} must be an immutable asset version: exact token required; mutable aliases, ranges, wildcards, and URLs are not allowed.`);
893
1098
  }
894
1099
  }
895
1100
  function enumeration(value, values, path) {
@@ -919,8 +1124,8 @@ function nullableToken(value, path) {
919
1124
  function digest(value, path) {
920
1125
  try {
921
1126
  return asSha256Hex(text(value, path, 64));
922
- } catch (cause) {
923
- throw new TypeError(`${path} must be a lowercase SHA-256 digest.`, { cause });
1127
+ } catch {
1128
+ throw new TypeError(`${path} must be a lowercase SHA-256 digest.`);
924
1129
  }
925
1130
  }
926
1131
  function uri(value, path) {
@@ -928,8 +1133,8 @@ function uri(value, path) {
928
1133
  let parsed;
929
1134
  try {
930
1135
  parsed = new URL(result);
931
- } catch (cause) {
932
- throw new TypeError(`${path} must be an absolute immutable asset URI.`, { cause });
1136
+ } catch {
1137
+ throw new TypeError(`${path} must be an absolute immutable asset URI.`);
933
1138
  }
934
1139
  if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.hash) throw new TypeError(`${path} must be credential-free HTTPS without a fragment.`);
935
1140
  const keys = [...parsed.searchParams.keys()].map((key) => key.toLowerCase());
@@ -1742,10 +1947,23 @@ function parseModelGpuCompatibilityDescriptor(value) {
1742
1947
  return freeze(input);
1743
1948
  }
1744
1949
  function parseJsonBytes(bytes, label) {
1950
+ const safeLabel = typeof label === "string" && /^[A-Za-z0-9 ._-]{1,80}$/u.test(label) ? label : "GPU contract";
1951
+ let snapshot;
1745
1952
  try {
1746
- return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1747
- } catch (cause) {
1748
- throw new TypeError(`${label} is not valid UTF-8 JSON.`, { cause });
1953
+ snapshot = snapshotUint8Array(bytes, GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes);
1954
+ } catch {
1955
+ throw new TypeError(`${safeLabel} is not bounded UTF-8 JSON.`);
1956
+ }
1957
+ let parsed;
1958
+ try {
1959
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(snapshot));
1960
+ } catch {
1961
+ throw new TypeError(`${safeLabel} is not valid UTF-8 JSON.`);
1962
+ }
1963
+ try {
1964
+ return snapshotGpuContract(parsed);
1965
+ } catch {
1966
+ throw new TypeError(`${safeLabel} is not bounded detached JSON contract data.`);
1749
1967
  }
1750
1968
  }
1751
1969
 
@@ -1760,9 +1978,6 @@ function error(code, message, path) {
1760
1978
  function interfaceMatches(item, model) {
1761
1979
  return item.interfaceId === model.gpuInterface.interfaceId && item.interfaceVersion === model.gpuInterface.interfaceVersion && item.manifestSha256 === model.gpuInterface.manifestSha256 && item.interfaceAbiHash === model.gpuInterface.interfaceAbiHash && item.modelAbiHash === model.modelAbiHash;
1762
1980
  }
1763
- function detachedContract(value) {
1764
- return JSON.parse(canonicalizeGpuContract(value));
1765
- }
1766
1981
  function hasValidationEvidence(value) {
1767
1982
  return typeof value === "object" && value !== null && !Array.isArray(value) && (Object.hasOwn(value, "validationEvidence") || Object.hasOwn(value, "additionalValidationEvidence"));
1768
1983
  }
@@ -1810,16 +2025,25 @@ function validateModelShaderCompatibility(input) {
1810
2025
  let profile;
1811
2026
  let capabilities;
1812
2027
  try {
1813
- const modelSnapshot = detachedContract(input.model);
1814
- const shaderSnapshot = detachedContract(input.shader);
1815
- const gpuInterfaceSnapshot = detachedContract(input.gpuInterface);
1816
- const profileValue = input.profile;
1817
- const profileSnapshot = profileValue === void 0 ? void 0 : detachedContract(profileValue);
2028
+ const snapshot = snapshotGpuContract(input);
2029
+ if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot)) {
2030
+ throw new TypeError("GPU compatibility input must be a bounded contract object.");
2031
+ }
2032
+ const envelope = snapshot;
2033
+ const keys = Object.keys(envelope);
2034
+ const allowed = /* @__PURE__ */ new Set(["model", "shader", "gpuInterface", "profile", "capabilities"]);
2035
+ if (keys.some((key) => !allowed.has(key)) || !["model", "shader", "gpuInterface"].every((key) => Object.hasOwn(envelope, key))) {
2036
+ throw new TypeError("GPU compatibility input has unknown or missing fields.");
2037
+ }
2038
+ const modelSnapshot = envelope.model;
2039
+ const shaderSnapshot = envelope.shader;
2040
+ const gpuInterfaceSnapshot = envelope.gpuInterface;
2041
+ const profileSnapshot = Object.hasOwn(envelope, "profile") ? envelope.profile : void 0;
1818
2042
  model = parseModelGpuCompatibilityDescriptor(modelSnapshot);
1819
2043
  shader = hasValidationEvidence(shaderSnapshot) ? parseShaderVersionManifest(shaderSnapshot) : parseShaderVersionManifestCore(shaderSnapshot);
1820
2044
  gpuInterface = parseGpuInterfaceManifest(gpuInterfaceSnapshot);
1821
2045
  profile = profileSnapshot === void 0 ? void 0 : parseShaderStyleProfileManifest(profileSnapshot);
1822
- capabilities = input.capabilities;
2046
+ capabilities = Object.hasOwn(envelope, "capabilities") ? envelope.capabilities : void 0;
1823
2047
  } catch (cause) {
1824
2048
  return {
1825
2049
  ok: false,
@@ -1997,34 +2221,146 @@ function requireTrustedPreparedShaderStyleProfile(value) {
1997
2221
  function diagnostic(code, message, path) {
1998
2222
  return { code, severity: "error", message, ...path ? { path } : {} };
1999
2223
  }
2224
+ var CatalogLoadError = class extends TypeError {
2225
+ diagnosticCode;
2226
+ constructor(message, diagnosticCode = "invalid-contract") {
2227
+ super(message);
2228
+ this.name = "CatalogLoadError";
2229
+ this.diagnosticCode = diagnosticCode;
2230
+ }
2231
+ };
2232
+ function catalogFailure(message, diagnosticCode = "invalid-contract") {
2233
+ return new CatalogLoadError(message, diagnosticCode);
2234
+ }
2235
+ function catalogContractStep(operation, fallback) {
2236
+ try {
2237
+ return operation();
2238
+ } catch (cause) {
2239
+ if (cause instanceof CatalogLoadError) throw cause;
2240
+ throw catalogFailure(cause instanceof TypeError ? cause.message : fallback);
2241
+ }
2242
+ }
2243
+ async function catalogContractStepAsync(operation, fallback) {
2244
+ try {
2245
+ return await operation();
2246
+ } catch (cause) {
2247
+ if (cause instanceof CatalogLoadError) throw cause;
2248
+ throw catalogFailure(cause instanceof TypeError ? cause.message : fallback);
2249
+ }
2250
+ }
2000
2251
  async function verifyBytes(bytes, expected, label) {
2001
- const actual = await computeSha256(bytes);
2002
- if (actual !== expected) throw new TypeError(`${label} digest does not match its immutable reference.`);
2252
+ const actual = await catalogContractStepAsync(
2253
+ () => computeSha256(bytes),
2254
+ `${label} digest could not be computed.`
2255
+ );
2256
+ if (actual !== expected) {
2257
+ throw catalogFailure(
2258
+ `${label} digest does not match its immutable reference.`,
2259
+ "digest-mismatch"
2260
+ );
2261
+ }
2262
+ }
2263
+ function inspectCatalogAsset(value, label, maximumBytes) {
2264
+ try {
2265
+ if (typeof value !== "object" || value === null) throw new TypeError();
2266
+ const keys = Reflect.ownKeys(value);
2267
+ if (keys.length !== 2 || !keys.includes("bytes") || !keys.includes("promoted")) {
2268
+ throw new TypeError();
2269
+ }
2270
+ const bytes = Reflect.getOwnPropertyDescriptor(value, "bytes");
2271
+ const promoted = Reflect.getOwnPropertyDescriptor(value, "promoted");
2272
+ if (!bytes?.enumerable || !Object.hasOwn(bytes, "value") || !promoted?.enumerable || !Object.hasOwn(promoted, "value") || typeof promoted.value !== "boolean") {
2273
+ throw new TypeError();
2274
+ }
2275
+ return Object.freeze({
2276
+ bytes: snapshotUint8Array(bytes.value, maximumBytes),
2277
+ promoted: promoted.value
2278
+ });
2279
+ } catch {
2280
+ throw catalogFailure(`${label} returned invalid detached asset bytes.`);
2281
+ }
2282
+ }
2283
+ async function loadCatalogAsset(operation, label, maximumBytes) {
2284
+ let value;
2285
+ try {
2286
+ value = await operation();
2287
+ } catch {
2288
+ throw catalogFailure(`${label} provider request failed.`);
2289
+ }
2290
+ return inspectCatalogAsset(value, label, maximumBytes);
2291
+ }
2292
+ function isCatalogAssetUri(catalog, uri2) {
2293
+ try {
2294
+ const result = catalog.isCatalogAssetUri(uri2);
2295
+ if (typeof result !== "boolean") throw new TypeError();
2296
+ return result;
2297
+ } catch {
2298
+ throw catalogFailure("Promoted catalog URI validation failed.");
2299
+ }
2003
2300
  }
2004
- function copyBytes(bytes) {
2005
- return new Uint8Array(bytes);
2301
+ function inspectLoadRequest(value) {
2302
+ try {
2303
+ if (typeof value !== "object" || value === null) throw new TypeError();
2304
+ const keys = Reflect.ownKeys(value);
2305
+ if (keys.some((key) => typeof key !== "string" || !["ref", "catalog", "signal"].includes(key)) || !keys.includes("ref") || !keys.includes("catalog")) {
2306
+ throw new TypeError();
2307
+ }
2308
+ const ref = Reflect.getOwnPropertyDescriptor(value, "ref");
2309
+ const catalog = Reflect.getOwnPropertyDescriptor(value, "catalog");
2310
+ const signal = Reflect.getOwnPropertyDescriptor(value, "signal");
2311
+ if (!ref?.enumerable || !Object.hasOwn(ref, "value") || !catalog?.enumerable || !Object.hasOwn(catalog, "value") || signal !== void 0 && (!signal.enumerable || !Object.hasOwn(signal, "value"))) {
2312
+ throw new TypeError();
2313
+ }
2314
+ return Object.freeze({
2315
+ ref: ref.value,
2316
+ catalog: catalog.value,
2317
+ ...signal === void 0 ? {} : { signal: signal.value }
2318
+ });
2319
+ } catch {
2320
+ throw catalogFailure("Style profile load request must use enumerable own data properties.");
2321
+ }
2322
+ }
2323
+ function referenceObject(value, keys, label) {
2324
+ let snapshot;
2325
+ try {
2326
+ snapshot = snapshotGpuContract(value);
2327
+ } catch {
2328
+ throw catalogFailure(`${label} must contain bounded detached JSON contract data.`);
2329
+ }
2330
+ if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot)) {
2331
+ throw catalogFailure(`${label} must be an object.`);
2332
+ }
2333
+ const record = snapshot;
2334
+ const actual = Object.keys(record);
2335
+ if (actual.some((key) => !keys.includes(key)) || keys.some((key) => !Object.hasOwn(record, key)) || actual.some((key) => typeof record[key] !== "string")) {
2336
+ throw catalogFailure(`${label} has unknown, missing, or non-string fields.`);
2337
+ }
2338
+ return record;
2006
2339
  }
2007
2340
  function snapshotProfileRef(ref) {
2008
- const profileId = ref.profileId;
2009
- const version = ref.version;
2010
- const manifestUri = ref.manifestUri;
2011
- const manifestSha256 = ref.manifestSha256;
2341
+ const value = referenceObject(ref, ["profileId", "version", "manifestUri", "manifestSha256"], "Style profile reference");
2342
+ const profileId = value.profileId;
2343
+ const version = value.version;
2344
+ const manifestUri = value.manifestUri;
2345
+ const manifestSha256 = value.manifestSha256;
2012
2346
  return Object.freeze({ profileId, version, manifestUri, manifestSha256 });
2013
2347
  }
2014
2348
  function snapshotShaderRef(ref) {
2015
- const shaderId = ref.shaderId;
2016
- const version = ref.version;
2017
- const manifestUri = ref.manifestUri;
2018
- const manifestSha256 = ref.manifestSha256;
2349
+ const value = referenceObject(ref, ["shaderId", "version", "manifestUri", "manifestSha256"], "Shader version reference");
2350
+ const shaderId = value.shaderId;
2351
+ const version = value.version;
2352
+ const manifestUri = value.manifestUri;
2353
+ const manifestSha256 = value.manifestSha256;
2019
2354
  return Object.freeze({ shaderId, version, manifestUri, manifestSha256 });
2020
2355
  }
2021
2356
  function snapshotInterfaceRef(ref) {
2022
- const interfaceId = ref.interfaceId;
2023
- const interfaceVersion = ref.interfaceVersion;
2024
- const manifestUri = ref.manifestUri;
2025
- const manifestSha256 = ref.manifestSha256;
2026
- const interfaceAbiHash = ref.interfaceAbiHash;
2027
- const modelAbiHash = ref.modelAbiHash;
2357
+ const value = referenceObject(ref, ["interfaceId", "interfaceVersion", "manifestUri", "manifestSha256", "interfaceAbiHash", "modelAbiHash"], "GPU interface reference");
2358
+ const interfaceId = value.interfaceId;
2359
+ const interfaceVersion = value.interfaceVersion;
2360
+ const manifestUri = value.manifestUri;
2361
+ const manifestSha256 = value.manifestSha256;
2362
+ const interfaceAbiHash = value.interfaceAbiHash;
2363
+ const modelAbiHash = value.modelAbiHash;
2028
2364
  return Object.freeze({
2029
2365
  interfaceId,
2030
2366
  interfaceVersion,
@@ -2034,8 +2370,24 @@ function snapshotInterfaceRef(ref) {
2034
2370
  modelAbiHash
2035
2371
  });
2036
2372
  }
2373
+ function assertCatalogAssetVersion(value, label) {
2374
+ try {
2375
+ assertImmutableAssetVersion(value);
2376
+ } catch {
2377
+ throw catalogFailure(`${label} must use an immutable asset version represented by an exact token.`);
2378
+ }
2379
+ }
2380
+ var ABORTED_GETTER = typeof AbortSignal === "undefined" ? void 0 : Reflect.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")?.get;
2037
2381
  function throwIfAborted(signal) {
2038
- if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError");
2382
+ if (signal === void 0) return;
2383
+ let aborted;
2384
+ try {
2385
+ if (!ABORTED_GETTER) throw new TypeError();
2386
+ aborted = Reflect.apply(ABORTED_GETTER, signal, []);
2387
+ } catch {
2388
+ throw catalogFailure("Abort signal could not be inspected safely.");
2389
+ }
2390
+ if (aborted === true) throw new DOMException("Aborted", "AbortError");
2039
2391
  }
2040
2392
  function exactShaderRefKey(ref) {
2041
2393
  return `${ref.shaderId}\0${ref.version}\0${ref.manifestUri}\0${ref.manifestSha256}`;
@@ -2071,7 +2423,7 @@ function assertDistinctEvidenceOwnership(shaders) {
2071
2423
  ]) {
2072
2424
  const owner = owners.get(value);
2073
2425
  if (owner !== void 0 && owner !== shaderKey) {
2074
- throw new TypeError(`Distinct shader versions in one style profile reuse the same ${kind}.`);
2426
+ throw catalogFailure(`Distinct shader versions in one style profile reuse the same ${kind}.`);
2075
2427
  }
2076
2428
  owners.set(value, shaderKey);
2077
2429
  }
@@ -2097,93 +2449,135 @@ async function mapLimit(values, limit, operation, signal) {
2097
2449
  }
2098
2450
  async function loadInterface(catalog, ref, signal) {
2099
2451
  throwIfAborted(signal);
2100
- assertImmutableAssetVersion(ref.interfaceVersion);
2101
- if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError("GPU interface URI is outside the promoted catalog root.");
2102
- const loaded = await catalog.loadInterface(ref, signal);
2103
- const bytes = copyBytes(loaded.bytes);
2452
+ assertCatalogAssetVersion(ref.interfaceVersion, "GPU interface reference");
2453
+ if (!isCatalogAssetUri(catalog, ref.manifestUri)) throw catalogFailure("GPU interface URI is outside the promoted catalog root.");
2454
+ const loaded = await loadCatalogAsset(
2455
+ () => catalog.loadInterface(ref, signal),
2456
+ "GPU interface",
2457
+ GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2458
+ );
2459
+ const bytes = loaded.bytes;
2104
2460
  const promoted = loaded.promoted;
2105
2461
  throwIfAborted(signal);
2106
- if (!promoted) throw new TypeError("GPU interface is not promoted.");
2462
+ if (!promoted) throw catalogFailure("GPU interface is not promoted.", "unpromoted-asset");
2107
2463
  await verifyBytes(bytes, ref.manifestSha256, "GPU interface manifest");
2108
- const manifest = parseGpuInterfaceManifest(parseJsonBytes(bytes, "GPU interface manifest"));
2464
+ const manifest = catalogContractStep(
2465
+ () => parseGpuInterfaceManifest(parseJsonBytes(bytes, "GPU interface manifest")),
2466
+ "GPU interface manifest failed strict contract validation."
2467
+ );
2109
2468
  if (manifest.interfaceId !== ref.interfaceId || manifest.interfaceVersion !== ref.interfaceVersion || manifest.interfaceAbiHash !== ref.interfaceAbiHash || manifest.modelAbiHash !== ref.modelAbiHash) {
2110
- throw new TypeError("GPU interface manifest identity does not match its exact reference.");
2469
+ throw catalogFailure("GPU interface manifest identity does not match its exact reference.");
2111
2470
  }
2112
- const modelAbiHash = await computeGpuAbiHash({ kind: "model", interface: manifest });
2113
- const interfaceAbiHash = await computeGpuAbiHash({ kind: "interface", interface: manifest });
2471
+ const modelAbiHash = await catalogContractStepAsync(
2472
+ () => computeGpuAbiHash({ kind: "model", interface: manifest }),
2473
+ "GPU interface model ABI hash regeneration failed."
2474
+ );
2475
+ const interfaceAbiHash = await catalogContractStepAsync(
2476
+ () => computeGpuAbiHash({ kind: "interface", interface: manifest }),
2477
+ "GPU interface ABI hash regeneration failed."
2478
+ );
2114
2479
  if (modelAbiHash !== manifest.modelAbiHash || interfaceAbiHash !== manifest.interfaceAbiHash) {
2115
- throw new TypeError("GPU interface ABI hashes do not match regenerated structural hashes.");
2480
+ throw catalogFailure("GPU interface ABI hashes do not match regenerated structural hashes.");
2116
2481
  }
2117
2482
  return manifest;
2118
2483
  }
2119
2484
  async function loadShader(catalog, ref, signal) {
2120
2485
  throwIfAborted(signal);
2121
- assertImmutableAssetVersion(ref.version);
2122
- if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError("Shader manifest URI is outside the promoted catalog root.");
2123
- const loaded = await catalog.loadShader(ref, signal);
2124
- const bytes = copyBytes(loaded.bytes);
2486
+ assertCatalogAssetVersion(ref.version, "Shader reference");
2487
+ if (!isCatalogAssetUri(catalog, ref.manifestUri)) throw catalogFailure("Shader manifest URI is outside the promoted catalog root.");
2488
+ const loaded = await loadCatalogAsset(
2489
+ () => catalog.loadShader(ref, signal),
2490
+ "Shader manifest",
2491
+ GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2492
+ );
2493
+ const bytes = loaded.bytes;
2125
2494
  const promoted = loaded.promoted;
2126
2495
  throwIfAborted(signal);
2127
- if (!promoted) throw new TypeError("Shader version is not promoted.");
2496
+ if (!promoted) throw catalogFailure("Shader version is not promoted.", "unpromoted-asset");
2128
2497
  await verifyBytes(bytes, ref.manifestSha256, "Shader manifest");
2129
- const manifest = parseShaderVersionManifest(parseJsonBytes(bytes, "Shader manifest"));
2498
+ const manifest = catalogContractStep(
2499
+ () => parseShaderVersionManifest(parseJsonBytes(bytes, "Shader manifest")),
2500
+ "Shader manifest failed strict contract validation."
2501
+ );
2130
2502
  if (manifest.shaderId !== ref.shaderId || manifest.version !== ref.version) {
2131
- throw new TypeError("Shader manifest identity does not match its exact reference.");
2503
+ throw catalogFailure("Shader manifest identity does not match its exact reference.");
2132
2504
  }
2133
2505
  for (const evidence of [
2134
2506
  manifest.validationEvidence,
2135
2507
  ...manifest.additionalValidationEvidence.map((item) => item.evidence)
2136
2508
  ]) {
2137
- if (!catalog.isCatalogAssetUri(evidence.uri)) throw new TypeError("Shader validation evidence URI is outside the promoted catalog root.");
2138
- if (!catalog.isCatalogAssetUri(evidence.attestationRef.uri)) throw new TypeError("Shader validation evidence attestation URI is outside the promoted catalog root.");
2509
+ if (!isCatalogAssetUri(catalog, evidence.uri)) throw catalogFailure("Shader validation evidence URI is outside the promoted catalog root.");
2510
+ if (!isCatalogAssetUri(catalog, evidence.attestationRef.uri)) throw catalogFailure("Shader validation evidence attestation URI is outside the promoted catalog root.");
2139
2511
  }
2140
2512
  const interfaceRef2 = snapshotInterfaceRef(manifest.gpuInterface);
2141
2513
  const gpuInterface = await loadInterface(catalog, interfaceRef2, signal);
2142
2514
  const normalizeModules = (values) => [...values].sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0).map(({ moduleId, sha256 }) => ({ moduleId, sha256 }));
2143
- if (canonicalizeGpuContract(normalizeModules(gpuInterface.modules)) !== canonicalizeGpuContract(normalizeModules(manifest.modules))) {
2144
- throw new TypeError("Shader modules differ from the exact reflected GPU interface module set.");
2145
- }
2146
- const shaderAbiHash = await computeGpuAbiHash({
2147
- kind: "shader",
2148
- interface: gpuInterface,
2149
- pipelines: manifest.pipelines,
2150
- requirements: manifest.requirements
2151
- });
2152
- if (shaderAbiHash !== manifest.shaderAbiHash) throw new TypeError("Shader ABI hash differs from regenerated pipeline/interface ABI.");
2515
+ if (catalogContractStep(
2516
+ () => canonicalizeGpuContract(normalizeModules(gpuInterface.modules)) !== canonicalizeGpuContract(normalizeModules(manifest.modules)),
2517
+ "Shader module-set comparison failed."
2518
+ )) {
2519
+ throw catalogFailure("Shader modules differ from the exact reflected GPU interface module set.");
2520
+ }
2521
+ const shaderAbiHash = await catalogContractStepAsync(
2522
+ () => computeGpuAbiHash({
2523
+ kind: "shader",
2524
+ interface: gpuInterface,
2525
+ pipelines: manifest.pipelines,
2526
+ requirements: manifest.requirements
2527
+ }),
2528
+ "Shader ABI hash regeneration failed."
2529
+ );
2530
+ if (shaderAbiHash !== manifest.shaderAbiHash) throw catalogFailure("Shader ABI hash differs from regenerated pipeline/interface ABI.");
2153
2531
  const modulePairs = await mapLimit(manifest.modules, 4, async (module) => {
2154
2532
  throwIfAborted(signal);
2155
- if (!catalog.isCatalogAssetUri(module.uri)) throw new TypeError(`Shader module ${module.moduleId} URI is outside the promoted catalog root.`);
2156
- const asset = await catalog.loadModule(ref, module.moduleId, module.uri, signal);
2157
- const moduleBytes = copyBytes(asset.bytes);
2533
+ if (!isCatalogAssetUri(catalog, module.uri)) throw catalogFailure(`Shader module ${module.moduleId} URI is outside the promoted catalog root.`);
2534
+ const asset = await loadCatalogAsset(
2535
+ () => catalog.loadModule(ref, module.moduleId, module.uri, signal),
2536
+ `Shader module ${module.moduleId}`,
2537
+ module.byteLength
2538
+ );
2539
+ const moduleBytes = asset.bytes;
2158
2540
  const promoted2 = asset.promoted;
2159
2541
  throwIfAborted(signal);
2160
- if (!promoted2) throw new TypeError(`Shader module ${module.moduleId} is not promoted.`);
2542
+ if (!promoted2) throw catalogFailure(`Shader module ${module.moduleId} is not promoted.`, "unpromoted-asset");
2161
2543
  if (moduleBytes.byteLength !== module.byteLength) {
2162
- throw new TypeError(`Shader module ${module.moduleId} byte length does not match its manifest.`);
2544
+ throw catalogFailure(`Shader module ${module.moduleId} byte length does not match its manifest.`);
2163
2545
  }
2164
2546
  await verifyBytes(moduleBytes, module.sha256, `Shader module ${module.moduleId}`);
2165
2547
  return [module.moduleId, moduleBytes];
2166
2548
  }, signal);
2167
2549
  const decoder = new TextDecoder("utf-8", { fatal: true });
2168
- validateShaderDerivedRequirements({ manifest, gpuInterface, moduleSources: new Map(modulePairs.map(([moduleId, bytes2]) => [moduleId, decoder.decode(bytes2)])) });
2550
+ catalogContractStep(
2551
+ () => validateShaderDerivedRequirements({ manifest, gpuInterface, moduleSources: new Map(modulePairs.map(([moduleId, bytes2]) => [moduleId, decoder.decode(bytes2)])) }),
2552
+ "Shader source requirement validation failed."
2553
+ );
2169
2554
  return { ref, manifest, gpuInterface, modules: new Map(modulePairs) };
2170
2555
  }
2171
2556
  async function loadShaderStyleProfile(input) {
2172
- const signal = input.signal;
2173
2557
  try {
2558
+ const request = inspectLoadRequest(input);
2559
+ const signal = request.signal;
2560
+ const catalog = request.catalog;
2174
2561
  throwIfAborted(signal);
2175
- const ref = snapshotProfileRef(input.ref);
2176
- assertImmutableAssetVersion(ref.version);
2177
- if (!input.catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError("Style profile URI is outside the promoted catalog root.");
2178
- const loaded = await input.catalog.loadProfile(ref, signal);
2179
- const profileBytes = copyBytes(loaded.bytes);
2562
+ const ref = snapshotProfileRef(request.ref);
2563
+ assertCatalogAssetVersion(ref.version, "Style profile reference");
2564
+ if (!isCatalogAssetUri(catalog, ref.manifestUri)) throw catalogFailure("Style profile URI is outside the promoted catalog root.");
2565
+ const loaded = await loadCatalogAsset(
2566
+ () => catalog.loadProfile(ref, signal),
2567
+ "Style profile",
2568
+ GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2569
+ );
2570
+ const profileBytes = loaded.bytes;
2180
2571
  const promoted = loaded.promoted;
2181
2572
  throwIfAborted(signal);
2182
2573
  if (!promoted) {
2183
2574
  return { ok: false, diagnostics: [diagnostic("unpromoted-asset", "Style profile is not promoted.")] };
2184
2575
  }
2185
2576
  await verifyBytes(profileBytes, ref.manifestSha256, "Style profile manifest");
2186
- const manifest = parseShaderStyleProfileManifest(parseJsonBytes(profileBytes, "Style profile manifest"));
2577
+ const manifest = catalogContractStep(
2578
+ () => parseShaderStyleProfileManifest(parseJsonBytes(profileBytes, "Style profile manifest")),
2579
+ "Style profile manifest failed strict contract validation."
2580
+ );
2187
2581
  if (manifest.profileId !== ref.profileId || manifest.version !== ref.version) {
2188
2582
  return { ok: false, diagnostics: [diagnostic("invalid-contract", "Style profile identity does not match its exact reference.")] };
2189
2583
  }
@@ -2194,12 +2588,12 @@ async function loadShaderStyleProfile(input) {
2194
2588
  const cacheKey = exactShaderRefKey(shaderRef);
2195
2589
  let shader = cache.get(cacheKey);
2196
2590
  if (!shader) {
2197
- shader = loadShader(input.catalog, shaderRef, signal);
2591
+ shader = loadShader(catalog, shaderRef, signal);
2198
2592
  cache.set(cacheKey, shader);
2199
2593
  }
2200
2594
  const resolved = await shader;
2201
2595
  if (!resolved.manifest.renderRoles.some((role) => role.role === binding2.role)) {
2202
- throw new TypeError(`Shader ${resolved.manifest.shaderId} does not implement role ${binding2.role}.`);
2596
+ throw catalogFailure(`Shader ${resolved.manifest.shaderId} does not implement role ${binding2.role}.`);
2203
2597
  }
2204
2598
  const validationScopes = new Map(
2205
2599
  resolved.manifest.additionalValidationEvidence.map((item) => [item.scope, item.evidence])
@@ -2207,10 +2601,10 @@ async function loadShaderStyleProfile(input) {
2207
2601
  for (const requirement of manifest.requiredValidationScopes) {
2208
2602
  const evidence = validationScopes.get(requirement.scope);
2209
2603
  if (!evidence) {
2210
- throw new TypeError(`Shader ${resolved.manifest.shaderId} lacks required validation scope ${requirement.scope}.`);
2604
+ throw catalogFailure(`Shader ${resolved.manifest.shaderId} lacks required validation scope ${requirement.scope}.`);
2211
2605
  }
2212
2606
  if (evidence.matrixId !== requirement.matrixId || evidence.matrixVersion !== requirement.matrixVersion || evidence.matrixSha256 !== requirement.matrixSha256) {
2213
- throw new TypeError(
2607
+ throw catalogFailure(
2214
2608
  `Shader ${resolved.manifest.shaderId} validation scope ${requirement.scope} is bound to a different matrix policy.`
2215
2609
  );
2216
2610
  }
@@ -2227,11 +2621,14 @@ async function loadShaderStyleProfile(input) {
2227
2621
  })
2228
2622
  };
2229
2623
  } catch (cause) {
2230
- if (signal?.aborted) throw cause;
2231
- const code = cause instanceof TypeError && /digest/u.test(cause.message) ? "digest-mismatch" : "invalid-contract";
2624
+ if (cause instanceof DOMException && cause.name === "AbortError") throw cause;
2625
+ const known = cause instanceof CatalogLoadError ? cause : void 0;
2232
2626
  return {
2233
2627
  ok: false,
2234
- diagnostics: [diagnostic(code, cause instanceof Error ? cause.message : "Style profile loading failed.")]
2628
+ diagnostics: [diagnostic(
2629
+ known?.diagnosticCode ?? "invalid-contract",
2630
+ known?.message ?? "Style profile loading failed."
2631
+ )]
2235
2632
  };
2236
2633
  }
2237
2634
  }