@aguacerowx/javascript-sdk 0.0.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.
@@ -0,0 +1,967 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.AguaceroCore = void 0;
7
+ var _events = require("./events.js");
8
+ var _coordinate_configs = require("./coordinate_configs.js");
9
+ var _unitConversions = require("./unitConversions.js");
10
+ var _dictionaries = require("./dictionaries.js");
11
+ var _defaultColormaps = require("./default-colormaps.js");
12
+ var _proj = _interopRequireDefault(require("proj4"));
13
+ var _fzstd = require("fzstd");
14
+ var _getBundleId = require("./getBundleId");
15
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
16
+ // AguaceroCore.js - The Headless "Engine"
17
+
18
+ // --- Non-UI Imports ---
19
+
20
+ // --- Non-UI Helper Functions ---
21
+ function hrdpsObliqueTransform(rotated_lon, rotated_lat) {
22
+ const o_lat_p = 53.91148;
23
+ const o_lon_p = 245.305142;
24
+ const DEG_TO_RAD = Math.PI / 180.0;
25
+ const RAD_TO_DEG = 180.0 / Math.PI;
26
+ const o_lat_p_rad = o_lat_p * DEG_TO_RAD;
27
+ const rot_lon_rad = rotated_lon * DEG_TO_RAD;
28
+ const rot_lat_rad = rotated_lat * DEG_TO_RAD;
29
+ const sin_rot_lat = Math.sin(rot_lat_rad);
30
+ const cos_rot_lat = Math.cos(rot_lat_rad);
31
+ const sin_rot_lon = Math.sin(rot_lon_rad);
32
+ const cos_rot_lon = Math.cos(rot_lon_rad);
33
+ const sin_o_lat_p = Math.sin(o_lat_p_rad);
34
+ const cos_o_lat_p = Math.cos(o_lat_p_rad);
35
+ const sin_lat = cos_o_lat_p * sin_rot_lat + sin_o_lat_p * cos_rot_lat * cos_rot_lon;
36
+ let lat = Math.asin(sin_lat) * RAD_TO_DEG;
37
+ const sin_lon_num = cos_rot_lat * sin_rot_lon;
38
+ const sin_lon_den = -sin_o_lat_p * sin_rot_lat + cos_o_lat_p * cos_rot_lat * cos_rot_lon;
39
+ let lon = Math.atan2(sin_lon_num, sin_lon_den) * RAD_TO_DEG + o_lon_p;
40
+ if (lon > 180) lon -= 360;else if (lon < -180) lon += 360;
41
+ return [lon, lat];
42
+ }
43
+ function findLatestModelRun(modelsData, modelName) {
44
+ const model = modelsData === null || modelsData === void 0 ? void 0 : modelsData[modelName];
45
+ if (!model) return null;
46
+ const availableDates = Object.keys(model).sort((a, b) => b.localeCompare(a));
47
+ for (const date of availableDates) {
48
+ const runs = model[date];
49
+ if (!runs) continue;
50
+ const availableRuns = Object.keys(runs).sort((a, b) => b.localeCompare(a));
51
+ if (availableRuns.length > 0) return {
52
+ date: date,
53
+ run: availableRuns[0]
54
+ };
55
+ }
56
+ return null;
57
+ }
58
+ class AguaceroCore extends _events.EventEmitter {
59
+ constructor(options = {}) {
60
+ super();
61
+ this.isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
62
+ this.apiKey = options.apiKey;
63
+ this.bundleId = (0, _getBundleId.getBundleId)();
64
+ this.baseGridUrl = 'https://d3dc62msmxkrd7.cloudfront.net';
65
+ if (!this.isReactNative) {
66
+ this.worker = this.createWorker();
67
+ this.workerRequestId = 0;
68
+ this.workerResolvers = new Map();
69
+ this.worker.addEventListener('message', this._handleWorkerMessage.bind(this));
70
+ this.resultQueue = [];
71
+ this.isProcessingQueue = false;
72
+ } else {
73
+ this.worker = null;
74
+ }
75
+ this.statusUrl = 'https://d3dc62msmxkrd7.cloudfront.net/model-status';
76
+ this.modelStatus = null;
77
+ this.mrmsStatus = null;
78
+ this.dataCache = new Map();
79
+ this.abortControllers = new Map();
80
+ this.isPlaying = false;
81
+ this.playIntervalId = null;
82
+ this.playbackSpeed = options.playbackSpeed || 500;
83
+ this.customColormaps = options.customColormaps || {};
84
+ const userLayerOptions = options.layerOptions || {};
85
+ const initialVariable = userLayerOptions.variable || null;
86
+ this.state = {
87
+ model: userLayerOptions.model || 'gfs',
88
+ isMRMS: false,
89
+ mrmsTimestamp: null,
90
+ variable: initialVariable,
91
+ date: null,
92
+ run: null,
93
+ forecastHour: 0,
94
+ visible: true,
95
+ opacity: userLayerOptions.opacity ?? 0.85,
96
+ units: options.initialUnit || 'imperial',
97
+ shaderSmoothingEnabled: options.shaderSmoothingEnabled ?? true
98
+ };
99
+ this.autoRefreshEnabled = options.autoRefresh ?? false;
100
+ this.autoRefreshIntervalSeconds = options.autoRefreshInterval ?? 60;
101
+ this.autoRefreshIntervalId = null;
102
+ }
103
+ async setState(newState) {
104
+ Object.assign(this.state, newState);
105
+ this._emitStateChange();
106
+ }
107
+ _emitStateChange() {
108
+ var _this$modelStatus, _this$modelStatus2;
109
+ const {
110
+ colormap,
111
+ baseUnit
112
+ } = this._getColormapForVariable(this.state.variable);
113
+ const toUnit = this._getTargetUnit(baseUnit, this.state.units);
114
+ const displayColormap = this._convertColormapUnits(colormap, baseUnit, toUnit);
115
+ let availableTimestamps = [];
116
+ if (this.state.isMRMS && this.state.variable && this.mrmsStatus) {
117
+ const timestamps = this.mrmsStatus[this.state.variable] || [];
118
+ availableTimestamps = [...timestamps].reverse();
119
+ }
120
+ this.emit('state:change', {
121
+ ...this.state,
122
+ availableModels: this.modelStatus ? Object.keys(this.modelStatus).sort() : [],
123
+ availableRuns: ((_this$modelStatus = this.modelStatus) === null || _this$modelStatus === void 0 ? void 0 : _this$modelStatus[this.state.model]) || {},
124
+ availableHours: this.state.isMRMS ? [] : ((_this$modelStatus2 = this.modelStatus) === null || _this$modelStatus2 === void 0 || (_this$modelStatus2 = _this$modelStatus2[this.state.model]) === null || _this$modelStatus2 === void 0 || (_this$modelStatus2 = _this$modelStatus2[this.state.date]) === null || _this$modelStatus2 === void 0 ? void 0 : _this$modelStatus2[this.state.run]) || [],
125
+ availableVariables: this.getAvailableVariables(this.state.isMRMS ? 'mrms' : this.state.model),
126
+ availableTimestamps: availableTimestamps,
127
+ isPlaying: this.isPlaying,
128
+ colormap: displayColormap,
129
+ colormapBaseUnit: toUnit
130
+ });
131
+ }
132
+ async initialize(options = {}) {
133
+ await this.fetchModelStatus(true);
134
+ await this.fetchMRMSStatus(true);
135
+ const latestRun = findLatestModelRun(this.modelStatus, this.state.model);
136
+ let initialState = this.state;
137
+ if (latestRun && !this.state.isMRMS) {
138
+ initialState = {
139
+ ...this.state,
140
+ ...latestRun,
141
+ forecastHour: 0
142
+ };
143
+ const availableVariables = this.getAvailableVariables(initialState.model);
144
+ if (availableVariables && availableVariables.length > 0) {
145
+ initialState.variable = availableVariables[0];
146
+ }
147
+ }
148
+ await this.setState(initialState);
149
+ if (options.autoRefresh ?? this.autoRefreshEnabled) {
150
+ this.startAutoRefresh(options.refreshInterval ?? this.autoRefreshIntervalSeconds);
151
+ }
152
+ }
153
+ destroy() {
154
+ this.pause();
155
+ this.stopAutoRefresh();
156
+ this.dataCache.clear();
157
+ if (this.worker) {
158
+ this.worker.terminate();
159
+ }
160
+ this.callbacks = {};
161
+ console.log(`AguaceroCore has been destroyed.`);
162
+ }
163
+
164
+ // --- Public API Methods ---
165
+
166
+ play() {
167
+ if (this.isPlaying) return;
168
+ this.isPlaying = true;
169
+ clearInterval(this.playIntervalId);
170
+ this.playIntervalId = setInterval(() => {
171
+ this.step(1);
172
+ }, this.playbackSpeed);
173
+ this.emit('playback:start', {
174
+ speed: this.playbackSpeed
175
+ });
176
+ this._emitStateChange(); // Notify UI that isPlaying is now true
177
+ }
178
+ pause() {
179
+ if (!this.isPlaying) return;
180
+ this.isPlaying = false;
181
+ clearInterval(this.playIntervalId);
182
+ this.playIntervalId = null;
183
+ this.emit('playback:stop');
184
+ this._emitStateChange(); // Notify UI that isPlaying is now false
185
+ }
186
+ togglePlay() {
187
+ this.isPlaying ? this.pause() : this.play();
188
+ }
189
+ step(direction = 1) {
190
+ var _this$modelStatus3;
191
+ const {
192
+ model,
193
+ date,
194
+ run,
195
+ forecastHour
196
+ } = this.state;
197
+ const forecastHours = (_this$modelStatus3 = this.modelStatus) === null || _this$modelStatus3 === void 0 || (_this$modelStatus3 = _this$modelStatus3[model]) === null || _this$modelStatus3 === void 0 || (_this$modelStatus3 = _this$modelStatus3[date]) === null || _this$modelStatus3 === void 0 ? void 0 : _this$modelStatus3[run];
198
+ if (!forecastHours || forecastHours.length === 0) return;
199
+ const currentIndex = forecastHours.indexOf(forecastHour);
200
+ if (currentIndex === -1) return;
201
+ const maxIndex = forecastHours.length - 1;
202
+ let nextIndex = currentIndex + direction;
203
+ if (nextIndex > maxIndex) nextIndex = 0;
204
+ if (nextIndex < 0) nextIndex = maxIndex;
205
+ this.setState({
206
+ forecastHour: forecastHours[nextIndex]
207
+ });
208
+ }
209
+ setPlaybackSpeed(speed) {
210
+ if (speed > 0) {
211
+ this.playbackSpeed = speed;
212
+ if (this.isPlaying) this.play();
213
+ }
214
+ }
215
+ async setShaderSmoothing(enabled) {
216
+ if (typeof enabled !== 'boolean' || enabled === this.state.shaderSmoothingEnabled) return;
217
+ await this.setState({
218
+ shaderSmoothingEnabled: enabled
219
+ });
220
+ }
221
+ async setOpacity(newOpacity) {
222
+ const clampedOpacity = Math.max(0, Math.min(1, newOpacity));
223
+ if (clampedOpacity === this.state.opacity) return;
224
+ await this.setState({
225
+ opacity: clampedOpacity
226
+ });
227
+ }
228
+ async setVariable(variable) {
229
+ await this.setState({
230
+ variable
231
+ });
232
+ }
233
+ async setModel(modelName) {
234
+ var _this$modelStatus4;
235
+ if (modelName === this.state.model || !((_this$modelStatus4 = this.modelStatus) !== null && _this$modelStatus4 !== void 0 && _this$modelStatus4[modelName])) return;
236
+ const latestRun = findLatestModelRun(this.modelStatus, modelName);
237
+ if (latestRun) {
238
+ await this.setState({
239
+ model: modelName,
240
+ date: latestRun.date,
241
+ run: latestRun.run,
242
+ forecastHour: 0
243
+ });
244
+ }
245
+ }
246
+ async setRun(runString) {
247
+ const [date, run] = runString.split(':');
248
+ if (date !== this.state.date || run !== this.state.run) {
249
+ await this.setState({
250
+ date,
251
+ run,
252
+ forecastHour: 0
253
+ });
254
+ }
255
+ }
256
+ async setUnits(newUnits) {
257
+ if (newUnits === this.state.units || !['metric', 'imperial'].includes(newUnits)) return;
258
+ await this.setState({
259
+ units: newUnits
260
+ });
261
+ }
262
+ async setMRMSVariable(variable) {
263
+ const sortedTimestamps = [...(this.mrmsStatus[variable] || [])].sort((a, b) => b - a);
264
+ const initialTimestamp = sortedTimestamps.length > 0 ? sortedTimestamps[0] : null;
265
+ await this.setState({
266
+ variable,
267
+ isMRMS: true,
268
+ mrmsTimestamp: initialTimestamp
269
+ });
270
+ }
271
+ async setMRMSTimestamp(timestamp) {
272
+ if (!this.state.isMRMS) return;
273
+ await this.setState({
274
+ mrmsTimestamp: timestamp
275
+ });
276
+ }
277
+ async switchMode(options) {
278
+ const {
279
+ mode,
280
+ variable,
281
+ model,
282
+ forecastHour,
283
+ mrmsTimestamp
284
+ } = options;
285
+ if (!mode || !variable) {
286
+ console.error("switchMode requires 'mode' ('mrms' | 'model') and 'variable' properties.");
287
+ return;
288
+ }
289
+ if (mode === 'model' && !model) {
290
+ console.error("switchMode with mode 'model' requires a 'model' property.");
291
+ return;
292
+ }
293
+ let targetState = {};
294
+ if (mode === 'mrms') {
295
+ let finalTimestamp = mrmsTimestamp;
296
+ if (finalTimestamp === undefined) {
297
+ const sortedTimestamps = [...(this.mrmsStatus[variable] || [])].sort((a, b) => b - a);
298
+ finalTimestamp = sortedTimestamps.length > 0 ? sortedTimestamps[0] : null;
299
+ }
300
+ targetState = {
301
+ isMRMS: true,
302
+ variable: variable,
303
+ mrmsTimestamp: finalTimestamp,
304
+ model: this.state.model,
305
+ date: null,
306
+ run: null,
307
+ forecastHour: 0
308
+ };
309
+ } else if (mode === 'model') {
310
+ const latestRun = findLatestModelRun(this.modelStatus, model);
311
+ if (!latestRun) {
312
+ console.error(`Could not find a valid run for model: ${model}`);
313
+ return;
314
+ }
315
+ targetState = {
316
+ isMRMS: false,
317
+ model: model,
318
+ variable: variable,
319
+ date: latestRun.date,
320
+ run: latestRun.run,
321
+ forecastHour: forecastHour !== undefined ? forecastHour : 0,
322
+ mrmsTimestamp: null
323
+ };
324
+ } else {
325
+ console.error(`Invalid mode specified in switchMode: '${mode}'`);
326
+ return;
327
+ }
328
+ await this.setState(targetState);
329
+ }
330
+
331
+ // --- Data and Calculation Methods ---
332
+
333
+ _reconstructData(decompressedDeltas, encoding) {
334
+ const expectedLength = encoding.length;
335
+ const reconstructedData = new Int8Array(expectedLength);
336
+ if (decompressedDeltas.length > 0 && expectedLength > 0) {
337
+ // First value is absolute
338
+ reconstructedData[0] = decompressedDeltas[0] > 127 ? decompressedDeltas[0] - 256 : decompressedDeltas[0];
339
+
340
+ // Subsequent values are deltas from the previous one
341
+ for (let i = 1; i < expectedLength; i++) {
342
+ const delta = decompressedDeltas[i] > 127 ? decompressedDeltas[i] - 256 : decompressedDeltas[i];
343
+ reconstructedData[i] = reconstructedData[i - 1] + delta;
344
+ }
345
+ }
346
+ // Return as a Uint8Array, which is what the rest of the code expects
347
+ return new Uint8Array(reconstructedData.buffer);
348
+ }
349
+ async _loadGridData(state) {
350
+ const {
351
+ model,
352
+ date,
353
+ run,
354
+ forecastHour,
355
+ variable,
356
+ isMRMS,
357
+ mrmsTimestamp
358
+ } = state;
359
+ let effectiveSmoothing = 0;
360
+ const customVariableSettings = this.customColormaps[variable];
361
+ if (customVariableSettings && typeof customVariableSettings.smoothing === 'number') {
362
+ effectiveSmoothing = customVariableSettings.smoothing;
363
+ }
364
+ let resourcePath;
365
+ let dataUrlIdentifier;
366
+ if (isMRMS) {
367
+ if (!mrmsTimestamp) return null;
368
+ const mrmsDate = new Date(mrmsTimestamp * 1000);
369
+ const y = mrmsDate.getUTCFullYear(),
370
+ m = (mrmsDate.getUTCMonth() + 1).toString().padStart(2, '0'),
371
+ d = mrmsDate.getUTCDate().toString().padStart(2, '0');
372
+ dataUrlIdentifier = `mrms-${mrmsTimestamp}-${variable}-${effectiveSmoothing}`;
373
+ resourcePath = `/grids/mrms/${y}${m}${d}/${mrmsTimestamp}/0/${variable}/${effectiveSmoothing}`;
374
+ } else {
375
+ dataUrlIdentifier = `${model}-${date}-${run}-${forecastHour}-${variable}-${effectiveSmoothing}`;
376
+ resourcePath = `/grids/${model}/${date}/${run}/${forecastHour}/${variable}/${effectiveSmoothing}`;
377
+ }
378
+ if (this.dataCache.has(dataUrlIdentifier)) {
379
+ return this.dataCache.get(dataUrlIdentifier);
380
+ }
381
+
382
+ // Create and store abort controller BEFORE creating the promise
383
+ const abortController = new AbortController();
384
+ this.abortControllers.set(dataUrlIdentifier, abortController);
385
+ const loadPromise = (async () => {
386
+ if (!this.apiKey) {
387
+ throw new Error('API key is not configured.');
388
+ }
389
+ try {
390
+ const directUrl = `${this.baseGridUrl}${resourcePath}`;
391
+
392
+ // --- START OF LOGGING CODE ---
393
+ const headers = {
394
+ 'x-api-key': this.apiKey
395
+ };
396
+ if (this.bundleId) {
397
+ headers['x-app-identifier'] = this.bundleId;
398
+ }
399
+
400
+ // Use the headers object we just logged
401
+ const response = await fetch(directUrl, {
402
+ headers: headers,
403
+ signal: abortController.signal
404
+ });
405
+ if (!response.ok) {
406
+ // This is where your error is being thrown from
407
+ throw new Error(`Failed to fetch grid data: ${response.status} ${response.statusText}`);
408
+ }
409
+ const {
410
+ data: b64Data,
411
+ encoding
412
+ } = await response.json();
413
+ const compressedData = Uint8Array.from(atob(b64Data), c => c.charCodeAt(0));
414
+ let finalData;
415
+ if (this.isReactNative) {
416
+ const decompressedDeltas = (0, _fzstd.decompress)(compressedData);
417
+ finalData = this._reconstructData(decompressedDeltas, encoding);
418
+ } else {
419
+ const requestId = this.workerRequestId++;
420
+ const workerPromise = new Promise((resolve, reject) => {
421
+ this.workerResolvers.set(requestId, {
422
+ resolve,
423
+ reject
424
+ });
425
+ });
426
+ this.worker.postMessage({
427
+ requestId,
428
+ compressedData,
429
+ encoding
430
+ }, [compressedData.buffer]);
431
+ const result = await workerPromise;
432
+ finalData = result.data;
433
+ }
434
+ const transformedData = new Uint8Array(finalData.length);
435
+ for (let i = 0; i < finalData.length; i++) {
436
+ const signedValue = finalData[i] > 127 ? finalData[i] - 256 : finalData[i];
437
+ transformedData[i] = signedValue + 128;
438
+ }
439
+
440
+ // Clean up abort controller on success
441
+ this.abortControllers.delete(dataUrlIdentifier);
442
+ return {
443
+ data: transformedData,
444
+ encoding
445
+ };
446
+ } catch (error) {
447
+ if (error.name === 'AbortError') {
448
+ console.log(`Request cancelled for ${resourcePath}`);
449
+ } else {
450
+ console.error(`Failed to load data for path ${resourcePath}:`, error);
451
+ }
452
+ this.dataCache.delete(dataUrlIdentifier);
453
+ this.abortControllers.delete(dataUrlIdentifier);
454
+ return null;
455
+ }
456
+ })();
457
+ this.dataCache.set(dataUrlIdentifier, loadPromise);
458
+ return loadPromise;
459
+ }
460
+ cancelAllRequests() {
461
+ // Abort all in-flight requests
462
+ this.abortControllers.forEach((controller, key) => {
463
+ controller.abort();
464
+ });
465
+
466
+ // Clear both maps
467
+ this.abortControllers.clear();
468
+ this.dataCache.clear();
469
+ console.log('All pending requests cancelled');
470
+ }
471
+ async getValueAtLngLat(lng, lat) {
472
+ const {
473
+ variable,
474
+ isMRMS,
475
+ mrmsTimestamp,
476
+ model,
477
+ date,
478
+ run,
479
+ forecastHour,
480
+ units
481
+ } = this.state;
482
+ if (!variable) return null;
483
+ const gridIndices = this._getGridIndexFromLngLat(lng, lat);
484
+ if (!gridIndices) return null;
485
+ const {
486
+ i,
487
+ j
488
+ } = gridIndices;
489
+ const gridModel = isMRMS ? 'mrms' : model;
490
+ const normalizedGridModel = this._normalizeModelName(gridModel);
491
+ const {
492
+ nx
493
+ } = _coordinate_configs.COORDINATE_CONFIGS[normalizedGridModel].grid_params;
494
+ const customSettings = this.customColormaps[variable];
495
+ const effectiveSmoothing = customSettings && typeof customSettings.smoothing === 'number' ? customSettings.smoothing : 0;
496
+ const dataUrlIdentifier = isMRMS ? `mrms-${mrmsTimestamp}-${variable}-${effectiveSmoothing}` : `${model}-${date}-${run}-${forecastHour}-${variable}-${effectiveSmoothing}`;
497
+ const gridDataPromise = this.dataCache.get(dataUrlIdentifier);
498
+ if (!gridDataPromise) return null;
499
+ try {
500
+ const gridData = await gridDataPromise;
501
+ if (!gridData || !gridData.data) return null;
502
+ const index1D = j * nx + i;
503
+ const byteValue = gridData.data[index1D];
504
+ const signedQuantizedValue = byteValue - 128;
505
+ const {
506
+ scale,
507
+ offset,
508
+ missing_quantized
509
+ } = gridData.encoding;
510
+ if (signedQuantizedValue === missing_quantized) return null;
511
+ const nativeValue = signedQuantizedValue * scale + offset;
512
+ const {
513
+ baseUnit
514
+ } = this._getColormapForVariable(variable);
515
+ let dataNativeUnit = baseUnit || (_dictionaries.DICTIONARIES.fld[variable] || {}).defaultUnit || 'none';
516
+ const displayUnit = this._getTargetUnit(dataNativeUnit, units);
517
+ const conversionFunc = (0, _unitConversions.getUnitConversionFunction)(dataNativeUnit, displayUnit);
518
+ const displayValue = conversionFunc ? conversionFunc(nativeValue) : nativeValue;
519
+ return {
520
+ lngLat: {
521
+ lng,
522
+ lat
523
+ },
524
+ variable: {
525
+ code: variable,
526
+ name: this.getVariableDisplayName(variable)
527
+ },
528
+ value: displayValue,
529
+ unit: displayUnit
530
+ };
531
+ } catch (error) {
532
+ return null;
533
+ }
534
+ }
535
+ getAvailableVariables(modelName = null) {
536
+ var _MODEL_CONFIGS$model;
537
+ const model = modelName || this.state.model;
538
+ return ((_MODEL_CONFIGS$model = _dictionaries.MODEL_CONFIGS[model]) === null || _MODEL_CONFIGS$model === void 0 ? void 0 : _MODEL_CONFIGS$model.vars) || [];
539
+ }
540
+ getVariableDisplayName(variableCode) {
541
+ const varInfo = _dictionaries.DICTIONARIES.fld[variableCode];
542
+ return (varInfo === null || varInfo === void 0 ? void 0 : varInfo.displayName) || (varInfo === null || varInfo === void 0 ? void 0 : varInfo.name) || variableCode;
543
+ }
544
+ _getColormapForVariable(variable) {
545
+ if (!variable) return {
546
+ colormap: [],
547
+ baseUnit: ''
548
+ };
549
+ if (this.customColormaps[variable] && this.customColormaps[variable].colormap) {
550
+ return {
551
+ colormap: this.customColormaps[variable].colormap,
552
+ baseUnit: this.customColormaps[variable].baseUnit || ''
553
+ };
554
+ }
555
+ const colormapKey = _dictionaries.DICTIONARIES.variable_cmap[variable] || variable;
556
+ const customColormap = this.customColormaps[colormapKey];
557
+ if (customColormap && customColormap.colormap) {
558
+ return {
559
+ colormap: customColormap.colormap,
560
+ baseUnit: customColormap.baseUnit || ''
561
+ };
562
+ }
563
+ const defaultColormapData = _defaultColormaps.DEFAULT_COLORMAPS[colormapKey];
564
+ if (defaultColormapData && defaultColormapData.units) {
565
+ const availableUnits = Object.keys(defaultColormapData.units);
566
+ if (availableUnits.length > 0) {
567
+ const baseUnit = availableUnits[0];
568
+ const unitData = defaultColormapData.units[baseUnit];
569
+ if (unitData && unitData.colormap) {
570
+ return {
571
+ colormap: unitData.colormap,
572
+ baseUnit: baseUnit
573
+ };
574
+ }
575
+ }
576
+ }
577
+ return {
578
+ colormap: [],
579
+ baseUnit: ''
580
+ };
581
+ }
582
+ _convertColormapUnits(colormap, fromUnits, toUnits) {
583
+ if (fromUnits === toUnits) return colormap;
584
+ const conversionFunc = (0, _unitConversions.getUnitConversionFunction)(fromUnits, toUnits);
585
+ if (!conversionFunc) return colormap;
586
+ const newColormap = [];
587
+ for (let i = 0; i < colormap.length; i += 2) {
588
+ newColormap.push(conversionFunc(colormap[i]), colormap[i + 1]);
589
+ }
590
+ return newColormap;
591
+ }
592
+ _normalizeModelName(modelName) {
593
+ const mapping = {
594
+ 'hrrr': ['mpashn', 'mpasrt', 'mpasht', 'hrrrsub', 'rrfs', 'namnest', 'mpasrn', 'mpasrn3', 'mpasht2'],
595
+ 'arw': ['arw2', 'fv3', 'href'],
596
+ 'rtma': ['nbm'],
597
+ 'ecmwf': ['ecmwfaifs'],
598
+ 'gfs': ['arpege', 'graphcastgfs']
599
+ };
600
+ for (const [normalized, aliases] of Object.entries(mapping)) {
601
+ if (aliases.includes(modelName)) return normalized;
602
+ }
603
+ return modelName;
604
+ }
605
+ _getGridCornersAndDef(model) {
606
+ const normalizedModel = this._normalizeModelName(model);
607
+ const gridDef = {
608
+ ..._coordinate_configs.COORDINATE_CONFIGS[normalizedModel],
609
+ modelName: model
610
+ };
611
+ if (!gridDef) return null;
612
+ const {
613
+ nx,
614
+ ny
615
+ } = gridDef.grid_params;
616
+ const gridType = gridDef.type;
617
+ let corners;
618
+ if (gridType === 'latlon') {
619
+ let {
620
+ lon_first,
621
+ lat_first,
622
+ lat_last,
623
+ lon_last,
624
+ dx_degrees,
625
+ dy_degrees
626
+ } = gridDef.grid_params;
627
+ corners = {
628
+ lon_tl: lon_first,
629
+ lat_tl: lat_first,
630
+ lon_tr: lon_last !== undefined ? lon_last : lon_first + (nx - 1) * dx_degrees,
631
+ lat_tr: lat_first,
632
+ lon_bl: lon_first,
633
+ lat_bl: lat_last !== undefined ? lat_last : lat_first + (ny - 1) * dy_degrees,
634
+ lon_br: lon_last !== undefined ? lon_last : lon_first + (nx - 1) * dx_degrees,
635
+ lat_br: lat_last !== undefined ? lat_last : lat_first + (ny - 1) * dy_degrees
636
+ };
637
+ } else if (gridType === 'rotated_latlon') {
638
+ const [lon_tl, lat_tl] = hrdpsObliqueTransform(gridDef.grid_params.lon_first, gridDef.grid_params.lat_first);
639
+ const [lon_tr, lat_tr] = hrdpsObliqueTransform(gridDef.grid_params.lon_first + (nx - 1) * gridDef.grid_params.dx_degrees, gridDef.grid_params.lat_first);
640
+ const [lon_bl, lat_bl] = hrdpsObliqueTransform(gridDef.grid_params.lon_first, gridDef.grid_params.lat_first + (ny - 1) * gridDef.grid_params.dy_degrees);
641
+ const [lon_br, lat_br] = hrdpsObliqueTransform(gridDef.grid_params.lon_first + (nx - 1) * gridDef.grid_params.dx_degrees, gridDef.grid_params.lat_first + (ny - 1) * gridDef.grid_params.dy_degrees);
642
+ corners = {
643
+ lon_tl,
644
+ lat_tl,
645
+ lon_tr,
646
+ lat_tr,
647
+ lon_bl,
648
+ lat_bl,
649
+ lon_br,
650
+ lat_br
651
+ };
652
+ } else if (gridType === 'lambert_conformal_conic' || gridType === 'polar_ stereographic') {
653
+ let projString = Object.entries(gridDef.proj_params).map(([k, v]) => `+${k}=${v}`).join(' ');
654
+ if (gridType === 'polar_stereographic') projString += ' +lat_0=90';
655
+ const {
656
+ x_origin,
657
+ y_origin,
658
+ dx,
659
+ dy
660
+ } = gridDef.grid_params;
661
+ const [lon_tl, lat_tl] = (0, _proj.default)(projString, 'EPSG:4326', [x_origin, y_origin]);
662
+ const [lon_tr, lat_tr] = (0, _proj.default)(projString, 'EPSG:4326', [x_origin + (nx - 1) * dx, y_origin]);
663
+ const [lon_bl, lat_bl] = (0, _proj.default)(projString, 'EPSG:4326', [x_origin, y_origin + (ny - 1) * dy]);
664
+ const [lon_br, lat_br] = (0, _proj.default)(projString, 'EPSG:4326', [x_origin + (nx - 1) * dx, y_origin + (ny - 1) * dy]);
665
+ corners = {
666
+ lon_tl,
667
+ lat_tl,
668
+ lon_tr,
669
+ lat_tr,
670
+ lon_bl,
671
+ lat_bl,
672
+ lon_br,
673
+ lat_br
674
+ };
675
+ } else {
676
+ return null;
677
+ }
678
+ return {
679
+ corners,
680
+ gridDef
681
+ };
682
+ }
683
+ _getTargetUnit(defaultUnit, system) {
684
+ if (system === 'metric') {
685
+ if (['°F', '°C'].includes(defaultUnit)) return 'celsius';
686
+ if (['kts', 'mph', 'm/s'].includes(defaultUnit)) return 'km/h';
687
+ if (['in', 'mm', 'cm'].includes(defaultUnit)) return 'mm';
688
+ }
689
+ if (['°F', '°C'].includes(defaultUnit)) return 'fahrenheit';
690
+ if (['kts', 'mph', 'm/s'].includes(defaultUnit)) return 'mph';
691
+ if (['in', 'mm', 'cm'].includes(defaultUnit)) return 'in';
692
+ return defaultUnit;
693
+ }
694
+ _getGridIndexFromLngLat(lng, lat) {
695
+ const gridModel = this.state.isMRMS ? 'mrms' : this.state.model;
696
+ const normalizedGridModel = this._normalizeModelName(gridModel);
697
+ const gridDef = _coordinate_configs.COORDINATE_CONFIGS[normalizedGridModel];
698
+ if (!gridDef) return null;
699
+ const {
700
+ nx,
701
+ ny
702
+ } = gridDef.grid_params;
703
+ const pixelCoords = this.latLonToGridPixel(lat, lng, gridDef, gridModel);
704
+ if (!pixelCoords || !isFinite(pixelCoords.x) || !isFinite(pixelCoords.y) || pixelCoords.x < 0 || pixelCoords.y < 0) return null;
705
+ const i = Math.round(pixelCoords.x);
706
+ const j = Math.round(pixelCoords.y);
707
+ if (i >= 0 && i < nx && j >= 0 && j < ny) return {
708
+ i,
709
+ j
710
+ };
711
+ return null;
712
+ }
713
+ latLonToProjected(lat, lon, gridDef) {
714
+ if (!isFinite(lat) || !isFinite(lon)) throw new Error(`Invalid coordinates: lat=${lat}, lon=${lon}`);
715
+ const gridType = gridDef.type;
716
+ if (gridType === 'latlon') return {
717
+ x: lon,
718
+ y: lat
719
+ };
720
+ let projString = Object.entries(gridDef.proj_params).map(([k, v]) => `+${k}=${v}`).join(' ');
721
+ if (gridType === 'polar_stereographic') projString += ' +lat_0=90';
722
+ const projected = (0, _proj.default)('EPSG:4326', projString, [lon, lat]);
723
+ return {
724
+ x: projected[0],
725
+ y: projected[1]
726
+ };
727
+ }
728
+ latLonToGridPixel(lat, lon, gridDef, modelName) {
729
+ if (!gridDef) return null;
730
+ if (modelName === 'rgem' && gridDef.type === 'polar_stereographic') return this.latLonToGridPixelPolarStereographic(lat, lon, gridDef);
731
+ const projected = this.latLonToProjected(lat, lon, gridDef);
732
+ let x, y;
733
+ const gridOrigin = {
734
+ x: gridDef.grid_params.lon_first,
735
+ y: gridDef.grid_params.lat_first
736
+ };
737
+ const gridPixelSize = {
738
+ x: gridDef.grid_params.dx_degrees,
739
+ y: gridDef.grid_params.dy_degrees
740
+ };
741
+ if (gridDef.type === 'latlon' || gridDef.type === 'rotated_latlon') {
742
+ let adjustedLon = projected.x;
743
+ if (modelName === 'mrms') {
744
+ if (adjustedLon < 0) adjustedLon += 360;
745
+ x = (adjustedLon - gridOrigin.x) / gridPixelSize.x;
746
+ y = (gridOrigin.y - projected.y) / gridPixelSize.y;
747
+ } else {
748
+ const isGFSType = gridDef.grid_params && gridDef.grid_params.lon_first === 0.0 && Math.abs(gridDef.grid_params.lat_first) === 90.0;
749
+ const isECMWFType = gridDef.grid_params && gridDef.grid_params.lon_first === 180.0 && gridDef.grid_params.lat_first === 90.0;
750
+ const isGEMType = modelName === 'gem' || gridDef.grid_params.lon_first === 180.0 && gridDef.grid_params.lat_first === -90.0 && gridDef.grid_params.lon_last === 179.85;
751
+ if (isGEMType) {
752
+ while (adjustedLon < gridOrigin.x) adjustedLon += 360;
753
+ x = (adjustedLon - gridOrigin.x) / gridPixelSize.x;
754
+ y = (projected.y - gridOrigin.y) / gridPixelSize.y;
755
+ return {
756
+ x,
757
+ y
758
+ };
759
+ }
760
+ let isFlippedGrid = isECMWFType ? true : gridDef.grid_params.lat_first < (gridDef.grid_params.lat_last || (gridDef.grid_params.ny - 1) * gridDef.grid_params.dy_degrees);
761
+ if (isGFSType) adjustedLon = projected.x + 180;else if (isECMWFType) {
762
+ if (adjustedLon < gridOrigin.x) adjustedLon += 360;
763
+ } else if (['arome1', 'arome25', 'arpegeeu', 'iconeu', 'icond2'].includes(modelName)) {
764
+ while (adjustedLon < 0) adjustedLon += 360;
765
+ while (adjustedLon >= 360) adjustedLon -= 360;
766
+ x = adjustedLon >= gridOrigin.x ? (adjustedLon - gridOrigin.x) / gridPixelSize.x : (adjustedLon + 360 - gridOrigin.x) / gridPixelSize.x;
767
+ if (['arome1', 'arome25', 'arpegeeu'].includes(modelName)) y = (gridOrigin.y - projected.y) / Math.abs(gridPixelSize.y);else if (['iconeu', 'icond2'].includes(modelName)) y = (projected.y - gridOrigin.y) / gridPixelSize.y;
768
+ return {
769
+ x,
770
+ y
771
+ };
772
+ } else {
773
+ const lonFirst = gridOrigin.x;
774
+ if (lonFirst > 180 && adjustedLon < 0) adjustedLon += 360;else if (lonFirst < 0 && adjustedLon > 180) adjustedLon -= 360;
775
+ }
776
+ x = (adjustedLon - gridOrigin.x) / gridPixelSize.x;
777
+ if (isFlippedGrid) {
778
+ if (isECMWFType) y = (gridOrigin.y - projected.y) / Math.abs(gridPixelSize.y);else {
779
+ const maxLat = gridDef.grid_params.lat_last || (gridDef.grid_params.ny - 1) * gridDef.grid_params.dy_degrees;
780
+ y = (maxLat - projected.y) / Math.abs(gridPixelSize.y);
781
+ }
782
+ } else y = (projected.y - gridOrigin.y) / gridPixelSize.y;
783
+ }
784
+ } else {
785
+ const projOrigin = {
786
+ x: gridDef.grid_params.x_origin,
787
+ y: gridDef.grid_params.y_origin
788
+ };
789
+ const projPixelSize = {
790
+ x: gridDef.grid_params.dx,
791
+ y: gridDef.grid_params.dy
792
+ };
793
+ x = (projected.x - projOrigin.x) / projPixelSize.x;
794
+ y = (projOrigin.y - projected.y) / Math.abs(projPixelSize.y);
795
+ }
796
+ return {
797
+ x,
798
+ y
799
+ };
800
+ }
801
+ latLonToGridPixelPolarStereographic(lat, lon, gridDef) {
802
+ try {
803
+ const projParams = gridDef.proj_params;
804
+ let projectionString = `+proj=${projParams.proj}`;
805
+ Object.keys(projParams).forEach(key => {
806
+ if (key !== 'proj') projectionString += ` +${key}=${projParams[key]}`;
807
+ });
808
+ projectionString += ' +lat_0=90 +no_defs';
809
+ const {
810
+ nx,
811
+ ny,
812
+ dx,
813
+ dy,
814
+ x_origin,
815
+ y_origin
816
+ } = gridDef.grid_params;
817
+ const x_min = x_origin;
818
+ const x_max = x_origin + (nx - 1) * dx;
819
+ const y_max = y_origin;
820
+ const y_min = y_origin + (ny - 1) * dy;
821
+ const [proj_x, proj_y] = (0, _proj.default)('EPSG:4326', projectionString, [lon, lat]);
822
+ if (!isFinite(proj_x) || !isFinite(proj_y)) return {
823
+ x: -1,
824
+ y: -1
825
+ };
826
+ const t_x = (proj_x - x_min) / (x_max - x_min);
827
+ const t_y = (proj_y - y_max) / (y_min - y_max);
828
+ const x = t_x * (nx - 1);
829
+ const y = t_y * (ny - 1);
830
+ return {
831
+ x,
832
+ y
833
+ };
834
+ } catch (error) {
835
+ console.warn(`[GridAccessor] RGEM polar stereographic conversion failed for ${lat}, ${lon}:`, error);
836
+ return {
837
+ x: -1,
838
+ y: -1
839
+ };
840
+ }
841
+ }
842
+
843
+ // --- Worker and Status Methods ---
844
+
845
+ createWorker() {
846
+ if (this.isReactNative) return null;
847
+ const workerCode = `
848
+ import { decompress } from 'https://cdn.skypack.dev/fzstd@0.1.1';
849
+
850
+ function _reconstructData(decompressedDeltas, encoding) {
851
+ const expectedLength = encoding.length;
852
+ const reconstructedData = new Int8Array(expectedLength);
853
+ if (decompressedDeltas.length > 0 && expectedLength > 0) {
854
+ reconstructedData[0] = decompressedDeltas[0] > 127 ? decompressedDeltas[0] - 256 : decompressedDeltas[0];
855
+ for (let i = 1; i < expectedLength; i++) {
856
+ const delta = decompressedDeltas[i] > 127 ? decompressedDeltas[i] - 256 : decompressedDeltas[i];
857
+ reconstructedData[i] = reconstructedData[i - 1] + delta;
858
+ }
859
+ }
860
+ return new Uint8Array(reconstructedData.buffer);
861
+ }
862
+
863
+ self.onmessage = async (e) => {
864
+ const { requestId, compressedData, encoding } = e.data;
865
+ try {
866
+ const decompressedDeltas = await decompress(compressedData);
867
+ const finalData = _reconstructData(decompressedDeltas, encoding);
868
+ self.postMessage({ success: true, requestId: requestId, decompressedData: finalData, encoding: encoding }, [finalData.buffer]);
869
+ } catch (error) {
870
+ self.postMessage({ success: false, requestId: requestId, error: error.message });
871
+ }
872
+ };
873
+ `;
874
+ const blob = new Blob([workerCode], {
875
+ type: 'application/javascript'
876
+ });
877
+ return new Worker(URL.createObjectURL(blob), {
878
+ type: 'module'
879
+ });
880
+ }
881
+ _processResultQueue() {
882
+ while (this.resultQueue.length > 0) {
883
+ const {
884
+ success,
885
+ requestId,
886
+ decompressedData,
887
+ encoding,
888
+ error
889
+ } = this.resultQueue.shift();
890
+ if (this.workerResolvers.has(requestId)) {
891
+ const {
892
+ resolve,
893
+ reject
894
+ } = this.workerResolvers.get(requestId);
895
+ if (success) {
896
+ resolve({
897
+ data: decompressedData
898
+ }); // Return as { data: ... }
899
+ } else {
900
+ reject(new Error(error));
901
+ }
902
+ this.workerResolvers.delete(requestId);
903
+ }
904
+ }
905
+ this.isProcessingQueue = false;
906
+ }
907
+ _handleWorkerMessage(e) {
908
+ if (this.isReactNative) return;
909
+ const {
910
+ success,
911
+ requestId,
912
+ decompressedData,
913
+ encoding,
914
+ error
915
+ } = e.data;
916
+ this.resultQueue.push({
917
+ success,
918
+ requestId,
919
+ decompressedData,
920
+ encoding,
921
+ error
922
+ });
923
+ if (!this.isProcessingQueue) {
924
+ this.isProcessingQueue = true;
925
+ requestAnimationFrame(() => this._processResultQueue());
926
+ }
927
+ }
928
+ async fetchModelStatus(force = false) {
929
+ if (!this.modelStatus || force) {
930
+ try {
931
+ const response = await fetch(this.statusUrl);
932
+ if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
933
+ this.modelStatus = (await response.json()).models;
934
+ } catch (error) {
935
+ this.modelStatus = null;
936
+ }
937
+ }
938
+ return this.modelStatus;
939
+ }
940
+ async fetchMRMSStatus(force = false) {
941
+ const mrmsStatusUrl = 'https://h3dfvh5pq6euq36ymlpz4zqiha0obqju.lambda-url.us-east-2.on.aws';
942
+ if (!this.mrmsStatus || force) {
943
+ try {
944
+ const response = await fetch(mrmsStatusUrl);
945
+ if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
946
+ this.mrmsStatus = await response.json();
947
+ } catch (error) {
948
+ this.mrmsStatus = null;
949
+ }
950
+ }
951
+ return this.mrmsStatus;
952
+ }
953
+ startAutoRefresh(intervalSeconds) {
954
+ this.stopAutoRefresh();
955
+ this.autoRefreshIntervalId = setInterval(async () => {
956
+ await this.fetchModelStatus(true);
957
+ this._emitStateChange();
958
+ }, (intervalSeconds || 60) * 1000);
959
+ }
960
+ stopAutoRefresh() {
961
+ if (this.autoRefreshIntervalId) {
962
+ clearInterval(this.autoRefreshIntervalId);
963
+ this.autoRefreshIntervalId = null;
964
+ }
965
+ }
966
+ }
967
+ exports.AguaceroCore = AguaceroCore;