@loaders.gl/scientific 0.0.0-stage → 5.0.0-alpha.13

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 (175) hide show
  1. package/README.md +21 -2
  2. package/dist/index.cjs +4313 -0
  3. package/dist/index.cjs.map +6 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +8 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/netcdf/bundled.cjs +1394 -0
  9. package/dist/netcdf/bundled.d.ts +2 -0
  10. package/dist/netcdf/bundled.d.ts.map +1 -0
  11. package/dist/netcdf/bundled.js +5 -0
  12. package/dist/netcdf/bundled.js.map +1 -0
  13. package/dist/netcdf/index.cjs +1394 -0
  14. package/dist/netcdf/index.cjs.map +6 -0
  15. package/dist/netcdf/index.d.ts +7 -0
  16. package/dist/netcdf/index.d.ts.map +1 -0
  17. package/dist/netcdf/index.js +8 -0
  18. package/dist/netcdf/index.js.map +1 -0
  19. package/dist/netcdf/iobuffer/iobuffer.d.ts +253 -0
  20. package/dist/netcdf/iobuffer/iobuffer.d.ts.map +1 -0
  21. package/dist/netcdf/iobuffer/iobuffer.js +450 -0
  22. package/dist/netcdf/iobuffer/iobuffer.js.map +1 -0
  23. package/dist/netcdf/netcdf-format.cjs +39 -0
  24. package/dist/netcdf/netcdf-format.d.ts +11 -0
  25. package/dist/netcdf/netcdf-format.d.ts.map +1 -0
  26. package/dist/netcdf/netcdf-format.js +14 -0
  27. package/dist/netcdf/netcdf-format.js.map +1 -0
  28. package/dist/netcdf/netcdf-loader-with-parser.cjs +995 -0
  29. package/dist/netcdf/netcdf-loader-with-parser.d.ts +60 -0
  30. package/dist/netcdf/netcdf-loader-with-parser.d.ts.map +1 -0
  31. package/dist/netcdf/netcdf-loader-with-parser.js +35 -0
  32. package/dist/netcdf/netcdf-loader-with-parser.js.map +1 -0
  33. package/dist/netcdf/netcdf-loader.cjs +84 -0
  34. package/dist/netcdf/netcdf-loader.d.ts +81 -0
  35. package/dist/netcdf/netcdf-loader.d.ts.map +1 -0
  36. package/dist/netcdf/netcdf-loader.js +41 -0
  37. package/dist/netcdf/netcdf-loader.js.map +1 -0
  38. package/dist/netcdf/netcdf-source-loader-types.cjs +78 -0
  39. package/dist/netcdf/netcdf-source-loader-types.d.ts +28 -0
  40. package/dist/netcdf/netcdf-source-loader-types.d.ts.map +1 -0
  41. package/dist/netcdf/netcdf-source-loader-types.js +32 -0
  42. package/dist/netcdf/netcdf-source-loader-types.js.map +1 -0
  43. package/dist/netcdf/netcdf-source-loader.cjs +1319 -0
  44. package/dist/netcdf/netcdf-source-loader.d.ts +59 -0
  45. package/dist/netcdf/netcdf-source-loader.d.ts.map +1 -0
  46. package/dist/netcdf/netcdf-source-loader.js +421 -0
  47. package/dist/netcdf/netcdf-source-loader.js.map +1 -0
  48. package/dist/netcdf/netcdfjs/netcdf-reader.d.ts +68 -0
  49. package/dist/netcdf/netcdfjs/netcdf-reader.d.ts.map +1 -0
  50. package/dist/netcdf/netcdfjs/netcdf-reader.js +172 -0
  51. package/dist/netcdf/netcdfjs/netcdf-reader.js.map +1 -0
  52. package/dist/netcdf/netcdfjs/netcdf-types.d.ts +70 -0
  53. package/dist/netcdf/netcdfjs/netcdf-types.d.ts.map +1 -0
  54. package/dist/netcdf/netcdfjs/netcdf-types.js +3 -0
  55. package/dist/netcdf/netcdfjs/netcdf-types.js.map +1 -0
  56. package/dist/netcdf/netcdfjs/read-data.d.ts +19 -0
  57. package/dist/netcdf/netcdfjs/read-data.d.ts.map +1 -0
  58. package/dist/netcdf/netcdfjs/read-data.js +51 -0
  59. package/dist/netcdf/netcdfjs/read-data.js.map +1 -0
  60. package/dist/netcdf/netcdfjs/read-header.d.ts +16 -0
  61. package/dist/netcdf/netcdfjs/read-header.d.ts.map +1 -0
  62. package/dist/netcdf/netcdfjs/read-header.js +227 -0
  63. package/dist/netcdf/netcdfjs/read-header.js.map +1 -0
  64. package/dist/netcdf/netcdfjs/read-type.d.ts +36 -0
  65. package/dist/netcdf/netcdfjs/read-type.d.ts.map +1 -0
  66. package/dist/netcdf/netcdfjs/read-type.js +135 -0
  67. package/dist/netcdf/netcdfjs/read-type.js.map +1 -0
  68. package/dist/netcdf/unbundled.cjs +1394 -0
  69. package/dist/netcdf/unbundled.d.ts +2 -0
  70. package/dist/netcdf/unbundled.d.ts.map +1 -0
  71. package/dist/netcdf/unbundled.js +5 -0
  72. package/dist/netcdf/unbundled.js.map +1 -0
  73. package/dist/netcdf.dev.js +3153 -0
  74. package/dist/netcdf.min.js +12 -0
  75. package/dist/zarr/bundled.d.ts +2 -0
  76. package/dist/zarr/bundled.d.ts.map +1 -0
  77. package/dist/zarr/bundled.js +5 -0
  78. package/dist/zarr/bundled.js.map +1 -0
  79. package/dist/zarr/geo-zarr-source-loader.d.ts +121 -0
  80. package/dist/zarr/geo-zarr-source-loader.d.ts.map +1 -0
  81. package/dist/zarr/geo-zarr-source-loader.js +692 -0
  82. package/dist/zarr/geo-zarr-source-loader.js.map +1 -0
  83. package/dist/zarr/index.cjs +14747 -0
  84. package/dist/zarr/index.cjs.map +6 -0
  85. package/dist/zarr/index.d.ts +11 -0
  86. package/dist/zarr/index.d.ts.map +1 -0
  87. package/dist/zarr/index.js +10 -0
  88. package/dist/zarr/index.js.map +1 -0
  89. package/dist/zarr/lib/consolidated-zarr.d.ts +31 -0
  90. package/dist/zarr/lib/consolidated-zarr.d.ts.map +1 -0
  91. package/dist/zarr/lib/consolidated-zarr.js +113 -0
  92. package/dist/zarr/lib/consolidated-zarr.js.map +1 -0
  93. package/dist/zarr/lib/load-zarr.d.ts +11 -0
  94. package/dist/zarr/lib/load-zarr.d.ts.map +1 -0
  95. package/dist/zarr/lib/load-zarr.js +22 -0
  96. package/dist/zarr/lib/load-zarr.js.map +1 -0
  97. package/dist/zarr/lib/spatial-multiscales.d.ts +14 -0
  98. package/dist/zarr/lib/spatial-multiscales.d.ts.map +1 -0
  99. package/dist/zarr/lib/spatial-multiscales.js +34 -0
  100. package/dist/zarr/lib/spatial-multiscales.js.map +1 -0
  101. package/dist/zarr/lib/utils.d.ts +28 -0
  102. package/dist/zarr/lib/utils.d.ts.map +1 -0
  103. package/dist/zarr/lib/utils.js +137 -0
  104. package/dist/zarr/lib/utils.js.map +1 -0
  105. package/dist/zarr/lib/zarr-data-cache.d.ts +13 -0
  106. package/dist/zarr/lib/zarr-data-cache.d.ts.map +1 -0
  107. package/dist/zarr/lib/zarr-data-cache.js +70 -0
  108. package/dist/zarr/lib/zarr-data-cache.js.map +1 -0
  109. package/dist/zarr/lib/zarr-pixel-source.d.ts +41 -0
  110. package/dist/zarr/lib/zarr-pixel-source.d.ts.map +1 -0
  111. package/dist/zarr/lib/zarr-pixel-source.js +97 -0
  112. package/dist/zarr/lib/zarr-pixel-source.js.map +1 -0
  113. package/dist/zarr/lib/zarrita-pixel-source.d.ts +40 -0
  114. package/dist/zarr/lib/zarrita-pixel-source.d.ts.map +1 -0
  115. package/dist/zarr/lib/zarrita-pixel-source.js +96 -0
  116. package/dist/zarr/lib/zarrita-pixel-source.js.map +1 -0
  117. package/dist/zarr/ome-zarr-source-loader.d.ts +195 -0
  118. package/dist/zarr/ome-zarr-source-loader.d.ts.map +1 -0
  119. package/dist/zarr/ome-zarr-source-loader.js +523 -0
  120. package/dist/zarr/ome-zarr-source-loader.js.map +1 -0
  121. package/dist/zarr/spatial-data-source.d.ts +95 -0
  122. package/dist/zarr/spatial-data-source.d.ts.map +1 -0
  123. package/dist/zarr/spatial-data-source.js +242 -0
  124. package/dist/zarr/spatial-data-source.js.map +1 -0
  125. package/dist/zarr/types.d.ts +105 -0
  126. package/dist/zarr/types.d.ts.map +1 -0
  127. package/dist/zarr/types.js +5 -0
  128. package/dist/zarr/types.js.map +1 -0
  129. package/dist/zarr/unbundled.d.ts +2 -0
  130. package/dist/zarr/unbundled.d.ts.map +1 -0
  131. package/dist/zarr/unbundled.js +5 -0
  132. package/dist/zarr/unbundled.js.map +1 -0
  133. package/dist/zarr/zarr-array-source.d.ts +102 -0
  134. package/dist/zarr/zarr-array-source.d.ts.map +1 -0
  135. package/dist/zarr/zarr-array-source.js +132 -0
  136. package/dist/zarr/zarr-array-source.js.map +1 -0
  137. package/dist/zarr/zarr-loader-types.d.ts +236 -0
  138. package/dist/zarr/zarr-loader-types.d.ts.map +1 -0
  139. package/dist/zarr/zarr-loader-types.js +128 -0
  140. package/dist/zarr/zarr-loader-types.js.map +1 -0
  141. package/dist/zarr.dev.js +16574 -0
  142. package/dist/zarr.min.js +79 -0
  143. package/package.json +62 -4
  144. package/src/index.ts +52 -0
  145. package/src/netcdf/bundled.ts +5 -0
  146. package/src/netcdf/index.ts +14 -0
  147. package/src/netcdf/iobuffer/iobuffer.ts +510 -0
  148. package/src/netcdf/netcdf-format.ts +16 -0
  149. package/src/netcdf/netcdf-loader-with-parser.ts +54 -0
  150. package/src/netcdf/netcdf-loader.ts +62 -0
  151. package/src/netcdf/netcdf-source-loader-types.ts +45 -0
  152. package/src/netcdf/netcdf-source-loader.ts +526 -0
  153. package/src/netcdf/netcdfjs/LICENSE +24 -0
  154. package/src/netcdf/netcdfjs/netcdf-reader.ts +196 -0
  155. package/src/netcdf/netcdfjs/netcdf-types.ts +75 -0
  156. package/src/netcdf/netcdfjs/read-data.ts +71 -0
  157. package/src/netcdf/netcdfjs/read-header.ts +277 -0
  158. package/src/netcdf/netcdfjs/read-type.ts +147 -0
  159. package/src/netcdf/unbundled.ts +5 -0
  160. package/src/zarr/bundled.ts +5 -0
  161. package/src/zarr/geo-zarr-source-loader.ts +998 -0
  162. package/src/zarr/index.ts +60 -0
  163. package/src/zarr/lib/consolidated-zarr.ts +190 -0
  164. package/src/zarr/lib/load-zarr.ts +31 -0
  165. package/src/zarr/lib/spatial-multiscales.ts +47 -0
  166. package/src/zarr/lib/utils.ts +162 -0
  167. package/src/zarr/lib/zarr-data-cache.ts +91 -0
  168. package/src/zarr/lib/zarr-pixel-source.ts +134 -0
  169. package/src/zarr/lib/zarrita-pixel-source.ts +141 -0
  170. package/src/zarr/ome-zarr-source-loader.ts +837 -0
  171. package/src/zarr/spatial-data-source.ts +370 -0
  172. package/src/zarr/types.ts +129 -0
  173. package/src/zarr/unbundled.ts +5 -0
  174. package/src/zarr/zarr-array-source.ts +225 -0
  175. package/src/zarr/zarr-loader-types.ts +166 -0
