@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.cjs CHANGED
@@ -99,68 +99,275 @@ function assertImmutableAssetVersion(value) {
99
99
  }
100
100
 
101
101
  // src/canonical-json.ts
102
- function isPlainObject(value) {
103
- const prototype = Object.getPrototypeOf(value);
104
- return prototype === Object.prototype || prototype === null;
102
+ var GPU_CONTRACT_SNAPSHOT_LIMITS = Object.freeze({
103
+ maximumDepth: 64,
104
+ maximumNodes: 262144,
105
+ maximumProperties: 131072,
106
+ maximumElements: 131072,
107
+ maximumArrayLength: 1e5,
108
+ maximumStringBytes: 1024 * 1024,
109
+ maximumAggregateStringBytes: 8 * 1024 * 1024,
110
+ maximumAggregateBytes: 16 * 1024 * 1024,
111
+ maximumInputBytes: 16 * 1024 * 1024
112
+ });
113
+ var QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS = Object.freeze({
114
+ maximumDepth: 96,
115
+ maximumNodes: 4e6,
116
+ maximumProperties: 2e6,
117
+ maximumElements: 2e6,
118
+ maximumArrayLength: 25e4,
119
+ maximumStringBytes: 4 * 1024 * 1024,
120
+ maximumAggregateStringBytes: 128 * 1024 * 1024,
121
+ maximumAggregateBytes: 256 * 1024 * 1024,
122
+ maximumInputBytes: 256 * 1024 * 1024
123
+ });
124
+ var FAILURE_MESSAGES = Object.freeze({
125
+ "aggregate-bytes": "GPU contract snapshot exceeds the aggregate byte limit.",
126
+ "aggregate-string-bytes": "GPU contract snapshot exceeds the aggregate string byte limit.",
127
+ "array-length": "GPU contract snapshot exceeds the single-array element limit.",
128
+ cycle: "GPU contract snapshot contains a circular reference.",
129
+ depth: "GPU contract snapshot exceeds the nesting-depth limit.",
130
+ elements: "GPU contract snapshot exceeds the total element limit.",
131
+ inspection: "GPU contract snapshot rejected unsafe object inspection.",
132
+ nodes: "GPU contract snapshot exceeds the total node limit.",
133
+ "non-finite": "GPU contract snapshot contains a non-finite number.",
134
+ properties: "GPU contract snapshot exceeds the total property limit.",
135
+ shape: "GPU contract snapshot requires plain JSON objects with own enumerable data properties and dense arrays.",
136
+ "string-bytes": "GPU contract snapshot exceeds the individual string byte limit.",
137
+ unicode: "GPU contract snapshot contains an invalid Unicode scalar string or unpaired UTF-16 surrogate.",
138
+ value: "GPU contract snapshot contains undefined or another value that JSON cannot represent."
139
+ });
140
+ var GpuContractSnapshotError = class extends TypeError {
141
+ code;
142
+ constructor(code) {
143
+ super(FAILURE_MESSAGES[code]);
144
+ this.name = "GpuContractSnapshotError";
145
+ this.code = code;
146
+ }
147
+ };
148
+ var TYPED_ARRAY_PROTOTYPE = Reflect.getPrototypeOf(Uint8Array.prototype);
149
+ var TYPED_ARRAY_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(
150
+ TYPED_ARRAY_PROTOTYPE,
151
+ "byteLength"
152
+ )?.get;
153
+ var TYPED_ARRAY_TAG = Reflect.getOwnPropertyDescriptor(
154
+ TYPED_ARRAY_PROTOTYPE,
155
+ Symbol.toStringTag
156
+ )?.get;
157
+ var UINT8_ARRAY_SET = Uint8Array.prototype.set;
158
+ function snapshotUint8Array(value, maximumBytes) {
159
+ if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0) {
160
+ throw new TypeError("GPU contract byte limit must be a non-negative safe integer.");
161
+ }
162
+ let byteLength;
163
+ let tag;
164
+ try {
165
+ if (!TYPED_ARRAY_BYTE_LENGTH || !TYPED_ARRAY_TAG) throw new TypeError();
166
+ byteLength = Reflect.apply(TYPED_ARRAY_BYTE_LENGTH, value, []);
167
+ tag = Reflect.apply(TYPED_ARRAY_TAG, value, []);
168
+ } catch {
169
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
170
+ }
171
+ if (tag !== "Uint8Array" || !Number.isSafeInteger(byteLength) || byteLength > maximumBytes) {
172
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
173
+ }
174
+ const output = new Uint8Array(byteLength);
175
+ try {
176
+ Reflect.apply(UINT8_ARRAY_SET, output, [value]);
177
+ } catch {
178
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
179
+ }
180
+ return output;
181
+ }
182
+ function fail(reason) {
183
+ throw new GpuContractSnapshotError(reason);
184
+ }
185
+ function inspected(operation) {
186
+ try {
187
+ return operation();
188
+ } catch {
189
+ return fail("inspection");
190
+ }
105
191
  }
106
- function assertUnicodeScalarString(value, path) {
192
+ function assertLimit(value, maximum, reason) {
193
+ if (!Number.isSafeInteger(value) || value > maximum) fail(reason);
194
+ }
195
+ function utf8ByteLength(value, maximum) {
196
+ let bytes = 0;
107
197
  for (let index = 0; index < value.length; index += 1) {
108
198
  const code = value.charCodeAt(index);
109
- if (code >= 55296 && code <= 56319) {
199
+ if (code <= 127) bytes += 1;
200
+ else if (code <= 2047) bytes += 2;
201
+ else if (code >= 55296 && code <= 56319) {
110
202
  const next = value.charCodeAt(index + 1);
111
- if (!(next >= 56320 && next <= 57343)) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);
203
+ if (!(next >= 56320 && next <= 57343)) fail("unicode");
204
+ bytes += 4;
112
205
  index += 1;
113
- } else if (code >= 56320 && code <= 57343) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);
206
+ } else if (code >= 56320 && code <= 57343) fail("unicode");
207
+ else bytes += 3;
208
+ if (bytes > maximum) fail("string-bytes");
114
209
  }
210
+ return bytes;
115
211
  }
