alpha2 0.4.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +5 -4
  2. package/THIRD_PARTY_NOTICES.md +4 -0
  3. package/dist/abort.d.ts +12 -0
  4. package/dist/abort.js +48 -0
  5. package/dist/active-clock.d.ts +35 -0
  6. package/dist/active-clock.js +99 -0
  7. package/dist/assets.d.ts +28 -22
  8. package/dist/assets.js +8 -12
  9. package/dist/audio-layout.d.ts +52 -74
  10. package/dist/audio-layout.js +114 -148
  11. package/dist/audio-timeline.d.ts +89 -117
  12. package/dist/audio-timeline.js +102 -118
  13. package/dist/audio-worker.d.ts +12 -21
  14. package/dist/audio-worker.js +8 -13
  15. package/dist/audio-worklet-processor.js +45 -58
  16. package/dist/audio-worklet.d.ts +45 -76
  17. package/dist/audio-worklet.js +44 -79
  18. package/dist/audio.d.ts +15 -23
  19. package/dist/audio.js +9 -13
  20. package/dist/builder.d.ts +45 -63
  21. package/dist/builder.js +49 -45
  22. package/dist/capabilities.d.ts +99 -16
  23. package/dist/capabilities.js +2 -2
  24. package/dist/captions.d.ts +45 -22
  25. package/dist/captions.js +60 -15
  26. package/dist/chroma-siting.d.ts +24 -41
  27. package/dist/chroma-siting.js +38 -71
  28. package/dist/containers.d.ts +41 -30
  29. package/dist/containers.js +59 -27
  30. package/dist/decoder-fallback.d.ts +13 -0
  31. package/dist/decoder-fallback.js +38 -0
  32. package/dist/decoder-order.d.ts +24 -39
  33. package/dist/decoder-order.js +28 -42
  34. package/dist/edit.d.ts +77 -154
  35. package/dist/edit.js +98 -180
  36. package/dist/effects.d.ts +108 -177
  37. package/dist/effects.js +7 -9
  38. package/dist/export-destination.d.ts +25 -41
  39. package/dist/export-destination.js +20 -32
  40. package/dist/export-failure.d.ts +34 -59
  41. package/dist/export-failure.js +54 -48
  42. package/dist/export-metrics.d.ts +116 -0
  43. package/dist/export-metrics.js +74 -0
  44. package/dist/export-retry.d.ts +46 -29
  45. package/dist/export-retry.js +86 -51
  46. package/dist/exporter.d.ts +67 -116
  47. package/dist/exporter.js +133 -133
  48. package/dist/extensions.d.ts +69 -115
  49. package/dist/extensions.js +55 -82
  50. package/dist/frame-intake.d.ts +92 -0
  51. package/dist/frame-intake.js +114 -0
  52. package/dist/frame-supply.d.ts +96 -162
  53. package/dist/frame-supply.js +181 -171
  54. package/dist/generated/project-schema.d.ts +701 -485
  55. package/dist/generated/project-schema.js +55 -2
  56. package/dist/generated/project-shape.js +261 -16
  57. package/dist/geometry.d.ts +28 -34
  58. package/dist/geometry.js +18 -23
  59. package/dist/gpu-recovery.d.ts +92 -0
  60. package/dist/gpu-recovery.js +135 -0
  61. package/dist/hdr-frames.d.ts +82 -67
  62. package/dist/hdr-frames.js +112 -49
  63. package/dist/index.d.ts +4 -0
  64. package/dist/index.js +4 -0
  65. package/dist/json-text.d.ts +13 -23
  66. package/dist/json-text.js +10 -20
  67. package/dist/layout-values.d.ts +14 -22
  68. package/dist/layout-values.js +18 -21
  69. package/dist/layout.d.ts +48 -63
  70. package/dist/layout.js +37 -37
  71. package/dist/loudness.d.ts +27 -32
  72. package/dist/loudness.js +19 -23
  73. package/dist/media.d.ts +85 -237
  74. package/dist/media.js +133 -287
  75. package/dist/mediabunny.d.ts +166 -245
  76. package/dist/mediabunny.js +741 -580
  77. package/dist/physical-frames.d.ts +5 -17
  78. package/dist/physical-frames.js +4 -11
  79. package/dist/player.d.ts +56 -47
  80. package/dist/player.js +155 -40
  81. package/dist/presented-frames.d.ts +2 -7
  82. package/dist/presented-frames.js +3 -8
  83. package/dist/project.d.ts +73 -117
  84. package/dist/project.js +384 -445
  85. package/dist/rate-control.d.ts +9 -23
  86. package/dist/rate-control.js +7 -18
  87. package/dist/renderer-choice.d.ts +41 -0
  88. package/dist/renderer-choice.js +82 -0
  89. package/dist/repacked-bytes.d.ts +0 -2
  90. package/dist/repacked-bytes.js +2 -5
  91. package/dist/robustness.d.ts +25 -37
  92. package/dist/robustness.js +71 -54
  93. package/dist/sha256.d.ts +5 -13
  94. package/dist/sha256.js +9 -24
  95. package/dist/text.d.ts +97 -71
  96. package/dist/text.js +33 -70
  97. package/dist/video-frames.d.ts +7 -25
  98. package/dist/video-frames.js +12 -29
  99. package/dist/waveform.d.ts +5 -11
  100. package/dist/waveform.js +4 -9
  101. package/dist/worker-error.d.ts +5 -20
  102. package/dist/worker-error.js +8 -25
  103. package/dist/worker.d.ts +82 -95
  104. package/dist/worker.js +235 -143
  105. package/package.json +26 -2
  106. package/wasm/alpha2_audio_worklet.wasm +0 -0
  107. package/wasm/alpha2_extensions.d.ts +26 -47
  108. package/wasm/alpha2_extensions.js +26 -47
  109. package/wasm/alpha2_extensions_bg.wasm +0 -0
  110. package/wasm/alpha2_wasm.d.ts +460 -567
  111. package/wasm/alpha2_wasm.js +594 -594
  112. package/wasm/alpha2_wasm_bg.wasm +0 -0
  113. package/wasm/alpha2_wasm_bg.wasm.d.ts +15 -8
  114. package/wasm/rust-crate-licenses.md +2 -2
  115. package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline1.js +1 -0
  116. package/wasm/snippets/alpha2-wasm-1313375d424845c0/inline2.js +82 -0
  117. package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
  118. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline0.js +0 -0
  119. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline3.js +0 -0