@@ -0,0 +1,837 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import * as zarrita from 'zarrita';
6
+ import type {Readable} from 'zarrita';
7
+ import type {
8
+ CoreAPI,
9
+ SourceLoader,
10
+ DataSourceOptions,
11
+ RasterData,
12
+ RasterChannelDataType,
13
+ RasterQueryCapabilities
14
+ } from '@loaders.gl/core/loader-utils';
15
+ import {
16
+ createScanQueryMetadata,
17
+ DataSource,
18
+ type ScanQueryMetadata,
19
+ type ScanQueryMetadataOptions,
20
+ type ScanQueryMetadataProvider
21
+ } from '@loaders.gl/core/loader-utils';
22
+
23
+ import type {Labels, Channel, Multiscale, RootAttrs, SupportedTypedArray} from './types';
24
+ import {guessLabels, guessTileSize, validLabels} from './lib/utils';
25
+ import ZarritaPixelSource from './lib/zarrita-pixel-source';
26
+ import {
27
+ loadConsolidatedMetadata,
28
+ type LoadConsolidatedMetadataOptions,
29
+ type ZarrConsolidatedMetadata,
30
+ type ZarrMetadataPath
31
+ } from './lib/consolidated-zarr';
32
+ export type {
33
+ LoadConsolidatedMetadataOptions,
34
+ ZarrConsolidatedFormat,
35
+ ZarrConsolidatedMetadata,
36
+ ZarrMetadataPath
37
+ } from './lib/consolidated-zarr';
38
+
39
+ // __VERSION__ is injected by babel-plugin-version-inline
40
+ // @ts-ignore TS2304: Cannot find name '__VERSION__'.
41
+ const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';
42
+
43
+ /** Options shared by Zarr-backed source loaders. */
44
+ export type ZarrSourceLoaderOptions = DataSourceOptions & {
45
+ /** Zarr store discovery and dimension options. */
46
+ zarr?: {
47
+ /** Consolidated metadata file to load, or `auto` to probe known names. */
48
+ metadataPath?: ZarrMetadataPath;
49
+ /** Group path within the store root. */
50
+ path?: string | null;
51
+ /** Explicit dimension labels when array or OME metadata does not provide them. */
52
+ labels?: string[];
53
+ /** Whether opening a source requires consolidated metadata. Defaults to `true`. */
54
+ requireConsolidatedMetadata?: boolean;
55
+ };
56
+ /** OME-Zarr raster layout and channel defaults. */
57
+ omezarr?: {
58
+ /** Whether multi-channel reads return one interleaved typed array by default. */
59
+ interleaved?: boolean;
60
+ /** Channel indices selected when a raster request omits `channels`. */
61
+ defaultChannels?: number[];
62
+ };
63
+ };
64
+
65
+ /** Source loader type for Zarr-backed runtime sources. */
66
+ export type ZarrSourceLoader<SourceT extends ZarrSource = ZarrSource> = SourceLoader<
67
+ SourceT,
68
+ ZarrSourceLoaderOptions
69
+ >;
70
+
71
+ /** Parameters used to request a 2D OME-Zarr plane. */
72
+ export type GetOMEZarrParameters = {
73
+ /** Zero-based pyramid level, or `auto` to select from the requested dimensions. */
74
+ level?: number | 'auto';
75
+ /** Target display width used by automatic level selection. */
76
+ width?: number;
77
+ /** Target display height used by automatic level selection. */
78
+ height?: number;
79
+ /** Zero-based time index. Defaults to the OME display setting or `0`. */
80
+ t?: number;
81
+ /** Zero-based z index. Defaults to the OME display setting or `0`. */
82
+ z?: number;
83
+ /** Zero-based channel indices to load. */
84
+ channels?: number[];
85
+ /** Whether to return one interleaved typed array. */
86
+ interleaved?: boolean;
87
+ /** Abort signal forwarded to metadata and chunk requests. */
88
+ signal?: AbortSignal;
89
+ };
90
+
91
+ /** Channel display metadata exposed by an OME-Zarr source. */
92
+ export type OMEZarrChannelMetadata = {
93
+ /** Zero-based channel index. */
94
+ index: number;
95
+ /** Optional OME channel label. */
96
+ name?: string;
97
+ /** Optional OME hexadecimal display color. */
98
+ color?: string;
99
+ /** Whether the channel is active in the OME display settings. */
100
+ active?: boolean;
101
+ };
102
+
103
+ /** Pyramid level metadata exposed by an OME-Zarr source. */
104
+ export type OMEZarrLevelMetadata = {
105
+ /** Zero-based pyramid level. */
106
+ level: number;
107
+ /** Dataset path relative to the selected image group. */
108
+ path: string;
109
+ /** Width of the level in pixels. */
110
+ width: number;
111
+ /** Height of the level in pixels. */
112
+ height: number;
113
+ /** OME coordinate transformations declared for this level. */
114
+ coordinateTransformations?: unknown[];
115
+ /** Scale relative to the full-resolution level. */
116
+ scale?: [number, number];
117
+ };
118
+
119
+ /** Normalized metadata exposed by {@link OMEZarrImageSource}. */
120
+ export type OMEZarrSourceLoaderMetadata = {
121
+ /** OME image name, or a name derived from the selected group path. */
122
+ name?: string;
123
+ /** Full-resolution width in pixels. */
124
+ width: number;
125
+ /** Full-resolution height in pixels. */
126
+ height: number;
127
+ /** Number of available channels. */
128
+ bandCount: number;
129
+ /** Numeric channel type. */
130
+ dtype: RasterChannelDataType;
131
+ /** Number of time indices. */
132
+ sizeT: number;
133
+ /** Number of z indices. */
134
+ sizeZ: number;
135
+ /** Number of channel indices. */
136
+ sizeC: number;
137
+ /** Default time index from OME display settings. */
138
+ defaultT: number;
139
+ /** Default z index from OME display settings. */
140
+ defaultZ: number;
141
+ /** Dimension labels reported by the array or OME metadata. */
142
+ labels: string[];
143
+ /** Native chunk dimensions for the full-resolution level. */
144
+ tileSize?: {width: number; height: number};
145
+ /** Available pyramid levels. */
146
+ levels: OMEZarrLevelMetadata[];
147
+ /** OME channel display metadata. */
148
+ channels: OMEZarrChannelMetadata[];
149
+ /** Normalized OME attributes retained for application-specific use. */
150
+ metadata: Record<string, unknown>;
151
+ /** Image-level coordinate transformations when present. */
152
+ coordinateTransformations?: unknown[];
153
+ };
154
+
155
+ /** Options for {@link loadZarrConsolidatedMetadata}. */
156
+ export type LoadZarrConsolidatedMetadataOptions = LoadConsolidatedMetadataOptions & {
157
+ /** Fetch implementation used for metadata requests. Defaults to global `fetch`. */
158
+ fetch?: (url: string, options?: RequestInit) => Promise<Response>;
159
+ };
160
+
161
+ type OMEZarrInit = {
162
+ /** Pixel sources ordered by pyramid level. */
163
+ data: ZarritaPixelSource<string[]>[];
164
+ /** Normalized metadata shared by all reads. */
165
+ metadata: OMEZarrSourceLoaderMetadata;
166
+ };
167
+
168
+ /**
169
+ * Loads consolidated metadata for a Zarr store root and extracts top-level arrays and groups.
170
+ */
171
+ export async function loadZarrConsolidatedMetadata(
172
+ url: string,
173
+ options: LoadZarrConsolidatedMetadataOptions = {}
174
+ ): Promise<ZarrConsolidatedMetadata> {
175
+ const fetcher = options.fetch || fetch;
176
+ return await loadConsolidatedMetadata(url, fetcher, options);
177
+ }
178
+
179
+ /**
180
+ * Base runtime source for Zarr-backed sources that resolve groups and consolidated metadata.
181
+ */
182
+ export abstract class ZarrSource extends DataSource<string, ZarrSourceLoaderOptions> {
183
+ /** Common raster-query capabilities shared by Zarr-backed sources. */
184
+ readonly rasterQueryCapabilities: RasterQueryCapabilities = Object.freeze({
185
+ bounds: 'pushdown',
186
+ level: 'pushdown',
187
+ variables: 'pushdown',
188
+ slices: 'pushdown',
189
+ streaming: false,
190
+ cancellation: true
191
+ });
192
+ /** Zarrita store used for metadata and chunk reads. */
193
+ protected readonly store: zarrita.FetchStore;
194
+ /** Selected group path within the store root. */
195
+ protected readonly path: string | null;
196
+ /** Shared consolidated metadata request. */
197
+ private consolidatedMetadataPromise: Promise<ZarrConsolidatedMetadata> | null = null;
198
+
199
+ /** Creates a Zarr-backed source. */
200
+ constructor(data: string, options: ZarrSourceLoaderOptions, coreApi?: CoreAPI) {
201
+ super(
202
+ data,
203
+ options,
204
+ {
205
+ zarr: {
206
+ metadataPath: 'auto',
207
+ path: null,
208
+ labels: undefined!,
209
+ requireConsolidatedMetadata: true
210
+ },
211
+ omezarr: {
212
+ interleaved: false,
213
+ defaultChannels: undefined!
214
+ }
215
+ },
216
+ coreApi
217
+ );
218
+
219
+ this.path = this.options.zarr?.path || null;
220
+ this.store = new zarrita.FetchStore(getZarritaStoreUrl(this.url), {
221
+ fetch: async (request: Request) => {
222
+ const headers = Object.fromEntries(request.headers.entries());
223
+ return await this.fetchZarrFile(request.url, {
224
+ method: request.method,
225
+ headers,
226
+ signal: request.signal
227
+ });
228
+ }
229
+ });
230
+ }
231
+
232
+ /** Returns raster-query capabilities without reading array chunks. */
233
+ getRasterQueryCapabilities(): RasterQueryCapabilities {
234
+ return this.rasterQueryCapabilities;
235
+ }
236
+
237
+ /** Fetches Zarr metadata or chunk data through the injected core API when available. */
238
+ private async fetchZarrFile(url: string, requestOptions?: RequestInit): Promise<Response> {
239
+ const fetchUrl = getFetchableUrl(url);
240
+ const response = this.hasCoreApi
241
+ ? await this.coreApi.fetchFile(fetchUrl, requestOptions)
242
+ : await this.fetch(fetchUrl, requestOptions);
243
+
244
+ // The Node file fetcher reports missing files as 400/ENOENT, while FetchStore
245
+ // needs a 404 response to continue its v2/v3 format probing.
246
+ if (response.status === 400 && response.statusText.includes('ENOENT')) {
247
+ return new Response(null, {status: 404, statusText: 'Not Found'});
248
+ }
249
+ return response;
250
+ }
251
+
252
+ /** Loads normalized consolidated metadata for the backing Zarr store. */
253
+ async getConsolidatedMetadata(signal?: AbortSignal): Promise<ZarrConsolidatedMetadata> {
254
+ if (!this.consolidatedMetadataPromise) {
255
+ this.consolidatedMetadataPromise = loadConsolidatedMetadata(
256
+ this.url,
257
+ (url, requestOptions) => this.fetchZarrFile(url, requestOptions),
258
+ {
259
+ metadataPath: this.options.zarr?.metadataPath,
260
+ signal
261
+ }
262
+ );
263
+ }
264
+
265
+ const consolidatedMetadataPromise = this.consolidatedMetadataPromise;
266
+ try {
267
+ return await consolidatedMetadataPromise;
268
+ } catch (error) {
269
+ if (this.consolidatedMetadataPromise === consolidatedMetadataPromise) {
270
+ this.consolidatedMetadataPromise = null;
271
+ }
272
+ throw error;
273
+ }
274
+ }
275
+
276
+ /** Opens the selected Zarr group after the configured metadata preflight. */
277
+ protected async openGroup(signal?: AbortSignal): Promise<zarrita.Group<Readable>> {
278
+ if (this.options.zarr?.requireConsolidatedMetadata) {
279
+ await this.getConsolidatedMetadata(signal);
280
+ }
281
+
282
+ const location = this.path ? zarrita.root(this.store).resolve(this.path) : this.store;
283
+ return await zarrita.open(location, {kind: 'group', signal});
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Source factory for OME-Zarr multiscale images and labels.
289
+ */
290
+ export const OMEZarrSourceLoaderWithParser = {
291
+ dataType: null as unknown as OMEZarrImageSource,
292
+ /** Runtime source type marker used by `createDataSource()` type inference. */
293
+ dataSource: null as unknown as OMEZarrImageSource,
294
+ batchType: null as never,
295
+ name: 'OMEZarrSourceLoader',
296
+ id: 'omezarr',
297
+ module: 'scientific',
298
+ version: VERSION,
299
+ extensions: ['zarr'],
300
+ mimeTypes: [],
301
+ type: 'omezarr',
302
+ fromUrl: true,
303
+ fromBlob: false,
304
+
305
+ options: {
306
+ zarr: {
307
+ metadataPath: 'auto',
308
+ path: null,
309
+ labels: undefined!,
310
+ requireConsolidatedMetadata: true
311
+ },
312
+ omezarr: {
313
+ interleaved: false,
314
+ defaultChannels: undefined!
315
+ }
316
+ } as ZarrSourceLoaderOptions,
317
+
318
+ defaultOptions: {
319
+ zarr: {
320
+ metadataPath: 'auto',
321
+ path: null,
322
+ labels: undefined!,
323
+ requireConsolidatedMetadata: true
324
+ },
325
+ omezarr: {
326
+ interleaved: false,
327
+ defaultChannels: undefined!
328
+ }
329
+ },
330
+
331
+ testURL: (url: string): boolean => /\.zarr(?:$|[/?#])/i.test(url),
332
+ createDataSource: (
333
+ data: string,
334
+ options: ZarrSourceLoaderOptions,
335
+ coreApi?: CoreAPI
336
+ ): OMEZarrImageSource => new OMEZarrImageSource(data, options, coreApi)
337
+ } as const satisfies ZarrSourceLoader<OMEZarrImageSource>;
338
+
339
+ /**
340
+ * Source that loads 2D planes from an OME-Zarr pyramid.
341
+ */
342
+ export class OMEZarrImageSource extends ZarrSource implements ScanQueryMetadataProvider {
343
+ /** Shared source initialization request. */
344
+ private initPromise: Promise<OMEZarrInit> | null = null;
345
+
346
+ /** Returns normalized OME-Zarr image and pyramid metadata. */
347
+ async getMetadata(signal?: AbortSignal): Promise<OMEZarrSourceLoaderMetadata> {
348
+ const {metadata} = await this.getInitPromise(signal);
349
+ return metadata;
350
+ }
351
+
352
+ /** Discovers the raster pyramid through the common scan metadata contract. */
353
+ async getQueryMetadata(options: ScanQueryMetadataOptions = {}): Promise<ScanQueryMetadata> {
354
+ const metadata = await this.getMetadata(options.signal);
355
+ return createScanQueryMetadata({
356
+ sourceType: 'omezarr',
357
+ queryType: 'raster',
358
+ execution: {status: 'supported', method: 'getRaster'},
359
+ name: metadata.name,
360
+ description: 'OME-Zarr multiscale image',
361
+ schema: {fields: [], metadata: {}},
362
+ capabilities: {
363
+ levelOfDetail: metadata.levels.length > 1 ? 'pushdown' : 'unsupported'
364
+ },
365
+ levels: metadata.levels.map(level => ({
366
+ index: level.level,
367
+ width: level.width,
368
+ height: level.height,
369
+ scale: level.scale
370
+ }))
371
+ });
372
+ }
373
+
374
+ /** Loads one 2D OME-Zarr plane or channel composite. */
375
+ async getRaster(parameters: GetOMEZarrParameters = {}): Promise<RasterData> {
376
+ const {data, metadata} = await this.getInitPromise(parameters.signal);
377
+ const level = selectOMEZarrLevel(metadata.levels, parameters);
378
+ const pixelSource = data[level];
379
+
380
+ if (!pixelSource) {
381
+ throw new Error(`OME-Zarr pyramid level ${level} is not available.`);
382
+ }
383
+
384
+ const interleavedSource = metadata.labels.includes('_c');
385
+ const interleaved =
386
+ parameters.interleaved ?? this.options.omezarr?.interleaved ?? interleavedSource;
387
+ const selection: Record<string, number> = {};
388
+ const timeIndex = normalizeAxisSelection(
389
+ parameters.t,
390
+ metadata.defaultT,
391
+ metadata.sizeT,
392
+ 'time'
393
+ );
394
+ const zIndex = normalizeAxisSelection(parameters.z, metadata.defaultZ, metadata.sizeZ, 'z');
395
+ if (metadata.labels.includes('t')) {
396
+ selection.t = timeIndex;
397
+ }
398
+ if (metadata.labels.includes('z')) {
399
+ selection.z = zIndex;
400
+ }
401
+ const channels = normalizeChannelSelection(
402
+ parameters.channels,
403
+ metadata.bandCount,
404
+ this.options.omezarr?.defaultChannels
405
+ );
406
+
407
+ if (interleavedSource) {
408
+ const raster = await pixelSource.getRaster({selection, signal: parameters.signal});
409
+ const rawData = raster.data as SupportedTypedArray;
410
+ const channelData = selectInterleavedChannels(
411
+ rawData,
412
+ metadata.bandCount,
413
+ channels,
414
+ interleaved
415
+ );
416
+ return {
417
+ data: channelData,
418
+ width: raster.width,
419
+ height: raster.height,
420
+ bandCount: channels.length,
421
+ dtype: metadata.dtype,
422
+ interleaved,
423
+ metadata: {selection, channels, level, sourceLabels: metadata.labels}
424
+ };
425
+ }
426
+
427
+ const rasters = await Promise.all(
428
+ channels.map(channel =>
429
+ pixelSource.getRaster({
430
+ selection: {...selection, c: channel},
431
+ signal: parameters.signal
432
+ })
433
+ )
434
+ );
435
+
436
+ const {width, height} = rasters[0];
437
+ const channelData = rasters.map(raster => raster.data as SupportedTypedArray);
438
+
439
+ return {
440
+ data: interleaved
441
+ ? interleaveTypedArrays(channelData, metadata.dtype)
442
+ : channelData.length === 1
443
+ ? channelData[0]
444
+ : channelData,
445
+ width,
446
+ height,
447
+ bandCount: channelData.length,
448
+ dtype: metadata.dtype,
449
+ interleaved,
450
+ metadata: {selection, channels, level, sourceLabels: metadata.labels}
451
+ };
452
+ }
453
+
454
+ /** Returns the shared initialization request for this source. */
455
+ private async getInitPromise(signal?: AbortSignal): Promise<OMEZarrInit> {
456
+ if (!this.initPromise) {
457
+ this.initPromise = this.initialize(signal);
458
+ }
459
+
460
+ const initPromise = this.initPromise;
461
+ try {
462
+ return await initPromise;
463
+ } catch (error) {
464
+ if (this.initPromise === initPromise) {
465
+ this.initPromise = null;
466
+ }
467
+ throw error;
468
+ }
469
+ }
470
+
471
+ /** Opens the image group and creates one pixel source per pyramid level. */
472
+ private async initialize(signal?: AbortSignal): Promise<OMEZarrInit> {
473
+ const group = await this.openGroup(signal);
474
+ const attrs = normalizeRootAttrs(group.attrs as unknown as RootAttrs);
475
+ const datasets = attrs.multiscales?.[0]?.datasets;
476
+
477
+ if (!datasets?.length) {
478
+ throw new Error('OMEZarrImageSource requires multiscales metadata on the selected group.');
479
+ }
480
+
481
+ const arrays = await Promise.all(
482
+ datasets.map(dataset => zarrita.open(group.resolve(dataset.path), {kind: 'array', signal}))
483
+ );
484
+
485
+ const labels = inferLabels(attrs, arrays[0], this.options.zarr?.labels);
486
+ const tileSize = guessTileSize({shape: arrays[0].shape, chunks: arrays[0].chunks}, labels);
487
+ const data = arrays.map(array => new ZarritaPixelSource(array, labels, tileSize));
488
+
489
+ return {
490
+ data,
491
+ metadata: normalizeOMEZarrMetadata(this.path || this.data, attrs, data)
492
+ };
493
+ }
494
+ }
495
+
496
+ /** Normalizes pre-0.5 and 0.5 OME attributes into one internal shape. */
497
+ function normalizeRootAttrs(attrs: RootAttrs): {
498
+ multiscales: Multiscale[];
499
+ omero: {
500
+ channels?: Channel[];
501
+ name?: string;
502
+ rdefs?: {defaultT?: number; defaultZ?: number; model: string};
503
+ };
504
+ coordinateTransformations?: unknown[];
505
+ } {
506
+ const omeAttrs = 'ome' in attrs && attrs.ome ? attrs.ome : null;
507
+ const multiscales =
508
+ ('multiscales' in attrs ? attrs.multiscales : undefined) || omeAttrs?.multiscales || [];
509
+ const legacyCoordinateTransformations =
510
+ 'coordinateTransformations' in attrs ? attrs.coordinateTransformations : undefined;
511
+
512
+ return {
513
+ multiscales,
514
+ omero: ('omero' in attrs ? attrs.omero : undefined) || omeAttrs?.omero || {},
515
+ coordinateTransformations:
516
+ multiscales[0]?.coordinateTransformations ||
517
+ legacyCoordinateTransformations ||
518
+ omeAttrs?.coordinateTransformations
519
+ };
520
+ }
521
+
522
+ /** Resolves dimension labels from explicit options, array metadata, or OME axes. */
523
+ function inferLabels(
524
+ attrs: ReturnType<typeof normalizeRootAttrs>,
525
+ array: zarrita.Array<zarrita.DataType, Readable>,
526
+ optionLabels?: string[]
527
+ ): Labels<string[]> {
528
+ const labels =
529
+ optionLabels ||
530
+ normalizeDimensionNames(array.dimensionNames) ||
531
+ getAxisNames(attrs.multiscales?.[0]?.axes) ||
532
+ guessLabels(attrs as RootAttrs);
533
+
534
+ if (!validLabels(labels, array.shape)) {
535
+ throw new Error('Invalid labels for OME-Zarr array dimensions.');
536
+ }
537
+
538
+ return labels;
539
+ }
540
+
541
+ /** Copies non-empty Zarr v3 dimension names. */
542
+ function normalizeDimensionNames(dimensionNames?: string[]): string[] | null {
543
+ if (!dimensionNames?.length) {
544
+ return null;
545
+ }
546
+
547
+ return [...dimensionNames];
548
+ }
549
+
550
+ /** Extracts named dimensions from OME multiscale axis metadata. */
551
+ function getAxisNames(
552
+ axes: Array<string | {name?: string; type?: string}> | undefined
553
+ ): string[] | null {
554
+ if (!axes?.length) {
555
+ return null;
556
+ }
557
+
558
+ const labels = axes
559
+ .map(axis => (typeof axis === 'string' ? axis : axis.name))
560
+ .filter((axisName): axisName is string => Boolean(axisName));
561
+
562
+ return labels.length ? labels : null;
563
+ }
564
+
565
+ /** Builds normalized OME-Zarr metadata from the opened pyramid sources. */
566
+ function normalizeOMEZarrMetadata(
567
+ data: string,
568
+ attrs: ReturnType<typeof normalizeRootAttrs>,
569
+ sources: ZarritaPixelSource<string[]>[]
570
+ ): OMEZarrSourceLoaderMetadata {
571
+ const baseSource = sources[0];
572
+ const interleaved = baseSource.labels[baseSource.labels.length - 1] === '_c';
573
+ const [height, width] = baseSource.shape.slice(interleaved ? -3 : -2);
574
+ const labels = [...baseSource.labels];
575
+ const dtype = normalizeDtype(baseSource.dtype);
576
+ const bandCount =
577
+ getAxisSize(baseSource.shape, labels, '_c') ||
578
+ getAxisSize(baseSource.shape, labels, 'c') ||
579
+ attrs.omero?.channels?.length ||
580
+ 1;
581
+ const levels = sources.map((source, level) => {
582
+ const levelInterleaved = source.labels[source.labels.length - 1] === '_c';
583
+ const [levelHeight, levelWidth] = source.shape.slice(levelInterleaved ? -3 : -2);
584
+ const dataset = attrs.multiscales[0]?.datasets[level];
585
+ return {
586
+ level,
587
+ path: dataset?.path || String(level),
588
+ width: levelWidth,
589
+ height: levelHeight,
590
+ coordinateTransformations: dataset?.coordinateTransformations,
591
+ scale: [width / levelWidth, height / levelHeight] as [number, number]
592
+ };
593
+ });
594
+
595
+ return {
596
+ name: attrs.omero?.name || getOMEZarrName(data),
597
+ width,
598
+ height,
599
+ bandCount,
600
+ dtype,
601
+ sizeT: getAxisSize(baseSource.shape, labels, 't') || 1,
602
+ sizeZ: getAxisSize(baseSource.shape, labels, 'z') || 1,
603
+ sizeC:
604
+ getAxisSize(baseSource.shape, labels, 'c') ||
605
+ getAxisSize(baseSource.shape, labels, '_c') ||
606
+ attrs.omero?.channels?.length ||
607
+ 1,
608
+ defaultT: attrs.omero?.rdefs?.defaultT ?? 0,
609
+ defaultZ: attrs.omero?.rdefs?.defaultZ ?? 0,
610
+ labels,
611
+ tileSize: {width: baseSource.tileWidth, height: baseSource.tileHeight},
612
+ levels,
613
+ channels: (attrs.omero?.channels || []).map(normalizeChannel),
614
+ metadata: attrs as unknown as Record<string, unknown>,
615
+ coordinateTransformations: attrs.coordinateTransformations
616
+ };
617
+ }
618
+
619
+ /** Selects an explicit level or the closest pyramid level for a target viewport. */
620
+ function selectOMEZarrLevel(
621
+ levels: OMEZarrLevelMetadata[],
622
+ parameters: GetOMEZarrParameters
623
+ ): number {
624
+ if (typeof parameters.level === 'number') {
625
+ return parameters.level;
626
+ }
627
+ if (parameters.level !== 'auto' || !parameters.width || !parameters.height) {
628
+ return 0;
629
+ }
630
+ const suitable = levels
631
+ .filter(level => level.width >= parameters.width! && level.height >= parameters.height!)
632
+ .sort((first, second) => first.width * first.height - second.width * second.height);
633
+ return (suitable[0] || levels[0]).level;
634
+ }
635
+
636
+ /** Converts OME display settings for one channel into public metadata. */
637
+ function normalizeChannel(channel: Channel, index: number): OMEZarrChannelMetadata {
638
+ return {
639
+ index,
640
+ name: channel.label,
641
+ color: channel.color,
642
+ active: channel.active
643
+ };
644
+ }
645
+
646
+ /** Returns the size of a named dimension when it is present. */
647
+ function getAxisSize(shape: number[], labels: string[], label: string): number | null {
648
+ const index = labels.indexOf(label);
649
+ return index >= 0 ? shape[index] : null;
650
+ }
651
+
652
+ /** Converts a Zarrita dtype into the raster source dtype union. */
653
+ function normalizeDtype(dtype: string): RasterChannelDataType {
654
+ switch (dtype) {
655
+ case 'uint8':
656
+ case 'uint16':
657
+ case 'uint32':
658
+ case 'int8':
659
+ case 'int16':
660
+ case 'int32':
661
+ case 'float32':
662
+ case 'float64':
663
+ return dtype;
664
+ default:
665
+ throw new Error(`OME-Zarr dtype ${dtype} is not currently supported.`);
666
+ }
667
+ }
668
+
669
+ /** Resolves and validates the channel selection for a raster request. */
670
+ function normalizeChannelSelection(
671
+ requestedChannels: number[] | undefined,
672
+ bandCount: number,
673
+ defaultChannels?: number[]
674
+ ): number[] {
675
+ const channelSelection =
676
+ requestedChannels || defaultChannels || Array.from({length: bandCount}, (_, index) => index);
677
+
678
+ if (channelSelection.length === 0) {
679
+ throw new Error('OME-Zarr channel selection must include at least one channel.');
680
+ }
681
+
682
+ for (const channel of channelSelection) {
683
+ if (!Number.isInteger(channel) || channel < 0 || channel >= bandCount) {
684
+ throw new Error(`Channel ${channel} is out of bounds for OME-Zarr with ${bandCount} bands.`);
685
+ }
686
+ }
687
+
688
+ return [...channelSelection];
689
+ }
690
+
691
+ /** Resolves and validates one optional time or z selection. */
692
+ function normalizeAxisSelection(
693
+ requestedIndex: number | undefined,
694
+ defaultIndex: number,
695
+ size: number,
696
+ axisName: 'time' | 'z'
697
+ ): number {
698
+ const index = requestedIndex ?? defaultIndex;
699
+ if (!Number.isInteger(index) || index < 0 || index >= size) {
700
+ throw new Error(`OME-Zarr ${axisName} index ${index} is out of bounds for axis size ${size}.`);
701
+ }
702
+ return index;
703
+ }
704
+
705
+ /** Derives a display name from a store URL or selected group path. */
706
+ function getOMEZarrName(data: string): string {
707
+ const normalizedData = data.replace(/[?#].*$/, '').replace(/\/+$/, '');
708
+ return normalizedData.split('/').pop() || normalizedData;
709
+ }
710
+
711
+ /** Converts file URLs emitted by FetchStore into paths accepted by core's Node file fetcher. */
712
+ function getFetchableUrl(url: string): string {
713
+ if (!url.startsWith('file:')) {
714
+ return url;
715
+ }
716
+
717
+ return decodeURIComponent(new URL(url).pathname);
718
+ }
719
+
720
+ /** Resolves browser-relative URLs because Zarrita's FetchStore requires an absolute URL. */
721
+ function getZarritaStoreUrl(url: string): string {
722
+ if (typeof globalThis.location?.href !== 'string') {
723
+ return url;
724
+ }
725
+
726
+ return new URL(url, globalThis.location.href).href;
727
+ }
728
+
729
+ /** Interleaves equally sized planar channel arrays. */
730
+ function interleaveTypedArrays(
731
+ data: SupportedTypedArray[],
732
+ dtype: RasterChannelDataType
733
+ ): SupportedTypedArray {
734
+ const TypedArrayConstructor = getTypedArrayConstructor(dtype);
735
+ const length = data[0]?.length || 0;
736
+ const channelCount = data.length;
737
+ const interleaved = new TypedArrayConstructor(length * channelCount);
738
+
739
+ for (let index = 0; index < length; index++) {
740
+ for (let channelIndex = 0; channelIndex < channelCount; channelIndex++) {
741
+ interleaved[index * channelCount + channelIndex] = data[channelIndex][index];
742
+ }
743
+ }
744
+
745
+ return interleaved;
746
+ }
747
+
748
+ /** Selects channels from an interleaved source and returns the requested layout. */
749
+ function selectInterleavedChannels(
750
+ data: SupportedTypedArray,
751
+ bandCount: number,
752
+ channels: number[],
753
+ interleaved: boolean
754
+ ): SupportedTypedArray | SupportedTypedArray[] {
755
+ if (
756
+ channels.length === bandCount &&
757
+ interleaved &&
758
+ channels.every((channel, index) => channel === index)
759
+ ) {
760
+ return data;
761
+ }
762
+
763
+ const TypedArrayConstructor = data.constructor as new (length: number) => SupportedTypedArray;
764
+ const pixelCount = data.length / bandCount;
765
+ const channelData = channels.map(() => new TypedArrayConstructor(pixelCount));
766
+
767
+ for (let pixelIndex = 0; pixelIndex < pixelCount; pixelIndex++) {
768
+ for (
769
+ let channelSelectionIndex = 0;
770
+ channelSelectionIndex < channels.length;
771
+ channelSelectionIndex++
772
+ ) {
773
+ channelData[channelSelectionIndex][pixelIndex] =
774
+ data[pixelIndex * bandCount + channels[channelSelectionIndex]];
775
+ }
776
+ }
777
+
778
+ if (interleaved) {
779
+ return interleaveTypedArrays(channelData, getTypedArrayDtype(TypedArrayConstructor));
780
+ }
781
+
782
+ return channelData.length === 1 ? channelData[0] : channelData;
783
+ }
784
+
785
+ /** Returns the typed-array constructor for a raster dtype. */
786
+ function getTypedArrayConstructor(
787
+ dtype: RasterChannelDataType
788
+ ): new (
789
+ length: number
790
+ ) => SupportedTypedArray {
791
+ switch (dtype) {
792
+ case 'uint8':
793
+ return Uint8Array;
794
+ case 'uint16':
795
+ return Uint16Array;
796
+ case 'uint32':
797
+ return Uint32Array;
798
+ case 'int8':
799
+ return Int8Array;
800
+ case 'int16':
801
+ return Int16Array;
802
+ case 'int32':
803
+ return Int32Array;
804
+ case 'float32':
805
+ return Float32Array;
806
+ case 'float64':
807
+ return Float64Array;
808
+ default:
809
+ throw new Error(`Unsupported dtype ${dtype}.`);
810
+ }
811
+ }
812
+
813
+ /** Returns the raster dtype represented by a typed-array constructor. */
814
+ function getTypedArrayDtype(
815
+ TypedArrayConstructor: new (length: number) => SupportedTypedArray
816
+ ): RasterChannelDataType {
817
+ switch (TypedArrayConstructor) {
818
+ case Uint8Array:
819
+ return 'uint8';
820
+ case Uint16Array:
821
+ return 'uint16';
822
+ case Uint32Array:
823
+ return 'uint32';
824
+ case Int8Array:
825
+ return 'int8';
826
+ case Int16Array:
827
+ return 'int16';
828
+ case Int32Array:
829
+ return 'int32';
830
+ case Float32Array:
831
+ return 'float32';
832
+ case Float64Array:
833
+ return 'float64';
834
+ default:
835
+ throw new Error('Unsupported TypedArray constructor.');
836
+ }
837
+ }