116
- function canonicalizeGpuContract(value) {
212
+ function quotedJsonByteLength(value, maximum) {
213
+ let raw = 0;
214
+ let quoted = 2;
215
+ for (let index = 0; index < value.length; index += 1) {
216
+ const code = value.charCodeAt(index);
217
+ if (code <= 127) {
218
+ raw += 1;
219
+ if (code <= 31) quoted += code === 8 || code === 9 || code === 10 || code === 12 || code === 13 ? 2 : 6;
220
+ else quoted += code === 34 || code === 92 ? 2 : 1;
221
+ } else if (code <= 2047) {
222
+ raw += 2;
223
+ quoted += 2;
224
+ } else if (code >= 55296 && code <= 56319) {
225
+ const next = value.charCodeAt(index + 1);
226
+ if (!(next >= 56320 && next <= 57343)) fail("unicode");
227
+ raw += 4;
228
+ quoted += 4;
229
+ index += 1;
230
+ } else if (code >= 56320 && code <= 57343) fail("unicode");
231
+ else {
232
+ raw += 3;
233
+ quoted += 3;
234
+ }
235
+ if (raw > maximum) fail("string-bytes");
236
+ }
237
+ return { raw, quoted };
238
+ }
239
+ function assertLimits(limits) {
240
+ for (const value of Object.values(limits)) {
241
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError("GPU contract snapshot limits must be positive safe integers.");
242
+ }
243
+ }
244
+ function snapshotGpuContract(value, limits = GPU_CONTRACT_SNAPSHOT_LIMITS) {
245
+ assertLimits(limits);
117
246
  const ancestors = /* @__PURE__ */ new Set();
118
- const visit = (current, path) => {
119
- if (current === null) return "null";
120
- if (typeof current === "string" || typeof current === "boolean") {
121
- if (typeof current === "string") assertUnicodeScalarString(current, path);
122
- return JSON.stringify(current);
247
+ let nodes = 0;
248
+ let properties = 0;
249
+ let elements = 0;
250
+ let aggregateStringBytes = 0;
251
+ let aggregateBytes = 0;
252
+ const addAggregate = (bytes) => {
253
+ aggregateBytes += bytes;
254
+ assertLimit(aggregateBytes, limits.maximumAggregateBytes, "aggregate-bytes");
255
+ };
256
+ const addString = (text2) => {
257
+ const measured = quotedJsonByteLength(text2, limits.maximumStringBytes);
258
+ aggregateStringBytes += measured.raw;
259
+ assertLimit(aggregateStringBytes, limits.maximumAggregateStringBytes, "aggregate-string-bytes");
260
+ return measured.quoted;
261
+ };
262
+ const visit = (current, depth) => {
263
+ if (depth > limits.maximumDepth) fail("depth");
264
+ nodes += 1;
265
+ assertLimit(nodes, limits.maximumNodes, "nodes");
266
+ if (current === null) {
267
+ addAggregate(4);
268
+ return null;
123
269
  }
124
- if (typeof current === "number") {
125
- if (!Number.isFinite(current)) {
126
- throw new TypeError(`${path} contains a non-finite number.`);
127
- }
128
- return Object.is(current, -0) ? "0" : JSON.stringify(current);
270
+ if (typeof current === "string") {
271
+ addAggregate(addString(current));
272
+ return current;
129
273
  }
130
- if (typeof current !== "object") {
131
- throw new TypeError(`${path} contains a value that JSON cannot represent.`);
274
+ if (typeof current === "boolean") {
275
+ addAggregate(current ? 4 : 5);
276
+ return current;
132
277
  }
133
- if (ancestors.has(current)) {
134
- throw new TypeError(`${path} contains a circular reference.`);
278
+ if (typeof current === "number") {
279
+ if (!Number.isFinite(current)) fail("non-finite");
280
+ const normalized = Object.is(current, -0) ? 0 : current;
281
+ addAggregate(JSON.stringify(normalized).length);
282
+ return normalized;
135
283
  }
284
+ if (typeof current !== "object") fail("value");
285
+ if (ancestors.has(current)) fail("cycle");
286
+ const isArray = inspected(() => Array.isArray(current));
287
+ const prototype = inspected(() => Reflect.getPrototypeOf(current));
288
+ if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) fail("shape");
136
289
  ancestors.add(current);
137
290
  try {
138
- if (Array.isArray(current)) {
139
- return `[${current.map((item, index) => visit(item, `${path}[${index}]`)).join(",")}]`;
291
+ if (isArray) {
292
+ const lengthDescriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, "length"));
293
+ if (!lengthDescriptor || !Object.hasOwn(lengthDescriptor, "value") || lengthDescriptor.enumerable || typeof lengthDescriptor.value !== "number" || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0) fail("shape");
294
+ const length = lengthDescriptor.value;
295
+ assertLimit(length, limits.maximumArrayLength, "array-length");
296
+ elements += length;
297
+ assertLimit(elements, limits.maximumElements, "elements");
298
+ const ownKeys2 = inspected(() => Reflect.ownKeys(current));
299
+ if (ownKeys2.some((key) => typeof key !== "string")) fail("shape");
300
+ if (ownKeys2.length !== length + 1) fail("shape");
301
+ const keySet = new Set(ownKeys2);
302
+ if (!keySet.delete("length")) fail("shape");
303
+ const output2 = new Array(length);
304
+ addAggregate(2 + Math.max(0, length - 1));
305
+ for (let index = 0; index < length; index += 1) {
306
+ const key = String(index);
307
+ if (!keySet.delete(key)) fail("shape");
308
+ const descriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, key));
309
+ if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) fail("shape");
310
+ Object.defineProperty(output2, key, {
311
+ configurable: true,
312
+ enumerable: true,
313
+ value: visit(descriptor.value, depth + 1),
314
+ writable: true
315
+ });
316
+ }
317
+ if (keySet.size !== 0) fail("shape");
318
+ return output2;
140
319
  }
141
- if (!isPlainObject(current)) {
142
- throw new TypeError(`${path} must contain only plain JSON objects.`);
320
+ const ownKeys = inspected(() => Reflect.ownKeys(current));
321
+ if (ownKeys.some((key) => typeof key !== "string")) fail("shape");
322
+ properties += ownKeys.length;
323
+ assertLimit(properties, limits.maximumProperties, "properties");
324
+ addAggregate(2 + Math.max(0, ownKeys.length - 1) + ownKeys.length);
325
+ const output = {};
326
+ for (const key of ownKeys) {
327
+ addAggregate(addString(key));
328
+ const descriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, key));
329
+ if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) fail("shape");
330
+ Object.defineProperty(output, key, {
331
+ configurable: true,
332
+ enumerable: true,
333
+ value: visit(descriptor.value, depth + 1),
334
+ writable: true
335
+ });
143
336
  }
144
- const keys = Object.keys(current).sort();
145
- const properties = keys.map((key) => {
146
- assertUnicodeScalarString(key, `${path} key`);
147
- const member = current[key];
148
- if (member === void 0) {
149
- throw new TypeError(`${path}.${key} is undefined.`);
150
- }
151
- return `${JSON.stringify(key)}:${visit(member, `${path}.${key}`)}`;
152
- });
153
- return `{${properties.join(",")}}`;
337
+ return output;
154
338
  } finally {
155
339
  ancestors.delete(current);
156
340
  }
157
341
  };
