@aguacerowx/javascript-sdk 0.0.10 → 0.0.12

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