@@ -1,6 +1,5 @@
1
- // Decoded frames reach the engine as planar YUV and are converted by the engine's shader, as
2
- // natively: a canvas or external texture would tone-map or clip HDR and misplace subsampled chroma.
3
- // SDR frames take this path too unless the host sets `videoConversion: "browser"`.
1
+ // Decoded frames reach the engine as planar YUV for its own shader to convert, because a canvas or
2
+ // external texture would tone-map or clip HDR and misplace subsampled chroma.
4
3
  /** WebCodecs pixel formats the engine converts from planar YUV. */
5
4
  const PLANAR_FORMATS = new Set([
6
5
  "I420",
@@ -25,14 +24,11 @@ const PLANAR_FORMATS = new Set([
25
24
  ]);
26
25
  export { chromaSitingForCodec, chromaSitingForStream, sampleAspectForStream, } from "./chroma-siting.js";
27
26
  /**
28
- * The engine's color description of a WebCodecs color space.
29
- *
30
- * Unspecified parts take the SDR BT.709 limited-range defaults; a PQ or HLG
31
- * transfer makes the signal HDR.
27
+ * Converts a WebCodecs color space to engine color metadata. Unspecified parts default to SDR
28
+ * BT.709 limited range; a PQ or HLG transfer marks the signal HDR.
32
29
  */
33
30
  export function colorMetadataFromVideoColorSpace(space) {
34
- // TypeScript's DOM library predates WebCodecs' HDR values ("pq", "hlg", "bt2020", "bt2020-ncl"),
35
- // so the fields are read as strings.
31
+ // TypeScript's DOM library lacks the HDR enum values, so read the fields as strings.
36
32
  const named = space;
37
33
  const transfer = (() => {
38
34
  switch (named?.transfer) {
@@ -79,84 +75,158 @@ export function colorMetadataFromVideoColorSpace(space) {
79
75
  };
80
76
  }
81
77
  /**
82
- * A frame with no planar YUV format the engine reads: an opaque frame (a hardware frame the
83
- * browser does not map to the CPU, `format` null) or an RGB one. Reading it again cannot help;
84
- * decoding it again in software can.
78
+ * The frame has no planar YUV format the engine reads: it is opaque (`format` null) or RGB.
79
+ * Retrying the read cannot help.
85
80
  */
86
81
  export class NonPlanarVideoFrameError extends Error {
82
+ code = "NON_PLANAR_FRAME";
87
83
  format;
88
84
  constructor(format) {
89
- super(`frame has no planar YUV format the engine reads (${format ?? "opaque"}); decode HDR sources, and sources whose color the project declares, in software`);
85
+ super(`frame has no planar YUV format the engine reads (${format ?? "opaque"})`);
90
86
  this.name = "NonPlanarVideoFrameError";
91
87
  this.format = format;
92
88
  }
93
89
  }
94
- /** Whether `frame` has a planar format the engine converts (`copyPlanarYuvFrame` can copy it). */
90
+ /** This browser cannot decode the track at all. */
91
+ export class DecodeUnavailableError extends Error {
92
+ code = "DECODE_UNAVAILABLE";
93
+ facts;
94
+ failure = {
95
+ code: "INVALID_INPUT",
96
+ phase: "decode",
97
+ stage: "decode-unavailable",
98
+ };
99
+ constructor(message, facts, options) {
100
+ super(message, options);
101
+ this.name = "DecodeUnavailableError";
102
+ this.facts = facts;
103
+ }
104
+ }
105
+ /**
106
+ * The browser decodes the track only to opaque or RGB frames and has no planar software decoder,
107
+ * but the source needs planes (HDR or project-declared color).
108
+ */
109
+ export class PlanarDecodeUnavailableError extends Error {
110
+ code = "PLANAR_DECODE_UNAVAILABLE";
111
+ facts;
112
+ failure = {
113
+ code: "INVALID_INPUT",
114
+ phase: "decode",
115
+ stage: "planar-decode-unavailable",
116
+ };
117
+ constructor(message, facts, options) {
118
+ super(message, options);
119
+ this.name = "PlanarDecodeUnavailableError";
120
+ this.facts = facts;
121
+ }
122
+ }
123
+ const CODEC_NAMES = [
124
+ [/^(hvc1|hev1|hevc)/i, "HEVC"],
125
+ [/^(avc1|avc3|avc|h264)/i, "H.264"],
126
+ [/^(av01|av1)/i, "AV1"],
127
+ [/^(vp09|vp9)/i, "VP9"],
128
+ [/^vp8/i, "VP8"],
129
+ [/^(mp4a|aac)/i, "AAC"],
130
+ [/^opus/i, "Opus"],
131
+ [/^vorbis/i, "Vorbis"],
132
+ [/^flac/i, "FLAC"],
133
+ ];
134
+ /** Human-readable codec name: `hvc1.2.4.L93.B0` is `HEVC`. */
135
+ export function codecName(codec) {
136
+ if (codec === null || codec === "")
137
+ return "unknown";
138
+ return CODEC_NAMES.find(([pattern]) => pattern.test(codec))?.[1] ?? codec;
139
+ }
140
+ /** Human-readable bit depth and chroma, such as `10-bit` and `4:2:2`. */
141
+ export function pictureDetails(facts) {
142
+ return [
143
+ ...(facts.bitDepth === undefined ? [] : [`${facts.bitDepth}-bit`]),
144
+ ...(facts.chroma === undefined || facts.chroma === "420"
145
+ ? []
146
+ : [`4:${facts.chroma.slice(1, 2)}:${facts.chroma.slice(2)}`]),
147
+ ];
148
+ }
149
+ /** User-facing refusal message built from `facts` alone, with a suggested workaround. */
150
+ export function decodeRefusalMessage(name, facts) {
151
+ const codec = codecName(facts.codec);
152
+ if (facts.kind === "audio") {
153
+ const channels = facts.channels === undefined
154
+ ? ""
155
+ : ` with ${facts.channels} channel${facts.channels === 1 ? "" : "s"}${facts.layout && facts.layout.length > 0
156
+ ? ` (${facts.layout.join(" ")})`
157
+ : ""}`;
158
+ const stereo = facts.channels !== undefined && facts.channels > 2
159
+ ? " or convert it to stereo"
160
+ : " or convert it to AAC";
161
+ return `${name}: this browser cannot decode ${codec} audio${channels}. Use another browser${stereo}.`;
162
+ }
163
+ const hdr = facts.transfer === "pq" || facts.transfer === "hlg";
164
+ const details = [
165
+ codec,
166
+ ...pictureDetails(facts),
167
+ ...(hdr ? [facts.transfer === "pq" ? "PQ" : "HLG"] : []),
168
+ ].join(", ");
169
+ const what = `${name} is ${hdr ? "HDR " : ""}video (${details})`;
170
+ if (facts.softwareDecoder !== undefined || facts.frameFormat !== undefined)
171
+ return `${what}: this browser decodes it only to frames the engine cannot read and has no software decoder that gives planes. Convert it to H.264 High 10 or AV1 10-bit, or export with the native host.`;
172
+ return `${what}: this browser cannot decode it. Convert it to H.264 or AV1, use another browser, or export with the native host.`;
173
+ }
174
+ /** Whether `copyPlanarYuvFrame` can copy `frame`. */
95
175
  export function isPlanarVideoFrame(frame) {
96
176
  return frame.format !== null && PLANAR_FORMATS.has(frame.format);
97
177
  }
98
- /** Whether a decoded frame's own color space says it is HDR. */
178
+ /** Whether the frame's own color space is HDR. */
99
179
  export function isHdrVideoFrame(frame) {
100
180
  const transfer = frame.colorSpace?.transfer;
101
181
  return transfer === "pq" || transfer === "hlg";
102
182
  }
103
183
  /**
104
- * Buffers planar copies reuse: a 4K 10-bit frame is 25 MB, which a fresh allocation zero-fills
105
- * and the garbage collector reclaims at the frame rate. A copy takes a buffer with
106
- * {@link PlanarCopyPool.acquire} and gives it back with {@link PlanarCopyPool.release} once its
107
- * upload has taken the bytes (an engine upload copies them into wasm memory before it returns).
108
- * Copies that overlap each take their own buffer.
184
+ * Reusable buffers for planar copies, avoiding a fresh zero-filled allocation per frame (25 MB for
185
+ * a 4K 10-bit frame). Release a buffer once its upload returns, since the engine copies the bytes
186
+ * into wasm memory.
109
187
  */
110
188
  export class PlanarCopyPool {
111
189
  #maxFree;
112
190
  #free = [];
113
- /** Keeps at most `maxFree` (default 2) buffers between copies. */
191
+ /** Keeps at most `maxFree` idle buffers. */
114
192
  constructor(maxFree = 2) {
115
193
  if (!Number.isSafeInteger(maxFree) || maxFree < 0)
116
194
  throw new RangeError("maxFree must be a non-negative safe integer");
117
195
  this.#maxFree = maxFree;
118
196
  }
119
- /** `bytes` bytes to copy into: a kept buffer large enough, or a new one. */
197
+ /** Returns a view of `bytes` bytes over a kept buffer, or a new one. */
120
198
  acquire(bytes) {
121
- // Kept smallest first: the first one large enough is the smallest that fits.
199
+ // Sorted smallest first, so this finds the best fit.
122
200
  const index = this.#free.findIndex((buffer) => buffer.byteLength >= bytes);
123
201
  const kept = index < 0 ? undefined : this.#free.splice(index, 1)[0];
124
202
  return new Uint8Array(kept ?? new ArrayBuffer(bytes), 0, bytes);
125
203
  }
126
- /** Gives back the buffer under `data`; nothing may read `data` afterwards. */
204
+ /** Returns the buffer under `data` to the pool; `data` must not be used afterwards. */
127
205
  release(data) {
128
206
  const buffer = data.buffer;
129
207
  if (!(buffer instanceof ArrayBuffer) || this.#free.includes(buffer))
130
208
  return;
131
209
  this.#free.push(buffer);
132
210
  this.#free.sort((left, right) => left.byteLength - right.byteLength);
133
- // The largest serve every size, so past the limit the smallest go.
211
+ // Evict the smallest, since larger buffers serve every size.
134
212
  this.#free.splice(0, Math.max(0, this.#free.length - this.#maxFree));
135
213
  }
136
- /** Drops every kept buffer. */
137
214
  clear() {
138
215
  this.#free = [];
139
216
  }
140
- /** Bytes the kept buffers hold. */
217
+ /** Total bytes of idle buffers. */
141
218
  get keptBytes() {
142
219
  return this.#free.reduce((sum, buffer) => sum + buffer.byteLength, 0);
143
220
  }
144
221
  }
145
222
  /**
146
- * Copies `frame` out as planar YUV and closes it.
147
- *
148
- * `declared` is the color the project declares for the source, which wins
149
- * over the frame's own color space, as it does natively. A frame without a
150
- * CPU-readable planar format (a hardware frame the browser will not map) is
151
- * refused rather than converted by the browser.
223
+ * Copies `frame` out as planar YUV and always closes it. `declared` color overrides the frame's own
224
+ * color space.
152
225
  *
153
- * `frame` is closed whether the copy succeeds or not. Rejects with
154
- * {@link NonPlanarVideoFrameError} when the frame has no planar format the
155
- * engine reads, and otherwise when it has no visible rectangle or `copyTo`
156
- * fails.
226
+ * With `pool`, `data` comes from the pool and the caller releases it after uploading.
157
227
  *
158
- * With `pool`, the copy's `data` is a buffer from it, which the caller gives back with
159
- * {@link PlanarCopyPool.release} after uploading; a failed copy gives it back itself.
228
+ * Rejects with {@link NonPlanarVideoFrameError} for a frame without a planar format, and otherwise
229
+ * when it has no visible rectangle or `copyTo` fails.
160
230
  */
161
231
  export async function copyPlanarYuvFrame(frame, declared, identity = {}, pool) {
162
232
  try {
@@ -167,10 +237,7 @@ export async function copyPlanarYuvFrame(frame, declared, identity = {}, pool) {
167
237
  }
168
238
  }
169
239
  /**
170
- * {@link copyPlanarYuvFrame} without closing `frame`: the caller owns it whether the copy succeeds
171
- * or not, so a frame whose planes the browser could not read back can be read again. Rejects as
172
- * {@link copyPlanarYuvFrame} does, with {@link NonPlanarVideoFrameError} for a frame no read can
173
- * copy; with `pool`, a failed copy gives its buffer back.
240
+ * {@link copyPlanarYuvFrame} without closing `frame`, so a failed readback can be retried.
174
241
  *
175
242
  * @internal For `FrameSupply`.
176
243
  */
@@ -181,7 +248,7 @@ export async function readPlanarYuvFrame(frame, declared, identity = {}, pool) {
181
248
  const visible = frame.visibleRect;
182
249
  if (!visible)
183
250
  throw new Error("frame has no visible rectangle");
184
- // copyTo copies the visible rectangle by default, so the copy is exactly the picture.
251
+ // `copyTo` copies only the visible rectangle by default.
185
252
  const size = frame.allocationSize();
186
253
  const data = pool?.acquire(size) ?? new Uint8Array(size);
187
254
  let planes;
@@ -212,11 +279,7 @@ export async function readPlanarYuvFrame(frame, declared, identity = {}, pool) {
212
279
  ...(identity.mirror === undefined ? {} : { mirror: identity.mirror }),
213
280
  };
214
281
  }
215
- /**
216
- * Uploads a planar frame for the engine to convert and present at
217
- * `outputWidth` x `outputHeight`, the size it is shown upright at. Throws what
218
- * the engine's `uploadYuvFrame` throws.
219
- */
282
+ /** Uploads a planar frame, shown upright at `outputWidth` by `outputHeight`. */
220
283
  export function uploadPlanarYuvFrame(engine, sourceId, mediaTimeTicks, frame, outputWidth, outputHeight) {
221
284
  return engine.uploadYuvFrame(sourceId, mediaTimeTicks, frame.format, frame.codedWidth, frame.codedHeight, frame.data, Uint32Array.from(frame.layout), Uint32Array.from(frame.visibleRect), frame.displayWidth, frame.displayHeight, JSON.stringify(frame.color), frame.chromaSiting, outputWidth, outputHeight, frame.rotation ?? 0, frame.mirror ?? false);
222
285
  }
package/dist/index.d.ts CHANGED
@@ -7,14 +7,18 @@ export * from "./audio-worker.js";
7
7
  export * from "./containers.js";
8
8
  export * from "./effects.js";
9
9
  export * from "./exporter.js";
10
+ export * from "./export-metrics.js";
10
11
  export * from "./extensions.js";
11
12
  export * from "./frame-supply.js";
13
+ export * from "./frame-intake.js";
14
+ export * from "./gpu-recovery.js";
12
15
  export * from "./hdr-frames.js";
13
16
  export * from "./loudness.js";
14
17
  export * from "./media.js";
15
18
  export * from "./player.js";
16
19
  export * from "./project.js";
17
20
  export * from "./rate-control.js";
21
+ export * from "./renderer-choice.js";
18
22
  export * from "./robustness.js";
19
23
  export * from "./text.js";
20
24
  export * from "./waveform.js";
package/dist/index.js CHANGED
@@ -7,14 +7,18 @@ export * from "./audio-worker.js";
7
7
  export * from "./containers.js";
8
8
  export * from "./effects.js";
9
9
  export * from "./exporter.js";
10
+ export * from "./export-metrics.js";
10
11
  export * from "./extensions.js";
11
12
  export * from "./frame-supply.js";
13
+ export * from "./frame-intake.js";
14
+ export * from "./gpu-recovery.js";
12
15
  export * from "./hdr-frames.js";
13
16
  export * from "./loudness.js";
14
17
  export * from "./media.js";
15
18
  export * from "./player.js";
16
19
  export * from "./project.js";
17
20
  export * from "./rate-control.js";
21
+ export * from "./renderer-choice.js";
18
22
  export * from "./robustness.js";
19
23
  export * from "./text.js";
20
24
  export * from "./waveform.js";
@@ -1,40 +1,30 @@
1
1
  /**
2
- * Reads JSON text as the engine's parser (serde_json) does, keeping what
3
- * `JSON.parse` forgets.
2
+ * Reads JSON text the way the engine's parser (`serde_json`) does.
4
3
  *
5
- * `JSON.parse` keeps the last of a repeated key, turns `1920.0`, `1.92e3`,
6
- * and `-0` into numbers like any other, and rounds an integer past 2^53. The
7
- * engine refuses a struct field given twice, reads those three spellings as
8
- * floating point, which no integer field accepts, and reads a 64-bit integer
9
- * exactly. {@link readJsonText} returns the same value as `JSON.parse`
10
- * together with where the text said any of these, so the shape check can
11
- * decide them field by field: a repeated key is allowed where the document
12
- * holds a map, a fractional spelling where it holds a float, and an integer
13
- * by its digits against the field's integer type.
4
+ * `JSON.parse` hides repeated keys, float spellings of integers (`1920.0`, `1.92e3`, `-0`) and
5
+ * integers past 2^53, all of which the engine treats differently. {@link readJsonText} records
6
+ * where they occur so the shape check can judge each field by its type.
14
7
  */
15
- /** Where the text said something its parsed value does not show. */
8
+ /** Source details the parsed value does not show. */
16
9
  export interface JsonSpelling {
17
10
  /**
18
- * Containers whose member, by key or index, is a number its parsed value does not spell: one
19
- * written as a float (with a fraction, an exponent, or as `-0`) or an integer past
20
- * `Number.MAX_SAFE_INTEGER`, with the member's text: every such text of a repeated key, which
21
- * the engine reads each of.
11
+ * Per container and member key or index, the source text of numbers written as floats
12
+ * (fraction, exponent or `-0`) or as integers past `Number.MAX_SAFE_INTEGER`. A repeated key
13
+ * keeps every text.
22
14
  */
23
15
  readonly numbers: WeakMap<object, Map<string | number, string[]>>;
24
- /** Objects whose text gives a key more than once, with those keys. */
16
+ /** Keys given more than once, per object. */
25
17
  readonly repeated: WeakMap<object, Set<string>>;
26
18
  }
27
- /** The deepest nesting the engine's parser reads (serde_json's recursion limit). */
19
+ /** Deepest nesting the engine's parser accepts (the `serde_json` recursion limit). */
28
20
  export declare const MAX_JSON_DEPTH = 127;
29
21
  /**
30
- * The value of `json`, which `JSON.parse` has already accepted, with its
31
- * spelling; `undefined` when it nests deeper than {@link MAX_JSON_DEPTH}.
22
+ * Parses `json`, which `JSON.parse` must already accept, with its spelling details. Returns
23
+ * `undefined` when it nests deeper than {@link MAX_JSON_DEPTH}.
32
24
  */
33
25
  export declare function readJsonText(json: string): {
34
26
  value: unknown;
35
27
  spelling: JsonSpelling;
36
28
  } | undefined;
37
- /**
38
- * Whether `text` has a UTF-16 surrogate without its pair, which UTF-8 (and the engine) cannot hold.
39
- */
29
+ /** Whether `text` has an unpaired UTF-16 surrogate, which UTF-8 cannot encode. */
40
30
  export declare function hasLoneSurrogate(text: string): boolean;
package/dist/json-text.js CHANGED
@@ -1,22 +1,15 @@
1
1
  /**
2
- * Reads JSON text as the engine's parser (serde_json) does, keeping what
3
- * `JSON.parse` forgets.
2
+ * Reads JSON text the way the engine's parser (`serde_json`) does.
4
3
  *
5
- * `JSON.parse` keeps the last of a repeated key, turns `1920.0`, `1.92e3`,
6
- * and `-0` into numbers like any other, and rounds an integer past 2^53. The
7
- * engine refuses a struct field given twice, reads those three spellings as
8
- * floating point, which no integer field accepts, and reads a 64-bit integer
9
- * exactly. {@link readJsonText} returns the same value as `JSON.parse`
10
- * together with where the text said any of these, so the shape check can
11
- * decide them field by field: a repeated key is allowed where the document
12
- * holds a map, a fractional spelling where it holds a float, and an integer
13
- * by its digits against the field's integer type.
4
+ * `JSON.parse` hides repeated keys, float spellings of integers (`1920.0`, `1.92e3`, `-0`) and
5
+ * integers past 2^53, all of which the engine treats differently. {@link readJsonText} records
6
+ * where they occur so the shape check can judge each field by its type.
14
7
  */
15
- /** The deepest nesting the engine's parser reads (serde_json's recursion limit). */
8
+ /** Deepest nesting the engine's parser accepts (the `serde_json` recursion limit). */
16
9
  export const MAX_JSON_DEPTH = 127;
17
10
  /**
18
- * The value of `json`, which `JSON.parse` has already accepted, with its
19
- * spelling; `undefined` when it nests deeper than {@link MAX_JSON_DEPTH}.
11
+ * Parses `json`, which `JSON.parse` must already accept, with its spelling details. Returns
12
+ * `undefined` when it nests deeper than {@link MAX_JSON_DEPTH}.
20
13
  */
21
14
  export function readJsonText(json) {
22
15
  const spelling = {
@@ -61,8 +54,7 @@ export function readJsonText(json) {
61
54
  ? JSON.parse(json.slice(start, at))
62
55
  : json.slice(start + 1, at - 1);
63
56
  };
64
- // Returns the member's value, and its text if it is a number its value does not spell (see
65
- // `JsonSpelling.numbers`).
57
+ // Returns the value and, for numbers recorded in `JsonSpelling.numbers`, the source text.
66
58
  const readValue = (depth) => {
67
59
  skipSpace();
68
60
  const char = json[at];
@@ -96,7 +88,7 @@ export function readJsonText(json) {
96
88
  skipSpace();
97
89
  const key = readString();
98
90
  skipSpace();
99
- at += 1; // Skip the `:`.
91
+ at += 1;
100
92
  const [item, text] = readValue(depth + 1);
101
93
  if (Object.hasOwn(object, key))
102
94
  note(spelling.repeated, object, key);
@@ -137,9 +129,7 @@ export function readJsonText(json) {
137
129
  }
138
130
  class TooDeep extends Error {
139
131
  }
140
- /**
141
- * Whether `text` has a UTF-16 surrogate without its pair, which UTF-8 (and the engine) cannot hold.
142
- */
132
+ /** Whether `text` has an unpaired UTF-16 surrogate, which UTF-8 cannot encode. */
143
133
  export function hasLoneSurrogate(text) {
144
134
  return /\p{Surrogate}/u.test(text);
145
135
  }
@@ -1,10 +1,7 @@
1
1
  /**
2
- * The CSS value forms a layout reads, parsed as `alpha2_model::layout_values` parses them, with
3
- * the same messages: lengths (a number, `"<n>px"`, `"<n>%"`), the four-side shorthand, grid track
4
- * lists and grid lines, and CSS hex colors. Internal: `validateProject` and the layout builder use
5
- * it.
2
+ * CSS value parsers for layout fields. Must match `alpha2_model::layout_values`, including error
3
+ * messages.
6
4
  */
7
- /** A parsed value, or why the text is not one. */
8
5
  export type Parsed<T> = {
9
6
  readonly ok: true;
10
7
  readonly value: T;
@@ -12,30 +9,29 @@ export type Parsed<T> = {
12
9
  readonly ok: false;
13
10
  readonly error: string;
14
11
  };
15
- /** A length's unit: a fraction of the shorter side, canvas pixels, or a percent. */
12
+ /** `fraction` is a fraction of the canvas's shorter side. */
16
13
  export type LengthUnit = "fraction" | "px" | "percent";
17
- /** A length as the engine reads it: its unit and its 32-bit value. */
14
+ /** `value` is a 32-bit float. */
18
15
  export interface Length {
19
16
  readonly unit: LengthUnit;
20
17
  readonly value: number;
21
18
  }
22
19
  /**
23
- * A CSS number without an exponent, read as a JSON number is: through 64 bits to the nearest
24
- * 32-bit float. `undefined` when it is not one or is not finite.
20
+ * Parses a CSS number without an exponent, rounded through f64 to f32 as the engine does.
21
+ * Returns `undefined` when invalid or not finite.
25
22
  */
26
23
  export declare function parseNumber(text: string): number | undefined;
27
- /** A length that may not be a percent (`LayoutSize`), from its string form. */
24
+ /** Parses a `LayoutSize` (no percent). */
28
25
  export declare function parseSize(text: string): Parsed<Length>;
29
- /** A length that may be a percent (`LayoutLength`), from its string form. */
26
+ /** Parses a `LayoutLength` (percent allowed). */
30
27
  export declare function parseLength(text: string): Parsed<Length>;
31
- /** Padding or margin sides (`Insets`), top first, from the shorthand string. */
28
+ /** Parses `Insets` from the shorthand string, top first. */
32
29
  export declare function parseInsets(text: string): Parsed<readonly [Length, Length, Length, Length]>;
33
- /** A translation (`LayoutOffset`) from the CSS `translate` string: x, then y (0 when missing). */
30
+ /** Parses a `LayoutOffset` from a CSS `translate` string; y defaults to 0. */
34
31
  export declare function parseOffset(text: string): Parsed<{
35
32
  readonly x: Length;
36
33
  readonly y: Length;
37
34
  }>;
38
- /** One side of a track's size. */
39
35
  export type TrackBreadth = {
40
36
  readonly kind: "length";
41
37
  readonly length: Length;
@@ -45,7 +41,6 @@ export type TrackBreadth = {
45
41
  } | {
46
42
  readonly kind: "auto" | "min-content" | "max-content";
47
43
  };
48
- /** One track's size. */
49
44
  export type TrackSize = {
50
45
  readonly kind: "breadth";
51
46
  readonly breadth: TrackBreadth;
@@ -57,9 +52,7 @@ export type TrackSize = {
57
52
  readonly kind: "fit-content";
58
53
  readonly limit: Length;
59
54
  };
60
- /** How often `repeat()` repeats: a count, `auto-fill`, or `auto-fit`. */
61
55
  export type RepeatCount = number | "auto-fill" | "auto-fit";
62
- /** One entry of a track list. */
63
56
  export type TrackComponent = {
64
57
  readonly kind: "single";
65
58
  readonly size: TrackSize;
@@ -68,9 +61,8 @@ export type TrackComponent = {
68
61
  readonly count: RepeatCount;
69
62
  readonly tracks: readonly TrackSize[];
70
63
  };
71
- /** A grid track list (`TrackList`), from its CSS string. */
64
+ /** Parses a grid `TrackList`. */
72
65
  export declare function parseTrackList(text: string): Parsed<TrackComponent[]>;
73
- /** One edge of a grid placement: `auto`, a line, or a span. */
74
66
  export type GridEdge = {
75
67
  readonly kind: "auto";
76
68
  } | {
@@ -80,17 +72,17 @@ export type GridEdge = {
80
72
  readonly kind: "span";
81
73
  readonly count: number;
82
74
  };
83
- /** Where a grid item lies on one axis (`GridPlacement`), from a line number or its CSS string. */
75
+ /** Parses a `GridPlacement` from a line number or its CSS string. */
84
76
  export declare function parsePlacement(value: number | string): Parsed<{
85
77
  readonly start: GridEdge;
86
78
  readonly end: GridEdge;
87
79
  }>;
88
- /** A straight sRGB color with alpha, each component in `0..=1`. */
80
+ /** Straight (non-premultiplied) sRGB with alpha, components in `0..=1`. */
89
81
  export interface Color {
90
82
  readonly red: number;
91
83
  readonly green: number;
92
84
  readonly blue: number;
93
85
  readonly alpha: number;
94
86
  }
95
- /** The color a CSS hex string names (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), as 32-bit floats. */
87
+ /** Parses `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` into f32 components. */
96
88
  export declare function parseHex(text: string): Parsed<Color>;
@@ -1,15 +1,13 @@
1
1
  /**
2
- * The CSS value forms a layout reads, parsed as `alpha2_model::layout_values` parses them, with
3
- * the same messages: lengths (a number, `"<n>px"`, `"<n>%"`), the four-side shorthand, grid track
4
- * lists and grid lines, and CSS hex colors. Internal: `validateProject` and the layout builder use
5
- * it.
2
+ * CSS value parsers for layout fields. Must match `alpha2_model::layout_values`, including error
3
+ * messages.
6
4
  */
7
5
  const ok = (value) => ({ ok: true, value });
8
6
  const refused = (error) => ({ ok: false, error });
9
7
  const NUMBER = /^-?(\d+\.?\d*|\.\d+)$/;
10
8
  /**
11
- * A CSS number without an exponent, read as a JSON number is: through 64 bits to the nearest
12
- * 32-bit float. `undefined` when it is not one or is not finite.
9
+ * Parses a CSS number without an exponent, rounded through f64 to f32 as the engine does.
10
+ * Returns `undefined` when invalid or not finite.
13
11
  */
14
12
  export function parseNumber(text) {
15
13
  if (!NUMBER.test(text))
@@ -17,11 +15,10 @@ export function parseNumber(text) {
17
15
  const value = Math.fround(Number(text));
18
16
  return Number.isFinite(value) ? value : undefined;
19
17
  }
20
- /** The tokens of a CSS value: runs of characters between ASCII spaces. */
21
18
  function tokens(text) {
22
19
  return text.split(" ").filter((token) => token.length > 0);
23
20
  }
24
- /** Strips ASCII spaces from both ends, as Rust's `trim_matches(' ')` does. */
21
+ /** Matches Rust's `trim_matches(' ')`: ASCII spaces only. */
25
22
  function trimSpaces(text) {
26
23
  return text.replace(/^ +| +$/g, "");
27
24
  }
@@ -36,7 +33,7 @@ function invalidLength(token, percent) {
36
33
  : 'a number or "<n>px"';
37
34
  return `invalid length "${token}"${hint}: write ${forms}`;
38
35
  }
39
- /** One token: a number or `<n>px`; `percent` says whether the field takes a percent. */
36
+ /** `percent` says whether the field accepts a percent. */
40
37
  function parseSizeToken(token, percent) {
41
38
  if (token.endsWith("px")) {
42
39
  const value = parseNumber(token.slice(0, -2));
@@ -54,11 +51,11 @@ function parseSizeToken(token, percent) {
54
51
  ? refused(invalidLength(token, percent))
55
52
  : ok({ unit: "fraction", value });
56
53
  }
57
- /** A length that may not be a percent (`LayoutSize`), from its string form. */
54
+ /** Parses a `LayoutSize` (no percent). */
58
55
  export function parseSize(text) {
59
56
  return parseSizeToken(trimSpaces(text), false);
60
57
  }
61
- /** A length that may be a percent (`LayoutLength`), from its string form. */
58
+ /** Parses a `LayoutLength` (percent allowed). */
62
59
  export function parseLength(text) {
63
60
  const trimmed = trimSpaces(text);
64
61
  if (trimmed.endsWith("%")) {
@@ -70,7 +67,7 @@ export function parseLength(text) {
70
67
  const size = parseSizeToken(trimmed, true);
71
68
  return size.ok ? size : refused(invalidLength(text, true));
72
69
  }
73
- /** The four sides of a CSS shorthand of one to four values, top first. */
70
+ /** Expands a one-to-four value CSS shorthand, top first. */
74
71
  function shorthand(values) {
75
72
  const [a, b, c, d] = values;
76
73
  switch (values.length) {
@@ -86,7 +83,7 @@ function shorthand(values) {
86
83
  return refused(`expected 1 to 4 lengths, got ${values.length}`);
87
84
  }
88
85
  }
89
- /** Padding or margin sides (`Insets`), top first, from the shorthand string. */
86
+ /** Parses `Insets` from the shorthand string, top first. */
90
87
  export function parseInsets(text) {
91
88
  const sides = [];
92
89
  for (const token of tokens(text)) {
@@ -97,7 +94,7 @@ export function parseInsets(text) {
97
94
  }
98
95
  return shorthand(sides);
99
96
  }
100
- /** A translation (`LayoutOffset`) from the CSS `translate` string: x, then y (0 when missing). */
97
+ /** Parses a `LayoutOffset` from a CSS `translate` string; y defaults to 0. */
101
98
  export function parseOffset(text) {
102
99
  const values = [];
103
100
  for (const token of tokens(text)) {
@@ -143,7 +140,7 @@ function parseBreadth(token, max) {
143
140
  ? ok({ kind: "length", length: length.value })
144
141
  : refused(unknownTrack(token));
145
142
  }
146
- /** Reads a track list left to right, as `TrackParser` does. */
143
+ /** Mirrors the Rust `TrackParser`. */
147
144
  class TrackParser {
148
145
  text;
149
146
  at = 0;
@@ -153,13 +150,13 @@ class TrackParser {
153
150
  rest() {
154
151
  return this.text.slice(this.at);
155
152
  }
156
- /** Skips spaces; whether anything is left. */
153
+ /** Skips spaces and returns whether anything is left. */
157
154
  skipSpaces() {
158
155
  while (this.rest().startsWith(" "))
159
156
  this.at += 1;
160
157
  return this.rest().length > 0;
161
158
  }
162
- /** The next token: up to a space, a comma or a parenthesis. */
159
+ /** Reads up to a space, comma or parenthesis. */
163
160
  token() {
164
161
  const rest = this.rest();
165
162
  const match = /[ ,()]/.exec(rest);
@@ -270,7 +267,7 @@ class TrackParser {
270
267
  return ok({ kind: "repeat", count, tracks });
271
268
  }
272
269
  }
273
- /** A grid track list (`TrackList`), from its CSS string. */
270
+ /** Parses a grid `TrackList`. */
274
271
  export function parseTrackList(text) {
275
272
  const parser = new TrackParser(text);
276
273
  const components = [];
@@ -303,7 +300,7 @@ function invalidLine(text) {
303
300
  ? `named grid lines are not supported: "${trimmed}"`
304
301
  : `invalid grid line "${trimmed}": write a line number, "span <n>", or "auto"`;
305
302
  }
306
- /** An i16, as a CSS integer: digits with an optional minus. */
303
+ /** Parses an i16 written as a CSS integer. */
307
304
  function gridInteger(word) {
308
305
  if (!/^-?\d+$/.test(word))
309
306
  return undefined;
@@ -326,7 +323,7 @@ function parseEdge(text) {
326
323
  }
327
324
  return undefined;
328
325
  }
329
- /** Where a grid item lies on one axis (`GridPlacement`), from a line number or its CSS string. */
326
+ /** Parses a `GridPlacement` from a line number or its CSS string. */
330
327
  export function parsePlacement(value) {
331
328
  if (typeof value === "number") {
332
329
  return Number.isInteger(value) && value >= -32768 && value <= 32767
@@ -349,7 +346,7 @@ export function parsePlacement(value) {
349
346
  ? refused(invalidLine(end))
350
347
  : ok({ start: first, end: second });
351
348
  }
352
- /** The color a CSS hex string names (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), as 32-bit floats. */
349
+ /** Parses `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` into f32 components. */
353
350
  export function parseHex(text) {
354
351
  const digits = text.startsWith("#") ? text.slice(1) : undefined;
355
352
  if (digits === undefined ||