158
- return visit(value, "$root");
342
+ return visit(value, 0);
343
+ }
344
+ function serializeSnapshot(value) {
345
+ if (value === null) return "null";
346
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
347
+ if (typeof value === "number") return JSON.stringify(value);
348
+ if (Array.isArray(value)) return `[${value.map(serializeSnapshot).join(",")}]`;
349
+ const input = value;
350
+ return `{${Object.keys(input).sort().map((key) => `${JSON.stringify(key)}:${serializeSnapshot(input[key])}`).join(",")}}`;
351
+ }
352
+ function canonicalizeGpuContract(value) {
353
+ return serializeSnapshot(snapshotGpuContract(value));
159
354
  }
160
355
  function parseCanonicalJson(value) {
161
- const parsed = JSON.parse(value);
162
- if (canonicalizeGpuContract(parsed) !== value) throw new TypeError("JSON input is valid but not in canonical form.");
163
- return parsed;
356
+ if (typeof value !== "string") throw new TypeError("Canonical GPU contract JSON must be a string.");
357
+ try {
358
+ utf8ByteLength(value, GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes);
359
+ } catch {
360
+ throw new TypeError("Canonical GPU contract JSON is invalid or exceeds its input bound.");
361
+ }
362
+ let parsed;
363
+ try {
364
+ parsed = JSON.parse(value);
365
+ } catch {
366
+ throw new TypeError("Canonical GPU contract JSON is invalid or exceeds its input bound.");
367
+ }
368
+ const snapshot = snapshotGpuContract(parsed);
369
+ if (serializeSnapshot(snapshot) !== value) throw new TypeError("JSON input is valid but not in canonical form.");
370
+ return snapshot;
164
371
  }
165
372
 
166
373
  // src/hash.ts
@@ -242,39 +449,41 @@ function modelProjection(manifest) {
242
449
  };
243
450
  }
