@fideus-labs/ngff-zarr 0.17.0 → 0.19.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 (81) hide show
  1. package/esm/browser-mod.d.ts +6 -5
  2. package/esm/browser-mod.d.ts.map +1 -1
  3. package/esm/browser-mod.js +5 -4
  4. package/esm/browser-mod.js.map +1 -1
  5. package/esm/io/from_ngff_zarr-browser.d.ts +8 -4
  6. package/esm/io/from_ngff_zarr-browser.d.ts.map +1 -1
  7. package/esm/io/from_ngff_zarr-browser.js +6 -4
  8. package/esm/io/from_ngff_zarr-browser.js.map +1 -1
  9. package/esm/io/from_ngff_zarr.d.ts +7 -3
  10. package/esm/io/from_ngff_zarr.d.ts.map +1 -1
  11. package/esm/io/from_ngff_zarr.js +5 -3
  12. package/esm/io/from_ngff_zarr.js.map +1 -1
  13. package/esm/io/hcs.d.ts.map +1 -1
  14. package/esm/io/hcs.js +11 -3
  15. package/esm/io/hcs.js.map +1 -1
  16. package/esm/io/to_ngff_zarr-browser.d.ts +24 -7
  17. package/esm/io/to_ngff_zarr-browser.d.ts.map +1 -1
  18. package/esm/io/to_ngff_zarr-browser.js +18 -10
  19. package/esm/io/to_ngff_zarr-browser.js.map +1 -1
  20. package/esm/io/to_ngff_zarr.d.ts +30 -13
  21. package/esm/io/to_ngff_zarr.d.ts.map +1 -1
  22. package/esm/io/to_ngff_zarr.js +30 -23
  23. package/esm/io/to_ngff_zarr.js.map +1 -1
  24. package/esm/io/to_ngff_zarr_ozx_common.d.ts +8 -8
  25. package/esm/io/to_ngff_zarr_ozx_common.d.ts.map +1 -1
  26. package/esm/io/to_ngff_zarr_ozx_common.js +5 -5
  27. package/esm/io/to_ngff_zarr_ozx_common.js.map +1 -1
  28. package/esm/mod.d.ts +4 -3
  29. package/esm/mod.d.ts.map +1 -1
  30. package/esm/mod.js +3 -2
  31. package/esm/mod.js.map +1 -1
  32. package/esm/process/to_multiscales-browser.d.ts +3 -3
  33. package/esm/process/to_multiscales-browser.d.ts.map +1 -1
  34. package/esm/process/to_multiscales-browser.js +1 -1
  35. package/esm/process/to_multiscales-node.d.ts +3 -3
  36. package/esm/process/to_multiscales-node.d.ts.map +1 -1
  37. package/esm/process/to_multiscales-node.js +1 -1
  38. package/esm/process/to_multiscales-shared.d.ts +3 -3
  39. package/esm/process/to_multiscales-shared.d.ts.map +1 -1
  40. package/esm/process/to_multiscales-shared.js +3 -3
  41. package/esm/process/to_multiscales-shared.js.map +1 -1
  42. package/esm/schemas/multiscales.d.ts +2 -1
  43. package/esm/schemas/multiscales.d.ts.map +1 -1
  44. package/esm/schemas/multiscales.js +3 -1
  45. package/esm/schemas/multiscales.js.map +1 -1
  46. package/esm/types/hcs.d.ts +10 -3
  47. package/esm/types/hcs.d.ts.map +1 -1
  48. package/esm/types/hcs.js +19 -6
  49. package/esm/types/hcs.js.map +1 -1
  50. package/esm/types/multiscales.d.ts +6 -3
  51. package/esm/types/multiscales.d.ts.map +1 -1
  52. package/esm/types/multiscales.js +3 -2
  53. package/esm/types/multiscales.js.map +1 -1
  54. package/esm/utils/codecs.d.ts +27 -0
  55. package/esm/utils/codecs.d.ts.map +1 -1
  56. package/esm/utils/codecs.js +84 -0
  57. package/esm/utils/codecs.js.map +1 -1
  58. package/esm/utils/compute_omero.d.ts +4 -4
  59. package/esm/utils/compute_omero.d.ts.map +1 -1
  60. package/esm/utils/compute_omero.js +3 -3
  61. package/esm/utils/compute_omero.js.map +1 -1
  62. package/esm/utils/factory.d.ts +3 -2
  63. package/esm/utils/factory.d.ts.map +1 -1
  64. package/esm/utils/factory.js +5 -3
  65. package/esm/utils/factory.js.map +1 -1
  66. package/esm/utils/from_zarr_attrs.d.ts.map +1 -1
  67. package/esm/utils/from_zarr_attrs.js +40 -0
  68. package/esm/utils/from_zarr_attrs.js.map +1 -1
  69. package/esm/utils/py_format.d.ts +18 -0
  70. package/esm/utils/py_format.d.ts.map +1 -0
  71. package/esm/utils/py_format.js +22 -0
  72. package/esm/utils/py_format.js.map +1 -0
  73. package/esm/utils/rfc4_validation.d.ts +8 -0
  74. package/esm/utils/rfc4_validation.d.ts.map +1 -1
  75. package/esm/utils/rfc4_validation.js +13 -2
  76. package/esm/utils/rfc4_validation.js.map +1 -1
  77. package/esm/utils/structural_validation.d.ts +379 -0
  78. package/esm/utils/structural_validation.d.ts.map +1 -0
  79. package/esm/utils/structural_validation.js +739 -0
  80. package/esm/utils/structural_validation.js.map +1 -0
  81. package/package.json +1 -1
