zarr-metadata 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/codecs.ts ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * The codecs this package interprets — `transpose` and `sharding_indexed` —
3
+ * syntax (configuration types) and semantics together, plus the pipeline
4
+ * walker that threads dimensional context between codecs (mirroring
5
+ * zarr-python's chunk-spec threading): a valid transpose permutes the
6
+ * per-dimension chunk sizes for the codecs after it, and any codec this
7
+ * module cannot reason about — `reshape` may change a chunk's rank, and
8
+ * unknown codecs may do anything — invalidates the dimensional context for
9
+ * the rest of the pipeline instead of letting stale array-level facts
10
+ * produce false verdicts.
11
+ *
12
+ * Other codecs' required fields (blosc, gzip, zstd, ...) are deliberately
13
+ * NOT known here: they are registry-schema facts enforced by schema-driven
14
+ * tooling, and a second hardcoded source of truth would drift.
15
+ */
16
+
17
+ import type { PathedIssue } from "./errors.js";
18
+ import { configurationMissing, fieldParts, isIntArray, type Path } from "./guards.js";
19
+
20
+ /** Configuration of the core `transpose` codec. */
21
+ export interface TransposeCodecConfiguration {
22
+ order: number[];
23
+ }
24
+
25
+ /** Configuration of the core `sharding_indexed` codec. */
26
+ export interface ShardingIndexedCodecConfiguration {
27
+ chunk_shape: number[];
28
+ codecs: unknown[];
29
+ index_codecs: unknown[];
30
+ index_location?: "start" | "end";
31
+ }
32
+
33
+ function isPermutation(order: number[]): boolean {
34
+ const seen = new Set(order);
35
+ return seen.size === order.length && order.every((entry) => entry >= 0 && entry < order.length);
36
+ }
37
+
38
+ /**
39
+ * Walk one codec pipeline. `initialDims` is the array dimensionality at
40
+ * this point (undefined when unknowable); `initialChunkSizes` holds the
41
+ * distinct chunk lengths per dimension this pipeline may encode — what a
42
+ * sharding codec's inner chunks must divide. A regular grid contributes
43
+ * one size per dimension; a rectilinear grid may contribute several.
44
+ */
45
+ export function pipelineIssues(
46
+ pipeline: unknown[],
47
+ path: Path,
48
+ initialDims: number | undefined,
49
+ initialChunkSizes: number[][] | undefined,
50
+ ): PathedIssue[] {
51
+ const issues: PathedIssue[] = [];
52
+ // The dimensional context THREADS through the pipeline: transpose permutes
53
+ // it, and anything this module cannot reason about invalidates it for the
54
+ // remaining codecs.
55
+ let dims = initialDims;
56
+ let chunkSizes = initialChunkSizes;
57
+ const dropContext = (): void => {
58
+ dims = undefined;
59
+ chunkSizes = undefined;
60
+ };
61
+ pipeline.forEach((entry, index) => {
62
+ const parts = fieldParts(entry);
63
+ if (parts === undefined) {
64
+ dropContext(); // structurally invalid entry: no further reasoning
65
+ return;
66
+ }
67
+ const { name, configuration } = parts;
68
+ const configMissing = configurationMissing(entry);
69
+ if (name === "transpose") {
70
+ if (configMissing) {
71
+ issues.push({
72
+ path: [...path, index],
73
+ message: '"transpose" requires a configuration with "order"',
74
+ kind: "missing_key",
75
+ });
76
+ dropContext();
77
+ return;
78
+ }
79
+ if (configuration !== undefined && !Object.hasOwn(configuration, "order")) {
80
+ issues.push({
81
+ path: [...path, index, "configuration", "order"],
82
+ message: "missing required key",
83
+ kind: "missing_key",
84
+ });
85
+ dropContext();
86
+ return;
87
+ }
88
+ const order = configuration?.["order"];
89
+ if (!isIntArray(order)) {
90
+ dropContext(); // shape errors are the schema layer's
91
+ return;
92
+ }
93
+ const orderPath = [...path, index, "configuration", "order"];
94
+ let sound = true;
95
+ if (!isPermutation(order)) {
96
+ sound = false;
97
+ issues.push({
98
+ path: orderPath,
99
+ message: `expected a permutation of the integers 0..${order.length - 1}`,
100
+ kind: "invalid_value",
101
+ });
102
+ }
103
+ if (dims !== undefined && order.length !== dims) {
104
+ sound = false;
105
+ issues.push({
106
+ path: orderPath,
107
+ message: `expected one entry per array dimension (${dims})`,
108
+ kind: "invalid_value",
109
+ });
110
+ }
111
+ if (!sound) {
112
+ dropContext();
113
+ } else if (chunkSizes !== undefined) {
114
+ const sizes = chunkSizes;
115
+ chunkSizes =
116
+ order.length === sizes.length
117
+ ? order.map((axis) => sizes[axis] as number[])
118
+ : undefined;
119
+ }
120
+ } else if (name === "sharding_indexed") {
121
+ if (configMissing) {
122
+ issues.push({
123
+ path: [...path, index],
124
+ message:
125
+ '"sharding_indexed" requires a configuration with "chunk_shape", "codecs", and "index_codecs"',
126
+ kind: "missing_key",
127
+ });
128
+ dropContext();
129
+ return;
130
+ }
131
+ if (configuration !== undefined) {
132
+ for (const key of ["chunk_shape", "codecs", "index_codecs"]) {
133
+ if (!Object.hasOwn(configuration, key)) {
134
+ issues.push({
135
+ path: [...path, index, "configuration", key],
136
+ message: "missing required key",
137
+ kind: "missing_key",
138
+ });
139
+ }
140
+ }
141
+ }
142
+ const chunkShape = configuration?.["chunk_shape"];
143
+ if (!isIntArray(chunkShape)) {
144
+ // Still walk a present inner pipeline (entries deserve their own
145
+ // verdicts) before the context becomes unknowable.
146
+ const inner = configuration?.["codecs"];
147
+ if (Array.isArray(inner)) {
148
+ issues.push(
149
+ ...pipelineIssues(
150
+ inner,
151
+ [...path, index, "configuration", "codecs"],
152
+ undefined,
153
+ undefined,
154
+ ),
155
+ );
156
+ }
157
+ dropContext();
158
+ return;
159
+ }
160
+ const chunkShapePath = [...path, index, "configuration", "chunk_shape"];
161
+ if (dims !== undefined && chunkShape.length !== dims) {
162
+ issues.push({
163
+ path: chunkShapePath,
164
+ message: `expected one length per array dimension (${dims})`,
165
+ kind: "invalid_value",
166
+ });
167
+ } else if (
168
+ chunkSizes !== undefined &&
169
+ chunkShape.length === chunkSizes.length &&
170
+ chunkShape.every((length) => length > 0)
171
+ ) {
172
+ let violation: { axis: number; size: number } | undefined;
173
+ chunkSizes.forEach((sizes, axis) => {
174
+ if (violation !== undefined) return;
175
+ const bad = sizes.find((size) => size % (chunkShape[axis] as number) !== 0);
176
+ if (bad !== undefined) violation = { axis, size: bad };
177
+ });
178
+ if (violation !== undefined) {
179
+ const { axis, size } = violation;
180
+ const sizesNow = chunkSizes;
181
+ const uniform = sizesNow.every((sizes) => sizes.length === 1);
182
+ issues.push({
183
+ path: chunkShapePath,
184
+ message: uniform
185
+ ? `expected ${JSON.stringify(chunkShape)} to evenly divide the outer chunk shape ${JSON.stringify(sizesNow.map((sizes) => sizes[0]))}`
186
+ : `expected ${JSON.stringify(chunkShape)} to evenly divide every chunk size of the grid (dimension ${axis} has chunk size ${size})`,
187
+ kind: "invalid_value",
188
+ });
189
+ }
190
+ }
191
+ const inner = configuration?.["codecs"];
192
+ if (Array.isArray(inner)) {
193
+ issues.push(
194
+ ...pipelineIssues(
195
+ inner,
196
+ [...path, index, "configuration", "codecs"],
197
+ chunkShape.length,
198
+ chunkShape.map((length) => [length]),
199
+ ),
200
+ );
201
+ }
202
+ // index_codecs encode the shard index, whose shape differs from the
203
+ // array's — no dimensional context applies there. After the
204
+ // array -> bytes boundary the dimensional context is spent.
205
+ dropContext();
206
+ } else {
207
+ // A codec this module cannot reason about (reshape may change a
208
+ // chunk's rank; unknown codecs may do anything): stale array-level
209
+ // facts must not judge the codecs after it.
210
+ dropContext();
211
+ }
212
+ });
213
+ return issues;
214
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The core data types this package interprets: fill-value syntax per type,
3
+ * in one place per family. Extension data types are skipped — their shapes
4
+ * are registry-schema facts, and the name space is open.
5
+ */
6
+
7
+ /** A float fill value: a JSON number, a non-finite sentinel, or a hex string. */
8
+ export type FloatFillValue = number | "NaN" | "Infinity" | "-Infinity" | string;
9
+
10
+ /** A complex fill value: `[real, imaginary]`, each a float fill form. */
11
+ export type ComplexFillValue = [FloatFillValue, FloatFillValue];
12
+
13
+ const INT_RANGES: Record<string, readonly [number, number]> = {
14
+ int8: [-128, 127],
15
+ int16: [-32768, 32767],
16
+ int32: [-2147483648, 2147483647],
17
+ int64: [-9223372036854775808, 9223372036854775807],
18
+ uint8: [0, 255],
19
+ uint16: [0, 65535],
20
+ uint32: [0, 4294967295],
21
+ uint64: [0, 18446744073709551615],
22
+ };
23
+
24
+ const FLOAT_HEX_DIGITS: Record<string, number> = {
25
+ float16: 4,
26
+ float32: 8,
27
+ float64: 16,
28
+ };
29
+
30
+ /** Hex digit width of each complex type's component floats. */
31
+ const COMPLEX_COMPONENT_HEX_DIGITS: Record<string, number> = {
32
+ complex64: 8,
33
+ complex128: 16,
34
+ };
35
+
36
+ function isFloatFill(value: unknown, hexDigits: number): boolean {
37
+ if (typeof value === "number") return true;
38
+ if (typeof value !== "string") return false;
39
+ if (value === "NaN" || value === "Infinity" || value === "-Infinity") return true;
40
+ return new RegExp(`^0x[0-9a-fA-F]{${hexDigits}}$`).test(value);
41
+ }
42
+
43
+ function floatFillMessage(name: string, hexDigits: number): string {
44
+ return (
45
+ `expected a number, "NaN", "Infinity", "-Infinity", or a ` +
46
+ `${hexDigits}-hex-digit "0x..." string for data type ${JSON.stringify(name)}`
47
+ );
48
+ }
49
+
50
+ /** The fill_value issue for a KNOWN core data type, if any; undefined otherwise. */
51
+ export function fillValueIssue(dataTypeName: string, fill: unknown): string | undefined {
52
+ if (dataTypeName === "bool") {
53
+ return typeof fill === "boolean"
54
+ ? undefined
55
+ : 'expected a boolean fill value for data type "bool"';
56
+ }
57
+ const intRange = INT_RANGES[dataTypeName];
58
+ if (intRange !== undefined) {
59
+ const [low, high] = intRange;
60
+ return Number.isInteger(fill) && (fill as number) >= low && (fill as number) <= high
61
+ ? undefined
62
+ : `expected an integer in [${low}, ${high}] for data type ${JSON.stringify(dataTypeName)}`;
63
+ }
64
+ const floatDigits = FLOAT_HEX_DIGITS[dataTypeName];
65
+ if (floatDigits !== undefined) {
66
+ return isFloatFill(fill, floatDigits)
67
+ ? undefined
68
+ : floatFillMessage(dataTypeName, floatDigits);
69
+ }
70
+ const complexDigits = COMPLEX_COMPONENT_HEX_DIGITS[dataTypeName];
71
+ if (complexDigits !== undefined) {
72
+ const ok =
73
+ Array.isArray(fill) &&
74
+ fill.length === 2 &&
75
+ fill.every((part) => isFloatFill(part, complexDigits));
76
+ return ok
77
+ ? undefined
78
+ : `expected a two-element [real, imaginary] array for data type ${JSON.stringify(dataTypeName)}`;
79
+ }
80
+ return undefined; // unrecognized data type: no verdict
81
+ }
package/src/guards.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Shared value guards for the content modules (chunk grids, codecs, data
3
+ * types) and the semantics orchestrator. The structural document layer
4
+ * (validation.ts) keeps its own copies deliberately: it is the
5
+ * corpus-governed layer and stays self-contained.
6
+ */
7
+
8
+ export type Path = ReadonlyArray<string | number>;
9
+
10
+ export function isPlainObject(value: unknown): value is Record<string, unknown> {
11
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
12
+ const proto: unknown = Object.getPrototypeOf(value);
13
+ return proto === null || proto === Object.prototype;
14
+ }
15
+
16
+ export function isIntArray(value: unknown): value is number[] {
17
+ return (
18
+ Array.isArray(value) &&
19
+ Object.keys(value).length === value.length &&
20
+ value.every((item) => Number.isInteger(item))
21
+ );
22
+ }
23
+
24
+ /** The `{name, configuration}` of a metadata field, when extractable. */
25
+ export function fieldParts(
26
+ field: unknown,
27
+ ): { name: string; configuration: Record<string, unknown> | undefined } | undefined {
28
+ if (typeof field === "string") return { name: field, configuration: undefined };
29
+ if (isPlainObject(field) && typeof field["name"] === "string") {
30
+ const configuration = field["configuration"];
31
+ return {
32
+ name: field["name"],
33
+ configuration: isPlainObject(configuration) ? configuration : undefined,
34
+ };
35
+ }
36
+ return undefined;
37
+ }
38
+
39
+ /**
40
+ * Whether a metadata field genuinely lacks a `configuration` member (a
41
+ * malformed one — `configuration: 5` — is the structural layer's
42
+ * complaint, not the semantic layer's).
43
+ */
44
+ export function configurationMissing(field: unknown): boolean {
45
+ return (
46
+ typeof field === "string" || (isPlainObject(field) && !Object.hasOwn(field, "configuration"))
47
+ );
48
+ }
package/src/index.ts CHANGED
@@ -20,6 +20,17 @@ export {
20
20
  type ParseResult,
21
21
  type PathedIssue,
22
22
  } from "./errors.js";
23
+ export type {
24
+ ChunkGridVerdict,
25
+ RectilinearChunkGridConfiguration,
26
+ RectilinearDimSpec,
27
+ RegularChunkGridConfiguration,
28
+ } from "./chunk-grids.js";
29
+ export type {
30
+ ShardingIndexedCodecConfiguration,
31
+ TransposeCodecConfiguration,
32
+ } from "./codecs.js";
33
+ export type { ComplexFillValue, FloatFillValue } from "./data-types.js";
23
34
  export * from "./schemas.js";
24
35
  export * from "./semantics.js";
25
36
  export type { StandardSchemaV1 } from "./standard-schema.js";