244
451
  async function computeGpuAbiHash(input) {
245
- if (input.kind === "model") {
452
+ const snapshot = snapshotGpuContract(input);
453
+ if (snapshot.kind === "model") {
246
454
  return computeSha256(
247
455
  `plasius.gpu.model-abi/v1
248
- ${canonicalizeGpuContract(modelProjection(input.interface))}`
456
+ ${canonicalizeGpuContract(modelProjection(snapshot.interface))}`
249
457
  );
250
458
  }
251
- if (input.kind === "interface") {
459
+ if (snapshot.kind === "interface") {
252
460
  return computeSha256(
253
461
  `plasius.gpu.interface-abi/v1
254
- ${canonicalizeGpuContract(interfaceProjection(input.interface))}`
462
+ ${canonicalizeGpuContract(interfaceProjection(snapshot.interface))}`
255
463
  );
256
464
  }
257
465
  const pipelines = sorted(
258
- input.pipelines,
466
+ snapshot.pipelines,
259
467
  (left, right) => compareString(left.pipelineId, right.pipelineId)
260
468
  );
261
469
  const requirements = {
262
- semantics: [...input.requirements.semantics].sort(),
263
- features: [...input.requirements.features].sort(),
264
- limits: sorted(input.requirements.limits, (left, right) => compareString(left.name, right.name)),
265
- formats: [...input.requirements.formats].sort()
470
+ semantics: [...snapshot.requirements.semantics].sort(),
471
+ features: [...snapshot.requirements.features].sort(),
472
+ limits: sorted(snapshot.requirements.limits, (left, right) => compareString(left.name, right.name)),
473
+ formats: [...snapshot.requirements.formats].sort()
266
474
  };
267
475
  return computeSha256(
268
476
  `plasius.gpu.shader-abi/v1
269
477
  ${canonicalizeGpuContract({
270
- interface: interfaceProjection(input.interface),
478
+ interface: interfaceProjection(snapshot.interface),
271
479
  pipelines,
272
480
  requirements
273
481
  })}`
274
482
  );
275
483
  }
276
484
  async function computeShaderManifestCoreSha256(manifest) {
277
- const core = Object.fromEntries(Object.entries(manifest).filter(
485
+ const snapshot = snapshotGpuContract(manifest);
486
+ const core = Object.fromEntries(Object.entries(snapshot).filter(
278
487
  ([key]) => key !== "validationEvidence" && key !== "additionalValidationEvidence"
279
488
  ));
280
489
  return computeSha256(
@@ -911,11 +1120,10 @@ var stages = ["vertex", "fragment", "compute"];
911
1120
  var roles = ["material", "lighting", "outline", "shadow", "post-processing"];
912
1121
  function detachedJson(value, path) {
913
1122
  try {
914
- return JSON.parse(canonicalizeGpuContract(value));
1123
+ return snapshotGpuContract(value);
915
1124
  } catch (cause) {
916
- const detail = cause instanceof Error ? cause.message : "Contract snapshot failed.";
917
- const boundedDetail = [...detail].slice(0, 512).join("");
918
- throw new TypeError(`${path} must contain detached JSON contract data: ${boundedDetail}`, { cause });
1125
+ const detail = cause instanceof GpuContractSnapshotError ? ` ${cause.message}` : "";
1126
+ throw new TypeError(`${path} must contain bounded detached JSON contract data.${detail}`);
919
1127
  }
920
1128
  }
921
1129
  function object(value, path) {
@@ -925,7 +1133,7 @@ function object(value, path) {
925
1133
  function exact(value, keys, path) {
926
1134
  const allowed = new Set(keys);
927
1135
  for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError(`${path}.${key} is not part of this contract version.`);
928
- for (const key of keys) if (!(key in value)) throw new TypeError(`${path}.${key} is required.`);
1136
+ for (const key of keys) if (!Object.hasOwn(value, key)) throw new TypeError(`${path}.${key} is required.`);
929
1137
  }
930
1138
  function text(value, path, maximum = 512) {
931
1139
  if (typeof value !== "string" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 31)) {
@@ -941,11 +1149,8 @@ function token(value, path) {
941
1149
  function immutableVersion(value, path) {
942
1150
  try {
943
1151
  return assertImmutableAssetVersion(value);
944
- } catch (cause) {
945
- throw new TypeError(
946
- `${path} must be an immutable asset version: exact token required; mutable aliases, ranges, wildcards, and URLs are not allowed.`,
947
- { cause }
948
- );
1152
+ } catch {
1153
+ throw new TypeError(`${path} must be an immutable asset version: exact token required; mutable aliases, ranges, wildcards, and URLs are not allowed.`);
949
1154
  }
950
1155
  }
951
1156
  function enumeration(value, values, path) {
@@ -975,8 +1180,8 @@ function nullableToken(value, path) {
975
1180
  function digest(value, path) {
976
1181
  try {
977
1182
  return asSha256Hex(text(value, path, 64));
978
- } catch (cause) {
979
- throw new TypeError(`${path} must be a lowercase SHA-256 digest.`, { cause });
1183
+ } catch {
1184
+ throw new TypeError(`${path} must be a lowercase SHA-256 digest.`);
980
1185
  }
981
1186
  }
982
1187
  function uri(value, path) {
@@ -984,8 +1189,8 @@ function uri(value, path) {
984
1189
  let parsed;
985
1190
  try {
986
1191
  parsed = new URL(result);
987
- } catch (cause) {
988
- throw new TypeError(`${path} must be an absolute immutable asset URI.`, { cause });
1192
+ } catch {
1193
+ throw new TypeError(`${path} must be an absolute immutable asset URI.`);
989
1194
  }
990
1195
  if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.hash) throw new TypeError(`${path} must be credential-free HTTPS without a fragment.`);
991
1196
  const keys = [...parsed.searchParams.keys()].map((key) => key.toLowerCase());
@@ -1798,10 +2003,23 @@ function parseModelGpuCompatibilityDescriptor(value) {
1798
2003
  return freeze(input);
1799
2004
  }
1800
2005
  function parseJsonBytes(bytes, label) {
2006
+ const safeLabel = typeof label === "string" && /^[A-Za-z0-9 ._-]{1,80}$/u.test(label) ? label : "GPU contract";
2007
+ let snapshot;
1801
2008
  try {
1802
- return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1803
- } catch (cause) {
1804
- throw new TypeError(`${label} is not valid UTF-8 JSON.`, { cause });
2009
+ snapshot = snapshotUint8Array(bytes, GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes);
2010
+ } catch {
2011
+ throw new TypeError(`${safeLabel} is not bounded UTF-8 JSON.`);
2012
+ }
2013
+ let parsed;
2014
+ try {
2015
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(snapshot));
2016
+ } catch {
2017
+ throw new TypeError(`${safeLabel} is not valid UTF-8 JSON.`);
2018
+ }
2019
+ try {
2020
+ return snapshotGpuContract(parsed);
2021
+ } catch {
2022
+ throw new TypeError(`${safeLabel} is not bounded detached JSON contract data.`);
1805
2023
  }
1806
2024
  }
1807
2025
 
@@ -1816,9 +2034,6 @@ function error(code, message, path) {
1816
2034
  function interfaceMatches(item, model) {
1817
2035
  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;
1818
2036
  }
1819
- function detachedContract(value) {
1820
- return JSON.parse(canonicalizeGpuContract(value));
1821
- }
1822
2037
  function hasValidationEvidence(value) {
1823
2038
  return typeof value === "object" && value !== null && !Array.isArray(value) && (Object.hasOwn(value, "validationEvidence") || Object.hasOwn(value, "additionalValidationEvidence"));
1824
2039
  }
@@ -1866,16 +2081,25 @@ function validateModelShaderCompatibility(input) {
1866
2081
  let profile;
1867
2082
  let capabilities;
1868
2083
  try {
1869
- const modelSnapshot = detachedContract(input.model);
1870
- const shaderSnapshot = detachedContract(input.shader);
1871
- const gpuInterfaceSnapshot = detachedContract(input.gpuInterface);
1872
- const profileValue = input.profile;
1873
- const profileSnapshot = profileValue === void 0 ? void 0 : detachedContract(profileValue);
2084
+ const snapshot = snapshotGpuContract(input);
2085
+ if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot)) {
2086
+ throw new TypeError("GPU compatibility input must be a bounded contract object.");
2087
+ }
2088
+ const envelope = snapshot;
2089
+ const keys = Object.keys(envelope);
2090
+ const allowed = /* @__PURE__ */ new Set(["model", "shader", "gpuInterface", "profile", "capabilities"]);
2091
+ if (keys.some((key) => !allowed.has(key)) || !["model", "shader", "gpuInterface"].every((key) => Object.hasOwn(envelope, key))) {
2092
+ throw new TypeError("GPU compatibility input has unknown or missing fields.");
2093
+ }
2094
+ const modelSnapshot = envelope.model;
2095
+ const shaderSnapshot = envelope.shader;
2096
+ const gpuInterfaceSnapshot = envelope.gpuInterface;
2097
+ const profileSnapshot = Object.hasOwn(envelope, "profile") ? envelope.profile : void 0;
1874
2098
  model = parseModelGpuCompatibilityDescriptor(modelSnapshot);
1875
2099
  shader = hasValidationEvidence(shaderSnapshot) ? parseShaderVersionManifest(shaderSnapshot) : parseShaderVersionManifestCore(shaderSnapshot);
1876
2100
  gpuInterface = parseGpuInterfaceManifest(gpuInterfaceSnapshot);
1877
2101
  profile = profileSnapshot === void 0 ? void 0 : parseShaderStyleProfileManifest(profileSnapshot);
1878
- capabilities = input.capabilities;
2102
+ capabilities = Object.hasOwn(envelope, "capabilities") ? envelope.capabilities : void 0;
1879
2103
  } catch (cause) {
1880
2104
  return {
1881
2105
  ok: false,
@@ -2053,34 +2277,146 @@ function requireTrustedPreparedShaderStyleProfile(value) {
2053
2277
  function diagnostic(code, message, path) {
2054
2278
  return { code, severity: "error", message, ...path ? { path } : {} };
2055
2279
  }
2280
+ var CatalogLoadError = class extends TypeError {
2281
+ diagnosticCode;
2282
+ constructor(message, diagnosticCode = "invalid-contract") {
2283
+ super(message);
2284
+ this.name = "CatalogLoadError";
2285
+ this.diagnosticCode = diagnosticCode;
2286
+ }
2287
+ };
2288
+ function catalogFailure(message, diagnosticCode = "invalid-contract") {
2289
+ return new CatalogLoadError(message, diagnosticCode);
2290
+ }
2291
+ function catalogContractStep(operation, fallback) {
2292
+ try {
2293
+ return operation();
2294
+ } catch (cause) {
2295
+ if (cause instanceof CatalogLoadError) throw cause;
2296
+ throw catalogFailure(cause instanceof TypeError ? cause.message : fallback);
2297
+ }
2298
+ }
2299
+ async function catalogContractStepAsync(operation, fallback) {
2300
+ try {
2301
+ return await operation();
2302
+ } catch (cause) {
2303
+ if (cause instanceof CatalogLoadError) throw cause;
2304
+ throw catalogFailure(cause instanceof TypeError ? cause.message : fallback);
2305
+ }
2306
+ }
2056
2307
  async function verifyBytes(bytes, expected, label) {
2057
- const actual = await computeSha256(bytes);
2058
- if (actual !== expected) throw new TypeError(`${label} digest does not match its immutable reference.`);
2308
+ const actual = await catalogContractStepAsync(
2309
+ () => computeSha256(bytes),
2310
+ `${label} digest could not be computed.`
2311
+ );
2312
+ if (actual !== expected) {
2313
+ throw catalogFailure(
2314
+ `${label} digest does not match its immutable reference.`,
2315
+ "digest-mismatch"
2316
+ );
2317
+ }
2318
+ }
2319
+ function inspectCatalogAsset(value, label, maximumBytes) {
2320
+ try {
2321
+ if (typeof value !== "object" || value === null) throw new TypeError();
2322
+ const keys = Reflect.ownKeys(value);
2323
+ if (keys.length !== 2 || !keys.includes("bytes") || !keys.includes("promoted")) {
2324
+ throw new TypeError();
2325
+ }
2326
+ const bytes = Reflect.getOwnPropertyDescriptor(value, "bytes");
2327
+ const promoted = Reflect.getOwnPropertyDescriptor(value, "promoted");
2328
+ if (!bytes?.enumerable || !Object.hasOwn(bytes, "value") || !promoted?.enumerable || !Object.hasOwn(promoted, "value") || typeof promoted.value !== "boolean") {
2329
+ throw new TypeError();
2330
+ }
2331
+ return Object.freeze({
2332
+ bytes: snapshotUint8Array(bytes.value, maximumBytes),
2333
+ promoted: promoted.value
2334
+ });
2335
+ } catch {
2336
+ throw catalogFailure(`${label} returned invalid detached asset bytes.`);
2337
+ }
2338
+ }
2339
+ async function loadCatalogAsset(operation, label, maximumBytes) {
2340
+ let value;
2341
+ try {
2342
+ value = await operation();
2343
+ } catch {
2344
+ throw catalogFailure(`${label} provider request failed.`);
2345
+ }
2346
+ return inspectCatalogAsset(value, label, maximumBytes);
2347
+ }
2348
+ function isCatalogAssetUri(catalog, uri2) {
2349
+ try {
2350
+ const result = catalog.isCatalogAssetUri(uri2);
2351
+ if (typeof result !== "boolean") throw new TypeError();
2352
+ return result;
2353
+ } catch {
2354
+ throw catalogFailure("Promoted catalog URI validation failed.");
2355
+ }
2059
2356
  }
2060
- function copyBytes(bytes) {
2061
- return new Uint8Array(bytes);
2357
+ function inspectLoadRequest(value) {
2358
+ try {
2359
+ if (typeof value !== "object" || value === null) throw new TypeError();
2360
+ const keys = Reflect.ownKeys(value);
2361
+ if (keys.some((key) => typeof key !== "string" || !["ref", "catalog", "signal"].includes(key)) || !keys.includes("ref") || !keys.includes("catalog")) {
2362
+ throw new TypeError();
2363
+ }
2364
+ const ref = Reflect.getOwnPropertyDescriptor(value, "ref");
2365
+ const catalog = Reflect.getOwnPropertyDescriptor(value, "catalog");
2366
+ const signal = Reflect.getOwnPropertyDescriptor(value, "signal");
2367
+ if (!ref?.enumerable || !Object.hasOwn(ref, "value") || !catalog?.enumerable || !Object.hasOwn(catalog, "value") || signal !== void 0 && (!signal.enumerable || !Object.hasOwn(signal, "value"))) {
2368
+ throw new TypeError();
2369
+ }
2370
+ return Object.freeze({
2371
+ ref: ref.value,
2372
+ catalog: catalog.value,
2373
+ ...signal === void 0 ? {} : { signal: signal.value }
2374
+ });
2375
+ } catch {
2376
+ throw catalogFailure("Style profile load request must use enumerable own data properties.");
2377
+ }
2378
+ }
2379
+ function referenceObject(value, keys, label) {
2380
+ let snapshot;
2381
+ try {
2382
+ snapshot = snapshotGpuContract(value);
2383
+ } catch {
2384
+ throw catalogFailure(`${label} must contain bounded detached JSON contract data.`);
2385
+ }
2386
+ if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot)) {
2387
+ throw catalogFailure(`${label} must be an object.`);
2388
+ }
2389
+ const record = snapshot;
2390
+ const actual = Object.keys(record);
2391
+ if (actual.some((key) => !keys.includes(key)) || keys.some((key) => !Object.hasOwn(record, key)) || actual.some((key) => typeof record[key] !== "string")) {
2392
+ throw catalogFailure(`${label} has unknown, missing, or non-string fields.`);
2393
+ }
2394
+ return record;
2062
2395
  }
2063
2396
  function snapshotProfileRef(ref) {
2064
- const profileId = ref.profileId;
2065
- const version = ref.version;
2066
- const manifestUri = ref.manifestUri;
2067
- const manifestSha256 = ref.manifestSha256;
2397
+ const value = referenceObject(ref, ["profileId", "version", "manifestUri", "manifestSha256"], "Style profile reference");
2398
+ const profileId = value.profileId;
2399
+ const version = value.version;
2400
+ const manifestUri = value.manifestUri;
2401
+ const manifestSha256 = value.manifestSha256;
2068
2402
  return Object.freeze({ profileId, version, manifestUri, manifestSha256 });
2069
2403
  }
2070
2404
  function snapshotShaderRef(ref) {
2071
- const shaderId = ref.shaderId;
2072
- const version = ref.version;
2073
- const manifestUri = ref.manifestUri;
2074
- const manifestSha256 = ref.manifestSha256;
2405
+ const value = referenceObject(ref, ["shaderId", "version", "manifestUri", "manifestSha256"], "Shader version reference");
2406
+ const shaderId = value.shaderId;
2407
+ const version = value.version;
2408
+ const manifestUri = value.manifestUri;
2409
+ const manifestSha256 = value.manifestSha256;
2075
2410
  return Object.freeze({ shaderId, version, manifestUri, manifestSha256 });
2076
2411
  }
2077
2412
  function snapshotInterfaceRef(ref) {
2078
- const interfaceId = ref.interfaceId;
2079
- const interfaceVersion = ref.interfaceVersion;
2080
- const manifestUri = ref.manifestUri;
2081
- const manifestSha256 = ref.manifestSha256;
2082
- const interfaceAbiHash = ref.interfaceAbiHash;
2083
- const modelAbiHash = ref.modelAbiHash;
2413
+ const value = referenceObject(ref, ["interfaceId", "interfaceVersion", "manifestUri", "manifestSha256", "interfaceAbiHash", "modelAbiHash"], "GPU interface reference");
2414
+ const interfaceId = value.interfaceId;
2415
+ const interfaceVersion = value.interfaceVersion;
2416
+ const manifestUri = value.manifestUri;
2417
+ const manifestSha256 = value.manifestSha256;
2418
+ const interfaceAbiHash = value.interfaceAbiHash;
2419
+ const modelAbiHash = value.modelAbiHash;
2084
2420
  return Object.freeze({
2085
2421
  interfaceId,
2086
2422
  interfaceVersion,
@@ -2090,8 +2426,24 @@ function snapshotInterfaceRef(ref) {
2090
2426
  modelAbiHash
2091
2427
  });
2092
2428
  }
2429
+ function assertCatalogAssetVersion(value, label) {
2430
+ try {
2431
+ assertImmutableAssetVersion(value);
2432
+ } catch {
2433
+ throw catalogFailure(`${label} must use an immutable asset version represented by an exact token.`);
2434
+ }
2435
+ }
2436
+ var ABORTED_GETTER = typeof AbortSignal === "undefined" ? void 0 : Reflect.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")?.get;
2093
2437
  function throwIfAborted(signal) {
2094
- if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError");
2438
+ if (signal === void 0) return;
2439
+ let aborted;
2440
+ try {
2441
+ if (!ABORTED_GETTER) throw new TypeError();
2442
+ aborted = Reflect.apply(ABORTED_GETTER, signal, []);
2443
+ } catch {
2444
+ throw catalogFailure("Abort signal could not be inspected safely.");
2445
+ }
2446
+ if (aborted === true) throw new DOMException("Aborted", "AbortError");
2095
2447
  }
2096
2448
  function exactShaderRefKey(ref) {
2097
2449
  return `${ref.shaderId}\0${ref.version}\0${ref.manifestUri}\0${ref.manifestSha256}`;
@@ -2127,7 +2479,7 @@ function assertDistinctEvidenceOwnership(shaders) {
2127
2479
  ]) {
2128
2480
  const owner = owners.get(value);
2129
2481
  if (owner !== void 0 && owner !== shaderKey) {
2130
- throw new TypeError(`Distinct shader versions in one style profile reuse the same ${kind}.`);
2482
+ throw catalogFailure(`Distinct shader versions in one style profile reuse the same ${kind}.`);
2131
2483
  }
2132
2484
  owners.set(value, shaderKey);
2133
2485
  }
@@ -2153,93 +2505,135 @@ async function mapLimit(values, limit, operation, signal) {
2153
2505
  }
2154
2506
  async function loadInterface(catalog, ref, signal) {
2155
2507
  throwIfAborted(signal);
2156
- assertImmutableAssetVersion(ref.interfaceVersion);
2157
- if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError("GPU interface URI is outside the promoted catalog root.");
2158
- const loaded = await catalog.loadInterface(ref, signal);
2159
- const bytes = copyBytes(loaded.bytes);
2508
+ assertCatalogAssetVersion(ref.interfaceVersion, "GPU interface reference");
2509
+ if (!isCatalogAssetUri(catalog, ref.manifestUri)) throw catalogFailure("GPU interface URI is outside the promoted catalog root.");
2510
+ const loaded = await loadCatalogAsset(
2511
+ () => catalog.loadInterface(ref, signal),
2512
+ "GPU interface",
2513
+ GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2514
+ );
2515
+ const bytes = loaded.bytes;
2160
2516
  const promoted = loaded.promoted;
2161
2517
  throwIfAborted(signal);
2162
- if (!promoted) throw new TypeError("GPU interface is not promoted.");
2518
+ if (!promoted) throw catalogFailure("GPU interface is not promoted.", "unpromoted-asset");
2163
2519
  await verifyBytes(bytes, ref.manifestSha256, "GPU interface manifest");
2164
- const manifest = parseGpuInterfaceManifest(parseJsonBytes(bytes, "GPU interface manifest"));
2520
+ const manifest = catalogContractStep(
2521
+ () => parseGpuInterfaceManifest(parseJsonBytes(bytes, "GPU interface manifest")),
2522
+ "GPU interface manifest failed strict contract validation."
2523
+ );
2165
2524
  if (manifest.interfaceId !== ref.interfaceId || manifest.interfaceVersion !== ref.interfaceVersion || manifest.interfaceAbiHash !== ref.interfaceAbiHash || manifest.modelAbiHash !== ref.modelAbiHash) {
2166
- throw new TypeError("GPU interface manifest identity does not match its exact reference.");
2525
+ throw catalogFailure("GPU interface manifest identity does not match its exact reference.");
2167
2526
  }
2168
- const modelAbiHash = await computeGpuAbiHash({ kind: "model", interface: manifest });
2169
- const interfaceAbiHash = await computeGpuAbiHash({ kind: "interface", interface: manifest });
2527
+ const modelAbiHash = await catalogContractStepAsync(
2528
+ () => computeGpuAbiHash({ kind: "model", interface: manifest }),
2529
+ "GPU interface model ABI hash regeneration failed."
2530
+ );
2531
+ const interfaceAbiHash = await catalogContractStepAsync(
2532
+ () => computeGpuAbiHash({ kind: "interface", interface: manifest }),
2533
+ "GPU interface ABI hash regeneration failed."
2534
+ );
2170
2535
  if (modelAbiHash !== manifest.modelAbiHash || interfaceAbiHash !== manifest.interfaceAbiHash) {
2171
- throw new TypeError("GPU interface ABI hashes do not match regenerated structural hashes.");
2536
+ throw catalogFailure("GPU interface ABI hashes do not match regenerated structural hashes.");
2172
2537
  }
2173
2538
  return manifest;
2174
2539
  }
2175
2540
  async function loadShader(catalog, ref, signal) {
2176
2541
  throwIfAborted(signal);
2177
- assertImmutableAssetVersion(ref.version);
2178
- if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError("Shader manifest URI is outside the promoted catalog root.");
2179
- const loaded = await catalog.loadShader(ref, signal);
2180
- const bytes = copyBytes(loaded.bytes);
2542
+ assertCatalogAssetVersion(ref.version, "Shader reference");
2543
+ if (!isCatalogAssetUri(catalog, ref.manifestUri)) throw catalogFailure("Shader manifest URI is outside the promoted catalog root.");
2544
+ const loaded = await loadCatalogAsset(
2545
+ () => catalog.loadShader(ref, signal),
2546
+ "Shader manifest",
2547
+ GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2548
+ );
2549
+ const bytes = loaded.bytes;
2181
2550
  const promoted = loaded.promoted;
2182
2551
  throwIfAborted(signal);
2183
- if (!promoted) throw new TypeError("Shader version is not promoted.");
2552
+ if (!promoted) throw catalogFailure("Shader version is not promoted.", "unpromoted-asset");
2184
2553
  await verifyBytes(bytes, ref.manifestSha256, "Shader manifest");
2185
- const manifest = parseShaderVersionManifest(parseJsonBytes(bytes, "Shader manifest"));
2554
+ const manifest = catalogContractStep(
2555
+ () => parseShaderVersionManifest(parseJsonBytes(bytes, "Shader manifest")),
2556
+ "Shader manifest failed strict contract validation."
2557
+ );
2186
2558
  if (manifest.shaderId !== ref.shaderId || manifest.version !== ref.version) {
2187
- throw new TypeError("Shader manifest identity does not match its exact reference.");
2559
+ throw catalogFailure("Shader manifest identity does not match its exact reference.");
2188
2560
  }
2189
2561
  for (const evidence of [
2190
2562
  manifest.validationEvidence,
2191
2563
  ...manifest.additionalValidationEvidence.map((item) => item.evidence)
2192
2564
  ]) {
2193
- if (!catalog.isCatalogAssetUri(evidence.uri)) throw new TypeError("Shader validation evidence URI is outside the promoted catalog root.");
2194
- if (!catalog.isCatalogAssetUri(evidence.attestationRef.uri)) throw new TypeError("Shader validation evidence attestation URI is outside the promoted catalog root.");
2565
+ if (!isCatalogAssetUri(catalog, evidence.uri)) throw catalogFailure("Shader validation evidence URI is outside the promoted catalog root.");
2566
+ if (!isCatalogAssetUri(catalog, evidence.attestationRef.uri)) throw catalogFailure("Shader validation evidence attestation URI is outside the promoted catalog root.");
2195
2567
  }
2196
2568
  const interfaceRef2 = snapshotInterfaceRef(manifest.gpuInterface);
2197
2569
  const gpuInterface = await loadInterface(catalog, interfaceRef2, signal);
2198
2570
  const normalizeModules = (values) => [...values].sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0).map(({ moduleId, sha256 }) => ({ moduleId, sha256 }));
2199
- if (canonicalizeGpuContract(normalizeModules(gpuInterface.modules)) !== canonicalizeGpuContract(normalizeModules(manifest.modules))) {
2200
- throw new TypeError("Shader modules differ from the exact reflected GPU interface module set.");
2201
- }
2202
- const shaderAbiHash = await computeGpuAbiHash({
2203
- kind: "shader",
2204
- interface: gpuInterface,
2205
- pipelines: manifest.pipelines,
2206
- requirements: manifest.requirements
2207
- });
2208
- if (shaderAbiHash !== manifest.shaderAbiHash) throw new TypeError("Shader ABI hash differs from regenerated pipeline/interface ABI.");
2571
+ if (catalogContractStep(
2572
+ () => canonicalizeGpuContract(normalizeModules(gpuInterface.modules)) !== canonicalizeGpuContract(normalizeModules(manifest.modules)),
2573
+ "Shader module-set comparison failed."
2574
+ )) {
2575
+ throw catalogFailure("Shader modules differ from the exact reflected GPU interface module set.");
2576
+ }
2577
+ const shaderAbiHash = await catalogContractStepAsync(
2578
+ () => computeGpuAbiHash({
2579
+ kind: "shader",
2580
+ interface: gpuInterface,
2581
+ pipelines: manifest.pipelines,
2582
+ requirements: manifest.requirements
2583
+ }),
2584
+ "Shader ABI hash regeneration failed."
2585
+ );
2586
+ if (shaderAbiHash !== manifest.shaderAbiHash) throw catalogFailure("Shader ABI hash differs from regenerated pipeline/interface ABI.");
2209
2587
  const modulePairs = await mapLimit(manifest.modules, 4, async (module2) => {
2210
2588
  throwIfAborted(signal);
2211
- if (!catalog.isCatalogAssetUri(module2.uri)) throw new TypeError(`Shader module ${module2.moduleId} URI is outside the promoted catalog root.`);
2212
- const asset = await catalog.loadModule(ref, module2.moduleId, module2.uri, signal);
2213
- const moduleBytes = copyBytes(asset.bytes);
2589
+ if (!isCatalogAssetUri(catalog, module2.uri)) throw catalogFailure(`Shader module ${module2.moduleId} URI is outside the promoted catalog root.`);
2590
+ const asset = await loadCatalogAsset(
2591
+ () => catalog.loadModule(ref, module2.moduleId, module2.uri, signal),
2592
+ `Shader module ${module2.moduleId}`,
2593
+ module2.byteLength
2594
+ );
2595
+ const moduleBytes = asset.bytes;
2214
2596
  const promoted2 = asset.promoted;
2215
2597
  throwIfAborted(signal);
2216
- if (!promoted2) throw new TypeError(`Shader module ${module2.moduleId} is not promoted.`);
2598
+ if (!promoted2) throw catalogFailure(`Shader module ${module2.moduleId} is not promoted.`, "unpromoted-asset");
2217
2599
  if (moduleBytes.byteLength !== module2.byteLength) {
2218
- throw new TypeError(`Shader module ${module2.moduleId} byte length does not match its manifest.`);
2600
+ throw catalogFailure(`Shader module ${module2.moduleId} byte length does not match its manifest.`);
2219
2601
  }
2220
2602
  await verifyBytes(moduleBytes, module2.sha256, `Shader module ${module2.moduleId}`);
2221
2603
  return [module2.moduleId, moduleBytes];
2222
2604
  }, signal);
2223
2605
  const decoder = new TextDecoder("utf-8", { fatal: true });
2224
- validateShaderDerivedRequirements({ manifest, gpuInterface, moduleSources: new Map(modulePairs.map(([moduleId, bytes2]) => [moduleId, decoder.decode(bytes2)])) });
2606
+ catalogContractStep(
2607
+ () => validateShaderDerivedRequirements({ manifest, gpuInterface, moduleSources: new Map(modulePairs.map(([moduleId, bytes2]) => [moduleId, decoder.decode(bytes2)])) }),
2608
+ "Shader source requirement validation failed."
2609
+ );
2225
2610
  return { ref, manifest, gpuInterface, modules: new Map(modulePairs) };
2226
2611
  }
2227
2612
  async function loadShaderStyleProfile(input) {
2228
- const signal = input.signal;
2229
2613
  try {
2614
+ const request = inspectLoadRequest(input);
2615
+ const signal = request.signal;
2616
+ const catalog = request.catalog;
2230
2617
  throwIfAborted(signal);
2231
- const ref = snapshotProfileRef(input.ref);
2232
- assertImmutableAssetVersion(ref.version);
2233
- if (!input.catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError("Style profile URI is outside the promoted catalog root.");
2234
- const loaded = await input.catalog.loadProfile(ref, signal);
2235
- const profileBytes = copyBytes(loaded.bytes);
2618
+ const ref = snapshotProfileRef(request.ref);
2619
+ assertCatalogAssetVersion(ref.version, "Style profile reference");
2620
+ if (!isCatalogAssetUri(catalog, ref.manifestUri)) throw catalogFailure("Style profile URI is outside the promoted catalog root.");
2621
+ const loaded = await loadCatalogAsset(
2622
+ () => catalog.loadProfile(ref, signal),
2623
+ "Style profile",
2624
+ GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2625
+ );
2626
+ const profileBytes = loaded.bytes;
2236
2627
  const promoted = loaded.promoted;
2237
2628
  throwIfAborted(signal);
2238
2629
  if (!promoted) {
2239
2630
  return { ok: false, diagnostics: [diagnostic("unpromoted-asset", "Style profile is not promoted.")] };
2240
2631
  }
2241
2632
  await verifyBytes(profileBytes, ref.manifestSha256, "Style profile manifest");
2242
- const manifest = parseShaderStyleProfileManifest(parseJsonBytes(profileBytes, "Style profile manifest"));
2633
+ const manifest = catalogContractStep(
2634
+ () => parseShaderStyleProfileManifest(parseJsonBytes(profileBytes, "Style profile manifest")),
2635
+ "Style profile manifest failed strict contract validation."
2636
+ );
2243
2637
  if (manifest.profileId !== ref.profileId || manifest.version !== ref.version) {
2244
2638
  return { ok: false, diagnostics: [diagnostic("invalid-contract", "Style profile identity does not match its exact reference.")] };
2245
2639
  }
@@ -2250,12 +2644,12 @@ async function loadShaderStyleProfile(input) {
2250
2644
  const cacheKey = exactShaderRefKey(shaderRef);
2251
2645
  let shader = cache.get(cacheKey);
2252
2646
  if (!shader) {
2253
- shader = loadShader(input.catalog, shaderRef, signal);
2647
+ shader = loadShader(catalog, shaderRef, signal);
2254
2648
  cache.set(cacheKey, shader);
2255
2649
  }
2256
2650
  const resolved = await shader;
2257
2651
  if (!resolved.manifest.renderRoles.some((role) => role.role === binding2.role)) {
2258
- throw new TypeError(`Shader ${resolved.manifest.shaderId} does not implement role ${binding2.role}.`);
2652
+ throw catalogFailure(`Shader ${resolved.manifest.shaderId} does not implement role ${binding2.role}.`);
2259
2653
  }
2260
2654
  const validationScopes = new Map(
2261
2655
  resolved.manifest.additionalValidationEvidence.map((item) => [item.scope, item.evidence])
@@ -2263,10 +2657,10 @@ async function loadShaderStyleProfile(input) {
2263
2657
  for (const requirement of manifest.requiredValidationScopes) {
2264
2658
  const evidence = validationScopes.get(requirement.scope);
2265
2659
  if (!evidence) {
2266
- throw new TypeError(`Shader ${resolved.manifest.shaderId} lacks required validation scope ${requirement.scope}.`);
2660
+ throw catalogFailure(`Shader ${resolved.manifest.shaderId} lacks required validation scope ${requirement.scope}.`);
2267
2661
  }
2268
2662
  if (evidence.matrixId !== requirement.matrixId || evidence.matrixVersion !== requirement.matrixVersion || evidence.matrixSha256 !== requirement.matrixSha256) {
2269
- throw new TypeError(
2663
+ throw catalogFailure(
2270
2664
  `Shader ${resolved.manifest.shaderId} validation scope ${requirement.scope} is bound to a different matrix policy.`
2271
2665
  );
2272
2666
  }
@@ -2283,11 +2677,14 @@ async function loadShaderStyleProfile(input) {
2283
2677
  })
2284
2678
  };
2285
2679
  } catch (cause) {
2286
- if (signal?.aborted) throw cause;
2287
- const code = cause instanceof TypeError && /digest/u.test(cause.message) ? "digest-mismatch" : "invalid-contract";
2680
+ if (cause instanceof DOMException && cause.name === "AbortError") throw cause;
2681
+ const known = cause instanceof CatalogLoadError ? cause : void 0;
2288
2682
  return {
2289
2683
  ok: false,
2290
- diagnostics: [diagnostic(code, cause instanceof Error ? cause.message : "Style profile loading failed.")]
2684
+ diagnostics: [diagnostic(
2685
+ known?.diagnosticCode ?? "invalid-contract",
2686
+ known?.message ?? "Style profile loading failed."
2687
+ )]
2291
2688
  };
2292
2689
  }
2293
2690
  }