@orkestrel/wgsl 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,1836 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _orkestrel_contract = require("@orkestrel/contract");
3
+ // src/core/constants.ts
4
+ /**
5
+ * Lists the condition codes a `WGSLError` carries.
6
+ *
7
+ * @remarks
8
+ * `ARGUMENT` marks a malformed argument, `COMPILE` a shader the compiler refuses, `VALIDATION` a
9
+ * declaration or command the package or the device refuses, `LIMIT` an exceeded device limit,
10
+ * `HOST` a lost device, `DESTROYED` a call after `destroy`, and `ABORT` an aborted signal or batch.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * WGSL_ERROR_CODES.includes('VALIDATION') // true
15
+ * ```
16
+ */
17
+ var WGSL_ERROR_CODES = Object.freeze([
18
+ "ARGUMENT",
19
+ "COMPILE",
20
+ "VALIDATION",
21
+ "LIMIT",
22
+ "HOST",
23
+ "DESTROYED",
24
+ "ABORT"
25
+ ]);
26
+ /**
27
+ * Keys the global brand a `WGSLError` carries, so another installed copy recognizes it.
28
+ *
29
+ * @remarks
30
+ * The key follows the package-and-class form, `Symbol.for('<package>.<ClassName>')`. The brand is
31
+ * a recognition marker and never proof that the class's constructor ran.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * WGSL_ERROR_BRAND === Symbol.for('@orkestrel/wgsl.WGSLError') // true
36
+ * ```
37
+ */
38
+ var WGSL_ERROR_BRAND = Symbol.for("@orkestrel/wgsl.WGSLError");
39
+ /**
40
+ * Lists the scalar types a uniform struct member can hold.
41
+ *
42
+ * @remarks
43
+ * Each scalar aligns to 4 bytes and takes 4 bytes in the `uniform` and `storage` address spaces.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * WGSL_SCALARS.includes('f32') // true
48
+ * ```
49
+ */
50
+ var WGSL_SCALARS = Object.freeze([
51
+ "u32",
52
+ "i32",
53
+ "f32"
54
+ ]);
55
+ /**
56
+ * Lists the access modes a storage slot can declare.
57
+ *
58
+ * @remarks
59
+ * Each member mirrors the WGSL `var<storage, ACCESS>` access mode of the same spelling.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * WGSL_ACCESSES.includes('read_write') // true
64
+ * ```
65
+ */
66
+ var WGSL_ACCESSES = Object.freeze(["read", "read_write"]);
67
+ /**
68
+ * Maps each WGSL extension a fragment variant can enable to the device feature that admits it.
69
+ *
70
+ * @remarks
71
+ * Each key mirrors the WGSL `enable` directive of the same spelling, and each value mirrors the
72
+ * WebGPU `GPUFeatureName` a device reports in `device.features`. The key order is the order in
73
+ * which a rendered program emits its `enable` directives.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * WGSL_EXTENSIONS.f16 // 'shader-f16'
78
+ * ```
79
+ */
80
+ var WGSL_EXTENSIONS = Object.freeze({
81
+ f16: "shader-f16",
82
+ subgroups: "subgroups"
83
+ });
84
+ /**
85
+ * Mirrors the WebGPU `GPUBufferUsage` bit values under one-word members.
86
+ *
87
+ * @remarks
88
+ * `read` mirrors `MAP_READ`, `write` mirrors `MAP_WRITE`, `source` mirrors `COPY_SRC`,
89
+ * `destination` mirrors `COPY_DST`, `uniform` mirrors `UNIFORM`, `storage` mirrors `STORAGE`,
90
+ * `indirect` mirrors `INDIRECT`, and `query` mirrors `QUERY_RESOLVE`. The library declares
91
+ * `GPUBufferUsage` only as a type, so `src/core` reads these values instead.
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * WGSL_USAGE.uniform | WGSL_USAGE.destination // 72
96
+ * ```
97
+ */
98
+ var WGSL_USAGE = Object.freeze({
99
+ read: 1,
100
+ write: 2,
101
+ source: 4,
102
+ destination: 8,
103
+ uniform: 64,
104
+ storage: 128,
105
+ indirect: 256,
106
+ query: 512
107
+ });
108
+ /**
109
+ * Mirrors the WebGPU `GPUMapMode` bit values under one-word members.
110
+ *
111
+ * @remarks
112
+ * `read` mirrors `READ` and `write` mirrors `WRITE`.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * WGSL_MAP.read // 1
117
+ * ```
118
+ */
119
+ var WGSL_MAP = Object.freeze({
120
+ read: 1,
121
+ write: 2
122
+ });
123
+ /**
124
+ * Mirrors the WebGPU `GPUShaderStage` bit value of the compute stage.
125
+ *
126
+ * @remarks
127
+ * `compute` mirrors `COMPUTE`.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * WGSL_STAGE.compute // 4
132
+ * ```
133
+ */
134
+ var WGSL_STAGE = Object.freeze({ compute: 4 });
135
+ /**
136
+ * Holds the default byte capacity of a session's uniform slab.
137
+ *
138
+ * @remarks
139
+ * The session's `uniform.size` option replaces it. At a 256-byte offset alignment the default
140
+ * holds 256 dispatches before a batch flushes.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * WGSL_UNIFORM_SIZE // 65536
145
+ * ```
146
+ */
147
+ var WGSL_UNIFORM_SIZE = 65536;
148
+ /**
149
+ * Holds the fragment that reads a workgroup's two-axis index from the entry input struct.
150
+ *
151
+ * @remarks
152
+ * It declares `fn place(invocation: Invocation) -> u32`, which returns
153
+ * `invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x`, the
154
+ * statement of infer's `readPlace` recast onto the `Invocation` struct. Pair it with
155
+ * `computeWGSLGrid`, and multiply by the workgroup size and add `local_invocation_index` for an
156
+ * invocation's index. It reads no binding and no uniform member.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * createWGSLProgram({ name: 'clear', entry, slots, uniform, uses: [WGSL_PLACE] }).fragments // [WGSL_PLACE]
161
+ * ```
162
+ */
163
+ var WGSL_PLACE = Object.freeze({
164
+ name: "place",
165
+ source: [
166
+ "fn place(invocation: Invocation) -> u32 {",
167
+ " return invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x;",
168
+ "}"
169
+ ].join("\n"),
170
+ uses: Object.freeze([])
171
+ });
172
+ /**
173
+ * Holds the fragment that sums one `f32` value from each invocation of a 64-invocation workgroup.
174
+ *
175
+ * @remarks
176
+ * It declares `var<workgroup> sums: array<f32, 64>` and
177
+ * `fn sum(invocation: Invocation, value: f32) -> f32`, which returns the workgroup's total to every
178
+ * invocation. The entry's workgroup size must hold 64 invocations, and every invocation must call
179
+ * it from uniform control flow. The default body reduces in a tree of halving strides. The
180
+ * `subgroups` variant stores each subgroup's `subgroupAdd` partial at its first invocation's index
181
+ * and `0.0` elsewhere, and invocation 0 adds the 64 entries in index order between 2 barriers, so
182
+ * its rounding order differs from the default body's. It reads no binding and no uniform member.
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * WGSL_SUM.variant?.extension // 'subgroups'
187
+ * ```
188
+ */
189
+ var WGSL_SUM = Object.freeze({
190
+ name: "sum",
191
+ source: [
192
+ "var<workgroup> sums: array<f32, 64>;",
193
+ "",
194
+ "fn sum(invocation: Invocation, value: f32) -> f32 {",
195
+ " let local = invocation.local_invocation_index;",
196
+ " sums[local] = value;",
197
+ " workgroupBarrier();",
198
+ " for (var stride = 32u; stride > 0u; stride = stride >> 1u) {",
199
+ " if (local < stride) {",
200
+ " sums[local] = sums[local] + sums[local + stride];",
201
+ " }",
202
+ " workgroupBarrier();",
203
+ " }",
204
+ " let total = sums[0];",
205
+ " workgroupBarrier();",
206
+ " return total;",
207
+ "}"
208
+ ].join("\n"),
209
+ uses: Object.freeze([]),
210
+ variant: Object.freeze({
211
+ extension: "subgroups",
212
+ source: [
213
+ "var<workgroup> sums: array<f32, 64>;",
214
+ "",
215
+ "fn sum(invocation: Invocation, value: f32) -> f32 {",
216
+ " let local = invocation.local_invocation_index;",
217
+ " let partial = subgroupAdd(value);",
218
+ " sums[local] = select(0.0, partial, invocation.subgroup_invocation_id == 0u);",
219
+ " workgroupBarrier();",
220
+ " if (local == 0u) {",
221
+ " var acc = 0.0;",
222
+ " for (var i = 0u; i < 64u; i += 1u) {",
223
+ " acc = acc + sums[i];",
224
+ " }",
225
+ " sums[0] = acc;",
226
+ " }",
227
+ " workgroupBarrier();",
228
+ " let total = sums[0];",
229
+ " workgroupBarrier();",
230
+ " return total;",
231
+ "}"
232
+ ].join("\n")
233
+ })
234
+ });
235
+ /**
236
+ * Holds the fragment that finds the largest `f32` value across the invocations of a 64-invocation workgroup.
237
+ *
238
+ * @remarks
239
+ * It declares `var<workgroup> peaks: array<f32, 64>` and
240
+ * `fn peak(invocation: Invocation, value: f32) -> f32`, which returns the workgroup's maximum to
241
+ * every invocation. The entry's workgroup size must hold 64 invocations, and every invocation must
242
+ * call it from uniform control flow. The default body reduces with `max` in a tree of halving
243
+ * strides. The `subgroups` variant stores each subgroup's `subgroupMax` partial at its first
244
+ * invocation's index and the lowest finite `f32` (`-3.4028234663852886e38`) elsewhere, and invocation 0 folds
245
+ * the 64 entries with `max` between 2 barriers (matching `@orkestrel/infer`, so it returns `-3.4028234663852886e38`
246
+ * rather than `-Infinity` when every input is `-Infinity`). It reads no binding and no uniform member.
247
+ *
248
+ * @example
249
+ * ```ts
250
+ * WGSL_PEAK.variant?.extension // 'subgroups'
251
+ * ```
252
+ */
253
+ var WGSL_PEAK = Object.freeze({
254
+ name: "peak",
255
+ source: [
256
+ "var<workgroup> peaks: array<f32, 64>;",
257
+ "",
258
+ "fn peak(invocation: Invocation, value: f32) -> f32 {",
259
+ " let local = invocation.local_invocation_index;",
260
+ " peaks[local] = value;",
261
+ " workgroupBarrier();",
262
+ " for (var stride = 32u; stride > 0u; stride = stride >> 1u) {",
263
+ " if (local < stride) {",
264
+ " peaks[local] = max(peaks[local], peaks[local + stride]);",
265
+ " }",
266
+ " workgroupBarrier();",
267
+ " }",
268
+ " let largest = peaks[0];",
269
+ " workgroupBarrier();",
270
+ " return largest;",
271
+ "}"
272
+ ].join("\n"),
273
+ uses: Object.freeze([]),
274
+ variant: Object.freeze({
275
+ extension: "subgroups",
276
+ source: [
277
+ "var<workgroup> peaks: array<f32, 64>;",
278
+ "",
279
+ "fn peak(invocation: Invocation, value: f32) -> f32 {",
280
+ " let local = invocation.local_invocation_index;",
281
+ " let partial = subgroupMax(value);",
282
+ " peaks[local] = select(-3.4028234663852886e38, partial, invocation.subgroup_invocation_id == 0u);",
283
+ " workgroupBarrier();",
284
+ " if (local == 0u) {",
285
+ " var acc = -3.4028234663852886e38;",
286
+ " for (var i = 0u; i < 64u; i += 1u) {",
287
+ " acc = max(acc, peaks[i]);",
288
+ " }",
289
+ " peaks[0] = acc;",
290
+ " }",
291
+ " workgroupBarrier();",
292
+ " let largest = peaks[0];",
293
+ " workgroupBarrier();",
294
+ " return largest;",
295
+ "}"
296
+ ].join("\n")
297
+ })
298
+ });
299
+ /**
300
+ * Holds the fragment that widens the IEEE 754 half-precision bits in the low 16 bits of a `u32` to an `f32`.
301
+ *
302
+ * @remarks
303
+ * It declares `fn widen(bits: u32) -> f32`, which builds the result from integer bit operations, so
304
+ * signed zeros, subnormals, infinities, and NaN payloads widen exactly and no `f16` extension is
305
+ * needed. An exponent of `0x1f` keeps the fraction under an all-ones `f32` exponent, so infinities
306
+ * stay infinite and NaN payloads survive. A subnormal half rebuilds its `f32` bits from
307
+ * `firstLeadingBit(fraction)`: the leading bit sets the exponent and the bits under it shift into
308
+ * the `f32` fraction, with no float arithmetic. It reads no binding and no uniform member.
309
+ *
310
+ * @example
311
+ * ```ts
312
+ * WGSL_HALF.name // 'half'
313
+ * ```
314
+ */
315
+ var WGSL_HALF = Object.freeze({
316
+ name: "half",
317
+ source: [
318
+ "fn widen(bits: u32) -> f32 {",
319
+ " let sign = (bits & 0x8000u) << 16u;",
320
+ " let exponent = (bits >> 10u) & 0x1fu;",
321
+ " let fraction = bits & 0x3ffu;",
322
+ " if (exponent == 0x1fu) {",
323
+ " return bitcast<f32>(sign | 0x7f800000u | (fraction << 13u));",
324
+ " }",
325
+ " if (exponent != 0u) {",
326
+ " return bitcast<f32>(sign | ((exponent + 112u) << 23u) | (fraction << 13u));",
327
+ " }",
328
+ " if (fraction == 0u) {",
329
+ " return bitcast<f32>(sign);",
330
+ " }",
331
+ " let top = firstLeadingBit(fraction);",
332
+ " return bitcast<f32>(sign | ((top + 103u) << 23u) | ((fraction << (23u - top)) & 0x7fffffu));",
333
+ "}"
334
+ ].join("\n"),
335
+ uses: Object.freeze([])
336
+ });
337
+ // src/core/errors.ts
338
+ /**
339
+ * Reports one WGSL failure under a stable condition code.
340
+ *
341
+ * @remarks
342
+ * Every refusal the factories, the linker, the helpers, and the slab raise arrives as one of these,
343
+ * so a caller branches on `code` rather than on message text. Narrow a caught value with
344
+ * `isWGSLError` before reading `code`.
345
+ *
346
+ * @example
347
+ * ```ts
348
+ * const error = new WGSLError('The slab capacity must be a multiple of 4.', { code: 'ARGUMENT' })
349
+ * error.code // 'ARGUMENT'
350
+ * ```
351
+ */
352
+ var WGSLError = class extends Error {
353
+ name = "WGSLError";
354
+ code;
355
+ context;
356
+ /**
357
+ * Creates one classified WGSL failure.
358
+ *
359
+ * @param message - Human-readable description of what failed
360
+ * @param options - The condition, optional structured context, and optional cause
361
+ */
362
+ constructor(message, options) {
363
+ super(message, "cause" in options ? { cause: options.cause } : void 0);
364
+ _orkestrel_contract.INTRINSICS.define(this, WGSL_ERROR_BRAND, { value: this });
365
+ this.code = options.code;
366
+ this.context = options.context;
367
+ }
368
+ };
369
+ /**
370
+ * Checks whether an unknown value is a WGSL error.
371
+ *
372
+ * @remarks
373
+ * Recognition requires a native `Error` whose prototype is not `Error.prototype`, an own brand
374
+ * property holding the tested value itself, a declared condition code, and an object, callable, or
375
+ * absent context. It recognizes an error from another installed copy of this package, and refuses a
376
+ * look-alike with the same code and no brand, a proxy over a branded error, and a plain object that
377
+ * only carries the brand.
378
+ *
379
+ * @param value - The value to inspect
380
+ * @returns True if the value is a `WGSLError`; false otherwise
381
+ *
382
+ * @example
383
+ * ```ts
384
+ * isWGSLError(new WGSLError('The batch was aborted.', { code: 'ABORT' })) // true
385
+ * isWGSLError(new Error('The batch was aborted.')) // false
386
+ * ```
387
+ */
388
+ function isWGSLError(value) {
389
+ return (0, _orkestrel_contract.holds)(() => {
390
+ if (!(0, _orkestrel_contract.isError)(value) || _orkestrel_contract.INTRINSICS.prototype(value) === _orkestrel_contract.INTRINSICS.error.prototype) return false;
391
+ if (_orkestrel_contract.INTRINSICS.describe(value, WGSL_ERROR_BRAND)?.value !== value) return false;
392
+ const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
393
+ const context = _orkestrel_contract.INTRINSICS.reflect.read(value, "context");
394
+ return WGSL_ERROR_CODES.some((declared) => declared === code) && (context === void 0 || (0, _orkestrel_contract.isObject)(context) || (0, _orkestrel_contract.isFunction)(context));
395
+ });
396
+ }
397
+ // src/core/validators.ts
398
+ /**
399
+ * Checks whether a value names a scalar type a uniform struct member can hold.
400
+ *
401
+ * @param value - The value to inspect
402
+ * @returns True if the value is one of the `WGSL_SCALARS` members; false otherwise
403
+ *
404
+ * @example
405
+ * ```ts
406
+ * isWGSLScalar('f32') // true
407
+ * isWGSLScalar('f64') // false
408
+ * ```
409
+ */
410
+ function isWGSLScalar(value) {
411
+ return WGSL_SCALARS.some((scalar) => scalar === value);
412
+ }
413
+ /**
414
+ * Checks whether a value names a storage slot access mode.
415
+ *
416
+ * @param value - The value to inspect
417
+ * @returns True if the value is one of the `WGSL_ACCESSES` members; false otherwise
418
+ *
419
+ * @example
420
+ * ```ts
421
+ * isWGSLAccess('read_write') // true
422
+ * isWGSLAccess('write') // false
423
+ * ```
424
+ */
425
+ function isWGSLAccess(value) {
426
+ return WGSL_ACCESSES.some((access) => access === value);
427
+ }
428
+ /**
429
+ * Checks whether a value names a WGSL extension a fragment variant can enable.
430
+ *
431
+ * @remarks
432
+ * Only an own key of `WGSL_EXTENSIONS` passes, so an inherited name such as `toString` fails.
433
+ *
434
+ * @param value - The value to inspect
435
+ * @returns True if the value is a key of `WGSL_EXTENSIONS`; false otherwise
436
+ *
437
+ * @example
438
+ * ```ts
439
+ * isWGSLExtension('subgroups') // true
440
+ * isWGSLExtension('shader-f16') // false
441
+ * ```
442
+ */
443
+ function isWGSLExtension(value) {
444
+ return (0, _orkestrel_contract.isString)(value) && Object.hasOwn(WGSL_EXTENSIONS, value);
445
+ }
446
+ /**
447
+ * Checks whether a value holds a positive safe integer count on each of three axes.
448
+ *
449
+ * @remarks
450
+ * The value must be an array of length 3, and each of its indices must hold a safe integer of at
451
+ * least 1, so a sparse array, a zero count, and a fraction fail.
452
+ *
453
+ * @param value - The value to inspect
454
+ * @returns True if the value is a `WGSLGrid`; false otherwise
455
+ *
456
+ * @example
457
+ * ```ts
458
+ * isWGSLGrid([64, 1, 1]) // true
459
+ * isWGSLGrid([0, 1, 1]) // false
460
+ * ```
461
+ */
462
+ function isWGSLGrid(value) {
463
+ if (!(0, _orkestrel_contract.isArray)(value) || value.length !== 3) return false;
464
+ try {
465
+ const [x, y, z] = value;
466
+ return (0, _orkestrel_contract.isSafeInteger)(x) && x >= 1 && (0, _orkestrel_contract.isSafeInteger)(y) && y >= 1 && (0, _orkestrel_contract.isSafeInteger)(z) && z >= 1;
467
+ } catch {
468
+ return false;
469
+ }
470
+ }
471
+ // src/core/helpers.ts
472
+ /**
473
+ * Collects every fragment the roots reach, each once, in dependency order.
474
+ *
475
+ * @remarks
476
+ * The walk is an iterative postorder over each fragment's `uses`, so a fragment follows every
477
+ * fragment it uses. A fragment reached twice, as in a diamond, appears once, keyed on identity.
478
+ * Thrown with code `VALIDATION` when two distinct fragments share one name, and when a fragment
479
+ * reaches itself, with the cycle's names in order in `context.cycle`.
480
+ *
481
+ * @param roots - The fragments an entry body calls, in the order they are listed
482
+ * @returns The reached fragments, frozen
483
+ *
484
+ * @example
485
+ * ```ts
486
+ * const square = createWGSLFragment({ name: 'square', source: 'fn square(value: f32) -> f32 { return value * value; }' })
487
+ * const cube = createWGSLFragment({ name: 'cube', source: 'fn cube(value: f32) -> f32 { return square(value) * value; }', uses: [square] })
488
+ * collectWGSLFragments([cube, square]).map((fragment) => fragment.name) // ['square', 'cube']
489
+ * ```
490
+ */
491
+ function collectWGSLFragments(roots) {
492
+ const order = [];
493
+ const linked = /* @__PURE__ */ new Set();
494
+ const names = /* @__PURE__ */ new Set();
495
+ const path = [];
496
+ const stack = roots.toReversed().map((root) => [root, false]);
497
+ while (stack.length > 0) {
498
+ const frame = stack.pop();
499
+ if (frame === void 0) break;
500
+ const [fragment, exit] = frame;
501
+ if (exit) {
502
+ path.pop();
503
+ linked.add(fragment);
504
+ order.push(fragment);
505
+ continue;
506
+ }
507
+ if (linked.has(fragment)) continue;
508
+ const start = path.indexOf(fragment);
509
+ if (start !== -1) {
510
+ const cycle = [...path.slice(start), fragment].map((member) => member.name);
511
+ throw new WGSLError(`The fragment ${(0, _orkestrel_contract.preview)(fragment.name)} reaches itself through ${cycle.join(" -> ")}; remove one of these uses.`, {
512
+ code: "VALIDATION",
513
+ context: { cycle }
514
+ });
515
+ }
516
+ if (names.has(fragment.name)) throw new WGSLError(`Two distinct fragments are named ${(0, _orkestrel_contract.preview)(fragment.name)}; a linked program holds one fragment per name, so rename one or pass the same fragment object.`, {
517
+ code: "VALIDATION",
518
+ context: { name: fragment.name }
519
+ });
520
+ names.add(fragment.name);
521
+ path.push(fragment);
522
+ stack.push([fragment, true], ...fragment.uses.toReversed().map((used) => [used, false]));
523
+ }
524
+ return Object.freeze(order);
525
+ }
526
+ /**
527
+ * Renders a program's complete WGSL text for one set of active extensions.
528
+ *
529
+ * @remarks
530
+ * The text holds, in order: an `enable` directive for each extension a linked fragment's active
531
+ * variant names, in `WGSL_EXTENSIONS` order; the uniform struct declaration; the `Invocation` entry
532
+ * input struct, which carries `local_invocation_index`, `workgroup_id`, and `num_workgroups`, plus
533
+ * `subgroup_invocation_id` and `subgroup_size` when `enable subgroups;` is emitted; one
534
+ * `@group(0) @binding(N)` storage line per slot in declaration order and the `@group(1) @binding(0)`
535
+ * uniform line; each linked fragment's active body, unchanged; and the entry function, which takes
536
+ * the input struct as `invocation`. A fragment's variant is active when `extensions` switches its
537
+ * extension on.
538
+ *
539
+ * @param program - The program to render
540
+ * @param extensions - Whether each extension is active
541
+ * @returns The WGSL text, ending in a line feed
542
+ *
543
+ * @example
544
+ * ```ts
545
+ * renderWGSLProgram(program, { f16: false, subgroups: false }).startsWith('struct Shape {') // true
546
+ * ```
547
+ */
548
+ function renderWGSLProgram(program, extensions) {
549
+ const variants = program.fragments.map((fragment) => fragment.variant !== void 0 && extensions[fragment.variant.extension] ? fragment.variant : void 0);
550
+ const enabled = Object.keys(WGSL_EXTENSIONS).filter((name) => variants.some((variant) => variant?.extension === name));
551
+ const invocation = [
552
+ "struct Invocation {",
553
+ " @builtin(local_invocation_index) local_invocation_index: u32,",
554
+ " @builtin(workgroup_id) workgroup_id: vec3u,",
555
+ " @builtin(num_workgroups) num_workgroups: vec3u,",
556
+ ...enabled.includes("subgroups") ? [" @builtin(subgroup_invocation_id) subgroup_invocation_id: u32,", " @builtin(subgroup_size) subgroup_size: u32,"] : [],
557
+ "}"
558
+ ];
559
+ const bindings = [...Object.entries(program.slots).map(([name, slot], index) => `@group(0) @binding(${index}) var<storage, ${slot.access}> ${name}: array<${slot.element}>;`), `@group(1) @binding(0) var<uniform> ${program.uniform.name}: ${program.uniform.struct.name};`];
560
+ const bodies = program.fragments.map((fragment, index) => variants[index]?.source ?? fragment.source);
561
+ const [x, y, z] = program.entry.size;
562
+ const entry = [
563
+ `@compute @workgroup_size(${x}, ${y}, ${z})`,
564
+ `fn ${program.entry.name}(invocation: Invocation) {`,
565
+ program.entry.source,
566
+ "}"
567
+ ];
568
+ return `${[
569
+ enabled.map((name) => `enable ${name};`).join("\n"),
570
+ program.uniform.struct.source,
571
+ invocation.join("\n"),
572
+ bindings.join("\n"),
573
+ ...bodies,
574
+ entry.join("\n")
575
+ ].filter((section) => section.length > 0).join("\n\n")}\n`;
576
+ }
577
+ /**
578
+ * Computes a dispatch's workgroup counts for a total: the x axis up to the limit, then the y axis.
579
+ *
580
+ * @remarks
581
+ * A program reads its workgroup's index as
582
+ * `invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x`, so a
583
+ * workgroup past the total finds no work. A total of 0 gives one workgroup. Thrown with code
584
+ * `ARGUMENT` when `total` is not a non-negative safe integer, `-0` included, or `limit` is not a
585
+ * positive safe integer, and with code `LIMIT` when the total passes `limit * limit`.
586
+ *
587
+ * @param total - The number of workgroups
588
+ * @param limit - The device's `maxComputeWorkgroupsPerDimension`
589
+ * @returns The counts on the x, y, and z axes
590
+ *
591
+ * @example
592
+ * ```ts
593
+ * computeWGSLGrid(70_000, 65_535) // [65535, 2, 1]
594
+ * ```
595
+ */
596
+ function computeWGSLGrid(total, limit) {
597
+ if (!(0, _orkestrel_contract.isNonNegativeInteger)(total) || !(0, _orkestrel_contract.isSafeInteger)(total)) throw new WGSLError(`A workgroup total must be a non-negative safe integer; received ${(0, _orkestrel_contract.preview)(total)}.`, {
598
+ code: "ARGUMENT",
599
+ context: { total }
600
+ });
601
+ if (!(0, _orkestrel_contract.isSafeInteger)(limit) || limit < 1) throw new WGSLError(`A per-axis workgroup limit must be a positive safe integer; received ${(0, _orkestrel_contract.preview)(limit)}.`, {
602
+ code: "ARGUMENT",
603
+ context: { limit }
604
+ });
605
+ const x = Math.max(1, Math.min(total, limit));
606
+ const y = Math.max(1, Math.ceil(total / x));
607
+ if (y > limit) throw new WGSLError(`A dispatch of ${total} workgroups passes the limit of ${limit} on each of two axes; split it into dispatches of at most ${limit * limit} workgroups.`, {
608
+ code: "LIMIT",
609
+ context: {
610
+ total,
611
+ limit
612
+ }
613
+ });
614
+ return Object.freeze([
615
+ x,
616
+ y,
617
+ 1
618
+ ]);
619
+ }
620
+ /**
621
+ * Computes the smallest multiple of an alignment at or above an offset.
622
+ *
623
+ * @remarks
624
+ * Thrown with code `ARGUMENT` when `offset` is not a non-negative safe integer, `-0` included, or
625
+ * `alignment` is not a positive safe integer.
626
+ *
627
+ * @param offset - The byte offset to align
628
+ * @param alignment - The byte alignment
629
+ * @returns The aligned byte offset
630
+ *
631
+ * @example
632
+ * ```ts
633
+ * computeWGSLOffset(36, 256) // 256
634
+ * ```
635
+ */
636
+ function computeWGSLOffset(offset, alignment) {
637
+ if (!(0, _orkestrel_contract.isNonNegativeInteger)(offset) || !(0, _orkestrel_contract.isSafeInteger)(offset)) throw new WGSLError(`A byte offset must be a non-negative safe integer; received ${(0, _orkestrel_contract.preview)(offset)}.`, {
638
+ code: "ARGUMENT",
639
+ context: { offset }
640
+ });
641
+ if (!(0, _orkestrel_contract.isSafeInteger)(alignment) || alignment < 1) throw new WGSLError(`A byte alignment must be a positive safe integer; received ${(0, _orkestrel_contract.preview)(alignment)}.`, {
642
+ code: "ARGUMENT",
643
+ context: { alignment }
644
+ });
645
+ return Math.ceil(offset / alignment) * alignment;
646
+ }
647
+ // src/core/WGSLBatch.ts
648
+ /**
649
+ * Records one command encoder's worth of dispatches and buffer reads, then submits them together.
650
+ *
651
+ * @remarks
652
+ * The batch owns its command encoder and its compute pass, and keeps one pass open across
653
+ * consecutive `encode` calls, skipping a `setPipeline` or a `setBindGroup(0, ...)` that repeats the
654
+ * previous one. Each dispatch writes its uniform values to the session's slab and binds them through
655
+ * the 5-argument `setBindGroup(1, group, offsets, 0, 1)` overload. When the slab is full, the batch
656
+ * ends its pass, uploads the slab, submits, clears the slab, and opens a fresh encoder. The pass
657
+ * ends before each `read` copy. Every upload and submit sits between a synchronous push and pop of a
658
+ * `validation` and an `out-of-memory` error scope; a device error on a submitted command buffer
659
+ * moves the session to `failed` with code `VALIDATION`. `read` resolves after the submission to a
660
+ * caller-owned copy of the bytes. Thrown with code `VALIDATION` when a call other than `abort` or
661
+ * `execute` arrives after `submit` or `abort`; with code `ARGUMENT` for a malformed grid or read
662
+ * range; and with code `LIMIT` when a grid axis passes the device's
663
+ * `maxComputeWorkgroupsPerDimension`. Open a batch through `session.batch()`, which supplies the
664
+ * options.
665
+ *
666
+ * @example
667
+ * ```ts
668
+ * const batch = session.batch()
669
+ * batch.encode(binding, { count: 64 }, [1, 1, 1])
670
+ * const bytes = batch.read(buffer, 0, 256)
671
+ * await batch.execute()
672
+ * new Uint32Array(await bytes)[0] // the first word the dispatch wrote
673
+ * ```
674
+ */
675
+ var WGSLBatch = class {
676
+ #device;
677
+ #limit;
678
+ #options;
679
+ #checkSession;
680
+ #slab;
681
+ #offsets = /* @__PURE__ */ new Uint32Array(1);
682
+ #submissions = [];
683
+ #reads = [];
684
+ #result = Promise.withResolvers();
685
+ #encoder;
686
+ #pass;
687
+ #pipeline;
688
+ #group;
689
+ #binding;
690
+ #uniform;
691
+ #status = "open";
692
+ /**
693
+ * Creates an open batch with a fresh command encoder.
694
+ *
695
+ * @param device - The device whose encoder records the commands and whose queue runs them
696
+ * @param options - The session's slab and the session hooks
697
+ */
698
+ constructor(device, options) {
699
+ this.#device = device;
700
+ this.#limit = device.limits.maxComputeWorkgroupsPerDimension;
701
+ this.#options = options;
702
+ this.#checkSession = options.check;
703
+ this.#slab = options.slab;
704
+ this.#encoder = device.createCommandEncoder();
705
+ }
706
+ get submitted() {
707
+ return this.#status === "submitted";
708
+ }
709
+ encode(binding, values, grid) {
710
+ this.#checkSession();
711
+ if (this.#status !== "open") this.#check();
712
+ if (!Array.isArray(grid) || grid.length !== 3) this.#refuseGrid(grid);
713
+ const x = grid[0];
714
+ const y = grid[1];
715
+ const z = grid[2];
716
+ if (typeof x !== "number" || typeof y !== "number" || typeof z !== "number" || x < 1 || y < 1 || z < 1 || (x | 0) !== x && !Number.isSafeInteger(x) || (y | 0) !== y && !Number.isSafeInteger(y) || (z | 0) !== z && !Number.isSafeInteger(z)) this.#refuseGrid(grid);
717
+ const limit = this.#limit;
718
+ if (x > limit || y > limit || z > limit) throw new WGSLError(`The grid [${x}, ${y}, ${z}] passes the device's ${limit} workgroups per axis; compute the grid with computeWGSLGrid or split the dispatch.`, {
719
+ code: "LIMIT",
720
+ context: {
721
+ grid: [
722
+ x,
723
+ y,
724
+ z
725
+ ],
726
+ limit
727
+ }
728
+ });
729
+ const { statement } = binding;
730
+ const struct = statement.program.uniform.struct;
731
+ const written = this.#slab.write(struct, values);
732
+ const offset = written === void 0 ? this.#flushWrite(struct, values) : written;
733
+ if (this.#binding === binding && this.#pass !== void 0 && this.#uniform !== void 0) {
734
+ this.#offsets[0] = offset;
735
+ this.#pass.setBindGroup(1, this.#uniform, this.#offsets, 0, 1);
736
+ this.#pass.dispatchWorkgroups(x, y, z);
737
+ return;
738
+ }
739
+ const pass = this.#pass ?? this.#open();
740
+ if (this.#pipeline !== statement.pipeline) {
741
+ pass.setPipeline(statement.pipeline);
742
+ this.#pipeline = statement.pipeline;
743
+ }
744
+ if (this.#group !== binding.group) {
745
+ pass.setBindGroup(0, binding.group);
746
+ this.#group = binding.group;
747
+ }
748
+ this.#binding = binding;
749
+ this.#uniform = statement.uniform;
750
+ this.#offsets[0] = offset;
751
+ pass.setBindGroup(1, statement.uniform, this.#offsets, 0, 1);
752
+ pass.dispatchWorkgroups(x, y, z);
753
+ }
754
+ read(buffer, offset, size) {
755
+ this.#check();
756
+ if ((buffer.usage & WGSL_USAGE.source) === 0) throw new WGSLError(`A read needs a buffer with the source usage (WGSL_USAGE.source), so the batch can copy it; its usage is ${buffer.usage}.`, {
757
+ code: "ARGUMENT",
758
+ context: { usage: buffer.usage }
759
+ });
760
+ if (!(0, _orkestrel_contract.isNonNegativeInteger)(offset) || !(0, _orkestrel_contract.isSafeInteger)(offset) || offset % 4 !== 0) throw new WGSLError(`A read starts at ${(0, _orkestrel_contract.preview)(offset)}; a read offset must be a non-negative safe multiple of 4 bytes.`, {
761
+ code: "ARGUMENT",
762
+ context: { offset }
763
+ });
764
+ if (!(0, _orkestrel_contract.isSafeInteger)(size) || size < 4 || size % 4 !== 0) throw new WGSLError(`A read spans ${(0, _orkestrel_contract.preview)(size)} bytes; a read size must be a safe multiple of 4 bytes, at least 4.`, {
765
+ code: "ARGUMENT",
766
+ context: { size }
767
+ });
768
+ if (offset + size > buffer.size) throw new WGSLError(`A read ends at byte ${offset + size}, past its buffer's ${buffer.size} bytes; shorten the range.`, {
769
+ code: "ARGUMENT",
770
+ context: {
771
+ offset,
772
+ size,
773
+ length: buffer.size
774
+ }
775
+ });
776
+ this.#close();
777
+ const staging = this.#options.lease(size);
778
+ this.#encoder.copyBufferToBuffer(buffer, offset, staging, 0, size);
779
+ const result = Promise.withResolvers();
780
+ result.promise.catch(() => void 0);
781
+ this.#reads.push([
782
+ staging,
783
+ size,
784
+ result
785
+ ]);
786
+ return result.promise;
787
+ }
788
+ submit() {
789
+ this.#check();
790
+ this.#close();
791
+ this.#commit();
792
+ this.#status = "submitted";
793
+ this.#options.release(this);
794
+ this.#result.resolve(this.#finish());
795
+ this.#options.track(this.#result.promise);
796
+ }
797
+ async execute(signal) {
798
+ if (signal?.aborted === true) {
799
+ this.abort();
800
+ throw new WGSLError("The signal aborted the batch before it finished.", {
801
+ code: "ABORT",
802
+ cause: signal.reason
803
+ });
804
+ }
805
+ if (this.#status === "open") this.submit();
806
+ const failure = signal === void 0 ? await this.#result.promise : await this.#race(signal);
807
+ if (failure !== void 0) throw failure;
808
+ }
809
+ abort() {
810
+ const error = new WGSLError("The batch was aborted, and its pending reads were rejected.", { code: "ABORT" });
811
+ for (const [, , result] of this.#reads) result.reject(error);
812
+ if (this.#status !== "open") return;
813
+ this.#status = "aborted";
814
+ this.#slab.clear();
815
+ for (const [staging] of this.#reads) this.#options.restore(staging);
816
+ this.#options.release(this);
817
+ this.#result.resolve(this.#discard(error));
818
+ this.#options.track(this.#result.promise);
819
+ }
820
+ #check() {
821
+ this.#options.check();
822
+ if (this.#status !== "open") throw new WGSLError(`The batch is ${this.#status} and takes no more commands; open another with session.batch().`, {
823
+ code: "VALIDATION",
824
+ context: { status: this.#status }
825
+ });
826
+ }
827
+ #refuseGrid(grid) {
828
+ throw new WGSLError(`A dispatch grid must hold three positive safe integer workgroup counts, such as [4, 1, 1]; received ${(0, _orkestrel_contract.preview)(grid)}.`, {
829
+ code: "ARGUMENT",
830
+ context: { grid }
831
+ });
832
+ }
833
+ #flushWrite(struct, values) {
834
+ this.#flush();
835
+ const retry = this.#slab.write(struct, values);
836
+ if (retry === void 0) throw new WGSLError(`The struct ${(0, _orkestrel_contract.preview)(struct.name)} does not fit an empty slab of ${this.#slab.capacity} bytes; raise the session's uniform size.`, {
837
+ code: "LIMIT",
838
+ context: {
839
+ name: struct.name,
840
+ size: struct.size
841
+ }
842
+ });
843
+ return retry;
844
+ }
845
+ #open() {
846
+ if (this.#pass !== void 0) return this.#pass;
847
+ const pass = this.#encoder.beginComputePass();
848
+ this.#pass = pass;
849
+ return pass;
850
+ }
851
+ #close() {
852
+ this.#pass?.end();
853
+ this.#pass = void 0;
854
+ this.#pipeline = void 0;
855
+ this.#group = void 0;
856
+ this.#binding = void 0;
857
+ this.#uniform = void 0;
858
+ }
859
+ #flush() {
860
+ this.#close();
861
+ this.#commit();
862
+ this.#encoder = this.#device.createCommandEncoder();
863
+ }
864
+ #commit() {
865
+ const device = this.#device;
866
+ device.pushErrorScope("out-of-memory");
867
+ device.pushErrorScope("validation");
868
+ this.#options.slab.upload();
869
+ device.queue.submit([this.#encoder.finish()]);
870
+ const validation = device.popErrorScope();
871
+ const memory = device.popErrorScope();
872
+ this.#slab.clear();
873
+ this.#submissions.push(this.#scope(validation, memory));
874
+ }
875
+ async #scope(validation, memory) {
876
+ try {
877
+ const [invalid, exhausted] = await Promise.all([validation, memory]);
878
+ const error = invalid ?? exhausted;
879
+ if (error === null) return void 0;
880
+ const filter = invalid === null ? "out-of-memory" : "validation";
881
+ return new WGSLError(`The device refused a submitted batch (${filter}): ${error.message}`, {
882
+ code: "VALIDATION",
883
+ context: {
884
+ filter,
885
+ message: error.message
886
+ }
887
+ });
888
+ } catch (cause) {
889
+ return new WGSLError(`The device stopped reporting a submitted batch's errors: ${(0, _orkestrel_contract.errorToMessage)(cause)}`, {
890
+ code: "HOST",
891
+ cause
892
+ });
893
+ }
894
+ }
895
+ async #drain() {
896
+ try {
897
+ const done = this.#device.queue.onSubmittedWorkDone();
898
+ const [errors] = await Promise.all([Promise.all(this.#submissions), done]);
899
+ const failure = errors.find((error) => error !== void 0);
900
+ if (failure !== void 0) this.#options.fail(failure);
901
+ return failure;
902
+ } catch (cause) {
903
+ const failure = new WGSLError(`The device stopped before the batch finished: ${(0, _orkestrel_contract.errorToMessage)(cause)}`, {
904
+ code: "HOST",
905
+ cause
906
+ });
907
+ this.#options.fail(failure);
908
+ return failure;
909
+ }
910
+ }
911
+ async #finish() {
912
+ const failure = await this.#drain();
913
+ if (failure === void 0) {
914
+ await Promise.all(this.#reads.map((read) => this.#map(read)));
915
+ return;
916
+ }
917
+ for (const [staging, , result] of this.#reads) {
918
+ result.reject(failure);
919
+ this.#options.restore(staging);
920
+ }
921
+ return failure;
922
+ }
923
+ async #discard(error) {
924
+ return await this.#drain() ?? error;
925
+ }
926
+ async #map(read) {
927
+ const [staging, size, result] = read;
928
+ try {
929
+ await staging.mapAsync(WGSL_MAP.read, 0, size);
930
+ result.resolve(staging.getMappedRange(0, size).slice(0));
931
+ staging.unmap();
932
+ } catch (cause) {
933
+ const error = new WGSLError(`The device could not map a read: ${(0, _orkestrel_contract.errorToMessage)(cause)}`, {
934
+ code: "HOST",
935
+ cause
936
+ });
937
+ result.reject(error);
938
+ } finally {
939
+ this.#options.restore(staging);
940
+ }
941
+ }
942
+ async #race(signal) {
943
+ const cleanup = new AbortController();
944
+ const aborted = new Promise((resolve) => {
945
+ signal.addEventListener("abort", () => {
946
+ this.abort();
947
+ resolve(new WGSLError("The signal aborted the batch while it ran.", {
948
+ code: "ABORT",
949
+ cause: signal.reason
950
+ }));
951
+ }, {
952
+ once: true,
953
+ signal: cleanup.signal
954
+ });
955
+ });
956
+ try {
957
+ return await Promise.race([this.#result.promise, aborted]);
958
+ } finally {
959
+ cleanup.abort();
960
+ }
961
+ }
962
+ };
963
+ // src/core/WGSLSlab.ts
964
+ /**
965
+ * Packs each dispatch's uniform values into one host buffer at the device's uniform offset alignment and uploads them in one write.
966
+ *
967
+ * @remarks
968
+ * The slab owns one `ArrayBuffer` with a `Uint32Array` view and a `Float32Array` view over it, and
969
+ * steps a struct's frozen `members` for each write. An `f32` member writes through the float view,
970
+ * so `-0` and subnormals keep their binary32 patterns; a `u32` or `i32` member writes through the
971
+ * unsigned view, so `-5` stores `0xFFFFFFFB`. Each write starts at the next multiple of the
972
+ * device's `minUniformBufferOffsetAlignment`. A write that meets a missing value zeroes the span it
973
+ * started and throws, so the bytes past `used` stay zero. `clear` zeroes the bytes the written
974
+ * values spanned.
975
+ * The constructor throws with code `ARGUMENT` when `capacity` is not a positive safe multiple of 4
976
+ * or passes the buffer's size, when the buffer lacks the `uniform` or `destination` usage, and when
977
+ * the device reports an alignment that is not a positive safe multiple of 4.
978
+ *
979
+ * @example
980
+ * ```ts
981
+ * const slab = new WGSLSlab(device, { buffer, capacity: 65536 })
982
+ * slab.write(createWGSLStruct('Shape', { rows: 'u32' }), { rows: 64 }) // 0
983
+ * slab.upload()
984
+ * ```
985
+ */
986
+ var WGSLSlab = class {
987
+ #device;
988
+ #buffer;
989
+ #capacity;
990
+ #alignment;
991
+ #mask;
992
+ #bytes;
993
+ #words;
994
+ #floats;
995
+ #used = 0;
996
+ /**
997
+ * Creates an empty slab over a uniform buffer.
998
+ *
999
+ * @param device - The device whose queue receives the upload and whose limits set the alignment
1000
+ * @param options - The uniform buffer and the slab's byte capacity
1001
+ */
1002
+ constructor(device, options) {
1003
+ const { buffer, capacity } = options;
1004
+ const alignment = device.limits.minUniformBufferOffsetAlignment;
1005
+ if (!(0, _orkestrel_contract.isSafeInteger)(capacity) || capacity < 4 || capacity % 4 !== 0) throw new WGSLError(`A slab capacity must be a positive safe multiple of 4 bytes; received ${(0, _orkestrel_contract.preview)(capacity)}.`, {
1006
+ code: "ARGUMENT",
1007
+ context: { capacity }
1008
+ });
1009
+ if ((buffer.usage & WGSL_USAGE.uniform) === 0 || (buffer.usage & WGSL_USAGE.destination) === 0) throw new WGSLError(`A slab buffer must carry the uniform and destination usages (WGSL_USAGE.uniform | WGSL_USAGE.destination); its usage is ${buffer.usage}.`, {
1010
+ code: "ARGUMENT",
1011
+ context: { usage: buffer.usage }
1012
+ });
1013
+ if (capacity > buffer.size) throw new WGSLError(`A slab capacity of ${capacity} bytes passes its buffer's ${buffer.size} bytes.`, {
1014
+ code: "ARGUMENT",
1015
+ context: {
1016
+ capacity,
1017
+ size: buffer.size
1018
+ }
1019
+ });
1020
+ if (!(0, _orkestrel_contract.isSafeInteger)(alignment) || alignment < 4 || alignment % 4 !== 0) throw new WGSLError(`The device reports a minUniformBufferOffsetAlignment of ${(0, _orkestrel_contract.preview)(alignment)}; a slab needs a positive safe multiple of 4.`, {
1021
+ code: "ARGUMENT",
1022
+ context: { alignment }
1023
+ });
1024
+ this.#device = device;
1025
+ this.#buffer = buffer;
1026
+ this.#capacity = capacity;
1027
+ this.#alignment = alignment;
1028
+ this.#mask = capacity <= 0x40000000 && alignment <= 0x40000000 && (alignment & alignment - 1) === 0 ? alignment - 1 : -1;
1029
+ this.#bytes = new ArrayBuffer(capacity);
1030
+ this.#words = new Uint32Array(this.#bytes);
1031
+ this.#floats = new Float32Array(this.#bytes);
1032
+ }
1033
+ get capacity() {
1034
+ return this.#capacity;
1035
+ }
1036
+ get used() {
1037
+ return this.#used;
1038
+ }
1039
+ write(struct, values) {
1040
+ const offset = this.#mask >= 0 ? this.#used + this.#mask & ~this.#mask : this.#used % this.#alignment === 0 ? this.#used : this.#used + (this.#alignment - this.#used % this.#alignment);
1041
+ if (offset + struct.size > this.#capacity) {
1042
+ if (struct.size > this.#capacity) throw new WGSLError(`The struct ${(0, _orkestrel_contract.preview)(struct.name)} takes ${struct.size} bytes, more than the slab's ${this.#capacity}; raise the uniform size.`, {
1043
+ code: "ARGUMENT",
1044
+ context: {
1045
+ name: struct.name,
1046
+ size: struct.size
1047
+ }
1048
+ });
1049
+ return;
1050
+ }
1051
+ const record = values;
1052
+ const base = this.#mask >= 0 ? offset >>> 2 : offset / 4;
1053
+ const { members } = struct;
1054
+ const first = members[0];
1055
+ if (members.length === 1 && first !== void 0) {
1056
+ const value = record[first.name];
1057
+ if (typeof value !== "number") throw new WGSLError(`The values for ${(0, _orkestrel_contract.preview)(struct.name)} carry no number for the field ${(0, _orkestrel_contract.preview)(first.name)}.`, {
1058
+ code: "ARGUMENT",
1059
+ context: {
1060
+ name: struct.name,
1061
+ field: first.name
1062
+ }
1063
+ });
1064
+ if (first.element === "f32") this.#floats[base + first.word] = value;
1065
+ else this.#words[base + first.word] = value;
1066
+ this.#used = offset + struct.size;
1067
+ return offset;
1068
+ }
1069
+ for (const member of members) {
1070
+ const value = record[member.name];
1071
+ if (typeof value !== "number") {
1072
+ this.#words.fill(0, base, base + struct.size / 4);
1073
+ throw new WGSLError(`The values for ${(0, _orkestrel_contract.preview)(struct.name)} carry no number for the field ${(0, _orkestrel_contract.preview)(member.name)}.`, {
1074
+ code: "ARGUMENT",
1075
+ context: {
1076
+ name: struct.name,
1077
+ field: member.name
1078
+ }
1079
+ });
1080
+ }
1081
+ if (member.element === "f32") this.#floats[base + member.word] = value;
1082
+ else this.#words[base + member.word] = value;
1083
+ }
1084
+ this.#used = offset + struct.size;
1085
+ return offset;
1086
+ }
1087
+ upload() {
1088
+ if (this.#used === 0) return;
1089
+ this.#device.queue.writeBuffer(this.#buffer, 0, this.#bytes, 0, this.#used);
1090
+ }
1091
+ clear() {
1092
+ this.#words.fill(0, 0, this.#used / 4);
1093
+ this.#used = 0;
1094
+ }
1095
+ };
1096
+ // src/core/WGSLStatement.ts
1097
+ /**
1098
+ * Runs one prepared program on its session's device and caches a storage bind group per set of slot ranges.
1099
+ *
1100
+ * @remarks
1101
+ * `bind` walks a per-statement `WeakMap` trie keyed on each slot's buffer, byte offset, and byte
1102
+ * size, so a repeated range set returns the same `WGSLBinding` without allocating, and a destroyed
1103
+ * buffer's entries leave with the buffer. A range set the trie lacks is checked before its bind
1104
+ * group is created: thrown with code `ARGUMENT` when the slot names differ from the program's, when
1105
+ * a buffer lacks the `storage` usage, when an offset is not a multiple of the device's
1106
+ * `minStorageBufferOffsetAlignment`, when a size is under 4 bytes or not a multiple of 4, and when a
1107
+ * range passes its buffer's end; with code `LIMIT` when a size passes the device's
1108
+ * `maxStorageBufferBindingSize`; and with code `VALIDATION` when a `read_write` slot shares its
1109
+ * `GPUBuffer` with any other slot, even over disjoint ranges, because Dawn refuses that pair.
1110
+ * `execute` opens a batch on the session, records one dispatch, and resolves when the device
1111
+ * finishes it.
1112
+ *
1113
+ * @example
1114
+ * ```ts
1115
+ * const statement = await session.prepare(program)
1116
+ * const binding = statement.bind({ destination: { buffer } })
1117
+ * await statement.execute(binding, { count: 64 }, [1, 1, 1])
1118
+ * ```
1119
+ */
1120
+ var WGSLStatement = class {
1121
+ program;
1122
+ pipeline;
1123
+ uniform;
1124
+ #session;
1125
+ #layout;
1126
+ #slots;
1127
+ #root;
1128
+ /**
1129
+ * Creates a statement over a pipeline its session prepared.
1130
+ *
1131
+ * @param session - The session whose device creates the bind groups and whose batches run the dispatches
1132
+ * @param options - The program, the pipeline, the storage layout, and the uniform bind group
1133
+ */
1134
+ constructor(session, options) {
1135
+ const slots = options.program.slots;
1136
+ this.program = options.program;
1137
+ this.pipeline = options.pipeline;
1138
+ this.uniform = options.uniform;
1139
+ this.#session = session;
1140
+ this.#layout = options.layout;
1141
+ this.#slots = Object.freeze(Object.entries(slots));
1142
+ this.#root = {
1143
+ next: /* @__PURE__ */ new WeakMap(),
1144
+ binding: this.#slots.length === 0 ? this.#create([]) : void 0
1145
+ };
1146
+ }
1147
+ bind(buffers) {
1148
+ const record = buffers;
1149
+ const cached = this.#find(this.#root, record, 0);
1150
+ if (cached !== void 0) return cached;
1151
+ const entries = this.#resolve(record);
1152
+ const binding = this.#create(entries);
1153
+ this.#store(this.#root, entries, 0, binding);
1154
+ return binding;
1155
+ }
1156
+ async execute(binding, values, grid, signal) {
1157
+ const batch = this.#session.batch();
1158
+ try {
1159
+ batch.encode(binding, values, grid);
1160
+ } catch (error) {
1161
+ batch.abort();
1162
+ throw error;
1163
+ }
1164
+ await batch.execute(signal);
1165
+ }
1166
+ #find(node, record, depth) {
1167
+ const entry = this.#slots[depth];
1168
+ if (entry === void 0) return node.binding;
1169
+ const binding = record[entry[0]];
1170
+ if (!(0, _orkestrel_contract.isObject)(binding)) return void 0;
1171
+ const offset = binding.offset ?? 0;
1172
+ const next = (node.next.get(binding.buffer)?.get(offset))?.get(binding.size ?? binding.buffer.size - offset);
1173
+ return next === void 0 ? void 0 : this.#find(next, record, depth + 1);
1174
+ }
1175
+ #resolve(record) {
1176
+ const name = this.program.name;
1177
+ const names = this.#slots.map(([slot]) => slot);
1178
+ const extra = Object.keys(record).filter((key) => !names.includes(key));
1179
+ const missing = names.filter((slot) => !(0, _orkestrel_contract.isObject)(record[slot]));
1180
+ if (extra.length > 0 || missing.length > 0) throw new WGSLError(`The program ${(0, _orkestrel_contract.preview)(name)} binds exactly the slots ${names.map(_orkestrel_contract.preview).join(", ") || "none"}; give each one a buffer range and no other key.`, {
1181
+ code: "ARGUMENT",
1182
+ context: {
1183
+ name,
1184
+ missing,
1185
+ extra
1186
+ }
1187
+ });
1188
+ const limits = this.#session.device.limits;
1189
+ const entries = this.#slots.map(([slot]) => this.#range(slot, record[slot], limits));
1190
+ const shared = names.filter((_slot, index) => this.#aliased(entries, index));
1191
+ if (shared.length > 0) throw new WGSLError(`The read_write slots ${shared.map(_orkestrel_contract.preview).join(", ")} of ${(0, _orkestrel_contract.preview)(name)} share a GPUBuffer with another slot; Dawn refuses a writable binding beside any other binding of one buffer, even over disjoint ranges, so bind a separate buffer.`, {
1192
+ code: "VALIDATION",
1193
+ context: {
1194
+ name,
1195
+ slots: shared
1196
+ }
1197
+ });
1198
+ return Object.freeze(entries);
1199
+ }
1200
+ #aliased(entries, index) {
1201
+ if (this.#slots[index]?.[1].access !== "read_write") return false;
1202
+ const buffer = entries[index]?.buffer;
1203
+ return entries.some((other, position) => position !== index && other.buffer === buffer);
1204
+ }
1205
+ #range(slot, binding, limits) {
1206
+ const name = this.program.name;
1207
+ if (binding === void 0 || !(0, _orkestrel_contract.isObject)(binding.buffer)) throw new WGSLError(`The slot ${(0, _orkestrel_contract.preview)(slot)} of ${(0, _orkestrel_contract.preview)(name)} needs a buffer range object whose buffer member holds a GPUBuffer.`, {
1208
+ code: "ARGUMENT",
1209
+ context: {
1210
+ name,
1211
+ slot
1212
+ }
1213
+ });
1214
+ const { buffer } = binding;
1215
+ if ((buffer.usage & WGSL_USAGE.storage) === 0) throw new WGSLError(`The slot ${(0, _orkestrel_contract.preview)(slot)} of ${(0, _orkestrel_contract.preview)(name)} needs a buffer with the storage usage (WGSL_USAGE.storage); its usage is ${buffer.usage}.`, {
1216
+ code: "ARGUMENT",
1217
+ context: {
1218
+ name,
1219
+ slot,
1220
+ usage: buffer.usage
1221
+ }
1222
+ });
1223
+ const offset = binding.offset ?? 0;
1224
+ const alignment = limits.minStorageBufferOffsetAlignment;
1225
+ if (!(0, _orkestrel_contract.isNonNegativeInteger)(offset) || !(0, _orkestrel_contract.isSafeInteger)(offset) || offset % alignment !== 0) throw new WGSLError(`The slot ${(0, _orkestrel_contract.preview)(slot)} of ${(0, _orkestrel_contract.preview)(name)} starts at ${(0, _orkestrel_contract.preview)(offset)}; a storage offset must be a non-negative multiple of the device's ${alignment}-byte alignment.`, {
1226
+ code: "ARGUMENT",
1227
+ context: {
1228
+ name,
1229
+ slot,
1230
+ offset,
1231
+ alignment
1232
+ }
1233
+ });
1234
+ const size = binding.size ?? buffer.size - offset;
1235
+ if (!(0, _orkestrel_contract.isSafeInteger)(size) || size < 4 || size % 4 !== 0) throw new WGSLError(`The slot ${(0, _orkestrel_contract.preview)(slot)} of ${(0, _orkestrel_contract.preview)(name)} spans ${(0, _orkestrel_contract.preview)(size)} bytes; a storage range must span a multiple of 4 bytes, at least 4.`, {
1236
+ code: "ARGUMENT",
1237
+ context: {
1238
+ name,
1239
+ slot,
1240
+ size
1241
+ }
1242
+ });
1243
+ if (offset + size > buffer.size) throw new WGSLError(`The slot ${(0, _orkestrel_contract.preview)(slot)} of ${(0, _orkestrel_contract.preview)(name)} ends at byte ${offset + size}, past its buffer's ${buffer.size} bytes.`, {
1244
+ code: "ARGUMENT",
1245
+ context: {
1246
+ name,
1247
+ slot,
1248
+ offset,
1249
+ size,
1250
+ length: buffer.size
1251
+ }
1252
+ });
1253
+ if (size > limits.maxStorageBufferBindingSize) throw new WGSLError(`The slot ${(0, _orkestrel_contract.preview)(slot)} of ${(0, _orkestrel_contract.preview)(name)} spans ${size} bytes, past the device's maxStorageBufferBindingSize of ${limits.maxStorageBufferBindingSize}; split the range.`, {
1254
+ code: "LIMIT",
1255
+ context: {
1256
+ name,
1257
+ slot,
1258
+ size,
1259
+ limit: limits.maxStorageBufferBindingSize
1260
+ }
1261
+ });
1262
+ return Object.freeze({
1263
+ buffer,
1264
+ offset,
1265
+ size
1266
+ });
1267
+ }
1268
+ #create(entries) {
1269
+ const group = this.#session.device.createBindGroup({
1270
+ label: this.program.name,
1271
+ layout: this.#layout,
1272
+ entries: entries.map((resource, binding) => ({
1273
+ binding,
1274
+ resource
1275
+ }))
1276
+ });
1277
+ return Object.freeze({
1278
+ statement: this,
1279
+ group
1280
+ });
1281
+ }
1282
+ #store(node, entries, depth, binding) {
1283
+ const entry = entries[depth];
1284
+ if (entry === void 0) return;
1285
+ const offsets = node.next.get(entry.buffer) ?? /* @__PURE__ */ new Map();
1286
+ const sizes = offsets.get(entry.offset) ?? /* @__PURE__ */ new Map();
1287
+ const leaf = depth === entries.length - 1 ? binding : void 0;
1288
+ const child = sizes.get(entry.size) ?? {
1289
+ next: /* @__PURE__ */ new WeakMap(),
1290
+ binding: leaf
1291
+ };
1292
+ sizes.set(entry.size, child);
1293
+ offsets.set(entry.offset, sizes);
1294
+ node.next.set(entry.buffer, offsets);
1295
+ this.#store(child, entries, depth + 1, binding);
1296
+ }
1297
+ };
1298
+ // src/core/WGSLSession.ts
1299
+ /**
1300
+ * Prepares programs as statements on a borrowed device and opens one batch of dispatches at a time.
1301
+ *
1302
+ * @remarks
1303
+ * The session reads its limits and features from the device and never requests or destroys the
1304
+ * device. An extension is active when the device reports its feature and the `extensions` option
1305
+ * does not switch it off. Pipelines sit in a table keyed on the rendered WGSL text: a ready map
1306
+ * beside a pending map, so a warm `prepare` creates no pipeline. A pending entry that fails with any
1307
+ * code but `COMPILE` leaves the table, so a later `prepare` retries it. Shader compilation runs
1308
+ * inside one synchronous push and pop of a `validation` error scope, and a compiler error rejects
1309
+ * that `prepare` with code `COMPILE` and its `line` and `column` in `context`; the session stays
1310
+ * `open`. Thrown with code `LIMIT` when a program's workgroup size or slot count passes the device's
1311
+ * limits, and with code `VALIDATION` from `batch()` while another batch is open. A device failure on
1312
+ * a submitted batch, or the device's `lost` promise, moves the session to `failed`, making
1313
+ * `prepare`, `batch`, and any open batch's `encode`, `read`, and `submit` throw that failure while
1314
+ * `destroy` resolves. `destroy` moves the session to `destroyed` at once, aborts the open batch,
1315
+ * waits for submitted work and reads, and destroys the uniform buffer and the staging buffers the
1316
+ * session created; a repeated `destroy` returns the same promise, settled `abort` and `execute`
1317
+ * replay their batch's own settlement, and `prepare`, `batch`, `encode`, `read`, and `submit` throw
1318
+ * with code `DESTROYED`. Thrown with code `ARGUMENT`
1319
+ * from the constructor when `uniform.size` is not a positive safe multiple of 4.
1320
+ *
1321
+ * @example
1322
+ * ```ts
1323
+ * const session = new WGSLSession(device, { extensions: { f16: false } })
1324
+ * const statement = await session.prepare(program)
1325
+ * await statement.execute(statement.bind({ destination: { buffer } }), { count: 64 }, [1, 1, 1])
1326
+ * await session.destroy()
1327
+ * ```
1328
+ */
1329
+ var WGSLSession = class {
1330
+ #device;
1331
+ #extensions;
1332
+ #buffer;
1333
+ #slab;
1334
+ #uniform;
1335
+ #ready = /* @__PURE__ */ new Map();
1336
+ #pending = /* @__PURE__ */ new Map();
1337
+ #layouts = /* @__PURE__ */ new Map();
1338
+ #groups = /* @__PURE__ */ new Map();
1339
+ #staging = /* @__PURE__ */ new Set();
1340
+ #leased = /* @__PURE__ */ new Set();
1341
+ #inflight = /* @__PURE__ */ new Set();
1342
+ #batch;
1343
+ #failure;
1344
+ #ending;
1345
+ /**
1346
+ * Creates an open session over a borrowed device, with its uniform slab and uniform layout.
1347
+ *
1348
+ * @param device - The device the session borrows
1349
+ * @param options - The extensions to switch off and the slab's byte size
1350
+ */
1351
+ constructor(device, options) {
1352
+ const size = options?.uniform?.size ?? 65536;
1353
+ if (!(0, _orkestrel_contract.isSafeInteger)(size) || size < 4 || size % 4 !== 0) throw new WGSLError(`A session's uniform size must be a positive safe multiple of 4 bytes; received ${(0, _orkestrel_contract.preview)(size)}.`, {
1354
+ code: "ARGUMENT",
1355
+ context: { size }
1356
+ });
1357
+ const requested = options?.extensions;
1358
+ const features = device.features;
1359
+ const usage = WGSL_USAGE.uniform | WGSL_USAGE.destination;
1360
+ const entry = {
1361
+ binding: 0,
1362
+ visibility: WGSL_STAGE.compute,
1363
+ buffer: {
1364
+ type: "uniform",
1365
+ hasDynamicOffset: true
1366
+ }
1367
+ };
1368
+ this.#device = device;
1369
+ this.#extensions = Object.freeze({
1370
+ f16: features.has(WGSL_EXTENSIONS.f16) && requested?.f16 !== false,
1371
+ subgroups: features.has(WGSL_EXTENSIONS.subgroups) && requested?.subgroups !== false
1372
+ });
1373
+ this.#buffer = device.createBuffer({
1374
+ label: "wgsl uniform",
1375
+ size,
1376
+ usage
1377
+ });
1378
+ this.#slab = new WGSLSlab(device, {
1379
+ buffer: this.#buffer,
1380
+ capacity: size
1381
+ });
1382
+ this.#uniform = device.createBindGroupLayout({
1383
+ label: "wgsl uniform",
1384
+ entries: [entry]
1385
+ });
1386
+ device.lost.then((info) => this.#lose(info));
1387
+ }
1388
+ get device() {
1389
+ return this.#device;
1390
+ }
1391
+ get extensions() {
1392
+ return this.#extensions;
1393
+ }
1394
+ get status() {
1395
+ if (this.#ending !== void 0) return "destroyed";
1396
+ return this.#failure === void 0 ? "open" : "failed";
1397
+ }
1398
+ async prepare(program) {
1399
+ this.#check();
1400
+ const { name, entry } = program;
1401
+ const slots = program.slots;
1402
+ const accesses = Object.values(slots).map((slot) => slot.access);
1403
+ this.#fit(name, entry.size, accesses.length);
1404
+ const text = renderWGSLProgram(program, this.#extensions);
1405
+ const layout = this.#layout(accesses);
1406
+ const pipeline = this.#ready.get(text) ?? await this.#compile(text, name, entry.name, layout);
1407
+ this.#check();
1408
+ const uniform = this.#group(program.uniform.struct.size);
1409
+ return new WGSLStatement(this, {
1410
+ program,
1411
+ pipeline,
1412
+ layout,
1413
+ uniform
1414
+ });
1415
+ }
1416
+ batch() {
1417
+ this.#check();
1418
+ if (this.#batch !== void 0) throw new WGSLError("The session already holds an open batch; submit or abort it before opening another.", { code: "VALIDATION" });
1419
+ const batch = new WGSLBatch(this.#device, {
1420
+ slab: this.#slab,
1421
+ check: () => this.#check(),
1422
+ lease: (size) => this.#lease(size),
1423
+ restore: (buffer) => this.#restore(buffer),
1424
+ release: (ended) => this.#release(ended),
1425
+ fail: (error) => this.#fail(error),
1426
+ track: (work) => this.#track(work)
1427
+ });
1428
+ this.#batch = batch;
1429
+ return batch;
1430
+ }
1431
+ destroy() {
1432
+ if (this.#ending !== void 0) return this.#ending;
1433
+ const ending = Promise.withResolvers();
1434
+ this.#ending = ending.promise;
1435
+ ending.resolve(this.#end());
1436
+ return ending.promise;
1437
+ }
1438
+ #check() {
1439
+ if (this.#ending !== void 0) throw new WGSLError("The session was destroyed; create another with createWGSLSession.", { code: "DESTROYED" });
1440
+ if (this.#failure !== void 0) throw this.#failure;
1441
+ }
1442
+ #fit(name, size, count) {
1443
+ const limits = this.#device.limits;
1444
+ const [x, y, z] = size;
1445
+ const wide = x > limits.maxComputeWorkgroupSizeX || y > limits.maxComputeWorkgroupSizeY;
1446
+ const deep = z > limits.maxComputeWorkgroupSizeZ;
1447
+ if (wide || deep || x * y * z > limits.maxComputeInvocationsPerWorkgroup) throw new WGSLError(`The program ${(0, _orkestrel_contract.preview)(name)} declares a workgroup of [${x}, ${y}, ${z}], past the device's per-axis workgroup sizes or its ${limits.maxComputeInvocationsPerWorkgroup} invocations per workgroup.`, {
1448
+ code: "LIMIT",
1449
+ context: {
1450
+ name,
1451
+ size: [
1452
+ x,
1453
+ y,
1454
+ z
1455
+ ]
1456
+ }
1457
+ });
1458
+ if (count > limits.maxStorageBuffersPerShaderStage) throw new WGSLError(`The program ${(0, _orkestrel_contract.preview)(name)} declares ${count} storage slots, past the device's ${limits.maxStorageBuffersPerShaderStage} storage buffers per shader stage.`, {
1459
+ code: "LIMIT",
1460
+ context: {
1461
+ name,
1462
+ count,
1463
+ limit: limits.maxStorageBuffersPerShaderStage
1464
+ }
1465
+ });
1466
+ }
1467
+ #layout(accesses) {
1468
+ const key = accesses.join(",");
1469
+ const cached = this.#layouts.get(key);
1470
+ if (cached !== void 0) return cached;
1471
+ const entries = accesses.map((access, binding) => ({
1472
+ binding,
1473
+ visibility: WGSL_STAGE.compute,
1474
+ buffer: { type: access === "read" ? "read-only-storage" : "storage" }
1475
+ }));
1476
+ const layout = this.#device.createBindGroupLayout({
1477
+ label: key,
1478
+ entries
1479
+ });
1480
+ this.#layouts.set(key, layout);
1481
+ return layout;
1482
+ }
1483
+ #group(size) {
1484
+ const cached = this.#groups.get(size);
1485
+ if (cached !== void 0) return cached;
1486
+ const resource = {
1487
+ buffer: this.#buffer,
1488
+ offset: 0,
1489
+ size
1490
+ };
1491
+ const group = this.#device.createBindGroup({
1492
+ label: "wgsl uniform",
1493
+ layout: this.#uniform,
1494
+ entries: [{
1495
+ binding: 0,
1496
+ resource
1497
+ }]
1498
+ });
1499
+ this.#groups.set(size, group);
1500
+ return group;
1501
+ }
1502
+ #compile(text, name, entry, layout) {
1503
+ const pending = this.#pending.get(text);
1504
+ if (pending !== void 0) return pending;
1505
+ const created = this.#build(text, name, entry, layout);
1506
+ this.#pending.set(text, created);
1507
+ created.then((pipeline) => {
1508
+ this.#ready.set(text, pipeline);
1509
+ this.#pending.delete(text);
1510
+ }, (error) => {
1511
+ if (!isWGSLError(error) || error.code !== "COMPILE") this.#pending.delete(text);
1512
+ });
1513
+ return created;
1514
+ }
1515
+ async #build(text, name, entry, layout) {
1516
+ const device = this.#device;
1517
+ const groups = [layout, this.#uniform];
1518
+ device.pushErrorScope("validation");
1519
+ const module = device.createShaderModule({
1520
+ label: name,
1521
+ code: text
1522
+ });
1523
+ const layouts = device.createPipelineLayout({
1524
+ label: name,
1525
+ bindGroupLayouts: groups
1526
+ });
1527
+ const popped = device.popErrorScope();
1528
+ const [info, error] = await Promise.all([module.getCompilationInfo(), popped]);
1529
+ const message = info.messages.find((candidate) => candidate.type === "error");
1530
+ if (message !== void 0) {
1531
+ const { lineNum: line, linePos: column } = message;
1532
+ throw new WGSLError(`The program ${(0, _orkestrel_contract.preview)(name)} does not compile at line ${line}, column ${column}: ${message.message}`, {
1533
+ code: "COMPILE",
1534
+ context: {
1535
+ name,
1536
+ line,
1537
+ column,
1538
+ message: message.message
1539
+ }
1540
+ });
1541
+ }
1542
+ if (error !== null) throw new WGSLError(`The device refused the shader module or pipeline layout of ${(0, _orkestrel_contract.preview)(name)}: ${error.message}`, {
1543
+ code: "VALIDATION",
1544
+ context: {
1545
+ name,
1546
+ message: error.message
1547
+ }
1548
+ });
1549
+ return this.#pipeline(module, layouts, name, entry);
1550
+ }
1551
+ async #pipeline(module, layout, name, entry) {
1552
+ try {
1553
+ return await this.#device.createComputePipelineAsync({
1554
+ label: name,
1555
+ layout,
1556
+ compute: {
1557
+ module,
1558
+ entryPoint: entry
1559
+ }
1560
+ });
1561
+ } catch (cause) {
1562
+ throw new WGSLError(`The device refused the compute pipeline of ${(0, _orkestrel_contract.preview)(name)}: ${(0, _orkestrel_contract.errorToMessage)(cause)}`, {
1563
+ code: "VALIDATION",
1564
+ context: { name },
1565
+ cause
1566
+ });
1567
+ }
1568
+ }
1569
+ #lease(size) {
1570
+ const buffer = this.#idle(size) ?? this.#allocate(size);
1571
+ this.#leased.add(buffer);
1572
+ return buffer;
1573
+ }
1574
+ #idle(size) {
1575
+ for (const buffer of this.#staging) {
1576
+ if (this.#leased.has(buffer) || buffer.mapState !== "unmapped") continue;
1577
+ if (buffer.size >= size) return buffer;
1578
+ }
1579
+ }
1580
+ #allocate(size) {
1581
+ const usage = WGSL_USAGE.read | WGSL_USAGE.destination;
1582
+ const buffer = this.#device.createBuffer({
1583
+ label: "wgsl staging",
1584
+ size,
1585
+ usage
1586
+ });
1587
+ this.#staging.add(buffer);
1588
+ return buffer;
1589
+ }
1590
+ #restore(buffer) {
1591
+ this.#leased.delete(buffer);
1592
+ this.#trim();
1593
+ }
1594
+ #release(batch) {
1595
+ if (this.#batch === batch) this.#batch = void 0;
1596
+ this.#trim();
1597
+ }
1598
+ #trim() {
1599
+ if (this.#batch !== void 0) return;
1600
+ const excess = [...this.#staging].filter((buffer) => !this.#leased.has(buffer)).slice(0, Math.max(0, this.#staging.size - 2));
1601
+ for (const buffer of excess) {
1602
+ this.#staging.delete(buffer);
1603
+ this.#retire(buffer);
1604
+ }
1605
+ }
1606
+ #retire(buffer) {
1607
+ const done = this.#device.queue.onSubmittedWorkDone();
1608
+ this.#track(done.then(() => buffer.destroy(), () => buffer.destroy()));
1609
+ }
1610
+ #fail(error) {
1611
+ this.#failure ??= error;
1612
+ }
1613
+ #track(work) {
1614
+ this.#inflight.add(work);
1615
+ work.then(() => this.#inflight.delete(work), () => this.#inflight.delete(work));
1616
+ }
1617
+ #lose(info) {
1618
+ this.#failure ??= new WGSLError(`The device was lost (${info.reason}): ${info.message}`, {
1619
+ code: "HOST",
1620
+ context: {
1621
+ reason: info.reason,
1622
+ message: info.message
1623
+ }
1624
+ });
1625
+ }
1626
+ async #end() {
1627
+ this.#batch?.abort();
1628
+ await Promise.allSettled(this.#inflight);
1629
+ for (const buffer of this.#staging) buffer.destroy();
1630
+ this.#buffer.destroy();
1631
+ this.#staging.clear();
1632
+ this.#leased.clear();
1633
+ this.#ready.clear();
1634
+ this.#pending.clear();
1635
+ this.#layouts.clear();
1636
+ this.#groups.clear();
1637
+ }
1638
+ };
1639
+ // src/core/factories.ts
1640
+ function createWGSLStruct(name, fields) {
1641
+ if (!(0, _orkestrel_contract.isNonEmptyString)(name)) throw new WGSLError(`A struct name must be a non-empty string; received ${(0, _orkestrel_contract.preview)(name)}.`, {
1642
+ code: "ARGUMENT",
1643
+ context: { name }
1644
+ });
1645
+ if (!(0, _orkestrel_contract.isRecord)(fields)) throw new WGSLError(`The struct ${(0, _orkestrel_contract.preview)(name)} needs a plain record of fields; received ${(0, _orkestrel_contract.preview)(fields)}.`, {
1646
+ code: "ARGUMENT",
1647
+ context: { name }
1648
+ });
1649
+ const entries = Object.entries(fields);
1650
+ if (entries.length === 0) throw new WGSLError(`The struct ${(0, _orkestrel_contract.preview)(name)} declares no field; declare at least one 'u32', 'i32', or 'f32' field.`, {
1651
+ code: "ARGUMENT",
1652
+ context: { name }
1653
+ });
1654
+ const invalid = entries.filter(([, element]) => !isWGSLScalar(element)).map(([field]) => field);
1655
+ if (invalid.length > 0) throw new WGSLError(`The struct ${(0, _orkestrel_contract.preview)(name)} declares ${invalid.map(_orkestrel_contract.preview).join(", ")} with a type outside 'u32', 'i32', and 'f32'.`, {
1656
+ code: "ARGUMENT",
1657
+ context: {
1658
+ name,
1659
+ fields: invalid
1660
+ }
1661
+ });
1662
+ const members = Object.freeze(entries.map(([field, element], word) => Object.freeze({
1663
+ name: field,
1664
+ element,
1665
+ word
1666
+ })));
1667
+ const lines = members.map((member) => `\t${member.name}: ${member.element},`);
1668
+ return Object.freeze({
1669
+ name,
1670
+ fields: Object.freeze(Object.fromEntries(entries)),
1671
+ size: members.length * 4,
1672
+ offsets: Object.freeze(Object.fromEntries(members.map((member) => [member.name, member.word * 4]))),
1673
+ members,
1674
+ source: `struct ${name} {\n${lines.join("\n")}\n}`
1675
+ });
1676
+ }
1677
+ /**
1678
+ * Creates a frozen fragment from author-written WGSL text and the fragments it uses.
1679
+ *
1680
+ * @remarks
1681
+ * The text reaches the compiler unchanged. Thrown with code `ARGUMENT` when the name is empty, when
1682
+ * a source is not a string, and when the variant names an extension outside `WGSL_EXTENSIONS`.
1683
+ *
1684
+ * @param input - The fragment's name, text, used fragments, and optional variant
1685
+ * @returns The fragment, frozen
1686
+ *
1687
+ * @example
1688
+ * ```ts
1689
+ * createWGSLFragment({ name: 'square', source: 'fn square(value: f32) -> f32 { return value * value; }' }).uses // []
1690
+ * ```
1691
+ */
1692
+ function createWGSLFragment(input) {
1693
+ if (!(0, _orkestrel_contract.isNonEmptyString)(input.name)) throw new WGSLError(`A fragment name must be a non-empty string; received ${(0, _orkestrel_contract.preview)(input.name)}.`, {
1694
+ code: "ARGUMENT",
1695
+ context: { name: input.name }
1696
+ });
1697
+ if (!(0, _orkestrel_contract.isString)(input.source)) throw new WGSLError(`The fragment ${(0, _orkestrel_contract.preview)(input.name)} needs WGSL text in source; received ${(0, _orkestrel_contract.preview)(input.source)}.`, {
1698
+ code: "ARGUMENT",
1699
+ context: { name: input.name }
1700
+ });
1701
+ const uses = Object.freeze([...input.uses ?? []]);
1702
+ const variant = input.variant;
1703
+ if (variant === void 0) return Object.freeze({
1704
+ name: input.name,
1705
+ source: input.source,
1706
+ uses
1707
+ });
1708
+ if (!isWGSLExtension(variant.extension)) throw new WGSLError(`The fragment ${(0, _orkestrel_contract.preview)(input.name)} names the extension ${(0, _orkestrel_contract.preview)(variant.extension)}; use 'f16' or 'subgroups'.`, {
1709
+ code: "ARGUMENT",
1710
+ context: { name: input.name }
1711
+ });
1712
+ if (!(0, _orkestrel_contract.isString)(variant.source)) throw new WGSLError(`The fragment ${(0, _orkestrel_contract.preview)(input.name)} needs WGSL text in variant.source; received ${(0, _orkestrel_contract.preview)(variant.source)}.`, {
1713
+ code: "ARGUMENT",
1714
+ context: { name: input.name }
1715
+ });
1716
+ return Object.freeze({
1717
+ name: input.name,
1718
+ source: input.source,
1719
+ uses,
1720
+ variant: Object.freeze({
1721
+ extension: variant.extension,
1722
+ source: variant.source
1723
+ })
1724
+ });
1725
+ }
1726
+ function createWGSLProgram(input) {
1727
+ const { entry, uniform } = input;
1728
+ if (!(0, _orkestrel_contract.isNonEmptyString)(input.name)) throw new WGSLError(`A program name must be a non-empty string; received ${(0, _orkestrel_contract.preview)(input.name)}.`, {
1729
+ code: "ARGUMENT",
1730
+ context: { name: input.name }
1731
+ });
1732
+ if (!(0, _orkestrel_contract.isNonEmptyString)(entry.name)) throw new WGSLError(`The program ${(0, _orkestrel_contract.preview)(input.name)} needs a non-empty entry name; received ${(0, _orkestrel_contract.preview)(entry.name)}.`, {
1733
+ code: "ARGUMENT",
1734
+ context: { name: input.name }
1735
+ });
1736
+ if (!isWGSLGrid(entry.size)) throw new WGSLError(`The entry ${(0, _orkestrel_contract.preview)(entry.name)} needs a workgroup size of three positive safe integers, such as [64, 1, 1].`, {
1737
+ code: "ARGUMENT",
1738
+ context: {
1739
+ name: input.name,
1740
+ size: entry.size
1741
+ }
1742
+ });
1743
+ if (!(0, _orkestrel_contract.isString)(entry.source)) throw new WGSLError(`The entry ${(0, _orkestrel_contract.preview)(entry.name)} needs WGSL text in source; received ${(0, _orkestrel_contract.preview)(entry.source)}.`, {
1744
+ code: "ARGUMENT",
1745
+ context: { name: input.name }
1746
+ });
1747
+ const slots = Object.entries(input.slots);
1748
+ const invalid = slots.filter(([, slot]) => !isWGSLAccess(slot.access) || !isWGSLScalar(slot.element)).map(([name]) => name);
1749
+ if (invalid.length > 0) throw new WGSLError(`The program ${(0, _orkestrel_contract.preview)(input.name)} declares slots ${invalid.map(_orkestrel_contract.preview).join(", ")} with an access outside 'read' and 'read_write' or an element outside 'u32', 'i32', and 'f32'.`, {
1750
+ code: "ARGUMENT",
1751
+ context: {
1752
+ name: input.name,
1753
+ slots: invalid
1754
+ }
1755
+ });
1756
+ if (!(0, _orkestrel_contract.isNonEmptyString)(uniform.name)) throw new WGSLError(`The program ${(0, _orkestrel_contract.preview)(input.name)} needs a non-empty uniform name; received ${(0, _orkestrel_contract.preview)(uniform.name)}.`, {
1757
+ code: "ARGUMENT",
1758
+ context: { name: input.name }
1759
+ });
1760
+ const [x, y, z] = entry.size;
1761
+ const size = [
1762
+ x,
1763
+ y,
1764
+ z
1765
+ ];
1766
+ return Object.freeze({
1767
+ name: input.name,
1768
+ entry: Object.freeze({
1769
+ name: entry.name,
1770
+ size: Object.freeze(size),
1771
+ source: entry.source
1772
+ }),
1773
+ slots: Object.freeze(Object.fromEntries(slots.map(([name, slot]) => [name, Object.freeze({
1774
+ access: slot.access,
1775
+ element: slot.element
1776
+ })]))),
1777
+ uniform: Object.freeze({
1778
+ name: uniform.name,
1779
+ struct: uniform.struct
1780
+ }),
1781
+ fragments: collectWGSLFragments(input.uses ?? [])
1782
+ });
1783
+ }
1784
+ /**
1785
+ * Creates an open session that prepares programs and runs batches on a borrowed device.
1786
+ *
1787
+ * @remarks
1788
+ * The session never requests or destroys the device; its `destroy` releases only the buffers it
1789
+ * created. Thrown with code `ARGUMENT` when `uniform.size` is not a positive safe multiple of 4.
1790
+ *
1791
+ * @param device - The device the session borrows
1792
+ * @param options - The extensions to switch off and the uniform slab's byte size
1793
+ * @returns The session
1794
+ *
1795
+ * @example
1796
+ * ```ts
1797
+ * const session = createWGSLSession(device, { extensions: { f16: false } })
1798
+ * session.status // 'open'
1799
+ * ```
1800
+ */
1801
+ function createWGSLSession(device, options) {
1802
+ return new WGSLSession(device, options);
1803
+ }
1804
+ exports.WGSLBatch = WGSLBatch;
1805
+ exports.WGSLError = WGSLError;
1806
+ exports.WGSLSession = WGSLSession;
1807
+ exports.WGSLSlab = WGSLSlab;
1808
+ exports.WGSLStatement = WGSLStatement;
1809
+ exports.WGSL_ACCESSES = WGSL_ACCESSES;
1810
+ exports.WGSL_ERROR_BRAND = WGSL_ERROR_BRAND;
1811
+ exports.WGSL_ERROR_CODES = WGSL_ERROR_CODES;
1812
+ exports.WGSL_EXTENSIONS = WGSL_EXTENSIONS;
1813
+ exports.WGSL_HALF = WGSL_HALF;
1814
+ exports.WGSL_MAP = WGSL_MAP;
1815
+ exports.WGSL_PEAK = WGSL_PEAK;
1816
+ exports.WGSL_PLACE = WGSL_PLACE;
1817
+ exports.WGSL_SCALARS = WGSL_SCALARS;
1818
+ exports.WGSL_STAGE = WGSL_STAGE;
1819
+ exports.WGSL_SUM = WGSL_SUM;
1820
+ exports.WGSL_UNIFORM_SIZE = WGSL_UNIFORM_SIZE;
1821
+ exports.WGSL_USAGE = WGSL_USAGE;
1822
+ exports.collectWGSLFragments = collectWGSLFragments;
1823
+ exports.computeWGSLGrid = computeWGSLGrid;
1824
+ exports.computeWGSLOffset = computeWGSLOffset;
1825
+ exports.createWGSLFragment = createWGSLFragment;
1826
+ exports.createWGSLProgram = createWGSLProgram;
1827
+ exports.createWGSLSession = createWGSLSession;
1828
+ exports.createWGSLStruct = createWGSLStruct;
1829
+ exports.isWGSLAccess = isWGSLAccess;
1830
+ exports.isWGSLError = isWGSLError;
1831
+ exports.isWGSLExtension = isWGSLExtension;
1832
+ exports.isWGSLGrid = isWGSLGrid;
1833
+ exports.isWGSLScalar = isWGSLScalar;
1834
+ exports.renderWGSLProgram = renderWGSLProgram;
1835
+
1836
+ //# sourceMappingURL=index.cjs.map