@plasius/gpu-shader 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +203 -0
- package/README.md +434 -0
- package/dist/cli.cjs +12742 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +4 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +12718 -0
- package/dist/cli.js.map +1 -0
- package/dist/contracts-C4eel8MT.d.cts +1220 -0
- package/dist/contracts-C4eel8MT.d.ts +1220 -0
- package/dist/index.cjs +2512 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +88 -0
- package/dist/index.d.ts +88 -0
- package/dist/index.js +2456 -0
- package/dist/index.js.map +1 -0
- package/dist/node.cjs +10131 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.cts +50 -0
- package/dist/node.d.ts +50 -0
- package/dist/node.js +10099 -0
- package/dist/node.js.map +1 -0
- package/dist/testing.cjs +1927 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +82 -0
- package/dist/testing.d.ts +82 -0
- package/dist/testing.js +1888 -0
- package/dist/testing.js.map +1 -0
- package/matrices/stable-webgpu-2026-07-13.json +545 -0
- package/package.json +100 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2512 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
GPU_INTERFACE_MANIFEST_VERSION: () => GPU_INTERFACE_MANIFEST_VERSION,
|
|
24
|
+
GPU_SHADER_STORE_FEATURE_FLAG: () => GPU_SHADER_STORE_FEATURE_FLAG,
|
|
25
|
+
GPU_SHADER_STYLE_SELECTION_CAPABILITY: () => GPU_SHADER_STYLE_SELECTION_CAPABILITY,
|
|
26
|
+
SHADER_COMPILE_UNIT_VERSION: () => SHADER_COMPILE_UNIT_VERSION,
|
|
27
|
+
SHADER_QUALIFICATION_BUNDLE_VERSION: () => SHADER_QUALIFICATION_BUNDLE_VERSION,
|
|
28
|
+
SHADER_QUALIFICATION_FIXTURE_VERSION: () => SHADER_QUALIFICATION_FIXTURE_VERSION,
|
|
29
|
+
SHADER_STYLE_PROFILE_MANIFEST_VERSION: () => SHADER_STYLE_PROFILE_MANIFEST_VERSION,
|
|
30
|
+
SHADER_VALIDATION_EVIDENCE_VERSION: () => SHADER_VALIDATION_EVIDENCE_VERSION,
|
|
31
|
+
SHADER_VERSION_MANIFEST_VERSION: () => SHADER_VERSION_MANIFEST_VERSION,
|
|
32
|
+
STABLE_WEBGPU_MATRIX_VERSION: () => STABLE_WEBGPU_MATRIX_VERSION,
|
|
33
|
+
SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES: () => SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES,
|
|
34
|
+
SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES: () => SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES,
|
|
35
|
+
activateStyleProfile: () => activateStyleProfile,
|
|
36
|
+
asSha256Hex: () => asSha256Hex,
|
|
37
|
+
canonicalizeGpuContract: () => canonicalizeGpuContract,
|
|
38
|
+
computeGpuAbiHash: () => computeGpuAbiHash,
|
|
39
|
+
computeSha256: () => computeSha256,
|
|
40
|
+
computeShaderManifestCoreSha256: () => computeShaderManifestCoreSha256,
|
|
41
|
+
createGpuRecordCodec: () => createGpuRecordCodec,
|
|
42
|
+
createShaderStyleController: () => createShaderStyleController,
|
|
43
|
+
loadShaderStyleProfile: () => loadShaderStyleProfile,
|
|
44
|
+
parseCanonicalJson: () => parseCanonicalJson,
|
|
45
|
+
parseGpuInterfaceManifest: () => parseGpuInterfaceManifest,
|
|
46
|
+
parseJsonBytes: () => parseJsonBytes,
|
|
47
|
+
parseModelGpuCompatibilityDescriptor: () => parseModelGpuCompatibilityDescriptor,
|
|
48
|
+
parseShaderStyleProfileManifest: () => parseShaderStyleProfileManifest,
|
|
49
|
+
parseShaderVersionManifest: () => parseShaderVersionManifest,
|
|
50
|
+
parseShaderVersionManifestCore: () => parseShaderVersionManifestCore,
|
|
51
|
+
prepareStyleProfile: () => prepareStyleProfile,
|
|
52
|
+
validateModelShaderCompatibility: () => validateModelShaderCompatibility
|
|
53
|
+
});
|
|
54
|
+
module.exports = __toCommonJS(src_exports);
|
|
55
|
+
|
|
56
|
+
// src/contracts.ts
|
|
57
|
+
var GPU_INTERFACE_MANIFEST_VERSION = "1.0.0";
|
|
58
|
+
var SHADER_VERSION_MANIFEST_VERSION = "1.0.0";
|
|
59
|
+
var SHADER_STYLE_PROFILE_MANIFEST_VERSION = "1.0.0";
|
|
60
|
+
var SHADER_COMPILE_UNIT_VERSION = "1.0.0";
|
|
61
|
+
var SHADER_VALIDATION_EVIDENCE_VERSION = "1.0.0";
|
|
62
|
+
var STABLE_WEBGPU_MATRIX_VERSION = "1.0.0";
|
|
63
|
+
var SHADER_QUALIFICATION_FIXTURE_VERSION = "1.0.0";
|
|
64
|
+
var SHADER_QUALIFICATION_BUNDLE_VERSION = "1.0.0";
|
|
65
|
+
var GPU_SHADER_STORE_FEATURE_FLAG = "asset.pipeline.shader-store.enabled";
|
|
66
|
+
var GPU_SHADER_STYLE_SELECTION_CAPABILITY = "gpu.shader.style.select";
|
|
67
|
+
var SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES = [
|
|
68
|
+
Object.freeze({
|
|
69
|
+
matrixId: "stable-webgpu",
|
|
70
|
+
matrixVersion: "2026-07-13",
|
|
71
|
+
matrixSha256: "9b47ff8162b055d49e38c4fe90b9074992ab8c9e1125926e936f8122e6119fd8"
|
|
72
|
+
})
|
|
73
|
+
];
|
|
74
|
+
Object.freeze(SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES);
|
|
75
|
+
var SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES = Object.freeze([]);
|
|
76
|
+
|
|
77
|
+
// src/canonical-json.ts
|
|
78
|
+
function isPlainObject(value) {
|
|
79
|
+
const prototype = Object.getPrototypeOf(value);
|
|
80
|
+
return prototype === Object.prototype || prototype === null;
|
|
81
|
+
}
|
|
82
|
+
function assertUnicodeScalarString(value, path) {
|
|
83
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
84
|
+
const code = value.charCodeAt(index);
|
|
85
|
+
if (code >= 55296 && code <= 56319) {
|
|
86
|
+
const next = value.charCodeAt(index + 1);
|
|
87
|
+
if (!(next >= 56320 && next <= 57343)) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);
|
|
88
|
+
index += 1;
|
|
89
|
+
} else if (code >= 56320 && code <= 57343) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function canonicalizeGpuContract(value) {
|
|
93
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
94
|
+
const visit = (current, path) => {
|
|
95
|
+
if (current === null) return "null";
|
|
96
|
+
if (typeof current === "string" || typeof current === "boolean") {
|
|
97
|
+
if (typeof current === "string") assertUnicodeScalarString(current, path);
|
|
98
|
+
return JSON.stringify(current);
|
|
99
|
+
}
|
|
100
|
+
if (typeof current === "number") {
|
|
101
|
+
if (!Number.isFinite(current)) {
|
|
102
|
+
throw new TypeError(`${path} contains a non-finite number.`);
|
|
103
|
+
}
|
|
104
|
+
return Object.is(current, -0) ? "0" : JSON.stringify(current);
|
|
105
|
+
}
|
|
106
|
+
if (typeof current !== "object") {
|
|
107
|
+
throw new TypeError(`${path} contains a value that JSON cannot represent.`);
|
|
108
|
+
}
|
|
109
|
+
if (ancestors.has(current)) {
|
|
110
|
+
throw new TypeError(`${path} contains a circular reference.`);
|
|
111
|
+
}
|
|
112
|
+
ancestors.add(current);
|
|
113
|
+
try {
|
|
114
|
+
if (Array.isArray(current)) {
|
|
115
|
+
return `[${current.map((item, index) => visit(item, `${path}[${index}]`)).join(",")}]`;
|
|
116
|
+
}
|
|
117
|
+
if (!isPlainObject(current)) {
|
|
118
|
+
throw new TypeError(`${path} must contain only plain JSON objects.`);
|
|
119
|
+
}
|
|
120
|
+
const keys = Object.keys(current).sort();
|
|
121
|
+
const properties = keys.map((key) => {
|
|
122
|
+
assertUnicodeScalarString(key, `${path} key`);
|
|
123
|
+
const member = current[key];
|
|
124
|
+
if (member === void 0) {
|
|
125
|
+
throw new TypeError(`${path}.${key} is undefined.`);
|
|
126
|
+
}
|
|
127
|
+
return `${JSON.stringify(key)}:${visit(member, `${path}.${key}`)}`;
|
|
128
|
+
});
|
|
129
|
+
return `{${properties.join(",")}}`;
|
|
130
|
+
} finally {
|
|
131
|
+
ancestors.delete(current);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
return visit(value, "$root");
|
|
135
|
+
}
|
|
136
|
+
function parseCanonicalJson(value) {
|
|
137
|
+
const parsed = JSON.parse(value);
|
|
138
|
+
if (canonicalizeGpuContract(parsed) !== value) throw new TypeError("JSON input is valid but not in canonical form.");
|
|
139
|
+
return parsed;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/hash.ts
|
|
143
|
+
var SHA256_PATTERN = /^[a-f0-9]{64}$/u;
|
|
144
|
+
function asSha256Hex(value) {
|
|
145
|
+
if (!SHA256_PATTERN.test(value)) {
|
|
146
|
+
throw new TypeError("SHA-256 values must be lowercase 64-character hexadecimal strings.");
|
|
147
|
+
}
|
|
148
|
+
return value;
|
|
149
|
+
}
|
|
150
|
+
async function computeSha256(value) {
|
|
151
|
+
const subtle = globalThis.crypto?.subtle;
|
|
152
|
+
if (!subtle) {
|
|
153
|
+
throw new Error("Web Crypto SHA-256 support is required.");
|
|
154
|
+
}
|
|
155
|
+
const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
|
|
156
|
+
const digest2 = await subtle.digest("SHA-256", bytes);
|
|
157
|
+
return asSha256Hex(
|
|
158
|
+
Array.from(new Uint8Array(digest2), (byte) => byte.toString(16).padStart(2, "0")).join("")
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
function sorted(items, compare) {
|
|
162
|
+
return [...items].sort(compare);
|
|
163
|
+
}
|
|
164
|
+
function compareString(left, right) {
|
|
165
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
166
|
+
}
|
|
167
|
+
function interfaceProjection(manifest) {
|
|
168
|
+
return {
|
|
169
|
+
contractVersion: manifest.contractVersion,
|
|
170
|
+
records: sorted(manifest.records, (left, right) => compareString(left.name, right.name)),
|
|
171
|
+
bindings: sorted(manifest.bindings, (left, right) => compareString(left.moduleId, right.moduleId) || left.group - right.group || left.binding - right.binding),
|
|
172
|
+
entryPoints: sorted(manifest.entryPoints, (left, right) => compareString(left.moduleId, right.moduleId) || compareString(left.stage, right.stage) || compareString(left.name, right.name)),
|
|
173
|
+
vertexInputs: sorted(manifest.vertexInputs, (left, right) => compareString(left.pipelineId, right.pipelineId) || left.shaderLocation - right.shaderLocation),
|
|
174
|
+
overrides: sorted(manifest.overrides, (left, right) => compareString(left.moduleId, right.moduleId) || compareString(left.name, right.name))
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function modelProjection(manifest) {
|
|
178
|
+
const recordsByName = new Map(manifest.records.map((record) => [record.name, record]));
|
|
179
|
+
const names = /* @__PURE__ */ new Set();
|
|
180
|
+
const includeRecord = (name) => {
|
|
181
|
+
if (names.has(name)) return;
|
|
182
|
+
const record = recordsByName.get(name);
|
|
183
|
+
if (!record) throw new TypeError(`Model ABI references missing record ${name}.`);
|
|
184
|
+
names.add(name);
|
|
185
|
+
const visitType = (type) => {
|
|
186
|
+
if (type.kind === "record") includeRecord(type.recordName);
|
|
187
|
+
if (type.kind === "array") visitType(type.element);
|
|
188
|
+
};
|
|
189
|
+
for (const member of record.members) visitType(member.type);
|
|
190
|
+
};
|
|
191
|
+
for (const name of manifest.modelAbi.recordNames) includeRecord(name);
|
|
192
|
+
for (const binding2 of manifest.modelAbi.bindings) {
|
|
193
|
+
if (binding2.resource.kind === "buffer" && binding2.resource.recordName) includeRecord(binding2.resource.recordName);
|
|
194
|
+
}
|
|
195
|
+
for (const semantic2 of manifest.modelAbi.semantics) {
|
|
196
|
+
if (semantic2.source.kind === "record-member") includeRecord(semantic2.source.recordName);
|
|
197
|
+
}
|
|
198
|
+
const semanticProjection = manifest.modelAbi.semantics.map((projection) => ({
|
|
199
|
+
semantic: projection.semantic,
|
|
200
|
+
source: projection.source.kind === "record-member" ? {
|
|
201
|
+
kind: projection.source.kind,
|
|
202
|
+
recordName: projection.source.recordName,
|
|
203
|
+
memberPath: projection.source.memberPath
|
|
204
|
+
} : { kind: projection.source.kind }
|
|
205
|
+
}));
|
|
206
|
+
return {
|
|
207
|
+
contractVersion: manifest.contractVersion,
|
|
208
|
+
records: sorted(
|
|
209
|
+
manifest.records.filter((record) => names.has(record.name)),
|
|
210
|
+
(left, right) => compareString(left.name, right.name)
|
|
211
|
+
).map(({ addressSpaces: _shaderUsage, ...record }) => record),
|
|
212
|
+
bindings: sorted(manifest.modelAbi.bindings, (left, right) => compareString(left.semantic ?? "", right.semantic ?? "") || compareString(canonicalizeGpuContract(left.resource), canonicalizeGpuContract(right.resource))).map(({ source: _selector, ...binding2 }) => binding2),
|
|
213
|
+
vertexInputs: sorted(manifest.modelAbi.vertexInputs, (left, right) => compareString(left.semantic ?? "", right.semantic ?? "") || left.offset - right.offset).map(({ source: _selector, ...vertex }) => vertex),
|
|
214
|
+
semantics: sorted(
|
|
215
|
+
semanticProjection,
|
|
216
|
+
(left, right) => compareString(left.semantic, right.semantic)
|
|
217
|
+
)
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
async function computeGpuAbiHash(input) {
|
|
221
|
+
if (input.kind === "model") {
|
|
222
|
+
return computeSha256(
|
|
223
|
+
`plasius.gpu.model-abi/v1
|
|
224
|
+
${canonicalizeGpuContract(modelProjection(input.interface))}`
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
if (input.kind === "interface") {
|
|
228
|
+
return computeSha256(
|
|
229
|
+
`plasius.gpu.interface-abi/v1
|
|
230
|
+
${canonicalizeGpuContract(interfaceProjection(input.interface))}`
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
const pipelines = sorted(
|
|
234
|
+
input.pipelines,
|
|
235
|
+
(left, right) => compareString(left.pipelineId, right.pipelineId)
|
|
236
|
+
);
|
|
237
|
+
const requirements = {
|
|
238
|
+
semantics: [...input.requirements.semantics].sort(),
|
|
239
|
+
features: [...input.requirements.features].sort(),
|
|
240
|
+
limits: sorted(input.requirements.limits, (left, right) => compareString(left.name, right.name)),
|
|
241
|
+
formats: [...input.requirements.formats].sort()
|
|
242
|
+
};
|
|
243
|
+
return computeSha256(
|
|
244
|
+
`plasius.gpu.shader-abi/v1
|
|
245
|
+
${canonicalizeGpuContract({
|
|
246
|
+
interface: interfaceProjection(input.interface),
|
|
247
|
+
pipelines,
|
|
248
|
+
requirements
|
|
249
|
+
})}`
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
async function computeShaderManifestCoreSha256(manifest) {
|
|
253
|
+
const core = Object.fromEntries(Object.entries(manifest).filter(
|
|
254
|
+
([key]) => key !== "validationEvidence" && key !== "additionalValidationEvidence"
|
|
255
|
+
));
|
|
256
|
+
return computeSha256(
|
|
257
|
+
`plasius.gpu.shader-manifest-core/v1
|
|
258
|
+
${canonicalizeGpuContract(core)}`
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// src/codec/codec.ts
|
|
263
|
+
function bufferRegion(value) {
|
|
264
|
+
if (value instanceof ArrayBuffer) {
|
|
265
|
+
return { buffer: value, byteOffset: 0, byteLength: value.byteLength };
|
|
266
|
+
}
|
|
267
|
+
if (!(value.buffer instanceof ArrayBuffer)) {
|
|
268
|
+
throw new TypeError("SharedArrayBuffer-backed views are not supported by the codec.");
|
|
269
|
+
}
|
|
270
|
+
return { buffer: value.buffer, byteOffset: value.byteOffset, byteLength: value.byteLength };
|
|
271
|
+
}
|
|
272
|
+
function integer(value, minimum, maximum, path) {
|
|
273
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < minimum || value > maximum) {
|
|
274
|
+
throw new TypeError(`${path} must be an integer from ${minimum} to ${maximum}.`);
|
|
275
|
+
}
|
|
276
|
+
return value;
|
|
277
|
+
}
|
|
278
|
+
function numeric(value, path) {
|
|
279
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
280
|
+
throw new TypeError(`${path} must be a finite number.`);
|
|
281
|
+
}
|
|
282
|
+
return value;
|
|
283
|
+
}
|
|
284
|
+
function scalarByteSize(scalar) {
|
|
285
|
+
if (scalar === "f16") return 2;
|
|
286
|
+
return 4;
|
|
287
|
+
}
|
|
288
|
+
function roundTiesToEven(value) {
|
|
289
|
+
const lower = Math.floor(value);
|
|
290
|
+
const fraction = value - lower;
|
|
291
|
+
if (fraction < 0.5) return lower;
|
|
292
|
+
if (fraction > 0.5) return lower + 1;
|
|
293
|
+
return lower % 2 === 0 ? lower : lower + 1;
|
|
294
|
+
}
|
|
295
|
+
function encodeFloat16Bits(value, path) {
|
|
296
|
+
const input = numeric(value, path);
|
|
297
|
+
const negative = input < 0 || Object.is(input, -0);
|
|
298
|
+
const magnitude = Math.abs(input);
|
|
299
|
+
if (magnitude > 65504) throw new TypeError(`${path} is outside the finite f16 range.`);
|
|
300
|
+
const sign = negative ? 32768 : 0;
|
|
301
|
+
if (magnitude === 0) return sign;
|
|
302
|
+
if (magnitude < 2 ** -14) {
|
|
303
|
+
const significand2 = roundTiesToEven(magnitude / 2 ** -24);
|
|
304
|
+
return sign | significand2;
|
|
305
|
+
}
|
|
306
|
+
let exponent = Math.floor(Math.log2(magnitude));
|
|
307
|
+
let significand = roundTiesToEven(magnitude / 2 ** (exponent - 10));
|
|
308
|
+
if (significand === 2048) {
|
|
309
|
+
exponent += 1;
|
|
310
|
+
significand = 1024;
|
|
311
|
+
}
|
|
312
|
+
if (exponent > 15) throw new TypeError(`${path} is outside the finite f16 range.`);
|
|
313
|
+
return sign | exponent + 15 << 10 | significand - 1024;
|
|
314
|
+
}
|
|
315
|
+
function decodeFloat16Bits(bits, path) {
|
|
316
|
+
const sign = (bits & 32768) === 0 ? 1 : -1;
|
|
317
|
+
const exponent = bits >>> 10 & 31;
|
|
318
|
+
const fraction = bits & 1023;
|
|
319
|
+
if (exponent === 31) throw new TypeError(`${path} contains a non-finite f16 value.`);
|
|
320
|
+
if (exponent === 0) return sign * fraction * 2 ** -24;
|
|
321
|
+
return sign * (1 + fraction / 1024) * 2 ** (exponent - 15);
|
|
322
|
+
}
|
|
323
|
+
function writeScalar(view, offset, scalar, value, path) {
|
|
324
|
+
switch (scalar) {
|
|
325
|
+
case "u32":
|
|
326
|
+
view.setUint32(offset, integer(value, 0, 4294967295, path), true);
|
|
327
|
+
return;
|
|
328
|
+
case "i32":
|
|
329
|
+
view.setInt32(offset, integer(value, -2147483648, 2147483647, path), true);
|
|
330
|
+
return;
|
|
331
|
+
case "f32":
|
|
332
|
+
{
|
|
333
|
+
const rounded = Math.fround(numeric(value, path));
|
|
334
|
+
if (!Number.isFinite(rounded)) throw new TypeError(`${path} is outside the finite f32 range.`);
|
|
335
|
+
view.setFloat32(offset, rounded, true);
|
|
336
|
+
}
|
|
337
|
+
return;
|
|
338
|
+
case "f16":
|
|
339
|
+
view.setUint16(offset, encodeFloat16Bits(value, path), true);
|
|
340
|
+
return;
|
|
341
|
+
case "bool":
|
|
342
|
+
throw new TypeError(`${path} uses bool, which is not host-shareable.`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
function readScalar(view, offset, scalar, path) {
|
|
346
|
+
switch (scalar) {
|
|
347
|
+
case "u32":
|
|
348
|
+
return view.getUint32(offset, true);
|
|
349
|
+
case "i32":
|
|
350
|
+
return view.getInt32(offset, true);
|
|
351
|
+
case "f32":
|
|
352
|
+
return view.getFloat32(offset, true);
|
|
353
|
+
case "f16":
|
|
354
|
+
return decodeFloat16Bits(view.getUint16(offset, true), path);
|
|
355
|
+
case "bool":
|
|
356
|
+
throw new TypeError(`${path} uses bool, which is not host-shareable.`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
function arrayValue(value, expected, path) {
|
|
360
|
+
if (!Array.isArray(value)) {
|
|
361
|
+
throw new TypeError(`${path} must be an array.`);
|
|
362
|
+
}
|
|
363
|
+
if (expected !== null && value.length !== expected) {
|
|
364
|
+
throw new RangeError(`${path} must contain exactly ${expected} values.`);
|
|
365
|
+
}
|
|
366
|
+
return value;
|
|
367
|
+
}
|
|
368
|
+
function assertRecordValue(value, record, path) {
|
|
369
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
370
|
+
throw new TypeError(`${path} must be an object.`);
|
|
371
|
+
}
|
|
372
|
+
const expected = new Set(record.members.map((member) => member.name));
|
|
373
|
+
for (const key of Object.keys(value)) {
|
|
374
|
+
if (!expected.has(key)) throw new TypeError(`${path}.${key} is not a reflected WGSL member.`);
|
|
375
|
+
}
|
|
376
|
+
for (const member of record.members) {
|
|
377
|
+
if (!Object.prototype.hasOwnProperty.call(value, member.name)) {
|
|
378
|
+
throw new TypeError(`${path}.${member.name} is required.`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
function runtimeMember(record) {
|
|
383
|
+
if (record.runtimeArrayMember === null) return null;
|
|
384
|
+
const member = record.members.find((candidate) => candidate.name === record.runtimeArrayMember);
|
|
385
|
+
if (!member || member.type.kind !== "array" || member.type.count !== null) {
|
|
386
|
+
throw new TypeError(`${record.name} has an invalid runtimeArrayMember declaration.`);
|
|
387
|
+
}
|
|
388
|
+
if (record.members.at(-1) !== member) {
|
|
389
|
+
throw new TypeError(`${record.name}.${member.name} must be the trailing member.`);
|
|
390
|
+
}
|
|
391
|
+
return { name: member.name, offset: member.offset, type: member.type };
|
|
392
|
+
}
|
|
393
|
+
function createGpuRecordCodec(record, records = [record]) {
|
|
394
|
+
const byName = new Map(records.map((candidate) => [candidate.name, candidate]));
|
|
395
|
+
if (!byName.has(record.name)) byName.set(record.name, record);
|
|
396
|
+
const runtime = runtimeMember(record);
|
|
397
|
+
const resolveRecord = (name) => {
|
|
398
|
+
const resolved = byName.get(name);
|
|
399
|
+
if (!resolved) throw new TypeError(`Reflected record ${name} is unavailable to the codec.`);
|
|
400
|
+
return resolved;
|
|
401
|
+
};
|
|
402
|
+
const writeType = (view, offset, type, value, path) => {
|
|
403
|
+
switch (type.kind) {
|
|
404
|
+
case "scalar":
|
|
405
|
+
writeScalar(view, offset, type.scalar, value, path);
|
|
406
|
+
return;
|
|
407
|
+
case "atomic":
|
|
408
|
+
writeScalar(view, offset, type.scalar, value, path);
|
|
409
|
+
return;
|
|
410
|
+
case "vector": {
|
|
411
|
+
const values = arrayValue(value, type.width, path);
|
|
412
|
+
const width = scalarByteSize(type.scalar);
|
|
413
|
+
values.forEach((item, index) => writeScalar(view, offset + index * width, type.scalar, item, `${path}[${index}]`));
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
case "matrix": {
|
|
417
|
+
const columns = arrayValue(value, type.columns, path);
|
|
418
|
+
columns.forEach((column, columnIndex) => {
|
|
419
|
+
const values = arrayValue(column, type.rows, `${path}[${columnIndex}]`);
|
|
420
|
+
values.forEach(
|
|
421
|
+
(item, rowIndex) => writeScalar(
|
|
422
|
+
view,
|
|
423
|
+
offset + columnIndex * type.columnStride + rowIndex * scalarByteSize(type.scalar),
|
|
424
|
+
type.scalar,
|
|
425
|
+
item,
|
|
426
|
+
`${path}[${columnIndex}][${rowIndex}]`
|
|
427
|
+
)
|
|
428
|
+
);
|
|
429
|
+
});
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
case "array": {
|
|
433
|
+
const values = arrayValue(value, type.count, path);
|
|
434
|
+
values.forEach(
|
|
435
|
+
(item, index) => writeType(view, offset + index * type.stride, type.element, item, `${path}[${index}]`)
|
|
436
|
+
);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
case "record":
|
|
440
|
+
writeRecord(view, offset, resolveRecord(type.recordName), value, path);
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
const writeRecord = (view, offset, target, value, path) => {
|
|
444
|
+
assertRecordValue(value, target, path);
|
|
445
|
+
for (const member of target.members) {
|
|
446
|
+
writeType(view, offset + member.offset, member.type, value[member.name], `${path}.${member.name}`);
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
const readType = (view, offset, type, path, runtimeCount) => {
|
|
450
|
+
switch (type.kind) {
|
|
451
|
+
case "scalar":
|
|
452
|
+
return readScalar(view, offset, type.scalar, path);
|
|
453
|
+
case "atomic":
|
|
454
|
+
return readScalar(view, offset, type.scalar, path);
|
|
455
|
+
case "vector":
|
|
456
|
+
return Array.from(
|
|
457
|
+
{ length: type.width },
|
|
458
|
+
(_, index) => readScalar(view, offset + index * scalarByteSize(type.scalar), type.scalar, `${path}[${index}]`)
|
|
459
|
+
);
|
|
460
|
+
case "matrix":
|
|
461
|
+
return Array.from(
|
|
462
|
+
{ length: type.columns },
|
|
463
|
+
(_, column) => Array.from(
|
|
464
|
+
{ length: type.rows },
|
|
465
|
+
(_2, row) => readScalar(
|
|
466
|
+
view,
|
|
467
|
+
offset + column * type.columnStride + row * scalarByteSize(type.scalar),
|
|
468
|
+
type.scalar,
|
|
469
|
+
`${path}[${column}][${row}]`
|
|
470
|
+
)
|
|
471
|
+
)
|
|
472
|
+
);
|
|
473
|
+
case "array": {
|
|
474
|
+
const count = type.count ?? runtimeCount;
|
|
475
|
+
if (count === void 0) throw new TypeError(`${path} requires a bounded runtime-array length.`);
|
|
476
|
+
return Array.from(
|
|
477
|
+
{ length: count },
|
|
478
|
+
(_, index) => readType(view, offset + index * type.stride, type.element, `${path}[${index}]`)
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
case "record":
|
|
482
|
+
return readRecord(view, offset, resolveRecord(type.recordName), path);
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
const readRecord = (view, offset, target, path, rootRuntimeCount) => {
|
|
486
|
+
const result = {};
|
|
487
|
+
for (const member of target.members) {
|
|
488
|
+
const count = member.name === target.runtimeArrayMember ? rootRuntimeCount : void 0;
|
|
489
|
+
result[member.name] = readType(view, offset + member.offset, member.type, `${path}.${member.name}`, count);
|
|
490
|
+
}
|
|
491
|
+
return result;
|
|
492
|
+
};
|
|
493
|
+
const byteLength = (value) => {
|
|
494
|
+
assertRecordValue(value, record, record.name);
|
|
495
|
+
if (!runtime) {
|
|
496
|
+
if (record.byteSize === null) throw new TypeError(`${record.name} is missing a fixed byte size.`);
|
|
497
|
+
return record.byteSize;
|
|
498
|
+
}
|
|
499
|
+
const values = arrayValue(value[runtime.name], null, `${record.name}.${runtime.name}`);
|
|
500
|
+
const tail = values.length * runtime.type.stride;
|
|
501
|
+
const total = runtime.offset + tail;
|
|
502
|
+
if (!Number.isSafeInteger(tail) || !Number.isSafeInteger(total) || total > 4294967295) {
|
|
503
|
+
throw new RangeError(`${record.name}.${runtime.name} exceeds the bounded GPU buffer size.`);
|
|
504
|
+
}
|
|
505
|
+
return total;
|
|
506
|
+
};
|
|
507
|
+
const encodeInto = (value, destination, byteOffset = 0) => {
|
|
508
|
+
if (!Number.isSafeInteger(byteOffset) || byteOffset < 0) {
|
|
509
|
+
throw new RangeError("byteOffset must be a non-negative safe integer.");
|
|
510
|
+
}
|
|
511
|
+
const length = byteLength(value);
|
|
512
|
+
const region = bufferRegion(destination);
|
|
513
|
+
if (byteOffset + length > region.byteLength) {
|
|
514
|
+
throw new RangeError(`Destination needs ${length} bytes from byteOffset ${byteOffset}.`);
|
|
515
|
+
}
|
|
516
|
+
const absoluteOffset = region.byteOffset + byteOffset;
|
|
517
|
+
new Uint8Array(region.buffer, absoluteOffset, length).fill(0);
|
|
518
|
+
writeRecord(new DataView(region.buffer), absoluteOffset, record, value, record.name);
|
|
519
|
+
return length;
|
|
520
|
+
};
|
|
521
|
+
return {
|
|
522
|
+
record,
|
|
523
|
+
minimumByteLength: record.minimumByteSize,
|
|
524
|
+
byteLength,
|
|
525
|
+
encode(value) {
|
|
526
|
+
const output = new ArrayBuffer(byteLength(value));
|
|
527
|
+
encodeInto(value, output);
|
|
528
|
+
return output;
|
|
529
|
+
},
|
|
530
|
+
encodeInto,
|
|
531
|
+
decode(source, options = {}) {
|
|
532
|
+
const region = bufferRegion(source);
|
|
533
|
+
const relativeOffset = options.byteOffset ?? 0;
|
|
534
|
+
if (!Number.isSafeInteger(relativeOffset) || relativeOffset < 0) {
|
|
535
|
+
throw new RangeError("byteOffset must be a non-negative safe integer.");
|
|
536
|
+
}
|
|
537
|
+
const available = options.byteLength ?? region.byteLength - relativeOffset;
|
|
538
|
+
if (!Number.isSafeInteger(available) || available < record.minimumByteSize) {
|
|
539
|
+
throw new RangeError(`Source must provide at least ${record.minimumByteSize} bytes.`);
|
|
540
|
+
}
|
|
541
|
+
if (relativeOffset + available > region.byteLength) {
|
|
542
|
+
throw new RangeError("Requested source region exceeds the supplied buffer.");
|
|
543
|
+
}
|
|
544
|
+
let count;
|
|
545
|
+
if (runtime) {
|
|
546
|
+
const tailLength = available - runtime.offset;
|
|
547
|
+
if (tailLength < 0 || tailLength % runtime.type.stride !== 0) {
|
|
548
|
+
throw new RangeError(`${record.name}.${runtime.name} byte length is not stride-aligned.`);
|
|
549
|
+
}
|
|
550
|
+
count = tailLength / runtime.type.stride;
|
|
551
|
+
if (!Number.isSafeInteger(count) || count > 4294967295) throw new RangeError(`${record.name}.${runtime.name} runtime count is unsafe.`);
|
|
552
|
+
} else if (record.byteSize !== available) {
|
|
553
|
+
throw new RangeError(`${record.name} requires exactly ${record.byteSize} bytes.`);
|
|
554
|
+
}
|
|
555
|
+
const absoluteOffset = region.byteOffset + relativeOffset;
|
|
556
|
+
return readRecord(new DataView(region.buffer), absoluteOffset, record, record.name, count);
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// src/requirements-validation.ts
|
|
562
|
+
var ENABLED_FEATURES = Object.freeze({
|
|
563
|
+
f16: "shader-f16",
|
|
564
|
+
clip_distances: "clip-distances",
|
|
565
|
+
dual_source_blending: "dual-source-blending",
|
|
566
|
+
subgroups: "subgroups",
|
|
567
|
+
primitive_index: "primitive-index",
|
|
568
|
+
subgroup_size_control: "subgroup-size-control"
|
|
569
|
+
});
|
|
570
|
+
var STAGES = ["vertex", "fragment", "compute"];
|
|
571
|
+
var INTER_STAGE_FRAGMENT_BUILTINS = /* @__PURE__ */ new Set([
|
|
572
|
+
"front_facing",
|
|
573
|
+
"sample_index",
|
|
574
|
+
"sample_mask",
|
|
575
|
+
"primitive_index",
|
|
576
|
+
"subgroup_invocation_id",
|
|
577
|
+
"subgroup_size"
|
|
578
|
+
]);
|
|
579
|
+
function commentFree(source) {
|
|
580
|
+
let result = "";
|
|
581
|
+
let index = 0;
|
|
582
|
+
let blockDepth = 0;
|
|
583
|
+
let line = false;
|
|
584
|
+
while (index < source.length) {
|
|
585
|
+
const pair = source.slice(index, index + 2);
|
|
586
|
+
if (line) {
|
|
587
|
+
if (source[index] === "\n") {
|
|
588
|
+
line = false;
|
|
589
|
+
result += "\n";
|
|
590
|
+
} else result += " ";
|
|
591
|
+
index += 1;
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
if (blockDepth > 0) {
|
|
595
|
+
if (pair === "/*") {
|
|
596
|
+
blockDepth += 1;
|
|
597
|
+
result += " ";
|
|
598
|
+
index += 2;
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
if (pair === "*/") {
|
|
602
|
+
blockDepth -= 1;
|
|
603
|
+
result += " ";
|
|
604
|
+
index += 2;
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
result += source[index] === "\n" ? "\n" : " ";
|
|
608
|
+
index += 1;
|
|
609
|
+
continue;
|
|
610
|
+
}
|
|
611
|
+
if (pair === "//") {
|
|
612
|
+
line = true;
|
|
613
|
+
result += " ";
|
|
614
|
+
index += 2;
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
if (pair === "/*") {
|
|
618
|
+
blockDepth = 1;
|
|
619
|
+
result += " ";
|
|
620
|
+
index += 2;
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
result += source[index];
|
|
624
|
+
index += 1;
|
|
625
|
+
}
|
|
626
|
+
if (blockDepth !== 0) throw new TypeError("WGSL contains an unterminated block comment.");
|
|
627
|
+
return result;
|
|
628
|
+
}
|
|
629
|
+
function inferWgslRequiredFeatures(sources) {
|
|
630
|
+
const result = /* @__PURE__ */ new Set();
|
|
631
|
+
for (const source of sources) {
|
|
632
|
+
const stripped = commentFree(source);
|
|
633
|
+
const consumed = stripped.replace(/\benable\s+([^;]+);/gu, (_match, list) => {
|
|
634
|
+
const names = list.split(",").map((item) => item.trim());
|
|
635
|
+
if (names.length === 0 || names.some((name) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name))) throw new TypeError("WGSL contains a malformed enable directive.");
|
|
636
|
+
for (const name of names) {
|
|
637
|
+
const feature = ENABLED_FEATURES[name];
|
|
638
|
+
if (!feature) throw new TypeError(`WGSL enable ${name} has no stable WebGPU feature mapping.`);
|
|
639
|
+
result.add(feature);
|
|
640
|
+
}
|
|
641
|
+
return " ".repeat(_match.length);
|
|
642
|
+
});
|
|
643
|
+
if (/\benable\b/u.test(consumed)) throw new TypeError("WGSL contains an unterminated or malformed enable directive.");
|
|
644
|
+
}
|
|
645
|
+
return [...result].sort();
|
|
646
|
+
}
|
|
647
|
+
function declaredLimits(requirements) {
|
|
648
|
+
return new Map(requirements.limits.map((limit) => [limit.name, limit]));
|
|
649
|
+
}
|
|
650
|
+
function requireAtLeast(limits, name, value) {
|
|
651
|
+
if (value === 0) return;
|
|
652
|
+
const requirement = limits.get(name);
|
|
653
|
+
if (!requirement || requirement.comparator !== "at-least" || requirement.value < value) {
|
|
654
|
+
throw new TypeError(`Shader requirements must declare ${name} at least ${value}.`);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function emptyResourceCounts() {
|
|
658
|
+
return { sampledTextures: 0, samplers: 0, storageBuffers: 0, storageTextures: 0, uniformBuffers: 0 };
|
|
659
|
+
}
|
|
660
|
+
function countResource(resource, counts) {
|
|
661
|
+
switch (resource.kind) {
|
|
662
|
+
case "buffer":
|
|
663
|
+
if (resource.addressSpace === "uniform") counts.uniformBuffers += 1;
|
|
664
|
+
else counts.storageBuffers += 1;
|
|
665
|
+
return;
|
|
666
|
+
case "sampler":
|
|
667
|
+
counts.samplers += 1;
|
|
668
|
+
return;
|
|
669
|
+
case "texture":
|
|
670
|
+
counts.sampledTextures += 1;
|
|
671
|
+
return;
|
|
672
|
+
case "storage-texture":
|
|
673
|
+
counts.storageTextures += 1;
|
|
674
|
+
return;
|
|
675
|
+
case "external-texture":
|
|
676
|
+
counts.sampledTextures += 4;
|
|
677
|
+
counts.samplers += 1;
|
|
678
|
+
counts.uniformBuffers += 1;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
function validatePipelineDerivedRequirements(input) {
|
|
682
|
+
const limits = declaredLimits(input.requirements);
|
|
683
|
+
const features = new Set(input.requirements.features);
|
|
684
|
+
const formats = new Set(input.requirements.formats);
|
|
685
|
+
const requiredFormats = /* @__PURE__ */ new Set();
|
|
686
|
+
const requiredLimits = /* @__PURE__ */ new Map();
|
|
687
|
+
const recordLimit = (name, value) => {
|
|
688
|
+
requiredLimits.set(name, Math.max(requiredLimits.get(name) ?? 0, value));
|
|
689
|
+
};
|
|
690
|
+
for (const pipeline2 of input.pipelines) {
|
|
691
|
+
recordLimit("maxBindGroups", pipeline2.layout.bindGroups.length);
|
|
692
|
+
recordLimit("maxBindingsPerBindGroup", Math.max(0, ...pipeline2.layout.bindGroups.map((group) => group.entries.length)));
|
|
693
|
+
const counts = new Map(STAGES.map((stage) => [stage, emptyResourceCounts()]));
|
|
694
|
+
for (const group of pipeline2.layout.bindGroups) {
|
|
695
|
+
for (const entry of group.entries) {
|
|
696
|
+
for (const stage of entry.visibility) countResource(entry.resource, counts.get(stage));
|
|
697
|
+
if (entry.resource.kind === "storage-texture") requiredFormats.add(entry.resource.format);
|
|
698
|
+
if (entry.resource.kind === "buffer") {
|
|
699
|
+
recordLimit(
|
|
700
|
+
entry.resource.addressSpace === "uniform" ? "maxUniformBufferBindingSize" : "maxStorageBufferBindingSize",
|
|
701
|
+
entry.resource.minimumBindingSize
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
for (const stageCounts of counts.values()) {
|
|
707
|
+
recordLimit("maxSampledTexturesPerShaderStage", stageCounts.sampledTextures);
|
|
708
|
+
recordLimit("maxSamplersPerShaderStage", stageCounts.samplers);
|
|
709
|
+
recordLimit("maxStorageBuffersPerShaderStage", stageCounts.storageBuffers);
|
|
710
|
+
recordLimit("maxStorageTexturesPerShaderStage", stageCounts.storageTextures);
|
|
711
|
+
recordLimit("maxUniformBuffersPerShaderStage", stageCounts.uniformBuffers);
|
|
712
|
+
}
|
|
713
|
+
if (pipeline2.kind === "render") {
|
|
714
|
+
if (pipeline2.primitive.unclippedDepth && !features.has("depth-clip-control")) {
|
|
715
|
+
throw new TypeError("Shader requirements omit pipeline-derived feature depth-clip-control.");
|
|
716
|
+
}
|
|
717
|
+
recordLimit("maxBindGroupsPlusVertexBuffers", pipeline2.layout.bindGroups.length + pipeline2.vertexBuffers.length);
|
|
718
|
+
recordLimit("maxVertexBuffers", pipeline2.vertexBuffers.length);
|
|
719
|
+
recordLimit("maxVertexAttributes", pipeline2.vertexBuffers.reduce((sum, buffer) => sum + buffer.attributes.length, 0));
|
|
720
|
+
recordLimit("maxVertexBufferArrayStride", Math.max(0, ...pipeline2.vertexBuffers.map((buffer) => buffer.arrayStride)));
|
|
721
|
+
recordLimit("maxColorAttachments", pipeline2.colorTargets.length);
|
|
722
|
+
pipeline2.colorTargets.forEach((target) => requiredFormats.add(target.format));
|
|
723
|
+
if (pipeline2.depthStencil) requiredFormats.add(pipeline2.depthStencil.format);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
for (const format of requiredFormats) {
|
|
727
|
+
if (!formats.has(format)) throw new TypeError(`Shader requirements list omits structurally required format ${format}.`);
|
|
728
|
+
}
|
|
729
|
+
for (const [name, value] of requiredLimits) requireAtLeast(limits, name, value);
|
|
730
|
+
}
|
|
731
|
+
function constantValue(interfaceManifest, moduleId, name, constants) {
|
|
732
|
+
const override = interfaceManifest.overrides.find((candidate) => candidate.moduleId === moduleId && candidate.name === name);
|
|
733
|
+
if (!override) throw new TypeError(`Compute workgroup dimension references missing override ${moduleId}:${name}.`);
|
|
734
|
+
const supplied = constants[name] ?? (override.id === null ? void 0 : constants[String(override.id)]);
|
|
735
|
+
const value = supplied ?? override.defaultValue;
|
|
736
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new TypeError(`Compute workgroup override ${moduleId}:${name} must resolve to a positive integer.`);
|
|
737
|
+
return value;
|
|
738
|
+
}
|
|
739
|
+
function pipelineStages(pipeline2) {
|
|
740
|
+
return pipeline2.kind === "compute" ? [{ moduleId: pipeline2.compute.moduleId, entryPoint: pipeline2.compute.entryPoint, stage: "compute" }] : [
|
|
741
|
+
{ moduleId: pipeline2.vertex.moduleId, entryPoint: pipeline2.vertex.entryPoint, stage: "vertex" },
|
|
742
|
+
...pipeline2.fragment ? [{ moduleId: pipeline2.fragment.moduleId, entryPoint: pipeline2.fragment.entryPoint, stage: "fragment" }] : []
|
|
743
|
+
];
|
|
744
|
+
}
|
|
745
|
+
function reflectedEntry(gpuInterface, stage, pipelineId) {
|
|
746
|
+
const entry = gpuInterface.entryPoints.find((candidate) => candidate.moduleId === stage.moduleId && candidate.name === stage.entryPoint && candidate.stage === stage.stage);
|
|
747
|
+
if (!entry) throw new TypeError(`Pipeline ${pipelineId} lacks reflected ${stage.stage} entry point ${stage.moduleId}:${stage.entryPoint}.`);
|
|
748
|
+
return entry;
|
|
749
|
+
}
|
|
750
|
+
function orderedStages(stages2) {
|
|
751
|
+
return [...new Set(stages2)].sort((left, right) => STAGES.indexOf(left) - STAGES.indexOf(right));
|
|
752
|
+
}
|
|
753
|
+
function clipDistanceSlots(entry) {
|
|
754
|
+
const clipDistances = entry.outputs.find((output) => output.locationKind === "builtin" && output.location === "clip_distances");
|
|
755
|
+
if (!clipDistances) return 0;
|
|
756
|
+
if (clipDistances.type.kind !== "array" || clipDistances.type.count === null) {
|
|
757
|
+
throw new TypeError("Reflected clip_distances output must be a fixed-size array.");
|
|
758
|
+
}
|
|
759
|
+
return Math.ceil(clipDistances.type.count / 4);
|
|
760
|
+
}
|
|
761
|
+
function highestLocationPlusOne(entry, direction) {
|
|
762
|
+
return Math.max(0, ...entry[direction].filter((item) => item.locationKind === "location").map((item) => Number(item.location) + 1));
|
|
763
|
+
}
|
|
764
|
+
function requiredInterStageVariables(pipeline2, vertex, fragment) {
|
|
765
|
+
const vertexOutputs = vertex.outputs.filter((output) => output.locationKind === "location").length;
|
|
766
|
+
const reservedVertexSlots = (pipeline2.primitive.topology === "point-list" ? 1 : 0) + clipDistanceSlots(vertex);
|
|
767
|
+
let required = Math.max(
|
|
768
|
+
vertexOutputs + reservedVertexSlots,
|
|
769
|
+
highestLocationPlusOne(vertex, "outputs") + reservedVertexSlots
|
|
770
|
+
);
|
|
771
|
+
if (fragment) {
|
|
772
|
+
const fragmentInputs = fragment.inputs.filter((input) => input.locationKind === "location").length;
|
|
773
|
+
const fragmentBuiltins = fragment.inputs.filter((input) => input.locationKind === "builtin" && INTER_STAGE_FRAGMENT_BUILTINS.has(String(input.location))).length;
|
|
774
|
+
required = Math.max(
|
|
775
|
+
required,
|
|
776
|
+
fragmentInputs + fragmentBuiltins,
|
|
777
|
+
highestLocationPlusOne(fragment, "inputs")
|
|
778
|
+
);
|
|
779
|
+
}
|
|
780
|
+
return required;
|
|
781
|
+
}
|
|
782
|
+
function interStageComponentCount(type, gpuInterface, activeRecords = /* @__PURE__ */ new Set()) {
|
|
783
|
+
switch (type.kind) {
|
|
784
|
+
case "scalar":
|
|
785
|
+
case "atomic":
|
|
786
|
+
return 1;
|
|
787
|
+
case "vector":
|
|
788
|
+
return type.width;
|
|
789
|
+
case "matrix":
|
|
790
|
+
return type.columns * type.rows;
|
|
791
|
+
case "array":
|
|
792
|
+
if (type.count === null) throw new TypeError("Inter-stage IO cannot contain a runtime-sized array.");
|
|
793
|
+
return type.count * interStageComponentCount(type.element, gpuInterface, activeRecords);
|
|
794
|
+
case "record": {
|
|
795
|
+
if (activeRecords.has(type.recordName)) throw new TypeError(`Inter-stage IO record ${type.recordName} is recursive.`);
|
|
796
|
+
const record = gpuInterface.records.find((candidate) => candidate.name === type.recordName);
|
|
797
|
+
if (!record) throw new TypeError(`Inter-stage IO references missing record ${type.recordName}.`);
|
|
798
|
+
const nested = new Set(activeRecords);
|
|
799
|
+
nested.add(type.recordName);
|
|
800
|
+
return record.members.reduce(
|
|
801
|
+
(sum, member) => sum + interStageComponentCount(member.type, gpuInterface, nested),
|
|
802
|
+
0
|
|
803
|
+
);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
function requiredInterStageComponents(vertex, fragment, gpuInterface) {
|
|
808
|
+
const countLocations = (items) => items.filter((item) => item.locationKind === "location").reduce((sum, item) => sum + interStageComponentCount(item.type, gpuInterface), 0);
|
|
809
|
+
return Math.max(
|
|
810
|
+
countLocations(vertex.outputs),
|
|
811
|
+
fragment ? countLocations(fragment.inputs) : 0
|
|
812
|
+
);
|
|
813
|
+
}
|
|
814
|
+
function validateShaderInterfaceRequirements(input) {
|
|
815
|
+
const { manifest, gpuInterface } = input;
|
|
816
|
+
if (manifest.gpuInterface.interfaceId !== gpuInterface.interfaceId || manifest.gpuInterface.interfaceVersion !== gpuInterface.interfaceVersion || manifest.gpuInterface.interfaceAbiHash !== gpuInterface.interfaceAbiHash || manifest.gpuInterface.modelAbiHash !== gpuInterface.modelAbiHash) {
|
|
817
|
+
throw new TypeError("Shader GPU interface reference differs from the reflected interface identity.");
|
|
818
|
+
}
|
|
819
|
+
const manifestModules = [...manifest.modules].map(({ moduleId, sha256 }) => ({ moduleId, sha256 })).sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0);
|
|
820
|
+
const interfaceModules = [...gpuInterface.modules].map(({ moduleId, sha256 }) => ({ moduleId, sha256 })).sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0);
|
|
821
|
+
if (canonicalizeGpuContract(manifestModules) !== canonicalizeGpuContract(interfaceModules)) {
|
|
822
|
+
throw new TypeError("Shader modules differ from the exact reflected interface module set.");
|
|
823
|
+
}
|
|
824
|
+
validatePipelineDerivedRequirements({ requirements: manifest.requirements, pipelines: manifest.pipelines });
|
|
825
|
+
const requiredSemantics = new Set(gpuInterface.modelAbi.semantics.map((projection) => projection.semantic));
|
|
826
|
+
const declaredSemantics = new Set(manifest.requirements.semantics);
|
|
827
|
+
for (const semantic2 of requiredSemantics) {
|
|
828
|
+
if (!declaredSemantics.has(semantic2)) throw new TypeError(`Shader requirements omit reflected model semantic ${semantic2}.`);
|
|
829
|
+
}
|
|
830
|
+
const limits = declaredLimits(manifest.requirements);
|
|
831
|
+
for (const pipeline2 of manifest.pipelines) {
|
|
832
|
+
const stages2 = pipelineStages(pipeline2);
|
|
833
|
+
const entries = stages2.map((stage) => ({ stage, entry: reflectedEntry(gpuInterface, stage, pipeline2.pipelineId) }));
|
|
834
|
+
for (const group of pipeline2.layout.bindGroups) {
|
|
835
|
+
for (const descriptorEntry of group.entries) {
|
|
836
|
+
const used = entries.filter(({ stage, entry }) => entry.bindingKeys.includes(`${stage.moduleId}:${group.group}:${descriptorEntry.binding}`));
|
|
837
|
+
if (used.length === 0) throw new TypeError(`Pipeline ${pipeline2.pipelineId} binding ${group.group}:${descriptorEntry.binding} is absent from its reflected entry points.`);
|
|
838
|
+
if (canonicalizeGpuContract(orderedStages(descriptorEntry.visibility)) !== canonicalizeGpuContract(orderedStages(used.map(({ stage }) => stage.stage)))) {
|
|
839
|
+
throw new TypeError(`Pipeline ${pipeline2.pipelineId} binding ${group.group}:${descriptorEntry.binding} visibility differs from reflected entry-point usage.`);
|
|
840
|
+
}
|
|
841
|
+
for (const { stage } of used) {
|
|
842
|
+
const reflected = gpuInterface.bindings.find((binding2) => binding2.moduleId === stage.moduleId && binding2.group === group.group && binding2.binding === descriptorEntry.binding);
|
|
843
|
+
if (!reflected || canonicalizeGpuContract(reflected.resource) !== canonicalizeGpuContract(descriptorEntry.resource)) {
|
|
844
|
+
throw new TypeError(`Pipeline ${pipeline2.pipelineId} binding ${stage.moduleId}:${group.group}:${descriptorEntry.binding} differs from the reflected interface.`);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
for (const { stage, entry } of entries) {
|
|
850
|
+
for (const key of entry.bindingKeys) {
|
|
851
|
+
const declared = pipeline2.layout.bindGroups.some((group) => group.entries.some((descriptorEntry) => key === `${stage.moduleId}:${group.group}:${descriptorEntry.binding}`));
|
|
852
|
+
if (!declared) throw new TypeError(`Pipeline ${pipeline2.pipelineId} omits reflected binding ${key}.`);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
if (pipeline2.kind === "compute") {
|
|
856
|
+
const entry = entries[0]?.entry;
|
|
857
|
+
if (!entry?.workgroupSize) throw new TypeError(`Compute pipeline ${pipeline2.pipelineId} lacks an exact reflected workgroup size.`);
|
|
858
|
+
if (entry.workgroupStorageSize === null) throw new TypeError(`Compute pipeline ${pipeline2.pipelineId} lacks an exact reflected workgroup storage size.`);
|
|
859
|
+
const values = entry.workgroupSize.map((dimension) => dimension.kind === "literal" ? dimension.value : constantValue(gpuInterface, entry.moduleId, dimension.name, pipeline2.compute.constants));
|
|
860
|
+
const invocations = values[0] * values[1] * values[2];
|
|
861
|
+
if (!Number.isSafeInteger(invocations)) throw new TypeError(`Compute pipeline ${pipeline2.pipelineId} workgroup invocation count is outside the safe manifest range.`);
|
|
862
|
+
requireAtLeast(limits, "maxComputeWorkgroupSizeX", values[0]);
|
|
863
|
+
requireAtLeast(limits, "maxComputeWorkgroupSizeY", values[1]);
|
|
864
|
+
requireAtLeast(limits, "maxComputeWorkgroupSizeZ", values[2]);
|
|
865
|
+
requireAtLeast(limits, "maxComputeInvocationsPerWorkgroup", invocations);
|
|
866
|
+
requireAtLeast(limits, "maxComputeWorkgroupStorageSize", entry.workgroupStorageSize);
|
|
867
|
+
} else {
|
|
868
|
+
const vertex = entries.find(({ stage }) => stage.stage === "vertex")?.entry;
|
|
869
|
+
const fragment = entries.find(({ stage }) => stage.stage === "fragment")?.entry;
|
|
870
|
+
if (!vertex) throw new TypeError(`Render pipeline ${pipeline2.pipelineId} lacks an exact reflected vertex entry point.`);
|
|
871
|
+
requireAtLeast(limits, "maxInterStageShaderVariables", requiredInterStageVariables(pipeline2, vertex, fragment));
|
|
872
|
+
requireAtLeast(limits, "maxInterStageShaderComponents", requiredInterStageComponents(vertex, fragment, gpuInterface));
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
function validateShaderDerivedRequirements(input) {
|
|
877
|
+
const expectedModuleIds = [...input.manifest.modules.map((module2) => module2.moduleId)].sort();
|
|
878
|
+
const actualModuleIds = [...input.moduleSources.keys()].sort();
|
|
879
|
+
if (expectedModuleIds.join("\n") !== actualModuleIds.join("\n")) throw new TypeError("Derived-requirement source modules differ from the exact shader manifest module set.");
|
|
880
|
+
validateShaderInterfaceRequirements(input);
|
|
881
|
+
const features = new Set(input.manifest.requirements.features);
|
|
882
|
+
for (const feature of inferWgslRequiredFeatures([...input.moduleSources.values()])) if (!features.has(feature)) throw new TypeError(`Shader requirements omit WGSL-derived feature ${feature}.`);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// src/compatibility.ts
|
|
886
|
+
function error(code, message, path) {
|
|
887
|
+
return { code, severity: "error", message, ...path ? { path } : {} };
|
|
888
|
+
}
|
|
889
|
+
function interfaceMatches(item, model) {
|
|
890
|
+
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;
|
|
891
|
+
}
|
|
892
|
+
function validateRequirements(shader, gpuInterface, model, capabilities, diagnostics) {
|
|
893
|
+
const semantics = new Set(model.providedSemantics);
|
|
894
|
+
const requiredSemantics = /* @__PURE__ */ new Set([
|
|
895
|
+
...shader.requirements.semantics,
|
|
896
|
+
...gpuInterface.modelAbi.semantics.map((projection) => projection.semantic)
|
|
897
|
+
]);
|
|
898
|
+
for (const semantic2 of requiredSemantics) {
|
|
899
|
+
if (!semantics.has(semantic2)) {
|
|
900
|
+
diagnostics.push(error("missing-semantic", `Model does not provide required semantic ${semantic2}.`, "requirements.semantics"));
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
if (!capabilities) return;
|
|
904
|
+
const features = new Set(capabilities.features);
|
|
905
|
+
for (const feature of shader.requirements.features) {
|
|
906
|
+
if (!features.has(feature)) {
|
|
907
|
+
diagnostics.push(error("missing-feature", `GPU does not provide required feature ${feature}.`, "requirements.features"));
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
const formats = new Set(capabilities.formats);
|
|
911
|
+
for (const format of shader.requirements.formats) {
|
|
912
|
+
if (!formats.has(format)) {
|
|
913
|
+
diagnostics.push(error("unsupported-format", `GPU runtime does not expose required format ${format}.`, "requirements.formats"));
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
for (const requirement of shader.requirements.limits) {
|
|
917
|
+
const available = capabilities.limits[requirement.name];
|
|
918
|
+
const satisfied = available !== void 0 && (requirement.comparator === "at-least" ? available >= requirement.value : available <= requirement.value);
|
|
919
|
+
if (!satisfied) {
|
|
920
|
+
diagnostics.push(error(
|
|
921
|
+
"limit-not-met",
|
|
922
|
+
`GPU limit ${requirement.name} does not meet the ${requirement.comparator} requirement.`,
|
|
923
|
+
"requirements.limits"
|
|
924
|
+
));
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
function validateModelShaderCompatibility(input) {
|
|
929
|
+
const diagnostics = [];
|
|
930
|
+
const { model, shader, gpuInterface, profile, capabilities } = input;
|
|
931
|
+
try {
|
|
932
|
+
validateShaderInterfaceRequirements({ manifest: shader, gpuInterface });
|
|
933
|
+
} catch (cause) {
|
|
934
|
+
diagnostics.push(error(
|
|
935
|
+
"invalid-contract",
|
|
936
|
+
cause instanceof Error ? cause.message : "Shader requirements differ from the reflected GPU interface.",
|
|
937
|
+
"requirements"
|
|
938
|
+
));
|
|
939
|
+
}
|
|
940
|
+
if (model.gpuInterface.modelAbiHash !== model.modelAbiHash) {
|
|
941
|
+
diagnostics.push(error("model-abi-mismatch", "Model manifest and GPU interface reference disagree on modelAbiHash.", "modelAbiHash"));
|
|
942
|
+
}
|
|
943
|
+
if (shader.gpuInterface.modelAbiHash !== model.modelAbiHash) {
|
|
944
|
+
diagnostics.push(error("model-abi-mismatch", "Shader GPU interface does not match the model ABI.", "gpuInterface.modelAbiHash"));
|
|
945
|
+
}
|
|
946
|
+
if (!shader.compatibleModelInterfaces.some((item) => interfaceMatches(item, model))) {
|
|
947
|
+
diagnostics.push(error("incompatible-model-interface", "Shader does not declare this exact model interface as compatible."));
|
|
948
|
+
}
|
|
949
|
+
if (profile) {
|
|
950
|
+
if (!profile.compatibleModelInterfaces.some((item) => interfaceMatches(item, model))) {
|
|
951
|
+
diagnostics.push(error("incompatible-model-interface", "Style profile does not declare this exact model interface as compatible."));
|
|
952
|
+
}
|
|
953
|
+
const provided = new Set(model.providedSemantics);
|
|
954
|
+
for (const semantic2 of profile.requiredSemantics) {
|
|
955
|
+
if (!provided.has(semantic2)) {
|
|
956
|
+
diagnostics.push(error("missing-semantic", `Model does not provide profile semantic ${semantic2}.`, "requiredSemantics"));
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
validateRequirements(shader, gpuInterface, model, capabilities, diagnostics);
|
|
961
|
+
if (diagnostics.length > 0) return { ok: false, diagnostics };
|
|
962
|
+
return {
|
|
963
|
+
ok: true,
|
|
964
|
+
value: {
|
|
965
|
+
modelAbiHash: model.modelAbiHash,
|
|
966
|
+
shaderAbiHash: shader.shaderAbiHash,
|
|
967
|
+
matchedInterfaceId: model.gpuInterface.interfaceId
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// src/manifest-validation.ts
|
|
973
|
+
var stages = ["vertex", "fragment", "compute"];
|
|
974
|
+
var roles = ["material", "lighting", "outline", "shadow", "post-processing"];
|
|
975
|
+
function object(value, path) {
|
|
976
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${path} must be an object.`);
|
|
977
|
+
return value;
|
|
978
|
+
}
|
|
979
|
+
function exact(value, keys, path) {
|
|
980
|
+
const allowed = new Set(keys);
|
|
981
|
+
for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError(`${path}.${key} is not part of this contract version.`);
|
|
982
|
+
for (const key of keys) if (!(key in value)) throw new TypeError(`${path}.${key} is required.`);
|
|
983
|
+
}
|
|
984
|
+
function text(value, path, maximum = 512) {
|
|
985
|
+
if (typeof value !== "string" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 31)) {
|
|
986
|
+
throw new TypeError(`${path} must be a bounded non-empty string without control characters.`);
|
|
987
|
+
}
|
|
988
|
+
return value;
|
|
989
|
+
}
|
|
990
|
+
function token(value, path) {
|
|
991
|
+
const result = text(value, path, 160);
|
|
992
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u.test(result) || result.includes("..")) throw new TypeError(`${path} must be a safe token.`);
|
|
993
|
+
return result;
|
|
994
|
+
}
|
|
995
|
+
function enumeration(value, values, path) {
|
|
996
|
+
if (!values.includes(value)) throw new TypeError(`${path} is invalid.`);
|
|
997
|
+
return value;
|
|
998
|
+
}
|
|
999
|
+
function integer2(value, path, minimum = 0, maximum = 4294967295) {
|
|
1000
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
|
|
1001
|
+
throw new TypeError(`${path} must be an integer from ${minimum} through ${maximum}.`);
|
|
1002
|
+
}
|
|
1003
|
+
return value;
|
|
1004
|
+
}
|
|
1005
|
+
function finite(value, path) {
|
|
1006
|
+
if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError(`${path} must be finite.`);
|
|
1007
|
+
return value;
|
|
1008
|
+
}
|
|
1009
|
+
function array(value, path, maximum = 4096) {
|
|
1010
|
+
if (!Array.isArray(value) || value.length > maximum) throw new TypeError(`${path} must be a bounded array.`);
|
|
1011
|
+
return value;
|
|
1012
|
+
}
|
|
1013
|
+
function nullableInteger(value, path) {
|
|
1014
|
+
return value === null ? null : integer2(value, path);
|
|
1015
|
+
}
|
|
1016
|
+
function nullableToken(value, path) {
|
|
1017
|
+
return value === null ? null : token(value, path);
|
|
1018
|
+
}
|
|
1019
|
+
function digest(value, path) {
|
|
1020
|
+
try {
|
|
1021
|
+
return asSha256Hex(text(value, path, 64));
|
|
1022
|
+
} catch (cause) {
|
|
1023
|
+
throw new TypeError(`${path} must be a lowercase SHA-256 digest.`, { cause });
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
function uri(value, path) {
|
|
1027
|
+
const result = text(value, path, 2048);
|
|
1028
|
+
let parsed;
|
|
1029
|
+
try {
|
|
1030
|
+
parsed = new URL(result);
|
|
1031
|
+
} catch (cause) {
|
|
1032
|
+
throw new TypeError(`${path} must be an absolute immutable asset URI.`, { cause });
|
|
1033
|
+
}
|
|
1034
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.hash) throw new TypeError(`${path} must be credential-free HTTPS without a fragment.`);
|
|
1035
|
+
const keys = [...parsed.searchParams.keys()].map((key) => key.toLowerCase());
|
|
1036
|
+
const forbidden = /* @__PURE__ */ new Set(["sig", "se", "sp", "sv", "spr", "st", "skoid", "sktid", "skt", "ske", "sks", "skv"]);
|
|
1037
|
+
if (keys.some((key) => forbidden.has(key)) || new Set(keys).size !== keys.length) throw new TypeError(`${path} must not contain SAS credentials or duplicate query parameters.`);
|
|
1038
|
+
if (parsed.href !== result) throw new TypeError(`${path} must use its canonical URL serialization.`);
|
|
1039
|
+
return result;
|
|
1040
|
+
}
|
|
1041
|
+
function unique(values, key, path) {
|
|
1042
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1043
|
+
for (const value of values) {
|
|
1044
|
+
const identity = key(value);
|
|
1045
|
+
if (seen.has(identity)) throw new TypeError(`${path} contains duplicate ${identity}.`);
|
|
1046
|
+
seen.add(identity);
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
function tokenArray(value, path, maximum = 4096) {
|
|
1050
|
+
const result = array(value, path, maximum).map((item, index) => token(item, `${path}[${index}]`));
|
|
1051
|
+
unique(result, String, path);
|
|
1052
|
+
return result;
|
|
1053
|
+
}
|
|
1054
|
+
function typeLayout(value, path, depth = 0) {
|
|
1055
|
+
if (depth > 24) throw new TypeError(`${path} exceeds the type nesting limit.`);
|
|
1056
|
+
const input = object(value, path);
|
|
1057
|
+
const kind = enumeration(input.kind, ["scalar", "atomic", "vector", "matrix", "array", "record"], `${path}.kind`);
|
|
1058
|
+
integer2(input.alignment, `${path}.alignment`, 1);
|
|
1059
|
+
if (kind === "array") {
|
|
1060
|
+
exact(input, ["kind", "element", "count", "stride", "alignment", "byteSize"], path);
|
|
1061
|
+
const element = typeLayout(input.element, `${path}.element`, depth + 1);
|
|
1062
|
+
const count = nullableInteger(input.count, `${path}.count`);
|
|
1063
|
+
const stride = integer2(input.stride, `${path}.stride`, 1);
|
|
1064
|
+
const byteSize = nullableInteger(input.byteSize, `${path}.byteSize`);
|
|
1065
|
+
if (input.alignment !== element.alignment || stride % element.alignment !== 0 || element.byteSize === null || stride < element.byteSize || (count === null ? byteSize !== null : byteSize !== count * stride)) {
|
|
1066
|
+
throw new TypeError(`${path} has inconsistent array layout algebra.`);
|
|
1067
|
+
}
|
|
1068
|
+
} else if (kind === "record") {
|
|
1069
|
+
exact(input, ["kind", "recordName", "alignment", "byteSize"], path);
|
|
1070
|
+
token(input.recordName, `${path}.recordName`);
|
|
1071
|
+
nullableInteger(input.byteSize, `${path}.byteSize`);
|
|
1072
|
+
} else {
|
|
1073
|
+
integer2(input.byteSize, `${path}.byteSize`, 1);
|
|
1074
|
+
if (kind === "scalar") {
|
|
1075
|
+
exact(input, ["kind", "scalar", "alignment", "byteSize"], path);
|
|
1076
|
+
enumeration(input.scalar, ["i32", "u32", "f32", "f16", "bool"], `${path}.scalar`);
|
|
1077
|
+
const size = input.scalar === "f16" ? 2 : 4;
|
|
1078
|
+
if (input.alignment !== size || input.byteSize !== size) throw new TypeError(`${path} has inconsistent scalar layout.`);
|
|
1079
|
+
} else if (kind === "atomic") {
|
|
1080
|
+
exact(input, ["kind", "scalar", "alignment", "byteSize"], path);
|
|
1081
|
+
enumeration(input.scalar, ["i32", "u32"], `${path}.scalar`);
|
|
1082
|
+
if (input.alignment !== 4 || input.byteSize !== 4) throw new TypeError(`${path} has inconsistent atomic layout.`);
|
|
1083
|
+
} else if (kind === "vector") {
|
|
1084
|
+
exact(input, ["kind", "scalar", "width", "alignment", "byteSize"], path);
|
|
1085
|
+
enumeration(input.scalar, ["i32", "u32", "f32", "f16", "bool"], `${path}.scalar`);
|
|
1086
|
+
const width = enumeration(input.width, [2, 3, 4], `${path}.width`);
|
|
1087
|
+
const scalarSize = input.scalar === "f16" ? 2 : 4;
|
|
1088
|
+
if (input.alignment !== (width === 2 ? 2 : 4) * scalarSize || input.byteSize !== width * scalarSize) throw new TypeError(`${path} has inconsistent vector layout.`);
|
|
1089
|
+
} else {
|
|
1090
|
+
exact(input, ["kind", "scalar", "columns", "rows", "columnStride", "alignment", "byteSize"], path);
|
|
1091
|
+
enumeration(input.scalar, ["f32", "f16"], `${path}.scalar`);
|
|
1092
|
+
const columns = enumeration(input.columns, [2, 3, 4], `${path}.columns`);
|
|
1093
|
+
const rows = enumeration(input.rows, [2, 3, 4], `${path}.rows`);
|
|
1094
|
+
const stride = integer2(input.columnStride, `${path}.columnStride`, 1);
|
|
1095
|
+
const scalarSize = input.scalar === "f16" ? 2 : 4;
|
|
1096
|
+
const alignment = (rows === 2 ? 2 : 4) * scalarSize;
|
|
1097
|
+
if (input.alignment !== alignment || stride !== Math.ceil(rows * scalarSize / alignment) * alignment || input.byteSize !== columns * stride) throw new TypeError(`${path} has inconsistent matrix layout.`);
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
return input;
|
|
1101
|
+
}
|
|
1102
|
+
function recordLayout(value, path) {
|
|
1103
|
+
const input = object(value, path);
|
|
1104
|
+
exact(input, ["name", "alignment", "byteSize", "minimumByteSize", "runtimeArrayMember", "addressSpaces", "members"], path);
|
|
1105
|
+
token(input.name, `${path}.name`);
|
|
1106
|
+
integer2(input.alignment, `${path}.alignment`, 1);
|
|
1107
|
+
nullableInteger(input.byteSize, `${path}.byteSize`);
|
|
1108
|
+
integer2(input.minimumByteSize, `${path}.minimumByteSize`);
|
|
1109
|
+
nullableToken(input.runtimeArrayMember, `${path}.runtimeArrayMember`);
|
|
1110
|
+
const spaces = array(input.addressSpaces, `${path}.addressSpaces`, 5).map((space, index) => enumeration(space, ["uniform", "storage", "function", "private", "workgroup"], `${path}.addressSpaces[${index}]`));
|
|
1111
|
+
unique(spaces, String, `${path}.addressSpaces`);
|
|
1112
|
+
const members = array(input.members, `${path}.members`);
|
|
1113
|
+
let priorEnd = 0;
|
|
1114
|
+
const names = [];
|
|
1115
|
+
members.forEach((value2, index) => {
|
|
1116
|
+
const memberPath = `${path}.members[${index}]`;
|
|
1117
|
+
const member = object(value2, memberPath);
|
|
1118
|
+
exact(member, ["name", "offset", "alignment", "valueByteSize", "occupiedByteSize", "explicitAlign", "explicitSize", "type"], memberPath);
|
|
1119
|
+
names.push(token(member.name, `${memberPath}.name`));
|
|
1120
|
+
const offset = integer2(member.offset, `${memberPath}.offset`);
|
|
1121
|
+
const alignment = integer2(member.alignment, `${memberPath}.alignment`, 1);
|
|
1122
|
+
const valueSize = nullableInteger(member.valueByteSize, `${memberPath}.valueByteSize`);
|
|
1123
|
+
const occupied = nullableInteger(member.occupiedByteSize, `${memberPath}.occupiedByteSize`);
|
|
1124
|
+
const explicitAlign = member.explicitAlign === null ? null : integer2(member.explicitAlign, `${memberPath}.explicitAlign`, 1);
|
|
1125
|
+
const explicitSize = member.explicitSize === null ? null : integer2(member.explicitSize, `${memberPath}.explicitSize`, 1);
|
|
1126
|
+
const type = typeLayout(member.type, `${memberPath}.type`);
|
|
1127
|
+
if (explicitAlign !== null && ((explicitAlign & explicitAlign - 1) !== 0 || explicitAlign < type.alignment)) {
|
|
1128
|
+
throw new TypeError(`${memberPath}.explicitAlign must be a power of two no smaller than the natural alignment.`);
|
|
1129
|
+
}
|
|
1130
|
+
if (explicitSize !== null && (type.byteSize === null || explicitSize < type.byteSize)) {
|
|
1131
|
+
throw new TypeError(`${memberPath}.explicitSize must not shrink a fixed-size WGSL type.`);
|
|
1132
|
+
}
|
|
1133
|
+
if (offset < priorEnd || offset % alignment !== 0 || alignment !== (explicitAlign ?? type.alignment) || valueSize !== type.byteSize || occupied !== (explicitSize ?? type.byteSize) || occupied !== null && valueSize !== null && occupied < valueSize) {
|
|
1134
|
+
throw new TypeError(`${memberPath} has inconsistent member layout algebra.`);
|
|
1135
|
+
}
|
|
1136
|
+
if (occupied === null && index !== members.length - 1) throw new TypeError(`${memberPath} is a non-final runtime array.`);
|
|
1137
|
+
if (occupied !== null) priorEnd = offset + occupied;
|
|
1138
|
+
});
|
|
1139
|
+
unique(names, String, `${path}.members`);
|
|
1140
|
+
if (input.byteSize === null !== (input.runtimeArrayMember !== null)) throw new TypeError(`${path} has inconsistent runtime array metadata.`);
|
|
1141
|
+
const maximumAlignment = Math.max(1, ...members.map((value2) => Number(value2.alignment)));
|
|
1142
|
+
if (input.alignment !== maximumAlignment) throw new TypeError(`${path}.alignment is inconsistent with its members.`);
|
|
1143
|
+
const tail = members.at(-1);
|
|
1144
|
+
const expectedMinimum = input.runtimeArrayMember === null ? Math.ceil(priorEnd / Number(input.alignment)) * Number(input.alignment) : Number(tail?.offset ?? 0);
|
|
1145
|
+
if (input.minimumByteSize !== expectedMinimum || input.byteSize !== null && input.byteSize !== expectedMinimum || input.runtimeArrayMember !== null && tail?.name !== input.runtimeArrayMember) {
|
|
1146
|
+
throw new TypeError(`${path} has inconsistent fixed/runtime size metadata.`);
|
|
1147
|
+
}
|
|
1148
|
+
if (input.runtimeArrayMember !== null) {
|
|
1149
|
+
const tailType = tail?.type;
|
|
1150
|
+
if (!tailType || tailType.kind !== "array" || tailType.count !== null) throw new TypeError(`${path}.runtimeArrayMember must name a direct trailing runtime-sized array.`);
|
|
1151
|
+
}
|
|
1152
|
+
return input;
|
|
1153
|
+
}
|
|
1154
|
+
function bindingResource(value, path) {
|
|
1155
|
+
const input = object(value, path);
|
|
1156
|
+
const kind = enumeration(input.kind, ["buffer", "sampler", "texture", "storage-texture", "external-texture"], `${path}.kind`);
|
|
1157
|
+
if (kind === "buffer") {
|
|
1158
|
+
exact(input, ["kind", "addressSpace", "access", "recordName", "minimumBindingSize"], path);
|
|
1159
|
+
enumeration(input.addressSpace, ["uniform", "storage"], `${path}.addressSpace`);
|
|
1160
|
+
enumeration(input.access, ["read", "write", "read_write"], `${path}.access`);
|
|
1161
|
+
if (input.addressSpace === "uniform" && input.access !== "read") throw new TypeError(`${path}.access must be read for uniform buffers.`);
|
|
1162
|
+
nullableToken(input.recordName, `${path}.recordName`);
|
|
1163
|
+
integer2(input.minimumBindingSize, `${path}.minimumBindingSize`);
|
|
1164
|
+
} else if (kind === "sampler") {
|
|
1165
|
+
exact(input, ["kind", "samplerType"], path);
|
|
1166
|
+
enumeration(input.samplerType, ["filtering", "non-filtering", "comparison"], `${path}.samplerType`);
|
|
1167
|
+
} else if (kind === "texture") {
|
|
1168
|
+
exact(input, ["kind", "sampleType", "viewDimension", "multisampled"], path);
|
|
1169
|
+
enumeration(input.sampleType, ["float", "unfilterable-float", "depth", "sint", "uint"], `${path}.sampleType`);
|
|
1170
|
+
enumeration(input.viewDimension, ["1d", "2d", "2d-array", "cube", "cube-array", "3d"], `${path}.viewDimension`);
|
|
1171
|
+
if (typeof input.multisampled !== "boolean") throw new TypeError(`${path}.multisampled must be boolean.`);
|
|
1172
|
+
} else if (kind === "storage-texture") {
|
|
1173
|
+
exact(input, ["kind", "access", "format", "viewDimension"], path);
|
|
1174
|
+
enumeration(input.access, ["write-only", "read-only", "read-write"], `${path}.access`);
|
|
1175
|
+
token(input.format, `${path}.format`);
|
|
1176
|
+
enumeration(input.viewDimension, ["1d", "2d", "2d-array", "3d"], `${path}.viewDimension`);
|
|
1177
|
+
} else exact(input, ["kind"], path);
|
|
1178
|
+
return input;
|
|
1179
|
+
}
|
|
1180
|
+
function visibility(value, path) {
|
|
1181
|
+
const result = array(value, path, 3).map((item, index) => enumeration(item, stages, `${path}[${index}]`));
|
|
1182
|
+
unique(result, String, path);
|
|
1183
|
+
if (result.length === 0) throw new TypeError(`${path} must include at least one shader stage.`);
|
|
1184
|
+
return result;
|
|
1185
|
+
}
|
|
1186
|
+
function binding(value, path, coordinates = true) {
|
|
1187
|
+
const input = object(value, path);
|
|
1188
|
+
exact(input, coordinates ? ["moduleId", "variableName", "group", "binding", "resource", "visibility"] : ["source", "resource", "semantic"], path);
|
|
1189
|
+
if (coordinates) {
|
|
1190
|
+
token(input.moduleId, `${path}.moduleId`);
|
|
1191
|
+
token(input.variableName, `${path}.variableName`);
|
|
1192
|
+
integer2(input.group, `${path}.group`);
|
|
1193
|
+
integer2(input.binding, `${path}.binding`);
|
|
1194
|
+
visibility(input.visibility, `${path}.visibility`);
|
|
1195
|
+
} else {
|
|
1196
|
+
const source = object(input.source, `${path}.source`);
|
|
1197
|
+
exact(source, ["moduleId", "group", "binding"], `${path}.source`);
|
|
1198
|
+
token(source.moduleId, `${path}.source.moduleId`);
|
|
1199
|
+
integer2(source.group, `${path}.source.group`);
|
|
1200
|
+
integer2(source.binding, `${path}.source.binding`);
|
|
1201
|
+
nullableToken(input.semantic, `${path}.semantic`);
|
|
1202
|
+
}
|
|
1203
|
+
bindingResource(input.resource, `${path}.resource`);
|
|
1204
|
+
return input;
|
|
1205
|
+
}
|
|
1206
|
+
function entryIo(value, path) {
|
|
1207
|
+
const input = object(value, path);
|
|
1208
|
+
exact(input, ["name", "locationKind", "location", "interpolation", "type"], path);
|
|
1209
|
+
token(input.name, `${path}.name`);
|
|
1210
|
+
const kind = enumeration(input.locationKind, ["location", "builtin"], `${path}.locationKind`);
|
|
1211
|
+
if (kind === "location") integer2(input.location, `${path}.location`);
|
|
1212
|
+
else token(input.location, `${path}.location`);
|
|
1213
|
+
if (input.interpolation !== null) token(input.interpolation, `${path}.interpolation`);
|
|
1214
|
+
typeLayout(input.type, `${path}.type`);
|
|
1215
|
+
return input;
|
|
1216
|
+
}
|
|
1217
|
+
function vertexInput(value, path, model = false) {
|
|
1218
|
+
const input = object(value, path);
|
|
1219
|
+
if (model) {
|
|
1220
|
+
exact(input, ["source", "format", "offset", "arrayStride", "stepMode", "semantic"], path);
|
|
1221
|
+
const source = object(input.source, `${path}.source`);
|
|
1222
|
+
exact(source, ["pipelineId", "shaderLocation"], `${path}.source`);
|
|
1223
|
+
token(source.pipelineId, `${path}.source.pipelineId`);
|
|
1224
|
+
integer2(source.shaderLocation, `${path}.source.shaderLocation`);
|
|
1225
|
+
token(input.semantic, `${path}.semantic`);
|
|
1226
|
+
} else {
|
|
1227
|
+
exact(input, ["pipelineId", "moduleId", "entryPoint", "shaderLocation", "shaderType", "bufferSlot", "format", "offset", "arrayStride", "stepMode", "semantic"], path);
|
|
1228
|
+
token(input.pipelineId, `${path}.pipelineId`);
|
|
1229
|
+
token(input.moduleId, `${path}.moduleId`);
|
|
1230
|
+
token(input.entryPoint, `${path}.entryPoint`);
|
|
1231
|
+
integer2(input.shaderLocation, `${path}.shaderLocation`);
|
|
1232
|
+
typeLayout(input.shaderType, `${path}.shaderType`);
|
|
1233
|
+
integer2(input.bufferSlot, `${path}.bufferSlot`);
|
|
1234
|
+
nullableToken(input.semantic, `${path}.semantic`);
|
|
1235
|
+
}
|
|
1236
|
+
token(input.format, `${path}.format`);
|
|
1237
|
+
integer2(input.offset, `${path}.offset`);
|
|
1238
|
+
integer2(input.arrayStride, `${path}.arrayStride`);
|
|
1239
|
+
enumeration(input.stepMode, ["vertex", "instance"], `${path}.stepMode`);
|
|
1240
|
+
return input;
|
|
1241
|
+
}
|
|
1242
|
+
function semantic(value, path) {
|
|
1243
|
+
const input = object(value, path);
|
|
1244
|
+
exact(input, ["semantic", "source"], path);
|
|
1245
|
+
token(input.semantic, `${path}.semantic`);
|
|
1246
|
+
const source = object(input.source, `${path}.source`);
|
|
1247
|
+
const kind = enumeration(source.kind, ["record-member", "vertex-attribute", "binding"], `${path}.source.kind`);
|
|
1248
|
+
if (kind === "record-member") {
|
|
1249
|
+
exact(source, ["kind", "recordName", "memberPath"], `${path}.source`);
|
|
1250
|
+
token(source.recordName, `${path}.source.recordName`);
|
|
1251
|
+
tokenArray(source.memberPath, `${path}.source.memberPath`, 24);
|
|
1252
|
+
} else if (kind === "vertex-attribute") {
|
|
1253
|
+
exact(source, ["kind", "pipelineId", "shaderLocation"], `${path}.source`);
|
|
1254
|
+
token(source.pipelineId, `${path}.source.pipelineId`);
|
|
1255
|
+
integer2(source.shaderLocation, `${path}.source.shaderLocation`);
|
|
1256
|
+
} else {
|
|
1257
|
+
exact(source, ["kind", "moduleId", "group", "binding"], `${path}.source`);
|
|
1258
|
+
token(source.moduleId, `${path}.source.moduleId`);
|
|
1259
|
+
integer2(source.group, `${path}.source.group`);
|
|
1260
|
+
integer2(source.binding, `${path}.source.binding`);
|
|
1261
|
+
}
|
|
1262
|
+
return input;
|
|
1263
|
+
}
|
|
1264
|
+
function interfaceRef(value, path) {
|
|
1265
|
+
const input = object(value, path);
|
|
1266
|
+
exact(input, ["interfaceId", "interfaceVersion", "manifestUri", "manifestSha256", "interfaceAbiHash", "modelAbiHash"], path);
|
|
1267
|
+
token(input.interfaceId, `${path}.interfaceId`);
|
|
1268
|
+
token(input.interfaceVersion, `${path}.interfaceVersion`);
|
|
1269
|
+
uri(input.manifestUri, `${path}.manifestUri`);
|
|
1270
|
+
digest(input.manifestSha256, `${path}.manifestSha256`);
|
|
1271
|
+
digest(input.interfaceAbiHash, `${path}.interfaceAbiHash`);
|
|
1272
|
+
digest(input.modelAbiHash, `${path}.modelAbiHash`);
|
|
1273
|
+
return input;
|
|
1274
|
+
}
|
|
1275
|
+
function programmable(value, path, moduleIds) {
|
|
1276
|
+
const input = object(value, path);
|
|
1277
|
+
exact(input, ["moduleId", "entryPoint", "constants"], path);
|
|
1278
|
+
const moduleId = token(input.moduleId, `${path}.moduleId`);
|
|
1279
|
+
if (!moduleIds.has(moduleId)) throw new TypeError(`${path}.moduleId is not in modules.`);
|
|
1280
|
+
token(input.entryPoint, `${path}.entryPoint`);
|
|
1281
|
+
const constants = object(input.constants, `${path}.constants`);
|
|
1282
|
+
for (const [name, value2] of Object.entries(constants)) {
|
|
1283
|
+
token(name, `${path}.constants key`);
|
|
1284
|
+
if (typeof value2 !== "boolean") finite(value2, `${path}.constants.${name}`);
|
|
1285
|
+
}
|
|
1286
|
+
return input;
|
|
1287
|
+
}
|
|
1288
|
+
function pipeline(value, path, moduleIds) {
|
|
1289
|
+
const input = object(value, path);
|
|
1290
|
+
const kind = enumeration(input.kind, ["compute", "render"], `${path}.kind`);
|
|
1291
|
+
const common = kind === "compute" ? ["kind", "pipelineId", "layout", "compute"] : ["kind", "pipelineId", "layout", "vertex", "fragment", "vertexBuffers", "primitive", "colorTargets", "depthStencil", "multisample"];
|
|
1292
|
+
exact(input, common, path);
|
|
1293
|
+
token(input.pipelineId, `${path}.pipelineId`);
|
|
1294
|
+
const layout = object(input.layout, `${path}.layout`);
|
|
1295
|
+
exact(layout, ["bindGroups"], `${path}.layout`);
|
|
1296
|
+
const groups = array(layout.bindGroups, `${path}.layout.bindGroups`);
|
|
1297
|
+
const groupIds = [];
|
|
1298
|
+
groups.forEach((value2, groupIndex) => {
|
|
1299
|
+
const groupPath = `${path}.layout.bindGroups[${groupIndex}]`;
|
|
1300
|
+
const group = object(value2, groupPath);
|
|
1301
|
+
exact(group, ["group", "entries"], groupPath);
|
|
1302
|
+
const groupId = integer2(group.group, `${groupPath}.group`);
|
|
1303
|
+
groupIds.push(groupId);
|
|
1304
|
+
const entries = array(group.entries, `${groupPath}.entries`);
|
|
1305
|
+
const bindingIds = [];
|
|
1306
|
+
entries.forEach((entryValue, entryIndex) => {
|
|
1307
|
+
const entryPath = `${groupPath}.entries[${entryIndex}]`;
|
|
1308
|
+
const entry = object(entryValue, entryPath);
|
|
1309
|
+
exact(entry, ["group", "binding", "resource", "visibility"], entryPath);
|
|
1310
|
+
if (integer2(entry.group, `${entryPath}.group`) !== groupId) throw new TypeError(`${entryPath}.group differs from its parent.`);
|
|
1311
|
+
bindingIds.push(integer2(entry.binding, `${entryPath}.binding`));
|
|
1312
|
+
bindingResource(entry.resource, `${entryPath}.resource`);
|
|
1313
|
+
visibility(entry.visibility, `${entryPath}.visibility`);
|
|
1314
|
+
});
|
|
1315
|
+
unique(bindingIds, String, `${groupPath}.entries`);
|
|
1316
|
+
});
|
|
1317
|
+
unique(groupIds, String, `${path}.layout.bindGroups`);
|
|
1318
|
+
[...groupIds].sort((a, b) => a - b).forEach((group, index) => {
|
|
1319
|
+
if (group !== index) throw new TypeError(`${path}.layout.bindGroups must be contiguous from zero.`);
|
|
1320
|
+
});
|
|
1321
|
+
if (kind === "compute") programmable(input.compute, `${path}.compute`, moduleIds);
|
|
1322
|
+
else {
|
|
1323
|
+
programmable(input.vertex, `${path}.vertex`, moduleIds);
|
|
1324
|
+
if (input.fragment !== null) programmable(input.fragment, `${path}.fragment`, moduleIds);
|
|
1325
|
+
array(input.vertexBuffers, `${path}.vertexBuffers`, 16).forEach((value2, bufferIndex) => {
|
|
1326
|
+
const bufferPath = `${path}.vertexBuffers[${bufferIndex}]`;
|
|
1327
|
+
const buffer = object(value2, bufferPath);
|
|
1328
|
+
exact(buffer, ["arrayStride", "stepMode", "attributes"], bufferPath);
|
|
1329
|
+
integer2(buffer.arrayStride, `${bufferPath}.arrayStride`, 0, 2048);
|
|
1330
|
+
enumeration(buffer.stepMode, ["vertex", "instance"], `${bufferPath}.stepMode`);
|
|
1331
|
+
array(buffer.attributes, `${bufferPath}.attributes`, 16).forEach((value3, attributeIndex) => {
|
|
1332
|
+
const attributePath = `${bufferPath}.attributes[${attributeIndex}]`;
|
|
1333
|
+
const attribute = object(value3, attributePath);
|
|
1334
|
+
exact(attribute, ["format", "offset", "shaderLocation", "semantic"], attributePath);
|
|
1335
|
+
token(attribute.format, `${attributePath}.format`);
|
|
1336
|
+
integer2(attribute.offset, `${attributePath}.offset`);
|
|
1337
|
+
integer2(attribute.shaderLocation, `${attributePath}.shaderLocation`);
|
|
1338
|
+
nullableToken(attribute.semantic, `${attributePath}.semantic`);
|
|
1339
|
+
});
|
|
1340
|
+
});
|
|
1341
|
+
const primitive = object(input.primitive, `${path}.primitive`);
|
|
1342
|
+
exact(primitive, ["topology", "stripIndexFormat", "frontFace", "cullMode", "unclippedDepth"], `${path}.primitive`);
|
|
1343
|
+
const topology = enumeration(primitive.topology, ["point-list", "line-list", "line-strip", "triangle-list", "triangle-strip"], `${path}.primitive.topology`);
|
|
1344
|
+
if (primitive.stripIndexFormat !== null) enumeration(primitive.stripIndexFormat, ["uint16", "uint32"], `${path}.primitive.stripIndexFormat`);
|
|
1345
|
+
if (primitive.stripIndexFormat !== null && topology !== "line-strip" && topology !== "triangle-strip") throw new TypeError(`${path}.primitive.stripIndexFormat is only valid for strip topologies.`);
|
|
1346
|
+
enumeration(primitive.frontFace, ["ccw", "cw"], `${path}.primitive.frontFace`);
|
|
1347
|
+
enumeration(primitive.cullMode, ["none", "front", "back"], `${path}.primitive.cullMode`);
|
|
1348
|
+
if (typeof primitive.unclippedDepth !== "boolean") throw new TypeError(`${path}.primitive.unclippedDepth must be boolean.`);
|
|
1349
|
+
const compare = ["never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always"];
|
|
1350
|
+
const operations = ["keep", "zero", "replace", "invert", "increment-clamp", "decrement-clamp", "increment-wrap", "decrement-wrap"];
|
|
1351
|
+
const factors = ["zero", "one", "src", "one-minus-src", "src-alpha", "one-minus-src-alpha", "dst", "one-minus-dst", "dst-alpha", "one-minus-dst-alpha", "src-alpha-saturated", "constant", "one-minus-constant"];
|
|
1352
|
+
const parseBlend = (value2, label) => {
|
|
1353
|
+
const component = object(value2, label);
|
|
1354
|
+
exact(component, ["operation", "srcFactor", "dstFactor"], label);
|
|
1355
|
+
enumeration(component.operation, ["add", "subtract", "reverse-subtract", "min", "max"], `${label}.operation`);
|
|
1356
|
+
enumeration(component.srcFactor, factors, `${label}.srcFactor`);
|
|
1357
|
+
enumeration(component.dstFactor, factors, `${label}.dstFactor`);
|
|
1358
|
+
};
|
|
1359
|
+
const colorTargets = array(input.colorTargets, `${path}.colorTargets`, 8);
|
|
1360
|
+
if (input.fragment === null && colorTargets.length !== 0) throw new TypeError(`${path}.colorTargets must be empty when fragment is null.`);
|
|
1361
|
+
colorTargets.forEach((value2, index) => {
|
|
1362
|
+
const label = `${path}.colorTargets[${index}]`;
|
|
1363
|
+
const target = object(value2, label);
|
|
1364
|
+
exact(target, ["format", "blend", "writeMask"], label);
|
|
1365
|
+
token(target.format, `${label}.format`);
|
|
1366
|
+
integer2(target.writeMask, `${label}.writeMask`, 0, 15);
|
|
1367
|
+
if (target.blend !== null) {
|
|
1368
|
+
const blend = object(target.blend, `${label}.blend`);
|
|
1369
|
+
exact(blend, ["color", "alpha"], `${label}.blend`);
|
|
1370
|
+
parseBlend(blend.color, `${label}.blend.color`);
|
|
1371
|
+
parseBlend(blend.alpha, `${label}.blend.alpha`);
|
|
1372
|
+
}
|
|
1373
|
+
});
|
|
1374
|
+
const parseStencil = (value2, label) => {
|
|
1375
|
+
const stencil = object(value2, label);
|
|
1376
|
+
exact(stencil, ["compare", "failOp", "depthFailOp", "passOp"], label);
|
|
1377
|
+
enumeration(stencil.compare, compare, `${label}.compare`);
|
|
1378
|
+
enumeration(stencil.failOp, operations, `${label}.failOp`);
|
|
1379
|
+
enumeration(stencil.depthFailOp, operations, `${label}.depthFailOp`);
|
|
1380
|
+
enumeration(stencil.passOp, operations, `${label}.passOp`);
|
|
1381
|
+
};
|
|
1382
|
+
if (input.depthStencil !== null) {
|
|
1383
|
+
const depth = object(input.depthStencil, `${path}.depthStencil`);
|
|
1384
|
+
exact(depth, ["format", "depthWriteEnabled", "depthCompare", "stencilFront", "stencilBack", "stencilReadMask", "stencilWriteMask", "depthBias", "depthBiasSlopeScale", "depthBiasClamp"], `${path}.depthStencil`);
|
|
1385
|
+
token(depth.format, `${path}.depthStencil.format`);
|
|
1386
|
+
if (typeof depth.depthWriteEnabled !== "boolean") throw new TypeError(`${path}.depthStencil.depthWriteEnabled must be boolean.`);
|
|
1387
|
+
enumeration(depth.depthCompare, compare, `${path}.depthStencil.depthCompare`);
|
|
1388
|
+
parseStencil(depth.stencilFront, `${path}.depthStencil.stencilFront`);
|
|
1389
|
+
parseStencil(depth.stencilBack, `${path}.depthStencil.stencilBack`);
|
|
1390
|
+
integer2(depth.stencilReadMask, `${path}.depthStencil.stencilReadMask`);
|
|
1391
|
+
integer2(depth.stencilWriteMask, `${path}.depthStencil.stencilWriteMask`);
|
|
1392
|
+
integer2(depth.depthBias, `${path}.depthStencil.depthBias`, -2147483648, 2147483647);
|
|
1393
|
+
finite(depth.depthBiasSlopeScale, `${path}.depthStencil.depthBiasSlopeScale`);
|
|
1394
|
+
finite(depth.depthBiasClamp, `${path}.depthStencil.depthBiasClamp`);
|
|
1395
|
+
}
|
|
1396
|
+
const multisample = object(input.multisample, `${path}.multisample`);
|
|
1397
|
+
exact(multisample, ["count", "mask", "alphaToCoverageEnabled"], `${path}.multisample`);
|
|
1398
|
+
enumeration(multisample.count, [1, 4], `${path}.multisample.count`);
|
|
1399
|
+
integer2(multisample.mask, `${path}.multisample.mask`);
|
|
1400
|
+
if (typeof multisample.alphaToCoverageEnabled !== "boolean") throw new TypeError(`${path}.multisample.alphaToCoverageEnabled must be boolean.`);
|
|
1401
|
+
if (multisample.alphaToCoverageEnabled && multisample.count === 1) throw new TypeError(`${path}.multisample.alphaToCoverageEnabled requires multisampling.`);
|
|
1402
|
+
}
|
|
1403
|
+
return input;
|
|
1404
|
+
}
|
|
1405
|
+
function compatibleModel(value, path) {
|
|
1406
|
+
const input = object(value, path);
|
|
1407
|
+
exact(input, ["interfaceId", "interfaceVersion", "manifestSha256", "interfaceAbiHash", "modelAbiHash"], path);
|
|
1408
|
+
token(input.interfaceId, `${path}.interfaceId`);
|
|
1409
|
+
token(input.interfaceVersion, `${path}.interfaceVersion`);
|
|
1410
|
+
digest(input.manifestSha256, `${path}.manifestSha256`);
|
|
1411
|
+
digest(input.interfaceAbiHash, `${path}.interfaceAbiHash`);
|
|
1412
|
+
digest(input.modelAbiHash, `${path}.modelAbiHash`);
|
|
1413
|
+
return input;
|
|
1414
|
+
}
|
|
1415
|
+
function validationEvidenceRef(value, path) {
|
|
1416
|
+
const evidence = object(value, path);
|
|
1417
|
+
exact(evidence, ["evidenceId", "uri", "sha256", "matrixId", "matrixVersion", "matrixSha256", "attestationRef"], path);
|
|
1418
|
+
token(evidence.evidenceId, `${path}.evidenceId`);
|
|
1419
|
+
uri(evidence.uri, `${path}.uri`);
|
|
1420
|
+
digest(evidence.sha256, `${path}.sha256`);
|
|
1421
|
+
token(evidence.matrixId, `${path}.matrixId`);
|
|
1422
|
+
token(evidence.matrixVersion, `${path}.matrixVersion`);
|
|
1423
|
+
digest(evidence.matrixSha256, `${path}.matrixSha256`);
|
|
1424
|
+
const attestation = object(evidence.attestationRef, `${path}.attestationRef`);
|
|
1425
|
+
exact(attestation, ["uri", "sha256"], `${path}.attestationRef`);
|
|
1426
|
+
uri(attestation.uri, `${path}.attestationRef.uri`);
|
|
1427
|
+
digest(attestation.sha256, `${path}.attestationRef.sha256`);
|
|
1428
|
+
if (evidence.uri === attestation.uri || evidence.sha256 === attestation.sha256) {
|
|
1429
|
+
throw new TypeError(`${path} evidence and attestation artifacts must have distinct URIs and digests.`);
|
|
1430
|
+
}
|
|
1431
|
+
return evidence;
|
|
1432
|
+
}
|
|
1433
|
+
function freeze(value) {
|
|
1434
|
+
if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
|
|
1435
|
+
for (const child of Object.values(value)) freeze(child);
|
|
1436
|
+
return Object.freeze(value);
|
|
1437
|
+
}
|
|
1438
|
+
function reflectedRecordBindingSize(record) {
|
|
1439
|
+
if (record.byteSize !== null) return record.byteSize;
|
|
1440
|
+
if (record.runtimeArrayMember === null) throw new TypeError(`Record ${record.name} has inconsistent runtime-array metadata.`);
|
|
1441
|
+
const member = record.members.find((candidate) => candidate.name === record.runtimeArrayMember);
|
|
1442
|
+
if (!member || member.type.kind !== "array" || member.type.count !== null) {
|
|
1443
|
+
throw new TypeError(`Record ${record.name} has invalid trailing runtime-array metadata.`);
|
|
1444
|
+
}
|
|
1445
|
+
const unrounded = member.offset + member.type.stride;
|
|
1446
|
+
return Math.ceil(unrounded / record.alignment) * record.alignment;
|
|
1447
|
+
}
|
|
1448
|
+
function parseGpuInterfaceManifest(value) {
|
|
1449
|
+
const input = object(value, "GpuInterfaceManifest");
|
|
1450
|
+
exact(input, ["contractVersion", "interfaceId", "interfaceVersion", "modules", "records", "bindings", "entryPoints", "vertexInputs", "overrides", "modelAbi", "modelAbiHash", "interfaceAbiHash", "generatedBy"], "GpuInterfaceManifest");
|
|
1451
|
+
if (input.contractVersion !== GPU_INTERFACE_MANIFEST_VERSION) throw new TypeError("Unsupported GPU interface contract version.");
|
|
1452
|
+
token(input.interfaceId, "GpuInterfaceManifest.interfaceId");
|
|
1453
|
+
token(input.interfaceVersion, "GpuInterfaceManifest.interfaceVersion");
|
|
1454
|
+
const moduleValues = array(input.modules, "GpuInterfaceManifest.modules");
|
|
1455
|
+
if (moduleValues.length === 0) throw new TypeError("GpuInterfaceManifest.modules must not be empty.");
|
|
1456
|
+
const moduleIds = moduleValues.map((value2, index) => {
|
|
1457
|
+
const path = `GpuInterfaceManifest.modules[${index}]`;
|
|
1458
|
+
const module2 = object(value2, path);
|
|
1459
|
+
exact(module2, ["moduleId", "sha256"], path);
|
|
1460
|
+
digest(module2.sha256, `${path}.sha256`);
|
|
1461
|
+
return token(module2.moduleId, `${path}.moduleId`);
|
|
1462
|
+
});
|
|
1463
|
+
unique(moduleIds, String, "GpuInterfaceManifest.modules");
|
|
1464
|
+
const moduleSet = new Set(moduleIds);
|
|
1465
|
+
const recordValues = array(input.records, "GpuInterfaceManifest.records");
|
|
1466
|
+
const parsedRecords = recordValues.map((item, index) => recordLayout(item, `GpuInterfaceManifest.records[${index}]`));
|
|
1467
|
+
unique(parsedRecords, (item) => item.name, "GpuInterfaceManifest.records");
|
|
1468
|
+
const records = new Map(parsedRecords.map((item) => [item.name, item]));
|
|
1469
|
+
for (const record of parsedRecords) for (const member of record.members) {
|
|
1470
|
+
const visit = (type) => {
|
|
1471
|
+
if (type.kind === "record") {
|
|
1472
|
+
const referenced = records.get(type.recordName);
|
|
1473
|
+
if (!referenced) throw new TypeError(`Record ${record.name} references missing ${type.recordName}.`);
|
|
1474
|
+
if (type.alignment !== referenced.alignment || type.byteSize !== referenced.byteSize) throw new TypeError(`Record reference ${record.name}.${member.name} has stale layout metadata.`);
|
|
1475
|
+
}
|
|
1476
|
+
if (type.kind === "array") visit(type.element);
|
|
1477
|
+
};
|
|
1478
|
+
visit(member.type);
|
|
1479
|
+
}
|
|
1480
|
+
const bindingValues = array(input.bindings, "GpuInterfaceManifest.bindings");
|
|
1481
|
+
const bindingKeys = [];
|
|
1482
|
+
bindingValues.forEach((item, index) => {
|
|
1483
|
+
const path = `GpuInterfaceManifest.bindings[${index}]`;
|
|
1484
|
+
const parsed = binding(item, path);
|
|
1485
|
+
const moduleId = String(parsed.moduleId);
|
|
1486
|
+
if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`);
|
|
1487
|
+
bindingKeys.push(`${moduleId}:${parsed.group}:${parsed.binding}`);
|
|
1488
|
+
const resource = parsed.resource;
|
|
1489
|
+
if (resource.kind === "buffer" && resource.recordName) {
|
|
1490
|
+
const record = records.get(resource.recordName);
|
|
1491
|
+
if (!record) throw new TypeError(`${path} references missing record.`);
|
|
1492
|
+
if (resource.minimumBindingSize !== reflectedRecordBindingSize(record)) throw new TypeError(`${path}.resource.minimumBindingSize differs from its reflected record.`);
|
|
1493
|
+
if (record.runtimeArrayMember !== null && resource.addressSpace !== "storage") throw new TypeError(`${path} exposes a runtime-sized array outside storage.`);
|
|
1494
|
+
}
|
|
1495
|
+
});
|
|
1496
|
+
unique(bindingKeys, String, "GpuInterfaceManifest.bindings");
|
|
1497
|
+
const bindingSet = new Set(bindingKeys);
|
|
1498
|
+
const overrideValues = array(input.overrides, "GpuInterfaceManifest.overrides");
|
|
1499
|
+
const overrideKeys = [];
|
|
1500
|
+
const overrideIds = [];
|
|
1501
|
+
overrideValues.forEach((item, index) => {
|
|
1502
|
+
const path = `GpuInterfaceManifest.overrides[${index}]`;
|
|
1503
|
+
const override = object(item, path);
|
|
1504
|
+
exact(override, ["moduleId", "name", "id", "type", "defaultValue"], path);
|
|
1505
|
+
const moduleId = token(override.moduleId, `${path}.moduleId`);
|
|
1506
|
+
if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`);
|
|
1507
|
+
const name = token(override.name, `${path}.name`);
|
|
1508
|
+
overrideKeys.push(`${moduleId}:${name}`);
|
|
1509
|
+
if (override.id !== null) overrideIds.push(`${moduleId}:${integer2(override.id, `${path}.id`)}`);
|
|
1510
|
+
enumeration(override.type, ["bool", "i32", "u32", "f32", "f16"], `${path}.type`);
|
|
1511
|
+
if (override.defaultValue !== null && typeof override.defaultValue !== "boolean") finite(override.defaultValue, `${path}.defaultValue`);
|
|
1512
|
+
});
|
|
1513
|
+
unique(overrideKeys, String, "GpuInterfaceManifest.overrides");
|
|
1514
|
+
unique(overrideIds, String, "GpuInterfaceManifest.overrides ids");
|
|
1515
|
+
const overrideSet = new Set(overrideKeys);
|
|
1516
|
+
const entryValues = array(input.entryPoints, "GpuInterfaceManifest.entryPoints");
|
|
1517
|
+
const entryKeys = [];
|
|
1518
|
+
if (entryValues.length === 0) throw new TypeError("GpuInterfaceManifest.entryPoints must not be empty.");
|
|
1519
|
+
entryValues.forEach((item, index) => {
|
|
1520
|
+
const path = `GpuInterfaceManifest.entryPoints[${index}]`;
|
|
1521
|
+
const entry = object(item, path);
|
|
1522
|
+
exact(entry, ["moduleId", "name", "stage", "inputs", "outputs", "bindingKeys", "overrideNames", "workgroupSize", "workgroupStorageSize"], path);
|
|
1523
|
+
const moduleId = token(entry.moduleId, `${path}.moduleId`);
|
|
1524
|
+
if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`);
|
|
1525
|
+
const stage = enumeration(entry.stage, stages, `${path}.stage`);
|
|
1526
|
+
entryKeys.push(`${moduleId}:${stage}:${token(entry.name, `${path}.name`)}`);
|
|
1527
|
+
for (const ioKey of ["inputs", "outputs"]) {
|
|
1528
|
+
const ios = array(entry[ioKey], `${path}.${ioKey}`).map((value2, ioIndex) => entryIo(value2, `${path}.${ioKey}[${ioIndex}]`));
|
|
1529
|
+
unique(ios, (io) => `${io.locationKind}:${io.location}`, `${path}.${ioKey}`);
|
|
1530
|
+
}
|
|
1531
|
+
const resources = tokenArray(entry.bindingKeys, `${path}.bindingKeys`);
|
|
1532
|
+
resources.forEach((key) => {
|
|
1533
|
+
if (!bindingSet.has(key)) throw new TypeError(`${path}.bindingKeys references missing ${key}.`);
|
|
1534
|
+
});
|
|
1535
|
+
const names = tokenArray(entry.overrideNames, `${path}.overrideNames`);
|
|
1536
|
+
names.forEach((name) => {
|
|
1537
|
+
if (!overrideSet.has(`${moduleId}:${name}`)) throw new TypeError(`${path}.overrideNames references missing ${name}.`);
|
|
1538
|
+
});
|
|
1539
|
+
if (stage === "compute") {
|
|
1540
|
+
const dimensions = array(entry.workgroupSize, `${path}.workgroupSize`, 3);
|
|
1541
|
+
if (dimensions.length !== 3) throw new TypeError(`${path}.workgroupSize must have three dimensions.`);
|
|
1542
|
+
dimensions.forEach((value2, dimensionIndex) => {
|
|
1543
|
+
const dimensionPath = `${path}.workgroupSize[${dimensionIndex}]`;
|
|
1544
|
+
const dimension = object(value2, dimensionPath);
|
|
1545
|
+
const kind = enumeration(dimension.kind, ["literal", "override"], `${dimensionPath}.kind`);
|
|
1546
|
+
if (kind === "literal") {
|
|
1547
|
+
exact(dimension, ["kind", "value"], dimensionPath);
|
|
1548
|
+
integer2(dimension.value, `${dimensionPath}.value`, 1);
|
|
1549
|
+
} else {
|
|
1550
|
+
exact(dimension, ["kind", "name"], dimensionPath);
|
|
1551
|
+
const name = token(dimension.name, `${dimensionPath}.name`);
|
|
1552
|
+
if (!overrideSet.has(`${moduleId}:${name}`)) throw new TypeError(`${dimensionPath} references missing override.`);
|
|
1553
|
+
}
|
|
1554
|
+
});
|
|
1555
|
+
integer2(entry.workgroupStorageSize, `${path}.workgroupStorageSize`);
|
|
1556
|
+
} else if (entry.workgroupSize !== null || entry.workgroupStorageSize !== null) throw new TypeError(`${path} workgroup metadata is only valid for compute.`);
|
|
1557
|
+
});
|
|
1558
|
+
unique(entryKeys, String, "GpuInterfaceManifest.entryPoints");
|
|
1559
|
+
const entrySet = new Set(entryKeys);
|
|
1560
|
+
const vertexValues = array(input.vertexInputs, "GpuInterfaceManifest.vertexInputs");
|
|
1561
|
+
const vertexKeys = [];
|
|
1562
|
+
const parsedVertices = [];
|
|
1563
|
+
vertexValues.forEach((item, index) => {
|
|
1564
|
+
const path = `GpuInterfaceManifest.vertexInputs[${index}]`;
|
|
1565
|
+
const vertex = vertexInput(item, path);
|
|
1566
|
+
parsedVertices.push(vertex);
|
|
1567
|
+
if (!entrySet.has(`${vertex.moduleId}:vertex:${vertex.entryPoint}`)) throw new TypeError(`${path} references missing vertex entry point.`);
|
|
1568
|
+
vertexKeys.push(`${vertex.pipelineId}:${vertex.shaderLocation}`);
|
|
1569
|
+
});
|
|
1570
|
+
unique(vertexKeys, String, "GpuInterfaceManifest.vertexInputs");
|
|
1571
|
+
const model = object(input.modelAbi, "GpuInterfaceManifest.modelAbi");
|
|
1572
|
+
exact(model, ["recordNames", "bindings", "vertexInputs", "semantics"], "GpuInterfaceManifest.modelAbi");
|
|
1573
|
+
tokenArray(model.recordNames, "GpuInterfaceManifest.modelAbi.recordNames").forEach((name) => {
|
|
1574
|
+
if (!records.has(name)) throw new TypeError(`Model ABI references missing record ${name}.`);
|
|
1575
|
+
});
|
|
1576
|
+
const modelBindings = array(model.bindings, "GpuInterfaceManifest.modelAbi.bindings").map((item, index) => binding(item, `GpuInterfaceManifest.modelAbi.bindings[${index}]`, false));
|
|
1577
|
+
for (const [index, projected] of modelBindings.entries()) {
|
|
1578
|
+
const source = projected.source;
|
|
1579
|
+
const reflectedIndex = bindingKeys.indexOf(`${source.moduleId}:${source.group}:${source.binding}`);
|
|
1580
|
+
const reflected = reflectedIndex < 0 ? null : object(bindingValues[reflectedIndex], `GpuInterfaceManifest.bindings[${reflectedIndex}]`);
|
|
1581
|
+
if (!reflected || canonicalizeGpuContract(reflected.resource) !== canonicalizeGpuContract(projected.resource)) throw new TypeError(`GpuInterfaceManifest.modelAbi.bindings[${index}] differs from its reflected source.`);
|
|
1582
|
+
const resource = projected.resource;
|
|
1583
|
+
if (resource.kind === "buffer" && resource.recordName === null) throw new TypeError(`GpuInterfaceManifest.modelAbi.bindings[${index}] must use a named WGSL record root.`);
|
|
1584
|
+
}
|
|
1585
|
+
const modelBindingSemantics = modelBindings.filter((item) => item.semantic !== null).map((item) => String(item.semantic));
|
|
1586
|
+
unique(modelBindingSemantics, String, "GpuInterfaceManifest.modelAbi.bindings semantics");
|
|
1587
|
+
const modelVertices = array(model.vertexInputs, "GpuInterfaceManifest.modelAbi.vertexInputs");
|
|
1588
|
+
const parsedModelVertices = modelVertices.map((item, index) => vertexInput(item, `GpuInterfaceManifest.modelAbi.vertexInputs[${index}]`, true));
|
|
1589
|
+
const modelVertexSemantics = parsedModelVertices.map((item) => String(item.semantic));
|
|
1590
|
+
unique(modelVertexSemantics, String, "GpuInterfaceManifest.modelAbi.vertexInputs");
|
|
1591
|
+
for (const [index, projected] of parsedModelVertices.entries()) {
|
|
1592
|
+
const source = projected.source;
|
|
1593
|
+
const reflected = parsedVertices.find((candidate) => candidate.pipelineId === source.pipelineId && candidate.shaderLocation === source.shaderLocation);
|
|
1594
|
+
if (!reflected || ["format", "offset", "arrayStride", "stepMode", "semantic"].some((key) => reflected[key] !== projected[key])) throw new TypeError(`GpuInterfaceManifest.modelAbi.vertexInputs[${index}] differs from its reflected source.`);
|
|
1595
|
+
}
|
|
1596
|
+
const semantics = array(model.semantics, "GpuInterfaceManifest.modelAbi.semantics").map((item, index) => semantic(item, `GpuInterfaceManifest.modelAbi.semantics[${index}]`));
|
|
1597
|
+
unique(semantics, (item) => String(item.semantic), "GpuInterfaceManifest.modelAbi.semantics");
|
|
1598
|
+
for (const projection of semantics) {
|
|
1599
|
+
const source = projection.source;
|
|
1600
|
+
const semanticName = String(projection.semantic);
|
|
1601
|
+
if (source.kind === "record-member") {
|
|
1602
|
+
let current = records.get(String(source.recordName));
|
|
1603
|
+
if (!current) throw new TypeError(`Semantic ${semanticName} references missing record.`);
|
|
1604
|
+
for (const [index, memberName] of source.memberPath.entries()) {
|
|
1605
|
+
const member = current.members.find((candidate) => candidate.name === memberName);
|
|
1606
|
+
if (!member) throw new TypeError(`Semantic ${semanticName} references missing member ${memberName}.`);
|
|
1607
|
+
if (index < source.memberPath.length - 1) {
|
|
1608
|
+
if (member.type.kind !== "record") throw new TypeError(`Semantic ${semanticName} traverses a non-record member.`);
|
|
1609
|
+
current = records.get(member.type.recordName);
|
|
1610
|
+
if (!current) throw new TypeError(`Semantic ${semanticName} references missing nested record.`);
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
} else if (source.kind === "vertex-attribute") {
|
|
1614
|
+
const vertex = parsedVertices.find((candidate) => candidate.pipelineId === source.pipelineId && candidate.shaderLocation === source.shaderLocation);
|
|
1615
|
+
const modelVertex = parsedModelVertices.find((candidate) => candidate.semantic === semanticName);
|
|
1616
|
+
const modelVertexSource = modelVertex?.source;
|
|
1617
|
+
if (!vertex || vertex.semantic !== semanticName || modelVertexSemantics.filter((item) => item === semanticName).length !== 1 || !modelVertexSource || modelVertexSource.pipelineId !== source.pipelineId || modelVertexSource.shaderLocation !== source.shaderLocation) throw new TypeError(`Semantic ${semanticName} does not resolve to exactly one matching model vertex stream.`);
|
|
1618
|
+
} else {
|
|
1619
|
+
const key = `${source.moduleId}:${source.group}:${source.binding}`;
|
|
1620
|
+
if (!bindingSet.has(key)) throw new TypeError(`Semantic ${semanticName} references missing binding ${key}.`);
|
|
1621
|
+
const modelBinding = modelBindings.find((candidate) => candidate.semantic === semanticName);
|
|
1622
|
+
if (modelBindingSemantics.filter((item) => item === semanticName).length !== 1 || !modelBinding || canonicalizeGpuContract(modelBinding.source) !== canonicalizeGpuContract({ moduleId: source.moduleId, group: source.group, binding: source.binding })) throw new TypeError(`Semantic ${semanticName} does not resolve to exactly one matching model binding.`);
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
for (const semanticName of [...modelVertexSemantics, ...modelBindingSemantics]) if (semantics.filter((item) => item.semantic === semanticName).length !== 1) throw new TypeError(`Model semantic ${semanticName} requires exactly one projection.`);
|
|
1626
|
+
digest(input.modelAbiHash, "GpuInterfaceManifest.modelAbiHash");
|
|
1627
|
+
digest(input.interfaceAbiHash, "GpuInterfaceManifest.interfaceAbiHash");
|
|
1628
|
+
const generated = object(input.generatedBy, "GpuInterfaceManifest.generatedBy");
|
|
1629
|
+
exact(generated, ["packageVersion", "reflector", "reflectorVersion"], "GpuInterfaceManifest.generatedBy");
|
|
1630
|
+
token(generated.packageVersion, "GpuInterfaceManifest.generatedBy.packageVersion");
|
|
1631
|
+
if (generated.reflector !== "wgsl_reflect" || generated.reflectorVersion !== "1.5.0") throw new TypeError("Unsupported reflector provenance.");
|
|
1632
|
+
return freeze(input);
|
|
1633
|
+
}
|
|
1634
|
+
function parseShaderVersionManifest(value) {
|
|
1635
|
+
const input = object(value, "ShaderVersionManifest");
|
|
1636
|
+
exact(input, ["contractVersion", "shaderId", "version", "modules", "gpuInterface", "pipelines", "renderRoles", "compatibleModelInterfaces", "requirements", "shaderAbiHash", "validationEvidence", "additionalValidationEvidence"], "ShaderVersionManifest");
|
|
1637
|
+
if (input.contractVersion !== SHADER_VERSION_MANIFEST_VERSION) throw new TypeError("Unsupported shader manifest contract version.");
|
|
1638
|
+
token(input.shaderId, "ShaderVersionManifest.shaderId");
|
|
1639
|
+
token(input.version, "ShaderVersionManifest.version");
|
|
1640
|
+
const moduleValues = array(input.modules, "ShaderVersionManifest.modules");
|
|
1641
|
+
if (moduleValues.length === 0) throw new TypeError("ShaderVersionManifest.modules must not be empty.");
|
|
1642
|
+
const moduleIds = moduleValues.map((item, index) => {
|
|
1643
|
+
const path = `ShaderVersionManifest.modules[${index}]`;
|
|
1644
|
+
const module2 = object(item, path);
|
|
1645
|
+
exact(module2, ["moduleId", "uri", "byteLength", "sha256", "contentType"], path);
|
|
1646
|
+
uri(module2.uri, `${path}.uri`);
|
|
1647
|
+
integer2(module2.byteLength, `${path}.byteLength`, 1);
|
|
1648
|
+
digest(module2.sha256, `${path}.sha256`);
|
|
1649
|
+
if (module2.contentType !== "text/wgsl; charset=utf-8") throw new TypeError(`${path}.contentType is not canonical WGSL.`);
|
|
1650
|
+
return token(module2.moduleId, `${path}.moduleId`);
|
|
1651
|
+
});
|
|
1652
|
+
unique(moduleIds, String, "ShaderVersionManifest.modules");
|
|
1653
|
+
const moduleSet = new Set(moduleIds);
|
|
1654
|
+
const shaderInterface = interfaceRef(input.gpuInterface, "ShaderVersionManifest.gpuInterface");
|
|
1655
|
+
const pipelines = array(input.pipelines, "ShaderVersionManifest.pipelines").map((item, index) => pipeline(item, `ShaderVersionManifest.pipelines[${index}]`, moduleSet));
|
|
1656
|
+
if (pipelines.length === 0) throw new TypeError("ShaderVersionManifest.pipelines must not be empty.");
|
|
1657
|
+
unique(pipelines, (item) => item.pipelineId, "ShaderVersionManifest.pipelines");
|
|
1658
|
+
const pipelineIds = new Set(pipelines.map((item) => item.pipelineId));
|
|
1659
|
+
const roleValues = array(input.renderRoles, "ShaderVersionManifest.renderRoles", 5);
|
|
1660
|
+
if (roleValues.length === 0) throw new TypeError("ShaderVersionManifest.renderRoles must not be empty.");
|
|
1661
|
+
const roleNames = [];
|
|
1662
|
+
const assigned = /* @__PURE__ */ new Set();
|
|
1663
|
+
roleValues.forEach((item, index) => {
|
|
1664
|
+
const path = `ShaderVersionManifest.renderRoles[${index}]`;
|
|
1665
|
+
const role = object(item, path);
|
|
1666
|
+
exact(role, ["role", "pipelineIds"], path);
|
|
1667
|
+
roleNames.push(enumeration(role.role, roles, `${path}.role`));
|
|
1668
|
+
const ids = tokenArray(role.pipelineIds, `${path}.pipelineIds`);
|
|
1669
|
+
if (ids.length === 0) throw new TypeError(`${path}.pipelineIds must not be empty.`);
|
|
1670
|
+
ids.forEach((id) => {
|
|
1671
|
+
if (!pipelineIds.has(id)) throw new TypeError(`${path} references missing pipeline ${id}.`);
|
|
1672
|
+
assigned.add(id);
|
|
1673
|
+
});
|
|
1674
|
+
});
|
|
1675
|
+
unique(roleNames, String, "ShaderVersionManifest.renderRoles");
|
|
1676
|
+
if (assigned.size !== pipelineIds.size) throw new TypeError("Every pipeline must belong to at least one render role.");
|
|
1677
|
+
const compatible = array(input.compatibleModelInterfaces, "ShaderVersionManifest.compatibleModelInterfaces").map((item, index) => compatibleModel(item, `ShaderVersionManifest.compatibleModelInterfaces[${index}]`));
|
|
1678
|
+
if (compatible.length === 0) throw new TypeError("ShaderVersionManifest.compatibleModelInterfaces must not be empty.");
|
|
1679
|
+
unique(compatible, (item) => `${item.interfaceId}:${item.interfaceVersion}:${item.manifestSha256}:${item.interfaceAbiHash}:${item.modelAbiHash}`, "ShaderVersionManifest.compatibleModelInterfaces");
|
|
1680
|
+
if (compatible.some((item) => item.modelAbiHash !== shaderInterface.modelAbiHash)) throw new TypeError("ShaderVersionManifest compatible model ABI hashes must equal gpuInterface.modelAbiHash.");
|
|
1681
|
+
const requirements = object(input.requirements, "ShaderVersionManifest.requirements");
|
|
1682
|
+
exact(requirements, ["semantics", "features", "limits", "formats"], "ShaderVersionManifest.requirements");
|
|
1683
|
+
tokenArray(requirements.semantics, "ShaderVersionManifest.requirements.semantics");
|
|
1684
|
+
tokenArray(requirements.features, "ShaderVersionManifest.requirements.features");
|
|
1685
|
+
tokenArray(requirements.formats, "ShaderVersionManifest.requirements.formats");
|
|
1686
|
+
const limits = array(requirements.limits, "ShaderVersionManifest.requirements.limits");
|
|
1687
|
+
const limitNames = [];
|
|
1688
|
+
limits.forEach((item, index) => {
|
|
1689
|
+
const path = `ShaderVersionManifest.requirements.limits[${index}]`;
|
|
1690
|
+
const limit = object(item, path);
|
|
1691
|
+
exact(limit, ["name", "comparator", "value"], path);
|
|
1692
|
+
const name = token(limit.name, `${path}.name`);
|
|
1693
|
+
limitNames.push(name);
|
|
1694
|
+
enumeration(limit.comparator, ["at-least", "at-most"], `${path}.comparator`);
|
|
1695
|
+
const value2 = finite(limit.value, `${path}.value`);
|
|
1696
|
+
if (!Number.isSafeInteger(value2) || value2 < 0) throw new TypeError(`${path}.value must be a non-negative safe integer.`);
|
|
1697
|
+
});
|
|
1698
|
+
unique(limitNames, String, "ShaderVersionManifest.requirements.limits");
|
|
1699
|
+
validatePipelineDerivedRequirements({
|
|
1700
|
+
requirements: input.requirements,
|
|
1701
|
+
pipelines
|
|
1702
|
+
});
|
|
1703
|
+
digest(input.shaderAbiHash, "ShaderVersionManifest.shaderAbiHash");
|
|
1704
|
+
const universalEvidence = validationEvidenceRef(input.validationEvidence, "ShaderVersionManifest.validationEvidence");
|
|
1705
|
+
if (!SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES.some((policy) => universalEvidence.matrixId === policy.matrixId && universalEvidence.matrixVersion === policy.matrixVersion && universalEvidence.matrixSha256 === policy.matrixSha256)) {
|
|
1706
|
+
throw new TypeError("ShaderVersionManifest.validationEvidence is not bound to a supported universal stable-WebGPU matrix policy.");
|
|
1707
|
+
}
|
|
1708
|
+
const additionalEvidence = array(input.additionalValidationEvidence, "ShaderVersionManifest.additionalValidationEvidence");
|
|
1709
|
+
const scopedEvidence = additionalEvidence.map((item, index) => {
|
|
1710
|
+
const path = `ShaderVersionManifest.additionalValidationEvidence[${index}]`;
|
|
1711
|
+
const scoped = object(item, path);
|
|
1712
|
+
exact(scoped, ["scope", "evidence"], path);
|
|
1713
|
+
const scope = token(scoped.scope, `${path}.scope`);
|
|
1714
|
+
if (scope === "universal") throw new TypeError(`${path}.scope universal is reserved for validationEvidence.`);
|
|
1715
|
+
const evidence = validationEvidenceRef(scoped.evidence, `${path}.evidence`);
|
|
1716
|
+
if (evidence.matrixSha256 === universalEvidence.matrixSha256) {
|
|
1717
|
+
throw new TypeError(`${path}.evidence must use an additive matrix policy, not the universal matrix policy.`);
|
|
1718
|
+
}
|
|
1719
|
+
return { scope, evidence };
|
|
1720
|
+
});
|
|
1721
|
+
unique(scopedEvidence, (item) => item.scope, "ShaderVersionManifest.additionalValidationEvidence scopes");
|
|
1722
|
+
unique(scopedEvidence, (item) => String(item.evidence.matrixSha256), "ShaderVersionManifest.additionalValidationEvidence matrix policies");
|
|
1723
|
+
const evidenceIds = /* @__PURE__ */ new Set([String(universalEvidence.evidenceId)]);
|
|
1724
|
+
const artifactUris = /* @__PURE__ */ new Set([
|
|
1725
|
+
String(universalEvidence.uri),
|
|
1726
|
+
String(universalEvidence.attestationRef.uri)
|
|
1727
|
+
]);
|
|
1728
|
+
const artifactDigests = /* @__PURE__ */ new Set([
|
|
1729
|
+
String(universalEvidence.sha256),
|
|
1730
|
+
String(universalEvidence.attestationRef.sha256)
|
|
1731
|
+
]);
|
|
1732
|
+
for (const [index, item] of scopedEvidence.entries()) {
|
|
1733
|
+
const path = `ShaderVersionManifest.additionalValidationEvidence[${index}].evidence`;
|
|
1734
|
+
if (evidenceIds.has(String(item.evidence.evidenceId))) throw new TypeError(`${path} reuses a universal or supplemental evidence ID.`);
|
|
1735
|
+
evidenceIds.add(String(item.evidence.evidenceId));
|
|
1736
|
+
const attestation = item.evidence.attestationRef;
|
|
1737
|
+
for (const candidate of [item.evidence.uri, attestation.uri]) {
|
|
1738
|
+
if (artifactUris.has(String(candidate))) throw new TypeError(`${path} reuses a universal or supplemental evidence/attestation URI.`);
|
|
1739
|
+
artifactUris.add(String(candidate));
|
|
1740
|
+
}
|
|
1741
|
+
for (const candidate of [item.evidence.sha256, attestation.sha256]) {
|
|
1742
|
+
if (artifactDigests.has(String(candidate))) throw new TypeError(`${path} reuses a universal or supplemental evidence/attestation digest.`);
|
|
1743
|
+
artifactDigests.add(String(candidate));
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
for (const [index, item] of scopedEvidence.entries()) if (!SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES.some((policy) => item.scope === policy.scope && item.evidence.matrixId === policy.matrixId && item.evidence.matrixVersion === policy.matrixVersion && item.evidence.matrixSha256 === policy.matrixSha256)) {
|
|
1747
|
+
throw new TypeError(`ShaderVersionManifest.additionalValidationEvidence[${index}].evidence is not bound to a supported additive WebGPU matrix policy.`);
|
|
1748
|
+
}
|
|
1749
|
+
return freeze(input);
|
|
1750
|
+
}
|
|
1751
|
+
function parseShaderVersionManifestCore(value) {
|
|
1752
|
+
const input = object(value, "ShaderVersionManifestCore");
|
|
1753
|
+
if ("validationEvidence" in input || "additionalValidationEvidence" in input) {
|
|
1754
|
+
throw new TypeError("ShaderVersionManifestCore must not contain validationEvidence or additionalValidationEvidence.");
|
|
1755
|
+
}
|
|
1756
|
+
const parsed = parseShaderVersionManifest({
|
|
1757
|
+
...input,
|
|
1758
|
+
validationEvidence: {
|
|
1759
|
+
evidenceId: "pending",
|
|
1760
|
+
uri: "https://catalog.invalid/evidence/pending.json",
|
|
1761
|
+
sha256: "0".repeat(64),
|
|
1762
|
+
matrixId: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixId,
|
|
1763
|
+
matrixVersion: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixVersion,
|
|
1764
|
+
matrixSha256: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixSha256,
|
|
1765
|
+
attestationRef: {
|
|
1766
|
+
uri: "https://catalog.invalid/evidence/pending.attestation-ref.json",
|
|
1767
|
+
sha256: "1".repeat(64)
|
|
1768
|
+
}
|
|
1769
|
+
},
|
|
1770
|
+
additionalValidationEvidence: []
|
|
1771
|
+
});
|
|
1772
|
+
const { validationEvidence, additionalValidationEvidence, ...core } = parsed;
|
|
1773
|
+
void validationEvidence;
|
|
1774
|
+
void additionalValidationEvidence;
|
|
1775
|
+
return freeze(core);
|
|
1776
|
+
}
|
|
1777
|
+
function parseShaderStyleProfileManifest(value) {
|
|
1778
|
+
const input = object(value, "ShaderStyleProfileManifest");
|
|
1779
|
+
exact(input, ["contractVersion", "profileId", "version", "style", "roles", "compatibleModelInterfaces", "requiredSemantics", "requiredValidationScopes"], "ShaderStyleProfileManifest");
|
|
1780
|
+
if (input.contractVersion !== SHADER_STYLE_PROFILE_MANIFEST_VERSION) throw new TypeError("Unsupported style-profile contract version.");
|
|
1781
|
+
token(input.profileId, "ShaderStyleProfileManifest.profileId");
|
|
1782
|
+
token(input.version, "ShaderStyleProfileManifest.version");
|
|
1783
|
+
token(input.style, "ShaderStyleProfileManifest.style");
|
|
1784
|
+
const roleValues = array(input.roles, "ShaderStyleProfileManifest.roles", 5);
|
|
1785
|
+
if (roleValues.length === 0) throw new TypeError("ShaderStyleProfileManifest.roles must not be empty.");
|
|
1786
|
+
const roleNames = [];
|
|
1787
|
+
roleValues.forEach((item, index) => {
|
|
1788
|
+
const path = `ShaderStyleProfileManifest.roles[${index}]`;
|
|
1789
|
+
const role = object(item, path);
|
|
1790
|
+
exact(role, ["role", "shader"], path);
|
|
1791
|
+
roleNames.push(enumeration(role.role, roles, `${path}.role`));
|
|
1792
|
+
const shader = object(role.shader, `${path}.shader`);
|
|
1793
|
+
exact(shader, ["shaderId", "version", "manifestUri", "manifestSha256"], `${path}.shader`);
|
|
1794
|
+
token(shader.shaderId, `${path}.shader.shaderId`);
|
|
1795
|
+
token(shader.version, `${path}.shader.version`);
|
|
1796
|
+
uri(shader.manifestUri, `${path}.shader.manifestUri`);
|
|
1797
|
+
digest(shader.manifestSha256, `${path}.shader.manifestSha256`);
|
|
1798
|
+
});
|
|
1799
|
+
unique(roleNames, String, "ShaderStyleProfileManifest.roles");
|
|
1800
|
+
const compatible = array(input.compatibleModelInterfaces, "ShaderStyleProfileManifest.compatibleModelInterfaces").map((item, index) => compatibleModel(item, `ShaderStyleProfileManifest.compatibleModelInterfaces[${index}]`));
|
|
1801
|
+
if (compatible.length === 0) throw new TypeError("ShaderStyleProfileManifest.compatibleModelInterfaces must not be empty.");
|
|
1802
|
+
unique(compatible, (item) => `${item.interfaceId}:${item.interfaceVersion}:${item.manifestSha256}:${item.interfaceAbiHash}:${item.modelAbiHash}`, "ShaderStyleProfileManifest.compatibleModelInterfaces");
|
|
1803
|
+
tokenArray(input.requiredSemantics, "ShaderStyleProfileManifest.requiredSemantics");
|
|
1804
|
+
const requiredValidationScopes = array(input.requiredValidationScopes, "ShaderStyleProfileManifest.requiredValidationScopes").map((item, index) => {
|
|
1805
|
+
const path = `ShaderStyleProfileManifest.requiredValidationScopes[${index}]`;
|
|
1806
|
+
const requirement = object(item, path);
|
|
1807
|
+
exact(requirement, ["scope", "matrixId", "matrixVersion", "matrixSha256"], path);
|
|
1808
|
+
const scope = token(requirement.scope, `${path}.scope`);
|
|
1809
|
+
if (scope === "universal") throw new TypeError(`${path}.scope must not use the reserved universal scope.`);
|
|
1810
|
+
token(requirement.matrixId, `${path}.matrixId`);
|
|
1811
|
+
token(requirement.matrixVersion, `${path}.matrixVersion`);
|
|
1812
|
+
const matrixSha256 = digest(requirement.matrixSha256, `${path}.matrixSha256`);
|
|
1813
|
+
if (SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES.some((policy) => policy.matrixSha256 === matrixSha256)) {
|
|
1814
|
+
throw new TypeError(`${path} must require an additive matrix policy, not the universal matrix policy.`);
|
|
1815
|
+
}
|
|
1816
|
+
if (!SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES.some((policy) => scope === policy.scope && requirement.matrixId === policy.matrixId && requirement.matrixVersion === policy.matrixVersion && matrixSha256 === policy.matrixSha256)) {
|
|
1817
|
+
throw new TypeError(`${path} is not a supported additive WebGPU matrix policy.`);
|
|
1818
|
+
}
|
|
1819
|
+
return requirement;
|
|
1820
|
+
});
|
|
1821
|
+
unique(requiredValidationScopes, (item) => String(item.scope), "ShaderStyleProfileManifest.requiredValidationScopes scopes");
|
|
1822
|
+
unique(requiredValidationScopes, (item) => String(item.matrixSha256), "ShaderStyleProfileManifest.requiredValidationScopes matrix policies");
|
|
1823
|
+
return freeze(input);
|
|
1824
|
+
}
|
|
1825
|
+
function parseModelGpuCompatibilityDescriptor(value) {
|
|
1826
|
+
const input = object(value, "ModelGpuCompatibilityDescriptor");
|
|
1827
|
+
exact(input, ["modelId", "version", "gpuInterface", "modelAbiHash", "providedSemantics", "defaultStyleProfile"], "ModelGpuCompatibilityDescriptor");
|
|
1828
|
+
token(input.modelId, "ModelGpuCompatibilityDescriptor.modelId");
|
|
1829
|
+
token(input.version, "ModelGpuCompatibilityDescriptor.version");
|
|
1830
|
+
const gpuInterface = interfaceRef(input.gpuInterface, "ModelGpuCompatibilityDescriptor.gpuInterface");
|
|
1831
|
+
const modelAbiHash = digest(input.modelAbiHash, "ModelGpuCompatibilityDescriptor.modelAbiHash");
|
|
1832
|
+
if (gpuInterface.modelAbiHash !== modelAbiHash) throw new TypeError("ModelGpuCompatibilityDescriptor.gpuInterface.modelAbiHash differs from modelAbiHash.");
|
|
1833
|
+
tokenArray(input.providedSemantics, "ModelGpuCompatibilityDescriptor.providedSemantics");
|
|
1834
|
+
if (input.defaultStyleProfile !== null) {
|
|
1835
|
+
const profile = object(input.defaultStyleProfile, "ModelGpuCompatibilityDescriptor.defaultStyleProfile");
|
|
1836
|
+
exact(profile, ["profileId", "version", "manifestUri", "manifestSha256"], "ModelGpuCompatibilityDescriptor.defaultStyleProfile");
|
|
1837
|
+
token(profile.profileId, "ModelGpuCompatibilityDescriptor.defaultStyleProfile.profileId");
|
|
1838
|
+
token(profile.version, "ModelGpuCompatibilityDescriptor.defaultStyleProfile.version");
|
|
1839
|
+
uri(profile.manifestUri, "ModelGpuCompatibilityDescriptor.defaultStyleProfile.manifestUri");
|
|
1840
|
+
digest(profile.manifestSha256, "ModelGpuCompatibilityDescriptor.defaultStyleProfile.manifestSha256");
|
|
1841
|
+
}
|
|
1842
|
+
return freeze(input);
|
|
1843
|
+
}
|
|
1844
|
+
function parseJsonBytes(bytes, label) {
|
|
1845
|
+
try {
|
|
1846
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
1847
|
+
} catch (cause) {
|
|
1848
|
+
throw new TypeError(`${label} is not valid UTF-8 JSON.`, { cause });
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
// src/runtime/trusted-values.ts
|
|
1853
|
+
var ReadonlyMapView = class {
|
|
1854
|
+
#source;
|
|
1855
|
+
constructor(source) {
|
|
1856
|
+
this.#source = source;
|
|
1857
|
+
Object.freeze(this);
|
|
1858
|
+
}
|
|
1859
|
+
get size() {
|
|
1860
|
+
return this.#source.size;
|
|
1861
|
+
}
|
|
1862
|
+
get(key) {
|
|
1863
|
+
return this.#source.get(key);
|
|
1864
|
+
}
|
|
1865
|
+
has(key) {
|
|
1866
|
+
return this.#source.has(key);
|
|
1867
|
+
}
|
|
1868
|
+
entries() {
|
|
1869
|
+
return this.#source.entries();
|
|
1870
|
+
}
|
|
1871
|
+
keys() {
|
|
1872
|
+
return this.#source.keys();
|
|
1873
|
+
}
|
|
1874
|
+
values() {
|
|
1875
|
+
return this.#source.values();
|
|
1876
|
+
}
|
|
1877
|
+
[Symbol.iterator]() {
|
|
1878
|
+
return this.#source[Symbol.iterator]();
|
|
1879
|
+
}
|
|
1880
|
+
forEach(callbackfn, thisArg) {
|
|
1881
|
+
for (const [key, value] of this.#source) callbackfn.call(thisArg, value, key, this);
|
|
1882
|
+
}
|
|
1883
|
+
};
|
|
1884
|
+
var loadedProfiles = /* @__PURE__ */ new WeakMap();
|
|
1885
|
+
var preparedProfiles = /* @__PURE__ */ new WeakSet();
|
|
1886
|
+
function immutableSnapshot(value) {
|
|
1887
|
+
if (Array.isArray(value)) {
|
|
1888
|
+
return Object.freeze(value.map((item) => immutableSnapshot(item)));
|
|
1889
|
+
}
|
|
1890
|
+
if (typeof value !== "object" || value === null) return value;
|
|
1891
|
+
const output = {};
|
|
1892
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1893
|
+
output[key] = immutableSnapshot(item);
|
|
1894
|
+
}
|
|
1895
|
+
return Object.freeze(output);
|
|
1896
|
+
}
|
|
1897
|
+
function readonlyMapView(source) {
|
|
1898
|
+
return new ReadonlyMapView(source);
|
|
1899
|
+
}
|
|
1900
|
+
function trustLoadedShaderStyleProfile(raw) {
|
|
1901
|
+
const shaderMemo = /* @__PURE__ */ new Map();
|
|
1902
|
+
const trustedShaders = /* @__PURE__ */ new Map();
|
|
1903
|
+
const publicShaders = /* @__PURE__ */ new Map();
|
|
1904
|
+
for (const [role, rawShader] of raw.shaders) {
|
|
1905
|
+
let trusted = shaderMemo.get(rawShader);
|
|
1906
|
+
if (!trusted) {
|
|
1907
|
+
const ref2 = immutableSnapshot(rawShader.ref);
|
|
1908
|
+
const manifest2 = immutableSnapshot(rawShader.manifest);
|
|
1909
|
+
const gpuInterface = immutableSnapshot(rawShader.gpuInterface);
|
|
1910
|
+
const privateModules = /* @__PURE__ */ new Map();
|
|
1911
|
+
const publicModules = /* @__PURE__ */ new Map();
|
|
1912
|
+
for (const [moduleId, bytes] of rawShader.modules) {
|
|
1913
|
+
const privateBytes = new Uint8Array(bytes);
|
|
1914
|
+
privateModules.set(moduleId, privateBytes);
|
|
1915
|
+
publicModules.set(moduleId, new Uint8Array(privateBytes));
|
|
1916
|
+
}
|
|
1917
|
+
const publicValue2 = Object.freeze({
|
|
1918
|
+
ref: ref2,
|
|
1919
|
+
manifest: manifest2,
|
|
1920
|
+
gpuInterface,
|
|
1921
|
+
modules: readonlyMapView(publicModules)
|
|
1922
|
+
});
|
|
1923
|
+
trusted = Object.freeze({
|
|
1924
|
+
publicValue: publicValue2,
|
|
1925
|
+
ref: ref2,
|
|
1926
|
+
manifest: manifest2,
|
|
1927
|
+
gpuInterface,
|
|
1928
|
+
modules: readonlyMapView(privateModules)
|
|
1929
|
+
});
|
|
1930
|
+
shaderMemo.set(rawShader, trusted);
|
|
1931
|
+
}
|
|
1932
|
+
trustedShaders.set(role, trusted);
|
|
1933
|
+
publicShaders.set(role, trusted.publicValue);
|
|
1934
|
+
}
|
|
1935
|
+
const ref = immutableSnapshot(raw.ref);
|
|
1936
|
+
const manifest = immutableSnapshot(raw.manifest);
|
|
1937
|
+
const publicValue = Object.freeze({
|
|
1938
|
+
ref,
|
|
1939
|
+
manifest,
|
|
1940
|
+
shaders: readonlyMapView(publicShaders)
|
|
1941
|
+
});
|
|
1942
|
+
loadedProfiles.set(publicValue, Object.freeze({
|
|
1943
|
+
publicValue,
|
|
1944
|
+
ref,
|
|
1945
|
+
manifest,
|
|
1946
|
+
shaders: readonlyMapView(trustedShaders)
|
|
1947
|
+
}));
|
|
1948
|
+
return publicValue;
|
|
1949
|
+
}
|
|
1950
|
+
function requireTrustedLoadedShaderStyleProfile(value) {
|
|
1951
|
+
const trusted = loadedProfiles.get(value);
|
|
1952
|
+
if (!trusted) {
|
|
1953
|
+
throw new TypeError("loaded must be returned by loadShaderStyleProfile.");
|
|
1954
|
+
}
|
|
1955
|
+
return trusted;
|
|
1956
|
+
}
|
|
1957
|
+
function trustPreparedShaderStyleProfile(value) {
|
|
1958
|
+
preparedProfiles.add(value);
|
|
1959
|
+
return Object.freeze(value);
|
|
1960
|
+
}
|
|
1961
|
+
function requireTrustedPreparedShaderStyleProfile(value) {
|
|
1962
|
+
if (!preparedProfiles.has(value)) {
|
|
1963
|
+
throw new TypeError("prepared must be returned by prepareStyleProfile.");
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
// src/runtime/catalog-loader.ts
|
|
1968
|
+
function diagnostic(code, message, path) {
|
|
1969
|
+
return { code, severity: "error", message, ...path ? { path } : {} };
|
|
1970
|
+
}
|
|
1971
|
+
async function verifyBytes(bytes, expected, label) {
|
|
1972
|
+
const actual = await computeSha256(bytes);
|
|
1973
|
+
if (actual !== expected) throw new TypeError(`${label} digest does not match its immutable reference.`);
|
|
1974
|
+
}
|
|
1975
|
+
function copyBytes(bytes) {
|
|
1976
|
+
return new Uint8Array(bytes);
|
|
1977
|
+
}
|
|
1978
|
+
function throwIfAborted(signal) {
|
|
1979
|
+
if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError");
|
|
1980
|
+
}
|
|
1981
|
+
function exactShaderRefKey(ref) {
|
|
1982
|
+
return `${ref.shaderId}\0${ref.version}\0${ref.manifestUri}\0${ref.manifestSha256}`;
|
|
1983
|
+
}
|
|
1984
|
+
function evidenceArtifacts(evidence) {
|
|
1985
|
+
return [
|
|
1986
|
+
evidence.evidenceId,
|
|
1987
|
+
evidence.uri,
|
|
1988
|
+
evidence.sha256,
|
|
1989
|
+
evidence.attestationRef.uri,
|
|
1990
|
+
evidence.attestationRef.sha256
|
|
1991
|
+
];
|
|
1992
|
+
}
|
|
1993
|
+
function assertDistinctEvidenceOwnership(shaders) {
|
|
1994
|
+
const uniqueShaders = /* @__PURE__ */ new Map();
|
|
1995
|
+
for (const shader of shaders) uniqueShaders.set(exactShaderRefKey(shader.ref), shader);
|
|
1996
|
+
const evidenceIds = /* @__PURE__ */ new Map();
|
|
1997
|
+
const artifactUris = /* @__PURE__ */ new Map();
|
|
1998
|
+
const artifactDigests = /* @__PURE__ */ new Map();
|
|
1999
|
+
for (const [shaderKey, shader] of uniqueShaders) {
|
|
2000
|
+
const evidenceValues = [
|
|
2001
|
+
shader.manifest.validationEvidence,
|
|
2002
|
+
...shader.manifest.additionalValidationEvidence.map((item) => item.evidence)
|
|
2003
|
+
];
|
|
2004
|
+
for (const evidence of evidenceValues) {
|
|
2005
|
+
const [evidenceId, evidenceUri, evidenceSha256, attestationUri, attestationSha256] = evidenceArtifacts(evidence);
|
|
2006
|
+
for (const [kind, value, owners] of [
|
|
2007
|
+
["evidence ID", evidenceId, evidenceIds],
|
|
2008
|
+
["evidence/attestation URI", evidenceUri, artifactUris],
|
|
2009
|
+
["evidence/attestation URI", attestationUri, artifactUris],
|
|
2010
|
+
["evidence/attestation digest", evidenceSha256, artifactDigests],
|
|
2011
|
+
["evidence/attestation digest", attestationSha256, artifactDigests]
|
|
2012
|
+
]) {
|
|
2013
|
+
const owner = owners.get(value);
|
|
2014
|
+
if (owner !== void 0 && owner !== shaderKey) {
|
|
2015
|
+
throw new TypeError(`Distinct shader versions in one style profile reuse the same ${kind}.`);
|
|
2016
|
+
}
|
|
2017
|
+
owners.set(value, shaderKey);
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
async function mapLimit(values, limit, operation, signal) {
|
|
2023
|
+
const results = new Array(values.length);
|
|
2024
|
+
let next = 0;
|
|
2025
|
+
const worker = async () => {
|
|
2026
|
+
while (next < values.length) {
|
|
2027
|
+
throwIfAborted(signal);
|
|
2028
|
+
const index = next++;
|
|
2029
|
+
const value = values[index];
|
|
2030
|
+
if (value !== void 0) {
|
|
2031
|
+
throwIfAborted(signal);
|
|
2032
|
+
results[index] = await operation(value, index);
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
};
|
|
2036
|
+
await Promise.all(Array.from({ length: Math.min(limit, values.length) }, () => worker()));
|
|
2037
|
+
return results;
|
|
2038
|
+
}
|
|
2039
|
+
async function loadInterface(catalog, ref, signal) {
|
|
2040
|
+
throwIfAborted(signal);
|
|
2041
|
+
if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError("GPU interface URI is outside the promoted catalog root.");
|
|
2042
|
+
const loaded = await catalog.loadInterface(ref, signal);
|
|
2043
|
+
const bytes = copyBytes(loaded.bytes);
|
|
2044
|
+
const promoted = loaded.promoted;
|
|
2045
|
+
throwIfAborted(signal);
|
|
2046
|
+
if (!promoted) throw new TypeError("GPU interface is not promoted.");
|
|
2047
|
+
await verifyBytes(bytes, ref.manifestSha256, "GPU interface manifest");
|
|
2048
|
+
const manifest = parseGpuInterfaceManifest(parseJsonBytes(bytes, "GPU interface manifest"));
|
|
2049
|
+
if (manifest.interfaceId !== ref.interfaceId || manifest.interfaceVersion !== ref.interfaceVersion || manifest.interfaceAbiHash !== ref.interfaceAbiHash || manifest.modelAbiHash !== ref.modelAbiHash) {
|
|
2050
|
+
throw new TypeError("GPU interface manifest identity does not match its exact reference.");
|
|
2051
|
+
}
|
|
2052
|
+
const modelAbiHash = await computeGpuAbiHash({ kind: "model", interface: manifest });
|
|
2053
|
+
const interfaceAbiHash = await computeGpuAbiHash({ kind: "interface", interface: manifest });
|
|
2054
|
+
if (modelAbiHash !== manifest.modelAbiHash || interfaceAbiHash !== manifest.interfaceAbiHash) {
|
|
2055
|
+
throw new TypeError("GPU interface ABI hashes do not match regenerated structural hashes.");
|
|
2056
|
+
}
|
|
2057
|
+
return manifest;
|
|
2058
|
+
}
|
|
2059
|
+
async function loadShader(catalog, ref, signal) {
|
|
2060
|
+
throwIfAborted(signal);
|
|
2061
|
+
if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError("Shader manifest URI is outside the promoted catalog root.");
|
|
2062
|
+
const loaded = await catalog.loadShader(ref, signal);
|
|
2063
|
+
const bytes = copyBytes(loaded.bytes);
|
|
2064
|
+
const promoted = loaded.promoted;
|
|
2065
|
+
throwIfAborted(signal);
|
|
2066
|
+
if (!promoted) throw new TypeError("Shader version is not promoted.");
|
|
2067
|
+
await verifyBytes(bytes, ref.manifestSha256, "Shader manifest");
|
|
2068
|
+
const manifest = parseShaderVersionManifest(parseJsonBytes(bytes, "Shader manifest"));
|
|
2069
|
+
if (manifest.shaderId !== ref.shaderId || manifest.version !== ref.version) {
|
|
2070
|
+
throw new TypeError("Shader manifest identity does not match its exact reference.");
|
|
2071
|
+
}
|
|
2072
|
+
for (const evidence of [
|
|
2073
|
+
manifest.validationEvidence,
|
|
2074
|
+
...manifest.additionalValidationEvidence.map((item) => item.evidence)
|
|
2075
|
+
]) {
|
|
2076
|
+
if (!catalog.isCatalogAssetUri(evidence.uri)) throw new TypeError("Shader validation evidence URI is outside the promoted catalog root.");
|
|
2077
|
+
if (!catalog.isCatalogAssetUri(evidence.attestationRef.uri)) throw new TypeError("Shader validation evidence attestation URI is outside the promoted catalog root.");
|
|
2078
|
+
}
|
|
2079
|
+
const gpuInterface = await loadInterface(catalog, manifest.gpuInterface, signal);
|
|
2080
|
+
const normalizeModules = (values) => [...values].sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0).map(({ moduleId, sha256 }) => ({ moduleId, sha256 }));
|
|
2081
|
+
if (canonicalizeGpuContract(normalizeModules(gpuInterface.modules)) !== canonicalizeGpuContract(normalizeModules(manifest.modules))) {
|
|
2082
|
+
throw new TypeError("Shader modules differ from the exact reflected GPU interface module set.");
|
|
2083
|
+
}
|
|
2084
|
+
const shaderAbiHash = await computeGpuAbiHash({
|
|
2085
|
+
kind: "shader",
|
|
2086
|
+
interface: gpuInterface,
|
|
2087
|
+
pipelines: manifest.pipelines,
|
|
2088
|
+
requirements: manifest.requirements
|
|
2089
|
+
});
|
|
2090
|
+
if (shaderAbiHash !== manifest.shaderAbiHash) throw new TypeError("Shader ABI hash differs from regenerated pipeline/interface ABI.");
|
|
2091
|
+
const modulePairs = await mapLimit(manifest.modules, 4, async (module2) => {
|
|
2092
|
+
throwIfAborted(signal);
|
|
2093
|
+
if (!catalog.isCatalogAssetUri(module2.uri)) throw new TypeError(`Shader module ${module2.moduleId} URI is outside the promoted catalog root.`);
|
|
2094
|
+
const asset = await catalog.loadModule(ref, module2.moduleId, module2.uri, signal);
|
|
2095
|
+
const moduleBytes = copyBytes(asset.bytes);
|
|
2096
|
+
const promoted2 = asset.promoted;
|
|
2097
|
+
throwIfAborted(signal);
|
|
2098
|
+
if (!promoted2) throw new TypeError(`Shader module ${module2.moduleId} is not promoted.`);
|
|
2099
|
+
if (moduleBytes.byteLength !== module2.byteLength) {
|
|
2100
|
+
throw new TypeError(`Shader module ${module2.moduleId} byte length does not match its manifest.`);
|
|
2101
|
+
}
|
|
2102
|
+
await verifyBytes(moduleBytes, module2.sha256, `Shader module ${module2.moduleId}`);
|
|
2103
|
+
return [module2.moduleId, moduleBytes];
|
|
2104
|
+
}, signal);
|
|
2105
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
2106
|
+
validateShaderDerivedRequirements({ manifest, gpuInterface, moduleSources: new Map(modulePairs.map(([moduleId, bytes2]) => [moduleId, decoder.decode(bytes2)])) });
|
|
2107
|
+
return { ref, manifest, gpuInterface, modules: new Map(modulePairs) };
|
|
2108
|
+
}
|
|
2109
|
+
async function loadShaderStyleProfile(input) {
|
|
2110
|
+
try {
|
|
2111
|
+
throwIfAborted(input.signal);
|
|
2112
|
+
if (!input.catalog.isCatalogAssetUri(input.ref.manifestUri)) throw new TypeError("Style profile URI is outside the promoted catalog root.");
|
|
2113
|
+
const loaded = await input.catalog.loadProfile(input.ref, input.signal);
|
|
2114
|
+
const profileBytes = copyBytes(loaded.bytes);
|
|
2115
|
+
const promoted = loaded.promoted;
|
|
2116
|
+
throwIfAborted(input.signal);
|
|
2117
|
+
if (!promoted) {
|
|
2118
|
+
return { ok: false, diagnostics: [diagnostic("unpromoted-asset", "Style profile is not promoted.")] };
|
|
2119
|
+
}
|
|
2120
|
+
await verifyBytes(profileBytes, input.ref.manifestSha256, "Style profile manifest");
|
|
2121
|
+
const manifest = parseShaderStyleProfileManifest(parseJsonBytes(profileBytes, "Style profile manifest"));
|
|
2122
|
+
if (manifest.profileId !== input.ref.profileId || manifest.version !== input.ref.version) {
|
|
2123
|
+
return { ok: false, diagnostics: [diagnostic("invalid-contract", "Style profile identity does not match its exact reference.")] };
|
|
2124
|
+
}
|
|
2125
|
+
const cache = /* @__PURE__ */ new Map();
|
|
2126
|
+
const pairs = await mapLimit(manifest.roles, 4, async (binding2) => {
|
|
2127
|
+
throwIfAborted(input.signal);
|
|
2128
|
+
const cacheKey = exactShaderRefKey(binding2.shader);
|
|
2129
|
+
let shader = cache.get(cacheKey);
|
|
2130
|
+
if (!shader) {
|
|
2131
|
+
shader = loadShader(input.catalog, binding2.shader, input.signal);
|
|
2132
|
+
cache.set(cacheKey, shader);
|
|
2133
|
+
}
|
|
2134
|
+
const resolved = await shader;
|
|
2135
|
+
if (!resolved.manifest.renderRoles.some((role) => role.role === binding2.role)) {
|
|
2136
|
+
throw new TypeError(`Shader ${resolved.manifest.shaderId} does not implement role ${binding2.role}.`);
|
|
2137
|
+
}
|
|
2138
|
+
const validationScopes = new Map(
|
|
2139
|
+
resolved.manifest.additionalValidationEvidence.map((item) => [item.scope, item.evidence])
|
|
2140
|
+
);
|
|
2141
|
+
for (const requirement of manifest.requiredValidationScopes) {
|
|
2142
|
+
const evidence = validationScopes.get(requirement.scope);
|
|
2143
|
+
if (!evidence) {
|
|
2144
|
+
throw new TypeError(`Shader ${resolved.manifest.shaderId} lacks required validation scope ${requirement.scope}.`);
|
|
2145
|
+
}
|
|
2146
|
+
if (evidence.matrixId !== requirement.matrixId || evidence.matrixVersion !== requirement.matrixVersion || evidence.matrixSha256 !== requirement.matrixSha256) {
|
|
2147
|
+
throw new TypeError(
|
|
2148
|
+
`Shader ${resolved.manifest.shaderId} validation scope ${requirement.scope} is bound to a different matrix policy.`
|
|
2149
|
+
);
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
return [binding2.role, resolved];
|
|
2153
|
+
}, input.signal);
|
|
2154
|
+
assertDistinctEvidenceOwnership(pairs.map(([, shader]) => shader));
|
|
2155
|
+
return {
|
|
2156
|
+
ok: true,
|
|
2157
|
+
value: trustLoadedShaderStyleProfile({
|
|
2158
|
+
ref: input.ref,
|
|
2159
|
+
manifest,
|
|
2160
|
+
shaders: new Map(pairs)
|
|
2161
|
+
})
|
|
2162
|
+
};
|
|
2163
|
+
} catch (cause) {
|
|
2164
|
+
if (input.signal?.aborted) throw cause;
|
|
2165
|
+
const code = cause instanceof TypeError && /digest/u.test(cause.message) ? "digest-mismatch" : "invalid-contract";
|
|
2166
|
+
return {
|
|
2167
|
+
ok: false,
|
|
2168
|
+
diagnostics: [diagnostic(code, cause instanceof Error ? cause.message : "Style profile loading failed.")]
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
// src/runtime/profile-preparer.ts
|
|
2174
|
+
function error2(code, message) {
|
|
2175
|
+
return { code, severity: "error", message };
|
|
2176
|
+
}
|
|
2177
|
+
var DeviceLostError = class extends Error {
|
|
2178
|
+
};
|
|
2179
|
+
async function boundedGpuWait(promise, device, timeoutMs, signal) {
|
|
2180
|
+
let timer;
|
|
2181
|
+
let abort;
|
|
2182
|
+
const timeout = new Promise((_, reject) => {
|
|
2183
|
+
timer = setTimeout(() => reject(new Error("GPU operation timed out.")), timeoutMs);
|
|
2184
|
+
});
|
|
2185
|
+
const lost = device.lost?.then((info) => {
|
|
2186
|
+
throw new DeviceLostError(info.message ?? info.reason ?? "GPU device was lost.");
|
|
2187
|
+
});
|
|
2188
|
+
const aborted = signal ? new Promise((_, reject) => {
|
|
2189
|
+
abort = () => reject(signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError"));
|
|
2190
|
+
if (signal.aborted) abort();
|
|
2191
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
2192
|
+
}) : void 0;
|
|
2193
|
+
try {
|
|
2194
|
+
return await Promise.race([promise, timeout, ...lost ? [lost] : [], ...aborted ? [aborted] : []]);
|
|
2195
|
+
} finally {
|
|
2196
|
+
if (timer) clearTimeout(timer);
|
|
2197
|
+
if (abort && signal) signal.removeEventListener("abort", abort);
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
function closeErrorScopeBestEffort(device, timeoutMs) {
|
|
2201
|
+
if (!device.popErrorScope) return;
|
|
2202
|
+
const cleanupTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(timeoutMs, 1e3) : 1e3;
|
|
2203
|
+
try {
|
|
2204
|
+
const pending = device.popErrorScope();
|
|
2205
|
+
void boundedGpuWait(pending, device, cleanupTimeout).catch(() => void 0);
|
|
2206
|
+
} catch {
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
function visibilityMask(stages2) {
|
|
2210
|
+
return stages2.reduce((mask, stage) => mask | (stage === "vertex" ? 1 : stage === "fragment" ? 2 : 4), 0);
|
|
2211
|
+
}
|
|
2212
|
+
function bindGroupEntry(entry) {
|
|
2213
|
+
const common = { binding: entry.binding, visibility: visibilityMask(entry.visibility) };
|
|
2214
|
+
switch (entry.resource.kind) {
|
|
2215
|
+
case "buffer":
|
|
2216
|
+
return {
|
|
2217
|
+
...common,
|
|
2218
|
+
buffer: {
|
|
2219
|
+
type: entry.resource.addressSpace === "uniform" ? "uniform" : entry.resource.access === "read" ? "read-only-storage" : "storage",
|
|
2220
|
+
minBindingSize: entry.resource.minimumBindingSize
|
|
2221
|
+
}
|
|
2222
|
+
};
|
|
2223
|
+
case "sampler":
|
|
2224
|
+
return { ...common, sampler: { type: entry.resource.samplerType } };
|
|
2225
|
+
case "texture":
|
|
2226
|
+
return {
|
|
2227
|
+
...common,
|
|
2228
|
+
texture: {
|
|
2229
|
+
sampleType: entry.resource.sampleType,
|
|
2230
|
+
viewDimension: entry.resource.viewDimension,
|
|
2231
|
+
multisampled: entry.resource.multisampled
|
|
2232
|
+
}
|
|
2233
|
+
};
|
|
2234
|
+
case "storage-texture":
|
|
2235
|
+
return {
|
|
2236
|
+
...common,
|
|
2237
|
+
storageTexture: {
|
|
2238
|
+
access: entry.resource.access,
|
|
2239
|
+
format: entry.resource.format,
|
|
2240
|
+
viewDimension: entry.resource.viewDimension
|
|
2241
|
+
}
|
|
2242
|
+
};
|
|
2243
|
+
case "external-texture":
|
|
2244
|
+
return { ...common, externalTexture: {} };
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
function pipelineLayout(device, pipeline2) {
|
|
2248
|
+
const ordered = [...pipeline2.layout.bindGroups].sort((left, right) => left.group - right.group);
|
|
2249
|
+
ordered.forEach((group, index) => {
|
|
2250
|
+
if (group.group !== index) throw new TypeError(`Pipeline ${pipeline2.pipelineId} bind groups must be contiguous from zero.`);
|
|
2251
|
+
});
|
|
2252
|
+
const groups = ordered.map((group) => device.createBindGroupLayout({
|
|
2253
|
+
entries: group.entries.map(bindGroupEntry)
|
|
2254
|
+
}));
|
|
2255
|
+
return device.createPipelineLayout({ bindGroupLayouts: groups });
|
|
2256
|
+
}
|
|
2257
|
+
async function createPipeline(device, pipeline2, modules, timeoutMs, signal) {
|
|
2258
|
+
const layout = pipelineLayout(device, pipeline2);
|
|
2259
|
+
const module2 = (moduleId) => {
|
|
2260
|
+
const resolved = modules.get(moduleId);
|
|
2261
|
+
if (!resolved) throw new TypeError(`Pipeline ${pipeline2.pipelineId} references missing module ${moduleId}.`);
|
|
2262
|
+
return resolved;
|
|
2263
|
+
};
|
|
2264
|
+
const constants = (values) => Object.fromEntries(Object.entries(values).map(([name, value]) => [name, typeof value === "boolean" ? Number(value) : value]));
|
|
2265
|
+
if (pipeline2.kind === "compute") {
|
|
2266
|
+
const descriptor2 = {
|
|
2267
|
+
label: pipeline2.pipelineId,
|
|
2268
|
+
layout,
|
|
2269
|
+
compute: {
|
|
2270
|
+
module: module2(pipeline2.compute.moduleId),
|
|
2271
|
+
entryPoint: pipeline2.compute.entryPoint,
|
|
2272
|
+
constants: constants(pipeline2.compute.constants)
|
|
2273
|
+
}
|
|
2274
|
+
};
|
|
2275
|
+
return device.createComputePipelineAsync ? boundedGpuWait(device.createComputePipelineAsync(descriptor2), device, timeoutMs, signal) : device.createComputePipeline?.(descriptor2);
|
|
2276
|
+
}
|
|
2277
|
+
const descriptor = {
|
|
2278
|
+
label: pipeline2.pipelineId,
|
|
2279
|
+
layout,
|
|
2280
|
+
vertex: {
|
|
2281
|
+
module: module2(pipeline2.vertex.moduleId),
|
|
2282
|
+
entryPoint: pipeline2.vertex.entryPoint,
|
|
2283
|
+
constants: constants(pipeline2.vertex.constants),
|
|
2284
|
+
buffers: pipeline2.vertexBuffers.map((buffer) => ({
|
|
2285
|
+
arrayStride: buffer.arrayStride,
|
|
2286
|
+
stepMode: buffer.stepMode,
|
|
2287
|
+
attributes: buffer.attributes.map((attribute) => ({ format: attribute.format, offset: attribute.offset, shaderLocation: attribute.shaderLocation }))
|
|
2288
|
+
}))
|
|
2289
|
+
},
|
|
2290
|
+
fragment: pipeline2.fragment ? {
|
|
2291
|
+
module: module2(pipeline2.fragment.moduleId),
|
|
2292
|
+
entryPoint: pipeline2.fragment.entryPoint,
|
|
2293
|
+
constants: constants(pipeline2.fragment.constants),
|
|
2294
|
+
targets: pipeline2.colorTargets
|
|
2295
|
+
} : void 0,
|
|
2296
|
+
primitive: {
|
|
2297
|
+
topology: pipeline2.primitive.topology,
|
|
2298
|
+
...pipeline2.primitive.stripIndexFormat ? { stripIndexFormat: pipeline2.primitive.stripIndexFormat } : {},
|
|
2299
|
+
frontFace: pipeline2.primitive.frontFace,
|
|
2300
|
+
cullMode: pipeline2.primitive.cullMode,
|
|
2301
|
+
unclippedDepth: pipeline2.primitive.unclippedDepth
|
|
2302
|
+
},
|
|
2303
|
+
depthStencil: pipeline2.depthStencil ?? void 0,
|
|
2304
|
+
multisample: pipeline2.multisample
|
|
2305
|
+
};
|
|
2306
|
+
return device.createRenderPipelineAsync ? boundedGpuWait(device.createRenderPipelineAsync(descriptor), device, timeoutMs, signal) : device.createRenderPipeline?.(descriptor);
|
|
2307
|
+
}
|
|
2308
|
+
async function prepareStyleProfile(input) {
|
|
2309
|
+
const loaded = requireTrustedLoadedShaderStyleProfile(input.loaded);
|
|
2310
|
+
const diagnostics = [];
|
|
2311
|
+
const actualCapabilities = {
|
|
2312
|
+
features: [...input.device.features],
|
|
2313
|
+
limits: input.device.limits,
|
|
2314
|
+
formats: input.capabilities.formats
|
|
2315
|
+
};
|
|
2316
|
+
for (const shader of loaded.shaders.values()) {
|
|
2317
|
+
const compatibility = validateModelShaderCompatibility({
|
|
2318
|
+
model: input.model,
|
|
2319
|
+
shader: shader.manifest,
|
|
2320
|
+
gpuInterface: shader.gpuInterface,
|
|
2321
|
+
profile: loaded.manifest,
|
|
2322
|
+
capabilities: actualCapabilities
|
|
2323
|
+
});
|
|
2324
|
+
if (!compatibility.ok) diagnostics.push(...compatibility.diagnostics);
|
|
2325
|
+
}
|
|
2326
|
+
if (diagnostics.length > 0) return { ok: false, diagnostics };
|
|
2327
|
+
const modules = /* @__PURE__ */ new Map();
|
|
2328
|
+
const pipelines = /* @__PURE__ */ new Map();
|
|
2329
|
+
let errorScopeOpen = false;
|
|
2330
|
+
try {
|
|
2331
|
+
if (input.device.pushErrorScope && input.device.popErrorScope) {
|
|
2332
|
+
input.device.pushErrorScope("validation");
|
|
2333
|
+
errorScopeOpen = true;
|
|
2334
|
+
}
|
|
2335
|
+
for (const [role, shader] of loaded.shaders) {
|
|
2336
|
+
const shaderModules = /* @__PURE__ */ new Map();
|
|
2337
|
+
for (const moduleManifest of shader.manifest.modules) {
|
|
2338
|
+
const bytes = shader.modules.get(moduleManifest.moduleId);
|
|
2339
|
+
if (!bytes) throw new TypeError(`Module ${moduleManifest.moduleId} is missing after verified loading.`);
|
|
2340
|
+
if (bytes.byteLength !== moduleManifest.byteLength) {
|
|
2341
|
+
throw new TypeError(`Module ${moduleManifest.moduleId} byte length changed after verified loading.`);
|
|
2342
|
+
}
|
|
2343
|
+
if (await computeSha256(bytes) !== moduleManifest.sha256) {
|
|
2344
|
+
throw new TypeError(`Module ${moduleManifest.moduleId} digest changed after verified loading.`);
|
|
2345
|
+
}
|
|
2346
|
+
const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
2347
|
+
const module2 = input.device.createShaderModule({
|
|
2348
|
+
label: `${shader.manifest.shaderId}:${moduleManifest.moduleId}`,
|
|
2349
|
+
code: source
|
|
2350
|
+
});
|
|
2351
|
+
const information = await boundedGpuWait(module2.getCompilationInfo(), input.device, input.timeoutMs ?? 3e4, input.signal);
|
|
2352
|
+
const failures = information.messages.filter((message) => message.type === "error");
|
|
2353
|
+
if (failures.length > 0) {
|
|
2354
|
+
throw new TypeError(`WGSL compilation failed for ${shader.manifest.shaderId}:${moduleManifest.moduleId}: ${failures[0]?.message ?? "unknown error"}`);
|
|
2355
|
+
}
|
|
2356
|
+
modules.set(`${role}:${moduleManifest.moduleId}`, module2);
|
|
2357
|
+
shaderModules.set(moduleManifest.moduleId, module2);
|
|
2358
|
+
}
|
|
2359
|
+
const roleManifest = shader.manifest.renderRoles.find((item) => item.role === role);
|
|
2360
|
+
if (!roleManifest) throw new TypeError(`Shader role ${role} disappeared during preparation.`);
|
|
2361
|
+
for (const pipelineId of roleManifest.pipelineIds) {
|
|
2362
|
+
const descriptor = shader.manifest.pipelines.find((item) => item.pipelineId === pipelineId);
|
|
2363
|
+
if (!descriptor) throw new TypeError(`Pipeline ${pipelineId} is missing from its shader manifest.`);
|
|
2364
|
+
const pipeline2 = await createPipeline(input.device, descriptor, shaderModules, input.timeoutMs ?? 3e4, input.signal);
|
|
2365
|
+
if (!pipeline2) throw new TypeError(`GPU implementation did not create pipeline ${pipelineId}.`);
|
|
2366
|
+
pipelines.set(`${role}:${pipelineId}`, pipeline2);
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
let scopedError = null;
|
|
2370
|
+
if (input.device.popErrorScope) {
|
|
2371
|
+
errorScopeOpen = false;
|
|
2372
|
+
scopedError = await boundedGpuWait(input.device.popErrorScope(), input.device, input.timeoutMs ?? 3e4, input.signal);
|
|
2373
|
+
}
|
|
2374
|
+
if (scopedError) throw new TypeError(scopedError.message ?? "GPU validation error while preparing style profile.");
|
|
2375
|
+
let disposed = false;
|
|
2376
|
+
const publicPipelines = readonlyMapView(pipelines);
|
|
2377
|
+
const prepared = trustPreparedShaderStyleProfile({
|
|
2378
|
+
loaded: loaded.publicValue,
|
|
2379
|
+
pipelines: publicPipelines,
|
|
2380
|
+
preparedAt: (input.now ?? Date.now)(),
|
|
2381
|
+
dispose() {
|
|
2382
|
+
if (disposed) return;
|
|
2383
|
+
disposed = true;
|
|
2384
|
+
pipelines.clear();
|
|
2385
|
+
modules.clear();
|
|
2386
|
+
}
|
|
2387
|
+
});
|
|
2388
|
+
return {
|
|
2389
|
+
ok: true,
|
|
2390
|
+
value: prepared
|
|
2391
|
+
};
|
|
2392
|
+
} catch (cause) {
|
|
2393
|
+
pipelines.clear();
|
|
2394
|
+
modules.clear();
|
|
2395
|
+
if (errorScopeOpen) {
|
|
2396
|
+
closeErrorScopeBestEffort(input.device, input.timeoutMs ?? 3e4);
|
|
2397
|
+
}
|
|
2398
|
+
return {
|
|
2399
|
+
ok: false,
|
|
2400
|
+
diagnostics: [error2(
|
|
2401
|
+
cause instanceof DeviceLostError ? "device-lost" : cause instanceof TypeError && /digest|byte length/u.test(cause.message) ? "digest-mismatch" : cause instanceof TypeError && /compilation/u.test(cause.message) ? "compilation-error" : cause instanceof Error && /timed out/u.test(cause.message) ? "timeout" : "pipeline-error",
|
|
2402
|
+
cause instanceof Error ? cause.message : "Style profile preparation failed."
|
|
2403
|
+
)]
|
|
2404
|
+
};
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
// src/runtime/style-controller.ts
|
|
2409
|
+
var controllers = /* @__PURE__ */ new WeakMap();
|
|
2410
|
+
function createShaderStyleController(input) {
|
|
2411
|
+
if (input.initial) requireTrustedPreparedShaderStyleProfile(input.initial);
|
|
2412
|
+
const now = input.now ?? Date.now;
|
|
2413
|
+
const state = {
|
|
2414
|
+
current: input.initial ? Object.freeze({ prepared: input.initial, activatedAt: now() }) : null,
|
|
2415
|
+
scheduler: input.scheduler,
|
|
2416
|
+
now,
|
|
2417
|
+
activationTail: Promise.resolve()
|
|
2418
|
+
};
|
|
2419
|
+
const controller = Object.freeze({
|
|
2420
|
+
get current() {
|
|
2421
|
+
return state.current;
|
|
2422
|
+
}
|
|
2423
|
+
});
|
|
2424
|
+
controllers.set(controller, state);
|
|
2425
|
+
return controller;
|
|
2426
|
+
}
|
|
2427
|
+
async function activateStyleProfile(input) {
|
|
2428
|
+
const controller = controllers.get(input.controller);
|
|
2429
|
+
if (!controller) {
|
|
2430
|
+
throw new TypeError("controller must be created by createShaderStyleController.");
|
|
2431
|
+
}
|
|
2432
|
+
requireTrustedPreparedShaderStyleProfile(input.prepared);
|
|
2433
|
+
const operation = controller.activationTail.then(async () => {
|
|
2434
|
+
const previous = controller.current;
|
|
2435
|
+
let callbackOpen = true;
|
|
2436
|
+
let callbackInvoked = false;
|
|
2437
|
+
let callbackViolation = null;
|
|
2438
|
+
const next = Object.freeze({ prepared: input.prepared, activatedAt: controller.now() });
|
|
2439
|
+
try {
|
|
2440
|
+
await controller.scheduler.schedule(() => {
|
|
2441
|
+
if (!callbackOpen || callbackInvoked) {
|
|
2442
|
+
callbackViolation ??= new TypeError("Frame-boundary scheduler invoked an activation callback more than once or after completion.");
|
|
2443
|
+
throw callbackViolation;
|
|
2444
|
+
}
|
|
2445
|
+
callbackInvoked = true;
|
|
2446
|
+
controller.current = next;
|
|
2447
|
+
});
|
|
2448
|
+
callbackOpen = false;
|
|
2449
|
+
if (callbackViolation) throw callbackViolation;
|
|
2450
|
+
if (!callbackInvoked) throw new TypeError("Frame-boundary scheduler completed without invoking the activation callback.");
|
|
2451
|
+
} catch (cause) {
|
|
2452
|
+
callbackOpen = false;
|
|
2453
|
+
if (controller.current === next) controller.current = previous;
|
|
2454
|
+
if (!previous || previous.prepared !== input.prepared) {
|
|
2455
|
+
try {
|
|
2456
|
+
input.prepared.dispose();
|
|
2457
|
+
} catch {
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
const diagnostic2 = {
|
|
2461
|
+
code: "activation-error",
|
|
2462
|
+
severity: "error",
|
|
2463
|
+
message: cause instanceof Error ? cause.message : "Frame-boundary activation failed."
|
|
2464
|
+
};
|
|
2465
|
+
return { ok: false, diagnostics: [diagnostic2] };
|
|
2466
|
+
}
|
|
2467
|
+
if (previous && previous.prepared !== input.prepared) {
|
|
2468
|
+
try {
|
|
2469
|
+
if (input.retire) await input.retire(previous.prepared);
|
|
2470
|
+
else previous.prepared.dispose();
|
|
2471
|
+
} catch {
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
return { ok: true, value: next };
|
|
2475
|
+
});
|
|
2476
|
+
controller.activationTail = operation.then(() => void 0, () => void 0);
|
|
2477
|
+
return operation;
|
|
2478
|
+
}
|
|
2479
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
2480
|
+
0 && (module.exports = {
|
|
2481
|
+
GPU_INTERFACE_MANIFEST_VERSION,
|
|
2482
|
+
GPU_SHADER_STORE_FEATURE_FLAG,
|
|
2483
|
+
GPU_SHADER_STYLE_SELECTION_CAPABILITY,
|
|
2484
|
+
SHADER_COMPILE_UNIT_VERSION,
|
|
2485
|
+
SHADER_QUALIFICATION_BUNDLE_VERSION,
|
|
2486
|
+
SHADER_QUALIFICATION_FIXTURE_VERSION,
|
|
2487
|
+
SHADER_STYLE_PROFILE_MANIFEST_VERSION,
|
|
2488
|
+
SHADER_VALIDATION_EVIDENCE_VERSION,
|
|
2489
|
+
SHADER_VERSION_MANIFEST_VERSION,
|
|
2490
|
+
STABLE_WEBGPU_MATRIX_VERSION,
|
|
2491
|
+
SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES,
|
|
2492
|
+
SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES,
|
|
2493
|
+
activateStyleProfile,
|
|
2494
|
+
asSha256Hex,
|
|
2495
|
+
canonicalizeGpuContract,
|
|
2496
|
+
computeGpuAbiHash,
|
|
2497
|
+
computeSha256,
|
|
2498
|
+
computeShaderManifestCoreSha256,
|
|
2499
|
+
createGpuRecordCodec,
|
|
2500
|
+
createShaderStyleController,
|
|
2501
|
+
loadShaderStyleProfile,
|
|
2502
|
+
parseCanonicalJson,
|
|
2503
|
+
parseGpuInterfaceManifest,
|
|
2504
|
+
parseJsonBytes,
|
|
2505
|
+
parseModelGpuCompatibilityDescriptor,
|
|
2506
|
+
parseShaderStyleProfileManifest,
|
|
2507
|
+
parseShaderVersionManifest,
|
|
2508
|
+
parseShaderVersionManifestCore,
|
|
2509
|
+
prepareStyleProfile,
|
|
2510
|
+
validateModelShaderCompatibility
|
|
2511
|
+
});
|
|
2512
|
+
//# sourceMappingURL=index.cjs.map
|