@@ -0,0 +1,739 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) Fideus Labs LLC
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * Structural validation for OME-Zarr v0.4 image/multiscales metadata.
5
+ *
6
+ * Where the Zod schema validation in {@link validateMetadata} answers "is this
7
+ * shaped like OME-Zarr?", the rules in this module answer "does this obey the
8
+ * specification's structural invariants?" -- axis counts, axis ordering,
9
+ * coordinate-transformation arity, finest-to-coarsest dataset ordering, and
10
+ * OMERO channel color format. These are spec MUSTs that a JSON Schema cannot
11
+ * express.
12
+ *
13
+ * Each rule is identified by a stable, kebab-case {@link SpecRule} value that is
14
+ * part of the observable surface: the identifiers, their evaluation order, and
15
+ * the dotted-segment location strings are kept byte-for-byte identical to the
16
+ * package's Python implementation so the two stay in lockstep (a property the
17
+ * cross-language parity tests assert). Rules fail fast -- the orchestrator
18
+ * throws a {@link ValidationError} on the first violation, in canonical
19
+ * specification order.
20
+ *
21
+ * This module provides the image/multiscales rule surface -- including the
22
+ * RFC 4 anatomical-orientation checks -- plus the HCS plate/well rules, which
23
+ * operate on separate metadata objects and are dispatched by the companion
24
+ * {@link validatePlate} and {@link validateWell} entry points.
25
+ */
26
+ import { validateColor, } from "../types/zarr_metadata.js";
27
+ import { hasRfc4OrientationMetadata, validateRfc4Orientation, } from "./rfc4_validation.js";
28
+ import { formatNameList } from "./py_format.js";
29
+ /**
30
+ * Stable, kebab-case identifiers for the structural specification rules.
31
+ *
32
+ * The string values are the observable surface -- they appear in
33
+ * {@link ValidationError.rule}, logs, and tests -- and must match the package's
34
+ * Python implementation exactly. Members are listed in canonical
35
+ * specification-MUST evaluation order.
36
+ */
37
+ export const SpecRule = {
38
+ /** Axis count within the v0.4 range of 2..5 inclusive. */
39
+ AxisCount: "axis-count",
40
+ /** At most one `time` axis and at most one `channel` axis. */
41
+ AxisType: "axis-type",
42
+ /** time before channel before space; spatial names suffix (z, y, x). */
43
+ AxisOrder: "axis-order",
44
+ /** Every scale/translation vector length equals the axis count. */
45
+ ScaleLengthMismatch: "scale-length-mismatch",
46
+ /** Exactly one scale per dataset; a translation must follow it. */
47
+ GlobalCoordTransformAfterPerLevel: "global-coord-transform-after-per-level",
48
+ /** Datasets ordered finest to coarsest; spatial scale must not shrink. */
49
+ DatasetOrderHighestToLowest: "dataset-order-highest-to-lowest",
50
+ /** Each OMERO channel color is exactly six hexadecimal digits. */
51
+ OmeroChannelColorFormat: "omero-channel-color-format",
52
+ /** All spatial-axis RFC 4 orientations share one `type`. */
53
+ AxisOrientationConsistentType: "axis-orientation-consistent-type",
54
+ /** If any spatial axis declares an orientation, all spatial axes do. */
55
+ AxisOrientationCompleteness: "axis-orientation-completeness",
56
+ /** Each well's rowIndex/columnIndex agrees with the row/column in its path. */
57
+ PlateRowIndexConsistency: "plate-row-index-consistency",
58
+ /** Each well image references an acquisition when the plate declares many. */
59
+ WellAcquisitionMissing: "well-acquisition-missing",
60
+ };
61
+ /**
62
+ * How much validation {@link validateStructural} performs.
63
+ *
64
+ * `"strict"` is the default and runs every structural image/multiscales rule.
65
+ * `"schema_only"` skips them -- schema validation is the separate concern of
66
+ * {@link validateMetadata}, which checks the raw attributes via Zod.
67
+ */
68
+ export const ValidationLevel = {
69
+ /** Skip structural rules; rely on Zod schema validation only. */
70
+ SchemaOnly: "schema_only",
71
+ /** Run every structural image/multiscales rule (the default). */
72
+ Strict: "strict",
73
+ };
74
+ /**
75
+ * Raised when a structural specification rule is violated.
76
+ *
77
+ * Carries the offending {@link SpecRule} and an optional `location` identifying
78
+ * the offending metadata node in dotted-segment (JSON-Pointer-style) form, e.g.
79
+ * `multiscales[0].datasets[2].coordinateTransformations[0]`. The `message` is
80
+ * formatted as `Spec rule [<rule>] violated: <message>`.
81
+ */
82
+ export class ValidationError extends Error {
83
+ /** The structural rule that was violated. */
84
+ rule;
85
+ /** Dotted-segment location of the offending metadata node, if known. */
86
+ location;
87
+ constructor(rule, message, location) {
88
+ super(`Spec rule [${rule}] violated: ${message}`);
89
+ this.name = "ValidationError";
90
+ this.rule = rule;
91
+ if (location !== undefined) {
92
+ this.location = location;
93
+ }
94
+ }
95
+ }
96
+ /**
97
+ * Check one coordinate transform's vector length against the axis count.
98
+ *
99
+ * Centralizes the length invariant shared by the global and per-dataset
100
+ * coordinate-transformation checks (see {@link SpecRule.ScaleLengthMismatch}),
101
+ * so the rule lives in one place. Transforms that carry no length-bearing
102
+ * vector are ignored.
103
+ *
104
+ * @param transform - The coordinate transform to inspect.
105
+ * @param axesLen - The expected vector length (the axis count).
106
+ * @returns `["scale", actual]` or `["translation", actual]` when the
107
+ * transform's vector length disagrees with `axesLen`; otherwise `null`.
108
+ */
109
+ function transformLenMismatch(transform, axesLen) {
110
+ if (transform.type === "scale") {
111
+ const actual = transform.scale.length;
112
+ if (actual !== axesLen) {
113
+ return ["scale", actual];
114
+ }
115
+ }
116
+ else if (transform.type === "translation") {
117
+ const actual = transform.translation.length;
118
+ if (actual !== axesLen) {
119
+ return ["translation", actual];
120
+ }
121
+ }
122
+ return null;
123
+ }
124
+ /**
125
+ * Return the first `scale` vector in a dataset, or `null` if none is present.
126
+ *
127
+ * Lets {@link validateDatasetOrder} compare adjacent multiscale levels without
128
+ * re-deriving the per-dataset `scale` lookup.
129
+ *
130
+ * @param dataset - The dataset whose coordinate transforms are scanned.
131
+ * @returns The first `scale` transform's vector, or `null` when the dataset
132
+ * declares no `scale` transform.
133
+ */
134
+ function firstScaleVector(dataset) {
135
+ for (const transform of dataset.coordinateTransformations) {
136
+ if (transform.type === "scale") {
137
+ return transform.scale;
138
+ }
139
+ }
140
+ return null;
141
+ }
142
+ /**
143
+ * Class-ordering rank for axis types: a `time` axis must precede a `channel`
144
+ * axis, which must precede any `space` axis. Lower rank must never follow
145
+ * higher rank (see {@link validateAxisOrder}). Axis types absent from this map
146
+ * (e.g. `array`) carry no rank, so a pair involving one is skipped -- mirroring
147
+ * the Python implementation's `dict.get(...) is None` handling.
148
+ */
149
+ const AXIS_TYPE_RANK = {
150
+ time: 0,
151
+ channel: 1,
152
+ space: 2,
153
+ };
154
+ /**
155
+ * Spatial axis names in canonical order. A valid set of `space` axis names is
156
+ * the matching-length suffix of this tuple: 1 -> `["x"]`, 2 -> `["y", "x"]`,
157
+ * 3 -> `["z", "y", "x"]` (see {@link validateSpatialAxisOrder}).
158
+ */
159
+ const SPATIAL_AXIS_NAMES = ["z", "y", "x"];
160
+ /**
161
+ * Render a number the way Python's `str()`/f-string renders a `float`: a
162
+ * whole-number value keeps a trailing `.0` (e.g. `2` -> `"2.0"`), matching the
163
+ * `list[float]` scale vectors the Python port interpolates into the
164
+ * dataset-order message. Non-integer scale ratios (e.g. `1.5`) already render
165
+ * identically across both languages, so they pass through unchanged. This keeps
166
+ * the message byte-for-byte identical to Python for the whole-number
167
+ * downsampling ratios OME-Zarr writers (including this package) emit to disk.
168
+ */
169
+ function pyFloat(value) {
170
+ return Number.isInteger(value) ? `${value}.0` : `${value}`;
171
+ }
172
+ /**
173
+ * Validate that the axis count is within the v0.4-permitted range.
174
+ *
175
+ * OME-Zarr v0.4 requires between 2 and 5 axes, inclusive.
176
+ *
177
+ * @param metadata - The parsed multiscales metadata to validate.
178
+ * @throws {ValidationError} With {@link SpecRule.AxisCount} when
179
+ * `metadata.axes.length` lies outside `2..5`; location `multiscales[0].axes`.
180
+ */
181
+ export function validateAxisCount(metadata) {
182
+ const count = metadata.axes.length;
183
+ if (count < 2 || count > 5) {
184
+ throw new ValidationError(SpecRule.AxisCount, `OME-Zarr v0.4 requires between 2 and 5 axes, inclusive; found ${count}.`, "multiscales[0].axes");
185
+ }
186
+ }
187
+ /**
188
+ * Validate axis-type multiplicity.
189
+ *
190
+ * At most one `time` axis and at most one `channel` axis may be present.
191
+ *
192
+ * @param metadata - The parsed multiscales metadata to validate.
193
+ * @throws {ValidationError} With {@link SpecRule.AxisType} when more than one
194
+ * `time` axis or more than one `channel` axis is present; location
195
+ * `multiscales[0].axes`.
196
+ */
197
+ export function validateAxisType(metadata) {
198
+ const timeCount = metadata.axes.filter((ax) => ax.type === "time").length;
199
+ if (timeCount > 1) {
200
+ throw new ValidationError(SpecRule.AxisType, `At most one 'time' axis is permitted; found ${timeCount}.`, "multiscales[0].axes");
201
+ }
202
+ const channelCount = metadata.axes.filter((ax) => ax.type === "channel").length;
203
+ if (channelCount > 1) {
204
+ throw new ValidationError(SpecRule.AxisType, `At most one 'channel' axis is permitted; found ${channelCount}.`, "multiscales[0].axes");
205
+ }
206
+ }
207
+ /**
208
+ * Validate the class ordering of axes.
209
+ *
210
+ * Axes are ranked by type (`time` < `channel` < `space`) and must be listed in
211
+ * non-decreasing rank order: every `time` axis precedes every `channel` axis,
212
+ * which precedes every `space` axis. The first adjacent pair that inverts this
213
+ * ranking is reported. Pairs involving an axis type with no rank (e.g. `array`)
214
+ * are skipped.
215
+ *
216
+ * @param metadata - The parsed multiscales metadata to validate.
217
+ * @throws {ValidationError} With {@link SpecRule.AxisOrder} for the first
218
+ * adjacent pair where a lower-ranked axis type follows a higher-ranked one;
219
+ * location `multiscales[0].axes[i+1]`.
220
+ */
221
+ export function validateAxisOrder(metadata) {
222
+ const axes = metadata.axes;
223
+ for (let i = 0; i < axes.length - 1; i++) {
224
+ const current = axes[i];
225
+ const following = axes[i + 1];
226
+ const currentRank = AXIS_TYPE_RANK[current.type];
227
+ const followingRank = AXIS_TYPE_RANK[following.type];
228
+ if (currentRank === undefined || followingRank === undefined) {
229
+ continue;
230
+ }
231
+ if (followingRank < currentRank) {
232
+ throw new ValidationError(SpecRule.AxisOrder, `Axis '${following.name}' of type '${following.type}' must not ` +
233
+ `follow axis '${current.name}' of type '${current.type}'; axes ` +
234
+ `must be ordered time, then channel, then space.`, `multiscales[0].axes[${i + 1}]`);
235
+ }
236
+ }
237
+ }
238
+ /**
239
+ * Validate the count and names of spatial axes.
240
+ *
241
+ * The `space` axes, taken in order, must be the matching-length suffix of
242
+ * `(z, y, x)`: one spatial axis must be `(x)`, two must be `(y, x)`, and three
243
+ * must be `(z, y, x)`. At most three `space` axes are permitted.
244
+ *
245
+ * @param metadata - The parsed multiscales metadata to validate.
246
+ * @throws {ValidationError} With {@link SpecRule.AxisOrder} when there are more
247
+ * than three `space` axes, or when their names are not the expected suffix of
248
+ * `(z, y, x)`; location `multiscales[0].axes` or the first offending axis.
249
+ */
250
+ export function validateSpatialAxisOrder(metadata) {
251
+ const spaceIndices = [];
252
+ metadata.axes.forEach((ax, i) => {
253
+ if (ax.type === "space") {
254
+ spaceIndices.push(i);
255
+ }
256
+ });
257
+ const count = spaceIndices.length;
258
+ if (count > 3) {
259
+ throw new ValidationError(SpecRule.AxisOrder, `OME-Zarr v0.4 permits at most 3 'space' axes; found ${count}.`, "multiscales[0].axes");
260
+ }
261
+ const expected = SPATIAL_AXIS_NAMES.slice(SPATIAL_AXIS_NAMES.length - count);
262
+ const actual = spaceIndices.map((i) => metadata.axes[i].name);
263
+ const mismatch = actual.findIndex((name, j) => name !== expected[j]);
264
+ if (mismatch !== -1) {
265
+ throw new ValidationError(SpecRule.AxisOrder, `Spatial axis names ${formatNameList(actual)} must be the ` +
266
+ `length-${count} suffix of (z, y, x): ${formatNameList(expected)}.`, `multiscales[0].axes[${spaceIndices[mismatch]}]`);
267
+ }
268
+ }
269
+ /**
270
+ * Validate that each dataset defines exactly one `scale` transform.
271
+ *
272
+ * Every dataset's `coordinateTransformations` must contain exactly one `scale`
273
+ * (the per-level voxel size). This shares the per-dataset
274
+ * coordinate-transform-shape rule identifier
275
+ * ({@link SpecRule.GlobalCoordTransformAfterPerLevel}); there is no dedicated
276
+ * identifier for the scale count.
277
+ *
278
+ * @param metadata - The parsed multiscales metadata to validate.
279
+ * @throws {ValidationError} With
280
+ * {@link SpecRule.GlobalCoordTransformAfterPerLevel} when a dataset has zero or
281
+ * more than one `scale` transform; location
282
+ * `multiscales[0].datasets[i].coordinateTransformations`.
283
+ */
284
+ export function validatePerDatasetScaleCount(metadata) {
285
+ for (let i = 0; i < metadata.datasets.length; i++) {
286
+ const dataset = metadata.datasets[i];
287
+ const scaleCount = dataset.coordinateTransformations.filter((t) => t.type === "scale").length;
288
+ if (scaleCount !== 1) {
289
+ throw new ValidationError(SpecRule.GlobalCoordTransformAfterPerLevel, `Each dataset must define exactly one 'scale' coordinate ` +
290
+ `transformation; dataset ${i} has ${scaleCount}.`, `multiscales[0].datasets[${i}].coordinateTransformations`);
291
+ }
292
+ }
293
+ }
294
+ /**
295
+ * Validate coordinate-transform vector lengths against the axis count.
296
+ *
297
+ * Every `scale` and `translation` vector -- in the global
298
+ * `coordinateTransformations` (if present) and in each dataset -- must have
299
+ * exactly one entry per axis. The first mismatch, scanned
300
+ * global-then-per-dataset, is reported. The length invariant itself lives in
301
+ * {@link transformLenMismatch}.
302
+ *
303
+ * @param metadata - The parsed multiscales metadata to validate.
304
+ * @throws {ValidationError} With {@link SpecRule.ScaleLengthMismatch} for the
305
+ * first transform whose vector length disagrees with `metadata.axes.length`;
306
+ * location identifies the offending transform.
307
+ */
308
+ export function validateScaleLength(metadata) {
309
+ const axesLen = metadata.axes.length;
310
+ const globalTransforms = metadata.coordinateTransformations;
311
+ if (globalTransforms) {
312
+ for (let j = 0; j < globalTransforms.length; j++) {
313
+ const mismatch = transformLenMismatch(globalTransforms[j], axesLen);
314
+ if (mismatch !== null) {
315
+ const [kind, actualLen] = mismatch;
316
+ throw new ValidationError(SpecRule.ScaleLengthMismatch, `Global '${kind}' transform has length ${actualLen}, but ` +
317
+ `there are ${axesLen} axes; lengths must match.`, `multiscales[0].coordinateTransformations[${j}]`);
318
+ }
319
+ }
320
+ }
321
+ for (let i = 0; i < metadata.datasets.length; i++) {
322
+ const dataset = metadata.datasets[i];
323
+ for (let j = 0; j < dataset.coordinateTransformations.length; j++) {
324
+ const mismatch = transformLenMismatch(dataset.coordinateTransformations[j], axesLen);
325
+ if (mismatch !== null) {
326
+ const [kind, actualLen] = mismatch;
327
+ throw new ValidationError(SpecRule.ScaleLengthMismatch, `Dataset ${i} '${kind}' transform has length ${actualLen}, ` +
328
+ `but there are ${axesLen} axes; lengths must match.`, `multiscales[0].datasets[${i}].coordinateTransformations[${j}]`);
329
+ }
330
+ }
331
+ }
332
+ }
333
+ /**
334
+ * Validate coordinate-transform ordering within each dataset.
335
+ *
336
+ * Within a dataset's `coordinateTransformations`, a `translation` (if present)
337
+ * must follow its `scale` -- a `scale` must never appear after a `translation`.
338
+ *
339
+ * @param metadata - The parsed multiscales metadata to validate.
340
+ * @throws {ValidationError} With
341
+ * {@link SpecRule.GlobalCoordTransformAfterPerLevel} for the first dataset
342
+ * where a `scale` follows a `translation`; location identifies the offending
343
+ * `scale`.
344
+ */
345
+ export function validateTransformOrder(metadata) {
346
+ for (let i = 0; i < metadata.datasets.length; i++) {
347
+ const dataset = metadata.datasets[i];
348
+ let seenTranslation = false;
349
+ for (let j = 0; j < dataset.coordinateTransformations.length; j++) {
350
+ const transform = dataset.coordinateTransformations[j];
351
+ if (transform.type === "translation") {
352
+ seenTranslation = true;
353
+ }
354
+ else if (transform.type === "scale" && seenTranslation) {
355
+ throw new ValidationError(SpecRule.GlobalCoordTransformAfterPerLevel, `In dataset ${i}, a 'scale' transform must not follow a ` +
356
+ `'translation'; a translation must follow its scale.`, `multiscales[0].datasets[${i}].coordinateTransformations[${j}]`);
357
+ }
358
+ }
359
+ }
360
+ }
361
+ /**
362
+ * Validate that datasets are ordered finest to coarsest.
363
+ *
364
+ * Multiscale datasets must be listed from highest resolution (finest, i.e.
365
+ * smallest spatial `scale`) to lowest (coarsest). For each adjacent pair, the
366
+ * later level's `scale` must not be smaller than the earlier level's on any
367
+ * `space` axis. Pairs whose `scale` vectors are missing or too short to index a
368
+ * spatial axis are skipped -- those shapes are the concern of
369
+ * {@link validatePerDatasetScaleCount} and {@link validateScaleLength} -- so
370
+ * this rule never indexes out of bounds.
371
+ *
372
+ * @param metadata - The parsed multiscales metadata to validate.
373
+ * @throws {ValidationError} With {@link SpecRule.DatasetOrderHighestToLowest}
374
+ * for the first adjacent pair whose later (coarser) level has a smaller spatial
375
+ * scale; location `multiscales[0].datasets[i+1]`.
376
+ */
377
+ export function validateDatasetOrder(metadata) {
378
+ const spaceIndices = [];
379
+ metadata.axes.forEach((ax, i) => {
380
+ if (ax.type === "space") {
381
+ spaceIndices.push(i);
382
+ }
383
+ });
384
+ const datasets = metadata.datasets;
385
+ for (let i = 0; i < datasets.length - 1; i++) {
386
+ const finer = firstScaleVector(datasets[i]);
387
+ const coarser = firstScaleVector(datasets[i + 1]);
388
+ if (finer === null || coarser === null) {
389
+ continue;
390
+ }
391
+ for (const axisIndex of spaceIndices) {
392
+ if (axisIndex >= finer.length || axisIndex >= coarser.length) {
393
+ // Scale too short to compare this axis: another rule's concern.
394
+ // Skip so we never index out of bounds here.
395
+ continue;
396
+ }
397
+ if (coarser[axisIndex] < finer[axisIndex]) {
398
+ const axisName = metadata.axes[axisIndex].name;
399
+ throw new ValidationError(SpecRule.DatasetOrderHighestToLowest, `Datasets must be ordered finest to coarsest; dataset ` +
400
+ `${i + 1} has spatial scale ${pyFloat(coarser[axisIndex])} ` +
401
+ `on axis '${axisName}', smaller than dataset ${i}'s ` +
402
+ `${pyFloat(finer[axisIndex])}.`, `multiscales[0].datasets[${i + 1}]`);
403
+ }
404
+ }
405
+ }
406
+ }
407
+ /**
408
+ * Validate the color format of each OMERO channel.
409
+ *
410
+ * When OMERO rendering metadata is present, every channel `color` must be
411
+ * exactly six hexadecimal digits (RGB). This reuses the package's existing
412
+ * {@link validateColor} predicate rather than re-implementing the format check,
413
+ * surfacing its failure message through the unified {@link ValidationError}
414
+ * channel.
415
+ *
416
+ * @param metadata - The parsed multiscales metadata to validate.
417
+ * @throws {ValidationError} With {@link SpecRule.OmeroChannelColorFormat} for
418
+ * the first channel whose `color` is not six hex digits; location
419
+ * `multiscales[0].omero.channels[i].color`.
420
+ */
421
+ export function validateOmeroColorHex(metadata) {
422
+ const omero = metadata.omero;
423
+ if (omero === undefined) {
424
+ return;
425
+ }
426
+ for (let i = 0; i < omero.channels.length; i++) {
427
+ try {
428
+ validateColor(omero.channels[i].color);
429
+ }
430
+ catch (error) {
431
+ throw new ValidationError(SpecRule.OmeroChannelColorFormat, error instanceof Error ? error.message : String(error), `multiscales[0].omero.channels[${i}].color`);
432
+ }
433
+ }
434
+ }
435
+ /**
436
+ * Render a parsed {@link Axis} back to the record form the RFC 4 helpers
437
+ * consume.
438
+ *
439
+ * Emits only the fields the RFC 4 helpers inspect -- `name`, `type`, and (for a
440
+ * spatial axis that declares it) `orientation` as a `{ type, value }` record. A
441
+ * stored `orientation` may be the serialized {@link AxisOrientation} form or
442
+ * an {@link AnatomicalOrientation}; both already expose a string `type` and
443
+ * `value`, so the record is built directly without further coercion.
444
+ *
445
+ * @param axis - The parsed axis to render.
446
+ * @returns A plain record carrying `name`, `type`, and, when present,
447
+ * `orientation`.
448
+ */
449
+ function axisToValidationRecord(axis) {
450
+ const record = {
451
+ name: axis.name,
452
+ type: axis.type,
453
+ };
454
+ const orientation = axis.orientation;
455
+ if (orientation !== undefined && orientation !== null) {
456
+ record.orientation = {
457
+ type: orientation.type,
458
+ value: orientation.value,
459
+ };
460
+ }
461
+ return record;
462
+ }
463
+ /**
464
+ * Validate RFC 4 anatomical-orientation metadata on the spatial axes.
465
+ *
466
+ * This rule does not reimplement RFC 4; it wraps the package's existing
467
+ * logic -- {@link hasRfc4OrientationMetadata} and
468
+ * {@link validateRfc4Orientation} -- and surfaces its failures through the
469
+ * unified {@link ValidationError} channel. The parsed {@link Axis} objects are
470
+ * first rendered back to the record form those helpers expect (see
471
+ * {@link axisToValidationRecord}).
472
+ *
473
+ * Orientation is optional in RFC 4, so when no spatial axis carries it the rule
474
+ * is a no-op.
475
+ *
476
+ * @param metadata - The parsed multiscales metadata to validate.
477
+ * @throws {ValidationError} With {@link SpecRule.AxisOrientationConsistentType}
478
+ * when the spatial axes' orientations do not all share one `type`, or
479
+ * {@link SpecRule.AxisOrientationCompleteness} when orientation is defined for
480
+ * some but not all spatial axes; location `multiscales[0].axes`. The original
481
+ * RFC 4 message text is preserved. Any other failure from
482
+ * {@link validateRfc4Orientation} -- e.g. an orientation value outside the
483
+ * RFC 4 vocabulary, a schema-level concern with no dedicated structural rule
484
+ * -- propagates unchanged.
485
+ */
486
+ export function validateAxisOrientation(metadata) {
487
+ const axesRecords = metadata.axes.map(axisToValidationRecord);
488
+ if (!hasRfc4OrientationMetadata(axesRecords)) {
489
+ return;
490
+ }
491
+ try {
492
+ validateRfc4Orientation(axesRecords);
493
+ }
494
+ catch (error) {
495
+ // validateRfc4Orientation throws exactly two messages this rule maps: a
496
+ // spatial-orientation "same type" mismatch and the all-or-none completeness
497
+ // failure. An out-of-vocabulary orientation value -- a schema-level concern
498
+ // with no dedicated structural rule -- carries neither marker and so
499
+ // propagates unchanged, matching the package's Python implementation.
500
+ //
501
+ // The "same type" / "all spatial axes" substrings below are a load-bearing
502
+ // contract with validateRfc4Orientation's message text: an unrecognized
503
+ // error falls through to the final `throw` and surfaces as a plain Error
504
+ // rather than a ValidationError. The message-stability test in
505
+ // structural_validation_orientation_test.ts pins both markers so editing
506
+ // that wording fails CI loudly instead of silently breaking this mapping.
507
+ const message = error instanceof Error ? error.message : String(error);
508
+ if (message.includes("same type")) {
509
+ throw new ValidationError(SpecRule.AxisOrientationConsistentType, message, "multiscales[0].axes");
510
+ }
511
+ if (message.includes("all spatial axes")) {
512
+ throw new ValidationError(SpecRule.AxisOrientationCompleteness, message, "multiscales[0].axes");
513
+ }
514
+ throw error;
515
+ }
516
+ }
517
+ /**
518
+ * Render a string as Python's `repr()` renders it, for byte-identical messages.
519
+ *
520
+ * The plate/well rule messages interpolate row, column, and well-path strings
521
+ * the way the Python implementation does with `{value!r}`: a single-quoted
522
+ * literal, switching to double quotes only when the value contains a single
523
+ * quote but no double quote. Keeping this byte-for-byte identical to Python is a
524
+ * property the cross-language parity tests assert. Inputs reaching these rules
525
+ * are alphanumeric path segments, so this resolves to a plain single-quoted
526
+ * form in practice.
527
+ */
528
+ function pyRepr(value) {
529
+ const quote = value.includes("'") && !value.includes('"') ? '"' : "'";
530
+ const escaped = value.replaceAll("\\", "\\\\").replaceAll(quote, `\\${quote}`);
531
+ return `${quote}${escaped}${quote}`;
532
+ }
533
+ /**
534
+ * Validate each plate well's recorded indices against its `path`.
535
+ *
536
+ * Every `PlateWell` records a `path` of the form `"<row>/<column>"` (e.g.
537
+ * `"B/03"`) alongside numeric `rowIndex` and `columnIndex` fields. OME-Zarr v0.4
538
+ * requires these to agree: the row segment must name an entry in `plate.rows`
539
+ * whose position equals `rowIndex`, and the column segment must name an entry in
540
+ * `plate.columns` whose position equals `columnIndex`. The first offending well,
541
+ * scanned in order, is reported.
542
+ *
543
+ * @param plate - The plate metadata whose wells are validated.
544
+ * @throws {ValidationError} With {@link SpecRule.PlateRowIndexConsistency} for
545
+ * the first well whose `path` is not `"<row>/<column>"`, whose row/column
546
+ * segment is absent from `plate.rows`/`plate.columns`, or whose recorded
547
+ * `rowIndex`/`columnIndex` disagrees with that segment's position; location
548
+ * `plate.wells[i]`.
549
+ */
550
+ export function validatePlateWellIndexConsistency(plate) {
551
+ const rowIndexByName = new Map();
552
+ plate.rows.forEach((row, i) => rowIndexByName.set(row.name, i));
553
+ const columnIndexByName = new Map();
554
+ plate.columns.forEach((column, i) => columnIndexByName.set(column.name, i));
555
+ for (let i = 0; i < plate.wells.length; i++) {
556
+ const well = plate.wells[i];
557
+ const location = `plate.wells[${i}]`;
558
+ const parts = well.path.split("/");
559
+ if (parts.length !== 2) {
560
+ throw new ValidationError(SpecRule.PlateRowIndexConsistency, `Well path ${pyRepr(well.path)} must have the form '<row>/<column>'.`, location);
561
+ }
562
+ const [rowName, columnName] = parts;
563
+ const expectedRow = rowIndexByName.get(rowName);
564
+ if (expectedRow === undefined) {
565
+ throw new ValidationError(SpecRule.PlateRowIndexConsistency, `Well path ${pyRepr(well.path)} names row ${pyRepr(rowName)}, which ` +
566
+ `is not declared in plate.rows.`, location);
567
+ }
568
+ const expectedColumn = columnIndexByName.get(columnName);
569
+ if (expectedColumn === undefined) {
570
+ throw new ValidationError(SpecRule.PlateRowIndexConsistency, `Well path ${pyRepr(well.path)} names column ${pyRepr(columnName)}, ` +
571
+ `which is not declared in plate.columns.`, location);
572
+ }
573
+ if (well.rowIndex !== expectedRow) {
574
+ throw new ValidationError(SpecRule.PlateRowIndexConsistency, `Well ${pyRepr(well.path)} has rowIndex ${well.rowIndex}, but row ` +
575
+ `${pyRepr(rowName)} is at index ${expectedRow} in plate.rows.`, location);
576
+ }
577
+ if (well.columnIndex !== expectedColumn) {
578
+ throw new ValidationError(SpecRule.PlateRowIndexConsistency, `Well ${pyRepr(well.path)} has columnIndex ${well.columnIndex}, but ` +
579
+ `column ${pyRepr(columnName)} is at index ${expectedColumn} in ` +
580
+ `plate.columns.`, location);
581
+ }
582
+ }
583
+ }
584
+ /**
585
+ * Validate that well images reference an acquisition when required.
586
+ *
587
+ * When a plate declares more than one acquisition, every image in each of its
588
+ * wells must carry an `acquisition` reference so the field can be attributed to
589
+ * a specific acquisition. Plates with zero or one acquisition impose no such
590
+ * requirement, so this rule is a no-op for them. The first image missing its
591
+ * reference, scanned in order, is reported.
592
+ *
593
+ * @param plate - The plate metadata declaring the acquisitions.
594
+ * @param well - The well metadata whose images are validated.
595
+ * @throws {ValidationError} With {@link SpecRule.WellAcquisitionMissing} for the
596
+ * first `WellImage` whose `acquisition` is absent while the plate declares
597
+ * multiple acquisitions; location `well.images[i].acquisition`.
598
+ */
599
+ export function validateWellAcquisition(plate, well) {
600
+ const acquisitions = plate.acquisitions;
601
+ if (acquisitions === undefined || acquisitions.length <= 1) {
602
+ return;
603
+ }
604
+ for (let i = 0; i < well.images.length; i++) {
605
+ const image = well.images[i];
606
+ if (image.acquisition === undefined || image.acquisition === null) {
607
+ throw new ValidationError(SpecRule.WellAcquisitionMissing, `Plate declares ${acquisitions.length} acquisitions, so well ` +
608
+ `image ${i} must reference one via 'acquisition'.`, `well.images[${i}].acquisition`);
609
+ }
610
+ }
611
+ }
612
+ /**
613
+ * Run the structural image/multiscales rules in canonical specification order.
614
+ *
615
+ * Orchestrates the per-rule `validate*` functions in this module. It is
616
+ * fail-fast: the rules run in canonical specification-MUST order and the first
617
+ * {@link ValidationError} thrown propagates to the caller -- later rules do not
618
+ * run. The rules run in this order:
619
+ *
620
+ * 1. {@link validateAxisCount}
621
+ * 2. {@link validateAxisType}
622
+ * 3. {@link validateAxisOrder}
623
+ * 4. {@link validateSpatialAxisOrder}
624
+ * 5. {@link validatePerDatasetScaleCount}
625
+ * 6. {@link validateScaleLength}
626
+ * 7. {@link validateTransformOrder}
627
+ * 8. {@link validateDatasetOrder}
628
+ * 9. {@link validateOmeroColorHex}
629
+ * 10. {@link validateAxisOrientation}
630
+ *
631
+ * Under {@link ValidationLevel.SchemaOnly} this function returns immediately
632
+ * without running any structural rule -- shape/schema validation is the
633
+ * separate concern of {@link validateMetadata}, which checks the raw
634
+ * attributes via Zod. The default level is {@link ValidationLevel.Strict}.
635
+ *
636
+ * This orchestrator covers the image/multiscales rules, including the RFC 4
637
+ * anatomical-orientation checks ({@link validateAxisOrientation}, a no-op when
638
+ * no axis declares orientation). The HCS plate/well structural rules operate on
639
+ * separate metadata objects and are dispatched by the companion
640
+ * {@link validatePlate} and {@link validateWell} entry points.
641
+ *
642
+ * @param metadata - The parsed OME-Zarr v0.4 multiscales metadata to validate.
643
+ * @param options - Validation options; defaults to
644
+ * `{ level: "strict", allowUnknownFields: true }`.
645
+ * @throws {ValidationError} For the first structural rule violated, carrying
646
+ * the offending {@link SpecRule} and `location`. Never thrown under
647
+ * {@link ValidationLevel.SchemaOnly}, which runs no structural rule.
648
+ */
649
+ export function validateStructural(metadata, options) {
650
+ const resolved = {
651
+ level: options?.level ?? ValidationLevel.Strict,
652
+ allowUnknownFields: options?.allowUnknownFields ?? true,
653
+ };
654
+ if (resolved.level === ValidationLevel.SchemaOnly) {
655
+ return;
656
+ }
657
+ validateAxisCount(metadata);
658
+ validateAxisType(metadata);
659
+ validateAxisOrder(metadata);
660
+ validateSpatialAxisOrder(metadata);
661
+ validatePerDatasetScaleCount(metadata);
662
+ validateScaleLength(metadata);
663
+ validateTransformOrder(metadata);
664
+ validateDatasetOrder(metadata);
665
+ validateOmeroColorHex(metadata);
666
+ validateAxisOrientation(metadata);
667
+ }
668
+ /**
669
+ * Run the structural HCS plate rules in canonical specification order.
670
+ *
671
+ * The plate-level counterpart to {@link validateStructural}: it orchestrates
672
+ * the structural rules that operate on a parsed {@link PlateMetadata}. Like its
673
+ * image/multiscales sibling it is fail-fast -- the first {@link ValidationError}
674
+ * thrown propagates to the caller and later rules do not run. The rules run in
675
+ * this order:
676
+ *
677
+ * 1. {@link validatePlateWellIndexConsistency}
678
+ *
679
+ * Per-well image rules (e.g. acquisition references) are the separate concern
680
+ * of {@link validateWell}, called where each well's own metadata is loaded.
681
+ *
682
+ * Under {@link ValidationLevel.SchemaOnly} this function returns immediately
683
+ * without running any structural rule -- shape/schema validation is the
684
+ * separate concern of {@link validateMetadata}, which checks the raw attributes
685
+ * via Zod. The default level is {@link ValidationLevel.Strict}.
686
+ *
687
+ * @param plate - The parsed OME-Zarr v0.4 plate metadata to validate.
688
+ * @param options - Validation options; defaults to
689
+ * `{ level: "strict", allowUnknownFields: true }`.
690
+ * @throws {ValidationError} For the first structural plate rule violated,
691
+ * carrying the offending {@link SpecRule} and `location`. Never thrown under
692
+ * {@link ValidationLevel.SchemaOnly}, which runs no structural rule.
693
+ */
694
+ export function validatePlate(plate, options) {
695
+ const resolved = {
696
+ level: options?.level ?? ValidationLevel.Strict,
697
+ allowUnknownFields: options?.allowUnknownFields ?? true,
698
+ };
699
+ if (resolved.level === ValidationLevel.SchemaOnly) {
700
+ return;
701
+ }
702
+ validatePlateWellIndexConsistency(plate);
703
+ }
704
+ /**
705
+ * Run the structural HCS well rules in canonical specification order.
706
+ *
707
+ * Validates a single {@link WellMetadata} in the context of its parent
708
+ * {@link PlateMetadata} -- the plate's acquisition declarations govern whether
709
+ * each well image must reference an acquisition. Fail-fast, like
710
+ * {@link validateStructural} and {@link validatePlate}. The rules run in this
711
+ * order:
712
+ *
713
+ * 1. {@link validateWellAcquisition}
714
+ *
715
+ * Under {@link ValidationLevel.SchemaOnly} this function returns immediately
716
+ * without running any structural rule -- shape/schema validation is the
717
+ * separate concern of {@link validateMetadata}, which checks the raw attributes
718
+ * via Zod. The default level is {@link ValidationLevel.Strict}.
719
+ *
720
+ * @param plate - The parsed plate metadata that owns `well`; supplies the
721
+ * acquisition context the well rules consult.
722
+ * @param well - The parsed well metadata to validate.
723
+ * @param options - Validation options; defaults to
724
+ * `{ level: "strict", allowUnknownFields: true }`.
725
+ * @throws {ValidationError} For the first structural well rule violated,
726
+ * carrying the offending {@link SpecRule} and `location`. Never thrown under
727
+ * {@link ValidationLevel.SchemaOnly}, which runs no structural rule.
728
+ */
729
+ export function validateWell(plate, well, options) {
730
+ const resolved = {
731
+ level: options?.level ?? ValidationLevel.Strict,
732
+ allowUnknownFields: options?.allowUnknownFields ?? true,
733
+ };
734
+ if (resolved.level === ValidationLevel.SchemaOnly) {
735
+ return;
736
+ }
737
+ validateWellAcquisition(plate, well);
738
+ }
739
+ //# sourceMappingURL=structural_validation.js.map