atmosx-nwws-parser 1.0.2

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 (84) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +6 -0
  3. package/dist/cjs/bootstrap.cjs +1009 -0
  4. package/dist/cjs/database.cjs +1114 -0
  5. package/dist/cjs/dictionaries/awips.cjs +379 -0
  6. package/dist/cjs/dictionaries/events.cjs +139 -0
  7. package/dist/cjs/dictionaries/icao.cjs +265 -0
  8. package/dist/cjs/dictionaries/offshore.cjs +40 -0
  9. package/dist/cjs/dictionaries/signatures.cjs +132 -0
  10. package/dist/cjs/eas.cjs +2857 -0
  11. package/dist/cjs/helper.cjs +3014 -0
  12. package/dist/cjs/parsers/events.cjs +2857 -0
  13. package/dist/cjs/parsers/stanza.cjs +1108 -0
  14. package/dist/cjs/parsers/text.cjs +1142 -0
  15. package/dist/cjs/parsers/types/api.cjs +2857 -0
  16. package/dist/cjs/parsers/types/cap.cjs +2857 -0
  17. package/dist/cjs/parsers/types/text.cjs +2857 -0
  18. package/dist/cjs/parsers/types/ugc.cjs +2857 -0
  19. package/dist/cjs/parsers/types/vtec.cjs +2857 -0
  20. package/dist/cjs/parsers/ugc.cjs +1139 -0
  21. package/dist/cjs/parsers/vtec.cjs +1060 -0
  22. package/dist/cjs/types.cjs +17 -0
  23. package/dist/cjs/utils.cjs +2857 -0
  24. package/dist/cjs/xmpp.cjs +2857 -0
  25. package/dist/esm/bootstrap.mjs +972 -0
  26. package/dist/esm/database.mjs +1079 -0
  27. package/dist/esm/dictionaries/awips.mjs +355 -0
  28. package/dist/esm/dictionaries/events.mjs +111 -0
  29. package/dist/esm/dictionaries/icao.mjs +241 -0
  30. package/dist/esm/dictionaries/offshore.mjs +16 -0
  31. package/dist/esm/dictionaries/signatures.mjs +106 -0
  32. package/dist/esm/eas.mjs +2824 -0
  33. package/dist/esm/helper.mjs +2974 -0
  34. package/dist/esm/parsers/events.mjs +2824 -0
  35. package/dist/esm/parsers/stanza.mjs +1072 -0
  36. package/dist/esm/parsers/text.mjs +1106 -0
  37. package/dist/esm/parsers/types/api.mjs +2824 -0
  38. package/dist/esm/parsers/types/cap.mjs +2824 -0
  39. package/dist/esm/parsers/types/text.mjs +2824 -0
  40. package/dist/esm/parsers/types/ugc.mjs +2824 -0
  41. package/dist/esm/parsers/types/vtec.mjs +2824 -0
  42. package/dist/esm/parsers/ugc.mjs +1104 -0
  43. package/dist/esm/parsers/vtec.mjs +1025 -0
  44. package/dist/esm/types.mjs +0 -0
  45. package/dist/esm/utils.mjs +2824 -0
  46. package/dist/esm/xmpp.mjs +2824 -0
  47. package/package.json +47 -0
  48. package/shapefiles/FireCounties.dbf +0 -0
  49. package/shapefiles/FireCounties.shp +0 -0
  50. package/shapefiles/FireZones.dbf +0 -0
  51. package/shapefiles/FireZones.shp +0 -0
  52. package/shapefiles/ForecastZones.dbf +0 -0
  53. package/shapefiles/ForecastZones.shp +0 -0
  54. package/shapefiles/Marine.dbf +0 -0
  55. package/shapefiles/Marine.shp +0 -0
  56. package/shapefiles/OffShoreZones.dbf +0 -0
  57. package/shapefiles/OffShoreZones.shp +0 -0
  58. package/shapefiles/USCounties.dbf +0 -0
  59. package/shapefiles/USCounties.shp +0 -0
  60. package/src/bootstrap.ts +171 -0
  61. package/src/database.ts +99 -0
  62. package/src/dictionaries/awips.ts +351 -0
  63. package/src/dictionaries/events.ts +109 -0
  64. package/src/dictionaries/icao.ts +237 -0
  65. package/src/dictionaries/offshore.ts +12 -0
  66. package/src/dictionaries/signatures.ts +103 -0
  67. package/src/eas.ts +428 -0
  68. package/src/helper.ts +167 -0
  69. package/src/parsers/events.ts +289 -0
  70. package/src/parsers/stanza.ts +103 -0
  71. package/src/parsers/text.ts +167 -0
  72. package/src/parsers/types/api.ts +94 -0
  73. package/src/parsers/types/cap.ts +89 -0
  74. package/src/parsers/types/text.ts +54 -0
  75. package/src/parsers/types/ugc.ts +85 -0
  76. package/src/parsers/types/vtec.ts +60 -0
  77. package/src/parsers/ugc.ts +148 -0
  78. package/src/parsers/vtec.ts +66 -0
  79. package/src/types.ts +187 -0
  80. package/src/utils.ts +216 -0
  81. package/src/xmpp.ts +123 -0
  82. package/test.js +1 -0
  83. package/tsconfig.json +14 -0
  84. package/tsup.config.ts +11 -0
@@ -0,0 +1,2824 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+
41
+ // src/bootstrap.ts
42
+ import * as fs from "fs";
43
+ import * as path from "path";
44
+ import * as events from "events";
45
+ import * as xmpp from "@xmpp/client";
46
+ import * as shapefile from "shapefile";
47
+ import * as xml2js from "xml2js";
48
+ import * as cron from "node-cron";
49
+ import sqlite3 from "better-sqlite3";
50
+ import axios from "axios";
51
+ import crypto from "crypto";
52
+ import os from "os";
53
+ import say from "say";
54
+
55
+ // src/dictionaries/events.ts
56
+ var EVENTS = {
57
+ "AF": "Ashfall",
58
+ "AS": "Air Stagnation",
59
+ "BH": "Beach Hazard",
60
+ "BW": "Brisk Wind",
61
+ "BZ": "Blizzard",
62
+ "CF": "Coastal Flood",
63
+ "DF": "Debris Flow",
64
+ "DS": "Dust Storm",
65
+ "EC": "Extreme Cold",
66
+ "EH": "Excessive Heat",
67
+ "XH": "Extreme Heat",
68
+ "EW": "Extreme Wind",
69
+ "FA": "Areal Flood",
70
+ "FF": "Flash Flood",
71
+ "FG": "Dense Fog",
72
+ "FL": "Flood",
73
+ "FR": "Frost",
74
+ "FW": "Fire Weather",
75
+ "FZ": "Freeze",
76
+ "GL": "Gale",
77
+ "HF": "Hurricane Force Wind",
78
+ "HT": "Heat",
79
+ "HU": "Hurricane",
80
+ "HW": "High Wind",
81
+ "HY": "Hydrologic",
82
+ "HZ": "Hard Freeze",
83
+ "IS": "Ice Storm",
84
+ "LE": "Lake Effect Snow",
85
+ "LO": "Low Water",
86
+ "LS": "Lakeshore Flood",
87
+ "LW": "Lake Wind",
88
+ "MA": "Special Marine",
89
+ "EQ": "Earthquake",
90
+ "MF": "Dense Fog",
91
+ "MH": "Ashfall",
92
+ "MS": "Dense Smoke",
93
+ "RB": "Small Craft for Rough Bar",
94
+ "RP": "Rip Current Risk",
95
+ "SC": "Small Craft",
96
+ "SE": "Hazardous Seas",
97
+ "SI": "Small Craft for Winds",
98
+ "SM": "Dense Smoke",
99
+ "SQ": "Snow Squall",
100
+ "SR": "Storm",
101
+ "SS": "Storm Surge",
102
+ "SU": "High Surf",
103
+ "SV": "Severe Thunderstorm",
104
+ "SW": "Small Craft for Hazardous Seas",
105
+ "TO": "Tornado",
106
+ "TR": "Tropical Storm",
107
+ "TS": "Tsunami",
108
+ "TY": "Typhoon",
109
+ "SP": "Special Weather",
110
+ "UP": "Heavy Freezing Spray",
111
+ "WC": "Wind Chill",
112
+ "WI": "Wind",
113
+ "WS": "Winter Storm",
114
+ "WW": "Winter Weather",
115
+ "ZF": "Freezing Fog",
116
+ "ZR": "Freezing Rain",
117
+ "ZY": "Freezing Spray"
118
+ };
119
+ var ACTIONS = {
120
+ "W": "Warning",
121
+ "F": "Forecast",
122
+ "A": "Watch",
123
+ "O": "Outlook",
124
+ "Y": "Advisory",
125
+ "N": "Synopsis",
126
+ "S": "Statement"
127
+ };
128
+ var STATUS = {
129
+ "NEW": "Issued",
130
+ "CON": "Updated",
131
+ "EXT": "Extended",
132
+ "EXA": "Extended",
133
+ "EXB": "Extended",
134
+ "UPG": "Upgraded",
135
+ "COR": "Correction",
136
+ "ROU": "Routine",
137
+ "CAN": "Cancelled",
138
+ "EXP": "Expired"
139
+ };
140
+ var TYPES = {
141
+ "O": "Operational Product",
142
+ "T": "Test Product",
143
+ "E": "Experimental Product",
144
+ "X": "Experimental Product (Non-Operational)"
145
+ };
146
+ var STATUS_CORRELATIONS = [
147
+ { type: "Update", forward: "Updated", cancel: false },
148
+ { type: "Cancel", forward: "Cancelled", cancel: true },
149
+ { type: "Alert", forward: "Issued", cancel: false },
150
+ { type: "Updated", forward: "Updated", cancel: false },
151
+ { type: "Expired", forward: "Expired", cancel: true },
152
+ { type: "Issued", forward: "Issued", cancel: false },
153
+ { type: "Extended", forward: "Updated", cancel: false },
154
+ { type: "Correction", forward: "Updated", cancel: false },
155
+ { type: "Upgraded", forward: "Upgraded", cancel: false },
156
+ { type: "Cancelled", forward: "Cancelled", cancel: true },
157
+ { type: "Routine", forward: "Routine", cancel: false }
158
+ ];
159
+
160
+ // src/dictionaries/offshore.ts
161
+ var OFFSHORE = {
162
+ "Special Weather Statement": "Special Weather Statement",
163
+ "Hurricane Warning": "Hurricane Warning",
164
+ "Hurricane Force Wind Warning": "Hurricane Force Wind Warning",
165
+ "Hurricane Watch": "Hurricane Watch",
166
+ "Tropical Storm Warning": "Tropical Storm Warning",
167
+ "Tropical Storm Watch": "Tropical Storm Watch",
168
+ "High Wind Warning": "High Wind Warning",
169
+ "Gale Warning": "Gale Warning",
170
+ "Small Craft Advisory": "Small Craft Advisory",
171
+ "Small Craft Warning": "Small Craft Warning"
172
+ };
173
+
174
+ // src/dictionaries/awips.ts
175
+ var AWIPS = {
176
+ ABV: `abv`,
177
+ ADA: `administrative-message`,
178
+ ADM: `administrative-message`,
179
+ ADR: `administrative-message`,
180
+ AHD: `area-hydrological-discussion`,
181
+ AHONT1: `high-density-observations-usaf-noaa`,
182
+ AHOPA1: `high-density-observations-usaf-noaa-west-pac`,
183
+ AHOPN1: `high-density-observations-usaf-noaa`,
184
+ AFD: `area-forecast-discussion`,
185
+ AQA: `air-quality-alert`,
186
+ AQI: `ground-level-ozone-forecast`,
187
+ AVA: `avalanche-watch`,
188
+ AVW: `avalanche-warning`,
189
+ AWU: `area-weather-update`,
190
+ AVG: `avalanche-weather-guidance`,
191
+ AWW: `airport-weather-warning`,
192
+ BLU: `blue-alert`,
193
+ CAE: `child-abduction-emergency`,
194
+ CDW: `civil-danger-warning`,
195
+ CEM: `civil-emergency-message`,
196
+ CFW: `coastal-hazard-message`,
197
+ CGR: `coastal-weather-observations`,
198
+ CLI: `daily-climate-report`,
199
+ CLM: `monthly-climate-report`,
200
+ CRF: `contingency-river-forecast`,
201
+ CWA: `center-weather-advisory`,
202
+ CWF: `coastal-waters-forecast`,
203
+ DGT: `drought-information`,
204
+ DSA: `tropical-disturbance-statement`,
205
+ DSW: `dust-storm-warning`,
206
+ EQI: `earthquake-information`,
207
+ EQR: `earthquake-report`,
208
+ EQW: `earthquake-warning`,
209
+ ESF: `hydrologic-outlook`,
210
+ EVI: `evacuation-immediate`,
211
+ EWW: `extreme-wind-warning`,
212
+ FFA: `flood-watch`,
213
+ FFG: `flash-flood-guidance`,
214
+ FFGMPD: `mesoscale-precipitation-discussion`,
215
+ FLS: `flood-advisory`,
216
+ FLW: `flood-warning`,
217
+ FFS: `flash-flood-statement`,
218
+ FFW: `flash-flood-warning`,
219
+ MWS: `marine-weather-statement`,
220
+ MWW: `marine-weather-warning`,
221
+ NMN: `network-message-notification`,
222
+ NOW: `short-term-forecast`,
223
+ NPW: `non-convective-advisory`,
224
+ NSH: `nearshore-marine-forecast`,
225
+ NUW: `nuclear-power-plant-warning`,
226
+ PMDAK: `alaska-discussion`,
227
+ PMDCA: `tropical-discussion`,
228
+ PMDEPD: `extended-forecast-discussion`,
229
+ PMDHI: `hawaii-discussion`,
230
+ PMDHMD: `model-diagnostic-discussion`,
231
+ PMDSA: `south-america-forecast-discussion`,
232
+ PMDSPD: `short-range-forecast-discussion`,
233
+ PNS: `public-information-statement`,
234
+ FRW: `fire-warning`,
235
+ FTM: `free-text-message`,
236
+ FWF: `fire-weather-planning-forecast`,
237
+ FWA: `fire-weather-administrative-message`,
238
+ FWS: `fire-weather-spot-forecast`,
239
+ GLF: `open-lake-forecast`,
240
+ HCM: `hydromet-coordination-message`,
241
+ HMT: `hmt`,
242
+ HMW: `hazardous-materials-warning`,
243
+ HPA: `high-pollution-advisory`,
244
+ HLS: `hurricane-local-statement`,
245
+ HMD: `rainfall-and-flood-outlook-product`,
246
+ HSF: `high-seas-forecast`,
247
+ HWO: `hazardous-weather-outlook`,
248
+ HYD: `supplementary-temp-and-precip`,
249
+ LAE: `local-area-emergency`,
250
+ LCO: `local-cooperative-observation`,
251
+ LEW: `law-enforcement-warning`,
252
+ LSR: `local-storm-report`,
253
+ ICE: `ice-outlook`,
254
+ MIS: `meteorological-impact-statement`,
255
+ OAV: `other-aviation-report`,
256
+ OEP: `taf-collaboration-product`,
257
+ OFF: `offshore-waters-forecast`,
258
+ OMR: `other-marine-reports`,
259
+ OSO: `weather-roundup`,
260
+ PFM: `point-forecast-matrices`,
261
+ PSH: `post-tropical-event-report`,
262
+ PWO: `public-severe-weather-outlook`,
263
+ QPFERD: `excessive-rainfall-discussion`,
264
+ QPFHSD: `heavy-snow-discussion`,
265
+ QPS: `quantitative-precipitation-forecast`,
266
+ REC: `recreational-forecast`,
267
+ REPNT0: `recco-observations-non-tropical-cyclone`,
268
+ REPNT1: `recco-observations-tropical-cyclone`,
269
+ REPNT2: `vortex-data-message`,
270
+ REPNTS: `supplementary-vortex-data-message`,
271
+ REPNT3: `dropsonde-observations`,
272
+ REPPN0: `recco-observations-non-tropical-cyclone`,
273
+ REPPN1: `recco-observations-tropical-cyclone`,
274
+ REPPN2: `vortex-data-message`,
275
+ REPPNS: `supplementary-vortex-data-message`,
276
+ REPPN3: `dropsonde-observations`,
277
+ REPPA0: `recco-observations-west-pac-non-tropical-cyclone`,
278
+ REPPA1: `recco-observations-west-pac-tropical-cyclone`,
279
+ REPPA2: `vortex-data-message-west-pac`,
280
+ REPPAS: `supplementary-vortex-data-message-west-pac`,
281
+ REPPA3: `dropsonde-observations-west-pac`,
282
+ REPRPD: `weather-reconnaissance-flights`,
283
+ RER: `record-event-report`,
284
+ RFD: `grassland-fire-danger`,
285
+ RFW: `red-flag-warning`,
286
+ RHW: `radiological-hazard-warning`,
287
+ RRM: `rainfall-storm-total`,
288
+ RTP: `regional-temperature-and-precipitation`,
289
+ RVA: `hydrologic-summary`,
290
+ RVD: `river-and-lake-summary`,
291
+ RVF: `river-forecast`,
292
+ RVS: `hydrologic-statement`,
293
+ RWR: `weather-roundup`,
294
+ RWS: `regional-weather-summary`,
295
+ SAB: `special-avalanche-bulletin`,
296
+ SCC: `storm-summary`,
297
+ SFT: `state-forecast-tabular-product`,
298
+ SIG: `convective-sigment`,
299
+ SMF: `smoke-management-weather-forecast`,
300
+ SMW: `special-marine-warning`,
301
+ SPS: `special-weather-statement`,
302
+ SPW: `shelter-in-place-warning`,
303
+ SQW: `snow-squall-warning`,
304
+ SRF: `surf-zone-forecast`,
305
+ STF: `tabular-state-forecast`,
306
+ STQ: `spot-forecast-request`,
307
+ SVR: `severe-thunderstorm-warning`,
308
+ SVS: `severe-weather-statement`,
309
+ SWOMCD: `mesoscale-convective-discussion`,
310
+ TAF: `terminal-aerodrome-forecast`,
311
+ TCD: `tropical-cyclone-discussion`,
312
+ TCE: `tropical-cyclone-position-estimate`,
313
+ TCM: `tropical-storm-forecast`,
314
+ TCU: `tropical-cyclone-update`,
315
+ TCV: `tropical-watch-warning-local-statement`,
316
+ TIB: `tsunami-information-statement`,
317
+ TID: `tide-data`,
318
+ TMA: `tsunami-message-acknowledgement`,
319
+ TOE: `telephone-outage-emergency`,
320
+ TOR: `tornado-warning`,
321
+ TWD: `tropical-weather-discussion`,
322
+ TWO: `tropical-weather-outlook`,
323
+ VAA: `volcanic-ash-advisory`,
324
+ VOW: `volcano-warning`,
325
+ WCN: `watch-county-notification`,
326
+ WRK: `work-product`,
327
+ WSV: `volcanic-ash-sigmet`,
328
+ WSW: `winter-weather-message`,
329
+ XTEUS: `wpc-contiguous-us-daily-max-min-temps`,
330
+ ZFP: `zone-forecast-package`,
331
+ RR1: `hydro-meteorological-data-report-pt1`,
332
+ RR2: `hydro-meteorological-data-report-pt2`,
333
+ RR3: `hydro-meteorological-data-report-pt3`,
334
+ RR4: `hydro-meteorological-data-report-pt4`,
335
+ RR5: `hydro-meteorological-data-report-pt5`,
336
+ RR6: `hydro-meteorological-data-report-pt6`,
337
+ RR7: `hydro-meteorological-data-report-pt7`,
338
+ RR8: `hydro-meteorological-data-report-pt8`,
339
+ RR9: `hydro-meteorological-data-report-pt9`,
340
+ SFP: `state-forecast-product`,
341
+ AFM: `area-forecast-matrices`,
342
+ AAG: `aag`,
343
+ ADV: `adv`,
344
+ AFP: `afp`,
345
+ AFW: `afw`,
346
+ AGO: `ago`,
347
+ AIR: `air`,
348
+ ALG: `alg`,
349
+ ALT: `alt`,
350
+ AVD: `avd`,
351
+ AWO: `awo`,
352
+ BOY: `boy`,
353
+ BRT: `brt`,
354
+ CF6: `cf6`,
355
+ CFP: `cfp`,
356
+ CLS: `cls`,
357
+ CMM: `cmm`,
358
+ COD: `cod`,
359
+ CRN: `crn`,
360
+ CUR: `cur`,
361
+ CWD: `cwd`,
362
+ CWS: `cws`,
363
+ DAY: `day`,
364
+ DDO: `ddo`,
365
+ DMO: `dmo`,
366
+ DSM: `dsm`,
367
+ ECD: `ecd`,
368
+ EFP: `efp`,
369
+ EOL: `eol`,
370
+ EOM: `eom`,
371
+ ESG: `esg`,
372
+ ESP: `esp`,
373
+ ESS: `ess`,
374
+ ETT: `ett`,
375
+ FA0: `fa0`,
376
+ FA7: `fa7`,
377
+ FA8: `fa8`,
378
+ FA9: `fa9`,
379
+ FD0: `fd0`,
380
+ FD1: `fd1`,
381
+ FD3: `fd3`,
382
+ FD5: `fd5`,
383
+ FD8: `fd8`,
384
+ FD9: `fd9`,
385
+ FDI: `fdi`,
386
+ FFH: `ffh`,
387
+ FFP: `ffp`,
388
+ FLR: `flr`,
389
+ FOP: `fop`,
390
+ FRH: `frh`,
391
+ FSH: `fsh`,
392
+ FTP: `ftp`,
393
+ FWD: `fwd`,
394
+ FWL: `fwl`,
395
+ FWM: `fwm`,
396
+ FWN: `fwn`,
397
+ FWO: `fwo`,
398
+ FZL: `fzl`,
399
+ GEN: `gen`,
400
+ GMT: `gmt`,
401
+ HD0: `hd0`,
402
+ HD2: `hd2`,
403
+ HD3: `hd3`,
404
+ HD4: `hd4`,
405
+ HD6: `hd6`,
406
+ HD8: `hd8`,
407
+ HML: `hml`,
408
+ HWR: `hwr`,
409
+ LAK: `lak`,
410
+ LEV: `lev`,
411
+ LLL: `lll`,
412
+ HP2: `hp2`,
413
+ HRR: `hrr`,
414
+ HYM: `hym`,
415
+ ICO: `ico`,
416
+ IDM: `idm`,
417
+ MAN: `man`,
418
+ MAP: `map`,
419
+ MAR: `mar`,
420
+ MAV: `mav`,
421
+ MCG: `mcg`,
422
+ MCX: `mcx`,
423
+ MET: `met`,
424
+ MEX: `mex`,
425
+ MFM: `mfm`,
426
+ MFP: `mfp`,
427
+ MHF: `mhf`,
428
+ MME: `mme`,
429
+ MMG: `mmg`,
430
+ MRP: `mrp`,
431
+ MSM: `msm`,
432
+ MTR: `mtr`,
433
+ MTT: `mtt`,
434
+ MVF: `mvf`,
435
+ NWR: `nwr`,
436
+ OFA: `ofa`,
437
+ OPU: `opu`,
438
+ OPW: `opw`,
439
+ OSB: `osb`,
440
+ PFW: `pfw`,
441
+ PLS: `pls`,
442
+ PMD: `pmd`,
443
+ POE: `poe`,
444
+ PRB: `prb`,
445
+ PTS: `pts`,
446
+ PWS: `pws`,
447
+ QPF: `qpf`,
448
+ QPG: `qpg`,
449
+ RBG: `rbg`,
450
+ REP: `rep`,
451
+ RFM: `rfm`,
452
+ RFR: `rfr`,
453
+ RRA: `rra`,
454
+ RRS: `rrs`,
455
+ RRY: `rry`,
456
+ RRZ: `rrz`,
457
+ RVC: `rvc`,
458
+ RVG: `rvg`,
459
+ RVK: `rvk`,
460
+ RVM: `rvm`,
461
+ RVO: `rvo`,
462
+ RVR: `rvr`,
463
+ RVU: `rvu`,
464
+ SAF: `saf`,
465
+ SAG: `sag`,
466
+ SAT: `sat`,
467
+ SAW: `saw`,
468
+ SCN: `scn`,
469
+ SCP: `scp`,
470
+ SCS: `scs`,
471
+ SCV: `scv`,
472
+ SEL: `sel`,
473
+ SGL: `sgl`,
474
+ SPE: `spe`,
475
+ SPN: `spn`,
476
+ SRG: `srg`,
477
+ SSM: `ssm`,
478
+ STA: `sta`,
479
+ SUM: `sum`,
480
+ SWE: `swe`,
481
+ SYN: `syn`,
482
+ TAP: `tap`,
483
+ TCA: `tca`,
484
+ TCP: `tcp`,
485
+ TCS: `tcs`,
486
+ TPT: `tpt`,
487
+ TST: `tst`,
488
+ TSU: `tsu`,
489
+ TUV: `tuv`,
490
+ TVL: `tvl`,
491
+ TWS: `tws`,
492
+ TXT: `txt`,
493
+ UVI: `uvi`,
494
+ VFT: `vft`,
495
+ WA0: `wa0`,
496
+ WA1: `wa1`,
497
+ WA2: `wa2`,
498
+ WA3: `wa3`,
499
+ WA4: `wa4`,
500
+ WA5: `wa5`,
501
+ WA6: `wa6`,
502
+ WA7: `wa7`,
503
+ WA8: `wa8`,
504
+ WA9: `wa9`,
505
+ WAR: `war`,
506
+ WAT: `wat`,
507
+ WCL: `wcl`,
508
+ WEE: `wee`,
509
+ WEK: `wek`,
510
+ WOU: `wou`,
511
+ WRM: `wrm`,
512
+ WS1: `ws1`,
513
+ WS2: `ws2`,
514
+ WS3: `ws3`,
515
+ WS4: `ws4`,
516
+ WS5: `ws5`,
517
+ WS6: `ws6`,
518
+ WSC: `wsc`,
519
+ WST: `wst`,
520
+ WTA: `wta`,
521
+ WWA: `wwa`,
522
+ WWP: `wwp`,
523
+ XF0: `xf0`,
524
+ XOB: `xob`
525
+ };
526
+
527
+ // src/dictionaries/signatures.ts
528
+ var TAGS = {
529
+ "A LARGE AND EXTREMELY DANGEROUS TORNADO": "Large and Dangerous Tornado",
530
+ "THIS IS A PARTICULARLY DANGEROUS SITUATION": "Particularly Dangerous Situation",
531
+ "RADAR INDICATED ROTATION": "Radar Indicated Tornado",
532
+ "WEATHER SPOTTERS CONFIRMED TORNADO": "Confirmed by Storm Spotters",
533
+ "A SEVERE THUNDERSTORM CAPABLE OF PRODUCING A TORNADO": "Developing Tornado",
534
+ "LAW ENFORCEMENT CONFIRMED TORNADO": "Reported by Law Enforcement",
535
+ "A TORNADO IS ON THE GROUND": "Confirmed Tornado",
536
+ "WEATHER SPOTTERS REPORTED FUNNEL CLOUD": "Confirmed Funnel Cloud by Storm Spotters",
537
+ "PUBLIC CONFIRMED TORNADO": "Public reports of Tornado",
538
+ "RADAR CONFIRMED": "Radar Confirmed",
539
+ "TORNADO WAS REPORTED BRIEFLY ON THE GROUND": "Tornado no longer on ground",
540
+ "SPOTTERS INDICATE THAT A FUNNEL CLOUD CONTINUES WITH THIS STORM": "Funnel Cloud Continues",
541
+ "A TORNADO MAY DEVELOP AT ANY TIME": "Potentional still exists for Tornado to form",
542
+ "LIFE-THREATENING SITUATION": "Life Threating Situation",
543
+ "COMPLETE DESTRUCTION IS POSSIBLE": "Extremly Damaging Tornado",
544
+ "POTENTIALLY DEADLY TORNADO": "Deadly Tornado",
545
+ "RADAR INDICATED": "Radar Indicated",
546
+ "HAIL DAMAGE TO VEHICLES IS EXPECTED": "Damaging to Vehicles",
547
+ "EXPECT WIND DAMAGE": "Wind Damage",
548
+ "FREQUENT LIGHTNING": "Frequent Lightning",
549
+ "PEOPLE AND ANIMALS OUTDOORS WILL BE INJURED": "Capable of Injuring People and Animals",
550
+ "TRAINED WEATHER SPOTTERS": "Confirmed by Storm Spotters",
551
+ "SOURCE...PUBLIC": "Confirmed by Public",
552
+ "SMALL CRAFT COULD BE DAMAGED": "Potential Damage to Small Craft",
553
+ "A TORNADO WATCH REMAINS IN EFFECT": "Active Tornado Watch",
554
+ "TENNIS BALL SIZE HAIL": "Tennis Ball Size Hail",
555
+ "BASEBALL SIZE HAIL": "Baseball Size Hail",
556
+ "GOLF BALL SIZE HAIL": "Golf Ball Size Hail",
557
+ "QUARTER SIZE HAIL": "Quarter Size Hail",
558
+ "PING PONG BALL SIZE HAIL": "Ping Pong Ball Size Hail",
559
+ "NICKEL SIZE HAIL": "Nickel Size Hail",
560
+ "DOPPLER RADAR.": "Confirmed by Radar",
561
+ "DOPPLER RADAR AND AUTOMATED GAUGES.": "Confirmed by Radar and Gauges",
562
+ "FLASH FLOODING CAUSED BY THUNDERSTORMS.": "Caused by Thunderstorm",
563
+ "SOURCE...EMERGENCY MANAGEMENT.": "Confirmed by Emergency Management",
564
+ "FLASH FLOODING CAUSED BY HEAVY RAIN.": "Caused by heavy rain",
565
+ "SOURCE...LAW ENFORCEMENT REPORTED.": "Confirmed by Law Enforcement"
566
+ };
567
+ var CANCEL_SIGNATURES = [
568
+ "THIS_MESSAGE_IS_FOR_TEST_PURPOSES_ONLY",
569
+ "this is a test",
570
+ "subsided sufficiently for the advisory to be cancelled",
571
+ "has been cancelled",
572
+ "will be allowed to expire",
573
+ "has diminished",
574
+ "and no longer",
575
+ "has been replaced",
576
+ "The threat has ended",
577
+ "has weakened below severe"
578
+ ];
579
+ var MESSAGE_SIGNATURES = [
580
+ { regex: /\r?\n/g, replacement: " " },
581
+ { regex: /\s+/g, replacement: " " },
582
+ { regex: /\*/g, replacement: "." },
583
+ { regex: /\bUTC\b/g, replacement: "Coordinated Universal Time" },
584
+ { regex: /\bGMT\b/g, replacement: "Greenwich Mean Time" },
585
+ { regex: /\bEST\b/g, replacement: "Eastern Standard Time" },
586
+ { regex: /\bEDT\b/g, replacement: "Eastern Daylight Time" },
587
+ { regex: /\bCST\b/g, replacement: "Central Standard Time" },
588
+ { regex: /\bCDT\b/g, replacement: "Central Daylight Time" },
589
+ { regex: /\bMST\b/g, replacement: "Mountain Standard Time" },
590
+ { regex: /\bMDT\b/g, replacement: "Mountain Daylight Time" },
591
+ { regex: /\bPST\b/g, replacement: "Pacific Standard Time" },
592
+ { regex: /\bPDT\b/g, replacement: "Pacific Daylight Time" },
593
+ { regex: /\bAKST\b/g, replacement: "Alaska Standard Time" },
594
+ { regex: /\bAKDT\b/g, replacement: "Alaska Daylight Time" },
595
+ { regex: /\bHST\b/g, replacement: "Hawaii Standard Time" },
596
+ { regex: /\bHDT\b/g, replacement: "Hawaii Daylight Time" },
597
+ { regex: /\bmph\b/g, replacement: "miles per hour" },
598
+ { regex: /\bkm\/h\b/g, replacement: "kilometers per hour" },
599
+ { regex: /\bkmh\b/g, replacement: "kilometers per hour" },
600
+ { regex: /\bkt\b/g, replacement: "knots" },
601
+ { regex: /\bNE\b/g, replacement: "northeast" },
602
+ { regex: /\bNW\b/g, replacement: "northwest" },
603
+ { regex: /\bSE\b/g, replacement: "southeast" },
604
+ { regex: /\bSW\b/g, replacement: "southwest" },
605
+ { regex: /\bNM\b/g, replacement: "nautical miles" },
606
+ { regex: /\bdeg\b/g, replacement: "degrees" },
607
+ { regex: /\btstm\b/g, replacement: "thunderstorm" },
608
+ { regex: /\bmm\b/g, replacement: "millimeters" },
609
+ { regex: /\bcm\b/g, replacement: "centimeters" },
610
+ { regex: /\bin\b/g, replacement: "inches" },
611
+ { regex: /\bft\b/g, replacement: "feet" },
612
+ { regex: /\bmi\b/g, replacement: "miles" },
613
+ { regex: /\bhr\b/g, replacement: "hour" },
614
+ { regex: /\bhourly\b/g, replacement: "per hour" },
615
+ { regex: /\bkg\b/g, replacement: "kilograms" },
616
+ { regex: /\bg\/kg\b/g, replacement: "grams per kilogram" },
617
+ { regex: /\bmb\b/g, replacement: "millibars" },
618
+ { regex: /\bhPa\b/g, replacement: "hectopascals" },
619
+ { regex: /\bPa\b/g, replacement: "pascals" },
620
+ { regex: /\bKPa\b/g, replacement: "kilopascals" },
621
+ { regex: /\bC\/hr\b/g, replacement: "degrees Celsius per hour" },
622
+ { regex: /\bF\/hr\b/g, replacement: "degrees Fahrenheit per hour" },
623
+ { regex: /\bC\/min\b/g, replacement: "degrees Celsius per minute" },
624
+ { regex: /\bF\/min\b/g, replacement: "degrees Fahrenheit per minute" },
625
+ { regex: /\bC\b/g, replacement: "degrees Celsius" },
626
+ { regex: /\bF\b/g, replacement: "degrees Fahrenheit" }
627
+ ];
628
+
629
+ // src/dictionaries/icao.ts
630
+ var ICAOs = {
631
+ "KLCH": "Lake Charles, LA",
632
+ "TSTL": "St. Louis, MO",
633
+ "PABC": "Bethel, AK",
634
+ "TCMH": "Columbus, OH",
635
+ "KEPZ": "El Paso, TX",
636
+ "KCYS": "Cheyenne, WY",
637
+ "KJKL": "Jackson, KY",
638
+ "KPAH": "Paducah, KY",
639
+ "KEMX": "Tucson, AZ",
640
+ "KMHX": "Morehead City, NC",
641
+ "PAPD": "Fairbanks, AK",
642
+ "KDLH": "Duluth, MN",
643
+ "TADW": "Andrews Air Force Base, MD",
644
+ "KOKX": "Brookhaven, NY",
645
+ "KLZK": "Little Rock, AR",
646
+ "KHGX": "Houston, TX",
647
+ "TMSY": "New Orleans, LA",
648
+ "KDGX": "Jackson/Brandon, MS",
649
+ "KCTP": "Caribou, ME",
650
+ "KAMA": "Amarillo, TX",
651
+ "PGUA": "Andersen AFB, GU",
652
+ "KAPX": "Gaylord, MI",
653
+ "PAHG": "Kenai, AK",
654
+ "KLWX": "Sterling, VA",
655
+ "HWPA2": "Homer, AK",
656
+ "KGRK": "Fort Hood, TX",
657
+ "KAKQ": "Wakefield, VA",
658
+ "ROCO2": "Norman, OK",
659
+ "KCLX": "Charleston, SC",
660
+ "TPHX": "Phoenix, AZ",
661
+ "KNKX": "San Diego, CA",
662
+ "TDEN": "Denver, CO",
663
+ "TLAS": "Las Vegas, NV",
664
+ "KBUF": "Buffalo, NY",
665
+ "KTLX": "Norman, OK",
666
+ "KILX": "Lincoln, IL",
667
+ "KHDC": "Hammond, LA",
668
+ "KVWX": "Evansville, IN",
669
+ "TCLT": "Charlotte, NC",
670
+ "TEWR": "Newark, NJ",
671
+ "KFSD": "Sioux Falls, SD",
672
+ "KEAX": "Pleasant Hill, MO",
673
+ "KICX": "Cedar City, UT",
674
+ "KHTX": "Huntsville, AL",
675
+ "PACG": "Sitka, AK",
676
+ "KSOX": "Santa Ana Mountains, CA",
677
+ "TPBI": "West Palm Beach, FL",
678
+ "TSLC": "Salt Lake City, UT",
679
+ "KGLD": "Goodland, KS",
680
+ "TRDU": "Raleigh-Durham, NC",
681
+ "KATX": "Seattle, WA",
682
+ "TICH": "Wichita, KS",
683
+ "TSDF": "Louisville, KY",
684
+ "TBOS": "Boston, MA",
685
+ "TDCA": "Washington, DC",
686
+ "KUEX": "Grand Island, NE",
687
+ "TLKA2": "Talkeetna, AK",
688
+ "KBGM": "Binghamton, NY",
689
+ "TLVE": "Cleveland, OH",
690
+ "KCAE": "Columbia, SC",
691
+ "KDVN": "Quad Cities, IA",
692
+ "KABR": "Aberdeen, SD",
693
+ "KBYX": "Key West, FL",
694
+ "KMPX": "Minneapolis, MN",
695
+ "KCRP": "Corpus Christi, TX",
696
+ "KCBW": "Caribou, ME",
697
+ "KMRX": "Knoxville, TN",
698
+ "KSHV": "Shreveport, LA",
699
+ "KIWA": "Phoenix, AZ",
700
+ "KRGX": "Reno, NV",
701
+ "PHKM": "Kamuela, HI",
702
+ "KABX": "Albuquerque, NM",
703
+ "KBMX": "Birmingham, AL",
704
+ "TMDW": "Chicago Midway, IL",
705
+ "KVAX": "Moody AFB, GA",
706
+ "KHDX": "Holloman AFB, NM",
707
+ "KBRO": "Brownsville, TX",
708
+ "KTWX": "Topeka, KS",
709
+ "KRTX": "Portland, OR",
710
+ "KCXX": "Burlington, VT",
711
+ "KFCX": "Roanoke, VA",
712
+ "KFFC": "Atlanta, GA",
713
+ "KBOX": "Boston, MA",
714
+ "KTLH": "Tallahassee, FL",
715
+ "KPUX": "Pueblo, CO",
716
+ "KFDR": "Altus AFB, OK",
717
+ "KGJX": "Grand Junction, CO",
718
+ "KDTX": "Detroit, MI",
719
+ "PHWA": "Waimea, HI",
720
+ "KMQT": "Marquette, MI",
721
+ "KSJT": "San Angelo, TX",
722
+ "KUDX": "Rapid City, SD",
723
+ "TIAH": "Houston, TX",
724
+ "KSRX": "Fort Smith, AR",
725
+ "TJFK": "New York City, NY",
726
+ "KDDC": "Dodge City, KS",
727
+ "PAKC": "King Salmon, AK",
728
+ "PAIH": "Middleton Island, AK",
729
+ "RODN": "Kadena AB, JA",
730
+ "TBWI": "Baltimore/Washington, MD",
731
+ "KIWX": "Northern Indiana, IN",
732
+ "KFDX": "Cannon AFB, NM",
733
+ "TMIA": "Miami, FL",
734
+ "KICT": "Wichita, KS",
735
+ "TMKE": "Milwaukee, WI",
736
+ "TFLL": "Fort Lauderdale, FL",
737
+ "KARX": "La Crosse, WI",
738
+ "KLRX": "Elko, NV",
739
+ "KDAX": "Sacramento, CA",
740
+ "KGRB": "Green Bay, WI",
741
+ "KLGX": "Langley Hill, WA",
742
+ "KFTG": "Denver, CO",
743
+ "KMKX": "Milwaukee, WI",
744
+ "TTUL": "Tulsa, OK",
745
+ "TDFW": "Dallas/Fort Worth, TX",
746
+ "TTPA": "Tampa Bay, FL",
747
+ "TDAL": "Dallas Love Field, TX",
748
+ "KDFX": "Laughlin AFB, TX",
749
+ "KSFX": "Pocatello, ID",
750
+ "KMTX": "Salt Lake City, UT",
751
+ "PAEC": "Nome, AK",
752
+ "RKSG": "Camp Humphreys, KR",
753
+ "KOAX": "Omaha, NE",
754
+ "PHMO": "Molokai, HI",
755
+ "TDTW": "Detroit, MI",
756
+ "THOU": "Houston, TX",
757
+ "AWPA2": "Anchorage, AK",
758
+ "KTYX": "Fort Drum, NY",
759
+ "KCCX": "State College, PA",
760
+ "TMSP": "Minneapolis, MN",
761
+ "KMVX": "Grand Forks, ND",
762
+ "KBIS": "Bismarck, ND",
763
+ "KBBX": "Beale AFB, CA",
764
+ "KVBX": "Vandenberg AFB, CA",
765
+ "KPOE": "Fort Polk, LA",
766
+ "KMOB": "Mobile, AL",
767
+ "KJGX": "Robins AFB, GA",
768
+ "KMUX": "San Francisco, CA",
769
+ "TMCI": "Kansas City, MO",
770
+ "KLSX": "St. Louis, MO",
771
+ "KMAX": "Medford, OR",
772
+ "KRAX": "Raleigh/Durham, NC",
773
+ "KINX": "Tulsa, OK",
774
+ "RKJK": "Kunsan AB, KR",
775
+ "KSGF": "Springfield, MO",
776
+ "TDAY": "Dayton, OH",
777
+ "KDOX": "Dover AFB, DE",
778
+ "KGGW": "Glasgow, MT",
779
+ "KAMX": "Miami, FL",
780
+ "KENX": "Albany, NY",
781
+ "KTFX": "Great Falls, MT",
782
+ "KPBZ": "Pittsburgh, PA",
783
+ "KMAF": "Midland/Odessa, TX",
784
+ "KPDT": "Pendleton, OR",
785
+ "KLNX": "North Platte, NE",
786
+ "KEOX": "Fort Rucker, AL",
787
+ "KGSP": "Greer, SC",
788
+ "KHPX": "Fort Campbell, KY",
789
+ "KGRR": "Grand Rapids, MI",
790
+ "KLOT": "Chicago, IL",
791
+ "TPIT": "Pittsburgh, PA",
792
+ "KEYX": "Edwards AFB, CA",
793
+ "TIAD": "Dulles, VA",
794
+ "KFWS": "Dallas/Fort Worth, TX",
795
+ "KMLB": "Melbourne, FL",
796
+ "KMBX": "Minot AFB, ND",
797
+ "KDMX": "Des Moines, IA",
798
+ "KEVX": "Eglin AFB, FL",
799
+ "TBNA": "Nashville, TN",
800
+ "KDYX": "Dyess AFB, TX",
801
+ "TOKC": "Oklahoma City, OK",
802
+ "PHKI": "South Kauai, HI",
803
+ "TMCO": "Orlando, FL",
804
+ "KDIX": "Philadelphia, PA",
805
+ "TORD": "Chicago, IL",
806
+ "KYUX": "Yuma, AZ",
807
+ "KVNX": "Vance AFB, OK",
808
+ "TJUA": "San Juan, PR",
809
+ "TATL": "Atlanta, GA",
810
+ "KVTX": "Los Angeles, CA",
811
+ "KIND": "Indianapolis, IN",
812
+ "KCBX": "Boise, ID",
813
+ "KGYX": "Portland, ME",
814
+ "KMXX": "Maxwell AFB, AL",
815
+ "TSJU": "San Juan, PR",
816
+ "KHNX": "San Joaquin Valley, CA",
817
+ "KLVX": "Louisville, KY",
818
+ "KMSX": "Missoula, MT",
819
+ "KJAX": "Jacksonville, FL",
820
+ "KNQA": "Memphis, TN",
821
+ "KRIW": "Riverton/Lander, WY",
822
+ "TCVG": "Covington, KY",
823
+ "KBLX": "Billings, MT",
824
+ "TPHL": "Philadelphia, PA",
825
+ "KRLX": "Charleston, WV",
826
+ "TMEM": "Memphis, TN",
827
+ "KCLE": "Cleveland, OH",
828
+ "KBHX": "Eureka, CA",
829
+ "KLBB": "Lubbock, TX",
830
+ "KOTX": "Spokane, WA",
831
+ "KEWX": "Austin/San Antonio, TX",
832
+ "KGWX": "Columbus AFB, MS",
833
+ "KESX": "Las Vegas, NV",
834
+ "KTBW": "Tampa, FL",
835
+ "KOHX": "Nashville, TN",
836
+ "KLTX": "Wilmington, NC",
837
+ "KFSX": "Flagstaff, AZ",
838
+ "TIDS": "Indianapolis, IN",
839
+ "KILN": "Cincinnati, OH",
840
+ "PAFG": "Fairbanks, AK",
841
+ "KPQR": "Portland, OR",
842
+ "KILM": "Wilmington, NC",
843
+ "KEKA": "Eureka, CA",
844
+ "KCHS": "Charleston, SC",
845
+ "KPHI": "Philadelphia/Mt. Holly, NJ",
846
+ "KUNR": "Rapid City, SD",
847
+ "KMFL": "Miami, FL",
848
+ "TJSJ": "San Juan, PR",
849
+ "KFGF": "Grand Forks, ND",
850
+ "KSEW": "Seattle, WA",
851
+ "PAFC": "Anchorage, AK",
852
+ "KLMK": "Louisville, KY",
853
+ "PHFO": "Honolulu, HI",
854
+ "KLIX": "New Orleans/Baton Rouge, LA",
855
+ "KBOI": "Boise, ID",
856
+ "KPIH": "Pocatello, ID",
857
+ "KMTR": "San Francisco/Monterey, CA",
858
+ "KGJT": "Grand Junction, CO",
859
+ "PAAQ": "Anchorage, AK",
860
+ "KABQ": "Albuquerque, NM",
861
+ "KTAE": "Tallahassee, FL",
862
+ "KCAR": "Caribou, ME",
863
+ "KMFR": "Medford, OR",
864
+ "PGUM": "Guam, GU",
865
+ "PAJK": "Juneau, AK"
866
+ };
867
+
868
+ // src/bootstrap.ts
869
+ var packages = {
870
+ fs,
871
+ path,
872
+ events,
873
+ xmpp,
874
+ shapefile,
875
+ xml2js,
876
+ sqlite3,
877
+ cron,
878
+ axios,
879
+ crypto,
880
+ os,
881
+ say
882
+ };
883
+ var cache = {
884
+ isReady: true,
885
+ sigHalt: false,
886
+ isConnected: false,
887
+ attemptingReconnect: false,
888
+ totalReconnects: 0,
889
+ lastStanza: null,
890
+ session: null,
891
+ lastConnect: null,
892
+ db: null,
893
+ events: new events.EventEmitter(),
894
+ isProcessingAudioQueue: false,
895
+ audioQueue: []
896
+ };
897
+ var settings = {
898
+ database: path.join(process.cwd(), "shapefiles.db"),
899
+ isNWWS: true,
900
+ NoaaWeatherWireService: {
901
+ clientReconnections: {
902
+ canReconnect: true,
903
+ currentInterval: 60
904
+ },
905
+ clientCredentials: {
906
+ username: null,
907
+ password: null,
908
+ nickname: "AtmosphericX Standalone Parser"
909
+ },
910
+ cache: {
911
+ read: false,
912
+ maxSizeMB: 5,
913
+ maxHistory: 5e3,
914
+ directory: null
915
+ },
916
+ alertPreferences: {
917
+ isCapOnly: false,
918
+ isShapefileUGC: false
919
+ }
920
+ },
921
+ NationalWeatherService: {
922
+ checkInterval: 15,
923
+ endpoint: "https://api.weather.gov/alerts/active"
924
+ },
925
+ global: {
926
+ useParentEvents: true,
927
+ betterEventParsing: true,
928
+ alertFiltering: {
929
+ filteredEvents: [],
930
+ filteredICOAs: [],
931
+ ignoredICOAs: [`KWNS`],
932
+ ignoredEvents: [`Unknown`, `Test Message`],
933
+ ugcFilter: [],
934
+ stateFilter: [],
935
+ checkExpired: true
936
+ },
937
+ easSettings: {
938
+ easAlerts: [],
939
+ easDirectory: null,
940
+ easIntroWav: null
941
+ }
942
+ }
943
+ };
944
+ var definitions = {
945
+ events: EVENTS,
946
+ actions: ACTIONS,
947
+ status: STATUS,
948
+ productTypes: TYPES,
949
+ correlations: STATUS_CORRELATIONS,
950
+ offshore: OFFSHORE,
951
+ awips: AWIPS,
952
+ cancelSignatures: CANCEL_SIGNATURES,
953
+ messageSignatures: MESSAGE_SIGNATURES,
954
+ tags: TAGS,
955
+ ICAO: ICAOs,
956
+ enhancedEvents: [
957
+ { "Tornado Warning": {
958
+ "Tornado Emergency": { description: "tornado emergency", condition: (tornadoThreatTag) => tornadoThreatTag === "OBSERVED" },
959
+ "PDS Tornado Warning": { description: "particularly dangerous situation", condition: (damageThreatTag) => damageThreatTag === "CONSIDERABLE" },
960
+ "Confirmed Tornado Warning": { condition: (tornadoThreatTag) => tornadoThreatTag === "OBSERVED" },
961
+ "Radar Indicated Tornado Warning": { condition: (tornadoThreatTag) => tornadoThreatTag !== "OBSERVED" }
962
+ } },
963
+ { "Tornado Watch": {
964
+ "PDS Tornado Watch": { description: "particularly dangerous situation" }
965
+ } },
966
+ { "Flash Flood Warning": {
967
+ "Flash Flood Emergency": { description: "flash flood emergency" },
968
+ "Considerable Flash Flood Warning": { condition: (damageThreatTag) => damageThreatTag === "CONSIDERABLE" }
969
+ } },
970
+ { "Severe Thunderstorm Warning": {
971
+ "EDS Severe Thunderstorm Warning": { description: "extremely dangerous situation" },
972
+ "Destructive Severe Thunderstorm Warning": { condition: (damageThreatTag) => damageThreatTag === "DESTRUCTIVE" },
973
+ "Considerable Severe Thunderstorm Warning": { condition: (damageThreatTag) => damageThreatTag === "CONSIDERABLE" }
974
+ } }
975
+ ],
976
+ expressions: {
977
+ vtec: `[OTEX].(NEW|CON|EXT|EXA|EXB|UPG|CAN|EXP|COR|ROU).[A-Z]{4}.[A-Z]{2}.[WAYSFON].[0-9]{4}.[0-9]{6}T[0-9]{4}Z-[0-9]{6}T[0-9]{4}Z`,
978
+ wmo: `[A-Z0-9]{6}\\s[A-Z]{4}\\s\\d{6}`,
979
+ ugc1: `(\\w{2}[CZ](\\d{3}((-|>)\\s?(
980
+
981
+ )?))+)`,
982
+ ugc2: `(\\d{6}(-|>)\\s?(
983
+
984
+ )?)`,
985
+ ugc3: `(\\d{6})(?=-|$)`,
986
+ dateline: `/d{3,4}s*(AM|PM)?s*[A-Z]{2,4}s+[A-Z]{3,}s+[A-Z]{3,}s+d{1,2}s+d{4}`,
987
+ wmoID: `[A-Z0-9]{2}([A-Z]{3})`
988
+ },
989
+ shapefiles: [
990
+ { id: `C`, file: `USCounties` },
991
+ { id: `Z`, file: `ForecastZones` },
992
+ { id: `Z`, file: `FireZones` },
993
+ { id: `Z`, file: `OffShoreZones` },
994
+ { id: `Z`, file: `FireCounties` },
995
+ { id: `Z`, file: `Marine` }
996
+ ],
997
+ messages: {
998
+ shapefile_creation: `[NOTICE] DO NOT CLOSE THIS PROJECT UNTIL THE SHAPEFILES ARE DONE COMPLETING!
999
+ THIS COULD TAKE A WHILE DEPENDING ON THE SPEED OF YOUR STORAGE!!
1000
+ IF YOU CLOSE YOUR PROJECT, THE SHAPEFILES WILL NOT BE CREATED AND YOU WILL NEED TO DELETE ${settings.database} AND RESTART TO CREATE THEM AGAIN!`,
1001
+ shapefile_creation_finished: `[NOTICE] SHAPEFILES HAVE BEEN SUCCESSFULLY CREATED AND THE DATABASE IS READY FOR USE!`,
1002
+ not_ready: "[ERROR] You can NOT create another instance without shutting down the current one first, please make sure to call the stop() method first!",
1003
+ invalid_nickname: "[WARNING] The nickname you provided is invalid, please provide a valid nickname to continue.",
1004
+ eas_no_directory: "[WARNING] You have not set a directory for EAS audio files to be saved to, please set the 'easDirectory' setting in the global settings to enable EAS audio generation."
1005
+ }
1006
+ };
1007
+
1008
+ // src/parsers/vtec.ts
1009
+ var VtecParser = class {
1010
+ /**
1011
+ * vtecExtractor extracts and parses VTEC codes from a given message string.
1012
+ *
1013
+ * @public
1014
+ * @static
1015
+ * @async
1016
+ * @param {string} message
1017
+ * @returns {unknown}
1018
+ */
1019
+ static vtecExtractor(message) {
1020
+ return __async(this, null, function* () {
1021
+ const vtecs = [];
1022
+ const matches = message.match(new RegExp(definitions.expressions.vtec, "g"));
1023
+ if (!matches) return null;
1024
+ for (let i = 0; i < matches.length; i++) {
1025
+ const vtec = matches[i];
1026
+ const parts = vtec.split(`.`);
1027
+ const dates = parts[6].split(`-`);
1028
+ vtecs.push({
1029
+ raw: vtec,
1030
+ type: definitions.productTypes[parts[0]],
1031
+ tracking: `${parts[2]}-${parts[3]}-${parts[4]}-${parts[5]}`,
1032
+ event: `${definitions.events[parts[3]]} ${definitions.actions[parts[4]]}`,
1033
+ status: definitions.status[parts[1]],
1034
+ wmo: message.match(new RegExp(definitions.expressions.wmo, "gimu")),
1035
+ expires: this.parseExpiryDate(dates)
1036
+ });
1037
+ }
1038
+ return vtecs;
1039
+ });
1040
+ }
1041
+ /**
1042
+ * parseExpiryDate converts VTEC expiry date format to a standard ISO 8601 format with timezone adjustment.
1043
+ *
1044
+ * @private
1045
+ * @static
1046
+ * @param {String[]} args
1047
+ * @returns {string}
1048
+ */
1049
+ static parseExpiryDate(args) {
1050
+ if (args[1] == `000000T0000Z`) return `Invalid Date Format`;
1051
+ const expires = `${(/* @__PURE__ */ new Date()).getFullYear().toString().substring(0, 2)}${args[1].substring(0, 2)}-${args[1].substring(2, 4)}-${args[1].substring(4, 6)}T${args[1].substring(7, 9)}:${args[1].substring(9, 11)}:00`;
1052
+ const local = new Date(new Date(expires).getTime() - 4 * 60 * 6e4);
1053
+ const pad = (n) => n.toString().padStart(2, "0");
1054
+ return `${local.getFullYear()}-${pad(local.getMonth() + 1)}-${pad(local.getDate())}T${pad(local.getHours())}:${pad(local.getMinutes())}:00.000-04:00`;
1055
+ }
1056
+ };
1057
+ var vtec_default = VtecParser;
1058
+
1059
+ // src/parsers/ugc.ts
1060
+ var UGCParser = class {
1061
+ /**
1062
+ * ugcExtractor extracts and parses UGC codes from a given message string.
1063
+ *
1064
+ * @public
1065
+ * @static
1066
+ * @async
1067
+ * @param {string} message
1068
+ * @returns {unknown}
1069
+ */
1070
+ static ugcExtractor(message) {
1071
+ return __async(this, null, function* () {
1072
+ const header = this.getHeader(message);
1073
+ const zones = this.getZones(header);
1074
+ const expiry = this.getExpiry(message);
1075
+ const locations = yield this.getLocations(zones);
1076
+ const ugc = zones.length > 0 ? { zones, locations, expiry } : null;
1077
+ return ugc;
1078
+ });
1079
+ }
1080
+ /**
1081
+ * getHeader extracts the UGC header from a UGC message string.
1082
+ *
1083
+ * @public
1084
+ * @static
1085
+ * @param {string} message
1086
+ * @returns {*}
1087
+ */
1088
+ static getHeader(message) {
1089
+ const start = message.search(new RegExp(definitions.expressions.ugc1, "gimu"));
1090
+ const end = message.substring(start).search(new RegExp(definitions.expressions.ugc2, "gimu"));
1091
+ const full = message.substring(start, start + end).replace(/\s+/g, "").slice(0, -1);
1092
+ return full;
1093
+ }
1094
+ /**
1095
+ * getExpiry extracts the expiry date and time from a UGC message and returns it as a Date object.
1096
+ *
1097
+ * @public
1098
+ * @static
1099
+ * @param {string} message
1100
+ * @returns {*}
1101
+ */
1102
+ static getExpiry(message) {
1103
+ const start = message.match(new RegExp(definitions.expressions.ugc3, "gimu"));
1104
+ if (start != null) {
1105
+ const day = parseInt(start[0].substring(0, 2), 10);
1106
+ const hour = parseInt(start[0].substring(2, 4), 10);
1107
+ const minute = parseInt(start[0].substring(4, 6), 10);
1108
+ const now = /* @__PURE__ */ new Date();
1109
+ const expires = new Date(now.getUTCFullYear(), now.getUTCMonth(), day, hour, minute, 0);
1110
+ return expires;
1111
+ }
1112
+ return null;
1113
+ }
1114
+ /**
1115
+ * getLocations retrieves unique location names for the provided UGC zone codes from the database.
1116
+ *
1117
+ * @public
1118
+ * @static
1119
+ * @async
1120
+ * @param {String[]} zones
1121
+ * @returns {unknown}
1122
+ */
1123
+ static getLocations(zones) {
1124
+ return __async(this, null, function* () {
1125
+ const locations = [];
1126
+ for (let i = 0; i < zones.length; i++) {
1127
+ const id = zones[i].trim();
1128
+ const located = yield cache.db.prepare(`SELECT location FROM shapefiles WHERE id = ?`).get(id);
1129
+ located != void 0 ? locations.push(located.location) : locations.push(id);
1130
+ }
1131
+ return Array.from(new Set(locations)).sort();
1132
+ });
1133
+ }
1134
+ /**
1135
+ * getCoordinates retrieves geographical coordinates for the provided UGC zone codes from the database.
1136
+ *
1137
+ * @public
1138
+ * @static
1139
+ * @param {String[]} zones
1140
+ * @returns {{}}
1141
+ */
1142
+ static getCoordinates(zones) {
1143
+ let coordinates = [];
1144
+ for (let i = 0; i < zones.length; i++) {
1145
+ const id = zones[i].trim();
1146
+ let located = cache.db.prepare(`SELECT geometry FROM shapefiles WHERE id = ?`).get(id);
1147
+ if (located != void 0) {
1148
+ let geometry = JSON.parse(located.geometry);
1149
+ if ((geometry == null ? void 0 : geometry.type) === "Polygon") {
1150
+ coordinates.push(...geometry.coordinates[0].map((coord) => [coord[0], coord[1]]));
1151
+ break;
1152
+ }
1153
+ }
1154
+ }
1155
+ return coordinates;
1156
+ }
1157
+ /**
1158
+ * getZones parses a UGC header string and returns an array of individual UGC zone codes.
1159
+ *
1160
+ * @public
1161
+ * @static
1162
+ * @param {string} header
1163
+ * @returns {*}
1164
+ */
1165
+ static getZones(header) {
1166
+ const ugcSplit = header.split("-");
1167
+ const zones = [];
1168
+ let state = ugcSplit[0].substring(0, 2);
1169
+ let format = ugcSplit[0].substring(2, 3);
1170
+ for (let i = 0; i < ugcSplit.length; i++) {
1171
+ if (/^[A-Z]/.test(ugcSplit[i])) {
1172
+ state = ugcSplit[i].substring(0, 2);
1173
+ if (ugcSplit[i].includes(">")) {
1174
+ let [start, end] = ugcSplit[i].split(">"), startNum = parseInt(start.substring(3), 10), endNum = parseInt(end, 10);
1175
+ for (let j = startNum; j <= endNum; j++) zones.push(`${state}${format}${j.toString().padStart(3, "0")}`);
1176
+ } else zones.push(ugcSplit[i]);
1177
+ continue;
1178
+ }
1179
+ if (ugcSplit[i].includes(">")) {
1180
+ let [start, end] = ugcSplit[i].split(">"), startNum = parseInt(start, 10), endNum = parseInt(end, 10);
1181
+ for (let j = startNum; j <= endNum; j++) zones.push(`${state}${format}${j.toString().padStart(3, "0")}`);
1182
+ } else zones.push(`${state}${format}${ugcSplit[i]}`);
1183
+ }
1184
+ return zones.filter((item) => item !== "");
1185
+ }
1186
+ };
1187
+ var ugc_default = UGCParser;
1188
+
1189
+ // src/parsers/text.ts
1190
+ var TextParser = class {
1191
+ /**
1192
+ * textProductToString extracts a specific value from a text-based weather product message based on a given key and optional removal strings.
1193
+ *
1194
+ * @public
1195
+ * @static
1196
+ * @param {string} message
1197
+ * @param {string} value
1198
+ * @param {string[]} [removal=[]]
1199
+ * @returns {(string | null)}
1200
+ */
1201
+ static textProductToString(message, value, removal = []) {
1202
+ const lines = message.split("\n");
1203
+ for (const line of lines) {
1204
+ if (line.includes(value)) {
1205
+ let result = line.slice(line.indexOf(value) + value.length).trim();
1206
+ for (const str of removal) {
1207
+ result = result.split(str).join("");
1208
+ }
1209
+ result = result.replace(value, "").replace("<", "").trim();
1210
+ return result || null;
1211
+ }
1212
+ }
1213
+ return null;
1214
+ }
1215
+ /**
1216
+ * textProductToPolygon extracts geographical coordinates from a text-based weather product message and returns them as an array of [longitude, latitude] pairs.
1217
+ *
1218
+ * @public
1219
+ * @static
1220
+ * @param {string} message
1221
+ * @returns {[number, number][]}
1222
+ */
1223
+ static textProductToPolygon(message) {
1224
+ const coordinates = [];
1225
+ const latLonMatch = message.match(/LAT\.{3}LON\s+([\d\s]+)/i);
1226
+ if (!latLonMatch || !latLonMatch[1]) return coordinates;
1227
+ const coordStrings = latLonMatch[1].replace(/\n/g, " ").trim().split(/\s+/);
1228
+ for (let i = 0; i < coordStrings.length - 1; i += 2) {
1229
+ const lat = parseFloat(coordStrings[i]) / 100;
1230
+ const lon = -parseFloat(coordStrings[i + 1]) / 100;
1231
+ if (!isNaN(lat) && !isNaN(lon)) {
1232
+ coordinates.push([lon, lat]);
1233
+ }
1234
+ }
1235
+ if (coordinates.length > 2) {
1236
+ coordinates.push(coordinates[0]);
1237
+ }
1238
+ return coordinates;
1239
+ }
1240
+ /**
1241
+ * textProductToDescription extracts the main description from a text-based weather product message.
1242
+ *
1243
+ * @public
1244
+ * @static
1245
+ * @param {string} message
1246
+ * @param {string} [handle=null]
1247
+ * @returns {string}
1248
+ */
1249
+ static textProductToDescription(message, handle = null) {
1250
+ const original = message;
1251
+ const dateRegex = /\d{3,4}\s*(AM|PM)?\s*[A-Z]{2,4}\s+[A-Z]{3,}\s+[A-Z]{3,}\s+\d{1,2}\s+\d{4}/gim;
1252
+ const discoveredDates = Array.from(message.matchAll(dateRegex));
1253
+ if (discoveredDates.length) {
1254
+ const lastMatch = discoveredDates[discoveredDates.length - 1][0];
1255
+ const startIdx = message.lastIndexOf(lastMatch);
1256
+ if (startIdx !== -1) {
1257
+ const endIdx = message.indexOf("&&", startIdx);
1258
+ message = message.substring(startIdx + lastMatch.length, endIdx !== -1 ? endIdx : void 0).trimStart();
1259
+ if (message.startsWith("/")) message = message.slice(1).trimStart();
1260
+ if (handle && message.includes(handle)) {
1261
+ const handleIdx = message.indexOf(handle);
1262
+ message = message.substring(handleIdx + handle.length).trimStart();
1263
+ if (message.startsWith("/")) message = message.slice(1).trimStart();
1264
+ }
1265
+ }
1266
+ } else if (handle) {
1267
+ const handleIdx = message.indexOf(handle);
1268
+ if (handleIdx !== -1) {
1269
+ let afterHandle = message.substring(handleIdx + handle.length).trimStart();
1270
+ if (afterHandle.startsWith("/")) afterHandle = afterHandle.slice(1).trimStart();
1271
+ const latEnd = afterHandle.indexOf("&&");
1272
+ message = latEnd !== -1 ? afterHandle.substring(0, latEnd).trim() : afterHandle.trim();
1273
+ }
1274
+ }
1275
+ return message.replace(/\s+/g, " ").trim().startsWith("ISSUED TIME...") ? original : message.trim();
1276
+ }
1277
+ /**
1278
+ * awipTextToEvent converts an AWIPS ID prefix from a text-based weather product message to its corresponding event type and prefix.
1279
+ *
1280
+ * @public
1281
+ * @static
1282
+ * @param {string} message
1283
+ * @returns {{ type: any; prefix: any; }}
1284
+ */
1285
+ static awipTextToEvent(message) {
1286
+ for (const [prefix, type] of Object.entries(definitions.awips)) {
1287
+ if (message.startsWith(prefix)) {
1288
+ return { type, prefix };
1289
+ }
1290
+ }
1291
+ return { type: `XX`, prefix: `XX` };
1292
+ }
1293
+ /**
1294
+ * getXmlValues recursively searches a parsed XML object for specified keys and extracts their values.
1295
+ *
1296
+ * @public
1297
+ * @static
1298
+ * @param {*} parsed
1299
+ * @param {string[]} valuesToExtract
1300
+ * @returns {Record<string, any>}
1301
+ */
1302
+ static getXmlValues(parsed, valuesToExtract) {
1303
+ const extracted = {};
1304
+ const findValueByKey = (obj, searchKey) => {
1305
+ const results = [];
1306
+ if (obj === null || typeof obj !== "object") {
1307
+ return results;
1308
+ }
1309
+ const searchKeyLower = searchKey.toLowerCase();
1310
+ for (const key in obj) {
1311
+ if (obj.hasOwnProperty(key) && key.toLowerCase() === searchKeyLower) {
1312
+ results.push(obj[key]);
1313
+ }
1314
+ }
1315
+ if (Array.isArray(obj)) {
1316
+ for (const item of obj) {
1317
+ if (item.valueName && item.valueName.toLowerCase() === searchKeyLower && item.value !== void 0) {
1318
+ results.push(item.value);
1319
+ }
1320
+ const nestedResults = findValueByKey(item, searchKey);
1321
+ results.push(...nestedResults);
1322
+ }
1323
+ }
1324
+ for (const key in obj) {
1325
+ if (obj.hasOwnProperty(key)) {
1326
+ const nestedResults = findValueByKey(obj[key], searchKey);
1327
+ results.push(...nestedResults);
1328
+ }
1329
+ }
1330
+ return results;
1331
+ };
1332
+ for (const key of valuesToExtract) {
1333
+ const values = findValueByKey(parsed.alert, key);
1334
+ const uniqueValues = [...new Set(values)];
1335
+ extracted[key] = uniqueValues.length === 0 ? null : uniqueValues.length === 1 ? uniqueValues[0] : uniqueValues;
1336
+ }
1337
+ return extracted;
1338
+ }
1339
+ };
1340
+ var text_default = TextParser;
1341
+
1342
+ // src/parsers/types/ugc.ts
1343
+ var UGCAlerts = class {
1344
+ /**
1345
+ * getTracking generates a unique tracking identifier based on the sender's ICAO code and a hash of the UGC zones.
1346
+ *
1347
+ * @private
1348
+ * @static
1349
+ * @param {types.BaseProperties} baseProperties
1350
+ * @param {string[]} zones
1351
+ * @returns {string}
1352
+ */
1353
+ static getTracking(baseProperties, zones) {
1354
+ return `${baseProperties.sender_icao} (${packages.crypto.createHash("md5").update(zones.join(``)).digest("hex")}})`;
1355
+ }
1356
+ /**
1357
+ * getEvent determines the event name based on offshore definitions or formats it from the attributes.
1358
+ *
1359
+ * @private
1360
+ * @static
1361
+ * @param {string} message
1362
+ * @param {Record<string, any>} attributes
1363
+ * @returns {*}
1364
+ */
1365
+ static getEvent(message, attributes) {
1366
+ const offshoreEvent = Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1367
+ if (offshoreEvent != void 0) return Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1368
+ return attributes.type.split(`-`).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(` `);
1369
+ }
1370
+ /**
1371
+ * event processes validated UGC alert messages, extracting relevant information and compiling it into structured event objects.
1372
+ *
1373
+ * @public
1374
+ * @static
1375
+ * @async
1376
+ * @param {types.TypeCompiled} validated
1377
+ * @returns {*}
1378
+ */
1379
+ static event(validated) {
1380
+ return __async(this, null, function* () {
1381
+ var _a;
1382
+ let processed = [];
1383
+ const messages = (_a = validated.message.split(/(?=\$\$|ISSUED TIME...|=================================================)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1384
+ if (!messages || messages.length == 0) return;
1385
+ for (let i = 0; i < messages.length; i++) {
1386
+ const tick = performance.now();
1387
+ const message = messages[i];
1388
+ const getUGC = yield ugc_default.ugcExtractor(message);
1389
+ if (getUGC != null) {
1390
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated, getUGC);
1391
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties);
1392
+ const getEvent = this.getEvent(message, getBaseProperties.attributes.getAwip);
1393
+ processed.push({
1394
+ preformance: performance.now() - tick,
1395
+ tracking: this.getTracking(getBaseProperties, getUGC.zones),
1396
+ header: getHeader,
1397
+ vtec: `N/A`,
1398
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: `Issued` }],
1399
+ properties: __spreadValues({ event: getEvent, parent: getEvent, action_type: `Issued` }, getBaseProperties)
1400
+ });
1401
+ }
1402
+ }
1403
+ events_default.validateEvents(processed);
1404
+ });
1405
+ }
1406
+ };
1407
+ var ugc_default2 = UGCAlerts;
1408
+
1409
+ // src/parsers/types/text.ts
1410
+ var UGCAlerts2 = class {
1411
+ static getTracking(baseProperties) {
1412
+ return `${baseProperties.sender_icao}`;
1413
+ }
1414
+ static getEvent(message, attributes) {
1415
+ const offshoreEvent = Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1416
+ if (offshoreEvent) return Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1417
+ return attributes.type.split(`-`).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(` `);
1418
+ }
1419
+ static event(validated) {
1420
+ return __async(this, null, function* () {
1421
+ var _a;
1422
+ let processed = [];
1423
+ const messages = (_a = validated.message.split(/(?=\$\$|ISSUED TIME...|=================================================)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1424
+ if (!messages || messages.length == 0) return;
1425
+ for (let i = 0; i < messages.length; i++) {
1426
+ const tick = performance.now();
1427
+ const message = messages[i];
1428
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated);
1429
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties);
1430
+ const getEvent = this.getEvent(message, getBaseProperties.attributes.getAwip);
1431
+ processed.push({
1432
+ preformance: performance.now() - tick,
1433
+ tracking: this.getTracking(getBaseProperties),
1434
+ header: getHeader,
1435
+ vtec: `N/A`,
1436
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: `Issued` }],
1437
+ properties: __spreadValues({ event: getEvent, parent: getEvent, action_type: `Issued` }, getBaseProperties)
1438
+ });
1439
+ }
1440
+ events_default.validateEvents(processed);
1441
+ });
1442
+ }
1443
+ };
1444
+ var text_default2 = UGCAlerts2;
1445
+
1446
+ // src/parsers/types/cap.ts
1447
+ var CapAlerts = class {
1448
+ static getTracking(extracted) {
1449
+ return extracted.vtec ? (() => {
1450
+ const vtecValue = Array.isArray(extracted.vtec) ? extracted.vtec[0] : extracted.vtec;
1451
+ const splitVTEC = vtecValue.split(".");
1452
+ return `${splitVTEC[2]}-${splitVTEC[3]}-${splitVTEC[4]}-${splitVTEC[5]}`;
1453
+ })() : `${extracted.wmoidentifier} (${extracted.ugc})`;
1454
+ }
1455
+ static event(validated) {
1456
+ return __async(this, null, function* () {
1457
+ var _a;
1458
+ let processed = [];
1459
+ const messages = (_a = validated.message.match(/<\?xml[\s\S]*?<\/alert>/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1460
+ if (messages == null || messages.length === 0) return;
1461
+ for (let message of messages) {
1462
+ const tick = performance.now();
1463
+ message = message.substring(message.indexOf(`<?xml version="1.0"`), message.lastIndexOf(`>`) + 1);
1464
+ const parser = new packages.xml2js.Parser({ explicitArray: false, mergeAttrs: true, trim: true });
1465
+ const parsed = yield parser.parseStringPromise(message);
1466
+ if (parsed == null || parsed.alert == null) continue;
1467
+ const extracted = text_default.getXmlValues(parsed, [
1468
+ `vtec`,
1469
+ `wmoidentifier`,
1470
+ `ugc`,
1471
+ `areadesc`,
1472
+ `expires`,
1473
+ `sent`,
1474
+ `msgtype`,
1475
+ `description`,
1476
+ `event`,
1477
+ `sendername`,
1478
+ `tornadodetection`,
1479
+ `polygon`,
1480
+ `maxHailSize`,
1481
+ `maxWindGust`,
1482
+ `thunderstormdamagethreat`,
1483
+ `tornadodamagethreat`,
1484
+ `waterspoutdetection`,
1485
+ `flooddetection`
1486
+ ]);
1487
+ const getHeader = events_default.getHeader(__spreadValues({}, validated.attributes));
1488
+ const getSource = text_default.textProductToString(extracted.description, `SOURCE...`, [`.`]) || `N/A`;
1489
+ processed.push({
1490
+ preformance: performance.now() - tick,
1491
+ tracking: this.getTracking(extracted),
1492
+ header: getHeader,
1493
+ vtec: extracted.vtec || `N/A`,
1494
+ history: [{ description: extracted.description || `N/A`, issued: extracted.sent ? new Date(extracted.sent).toLocaleString() : `N/A`, type: extracted.msgtype || `N/A` }],
1495
+ properties: {
1496
+ locations: extracted.areadesc || `N/A`,
1497
+ event: extracted.event || `N/A`,
1498
+ issued: extracted.sent ? new Date(extracted.sent).toLocaleString() : `N/A`,
1499
+ expires: extracted.expires ? new Date(extracted.expires).toLocaleString() : `N/A`,
1500
+ parent: extracted.event || `N/A`,
1501
+ action_type: extracted.msgtype || `N/A`,
1502
+ description: extracted.description || `N/A`,
1503
+ sender_name: extracted.sendername || `N/A`,
1504
+ sender_icao: extracted.wmoidentifier ? extracted.wmoidentifier.substring(extracted.wmoidentifier.length - 4) : `N/A`,
1505
+ attributes: validated.attributes,
1506
+ geocode: {
1507
+ UGC: [extracted.ugc]
1508
+ },
1509
+ parameters: {
1510
+ wmo: extracted.wmoidentifier || `N/A`,
1511
+ source: getSource,
1512
+ max_hail_size: extracted.maxHailSize || `N/A`,
1513
+ max_wind_gust: extracted.maxWindGust || `N/A`,
1514
+ damage_threat: extracted.thunderstormdamagethreat || `N/A`,
1515
+ tornado_detection: extracted.tornadodetection || extracted.waterspoutdetection || `N/A`,
1516
+ flood_detection: extracted.flooddetection || `N/A`,
1517
+ discussion_tornado_intensity: `N/A`,
1518
+ discussion_wind_intensity: `N/A`,
1519
+ discussion_hail_intensity: `N/A`
1520
+ },
1521
+ geometry: extracted.polygon ? { type: `Polygon`, coordinates: extracted.polygon.split(` `).map((coord) => coord.split(`,`).map((num) => parseFloat(num))) } : null
1522
+ }
1523
+ });
1524
+ }
1525
+ events_default.validateEvents(processed);
1526
+ });
1527
+ }
1528
+ };
1529
+ var cap_default = CapAlerts;
1530
+
1531
+ // src/parsers/types/api.ts
1532
+ var APIAlerts = class {
1533
+ static getTracking(extracted) {
1534
+ return extracted.vtec ? (() => {
1535
+ const vtecValue = Array.isArray(extracted.vtec) ? extracted.vtec[0] : extracted.vtec;
1536
+ const splitVTEC = vtecValue.split(".");
1537
+ return `${splitVTEC[2]}-${splitVTEC[3]}-${splitVTEC[4]}-${splitVTEC[5]}`;
1538
+ })() : `${extracted.wmoidentifier} (${extracted.ugc})`;
1539
+ }
1540
+ static getICAO(vtec) {
1541
+ var _a, _b;
1542
+ const icao = vtec ? vtec.split(`.`)[2] : `N/A`;
1543
+ const name = (_b = (_a = definitions.ICAO) == null ? void 0 : _a[icao]) != null ? _b : `N/A`;
1544
+ return { icao, name };
1545
+ }
1546
+ static event(validated) {
1547
+ return __async(this, null, function* () {
1548
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca;
1549
+ let processed = [];
1550
+ const messages = Object.values(JSON.parse(validated.message).features);
1551
+ for (let feature of messages) {
1552
+ const tick = performance.now();
1553
+ const getVTEC = (_d = (_c = (_b = (_a = feature == null ? void 0 : feature.properties) == null ? void 0 : _a.parameters) == null ? void 0 : _b.VTEC) == null ? void 0 : _c[0]) != null ? _d : null;
1554
+ const getWmo = (_g = (_f = (_e = feature == null ? void 0 : feature.properties) == null ? void 0 : _e.parameters) == null ? void 0 : _f.WMOidentifier[0]) != null ? _g : null;
1555
+ const getUgc = (_j = (_i = (_h = feature == null ? void 0 : feature.properties) == null ? void 0 : _h.geocode) == null ? void 0 : _i.UGC) != null ? _j : null;
1556
+ const getHeadline = (_n = (_m = (_l = (_k = feature == null ? void 0 : feature.properties) == null ? void 0 : _k.parameters) == null ? void 0 : _l.NWSheadline) == null ? void 0 : _m[0]) != null ? _n : "";
1557
+ const getDescription = `${getHeadline} ${(_p = (_o = feature == null ? void 0 : feature.properties) == null ? void 0 : _o.description) != null ? _p : ``}`;
1558
+ const getAWIP = (_t = (_s = (_r = (_q = feature == null ? void 0 : feature.properties) == null ? void 0 : _q.parameters) == null ? void 0 : _r.AWIPSidentifier) == null ? void 0 : _s[0]) != null ? _t : null;
1559
+ const getHeader = events_default.getHeader(__spreadValues({}, { getAwip: { prefix: getAWIP == null ? void 0 : getAWIP.slice(0, -3) } }));
1560
+ const getSource = text_default.textProductToString(getDescription, `SOURCE...`, [`.`]) || `N/A`;
1561
+ const getOffice = this.getICAO(getVTEC || ``);
1562
+ processed.push({
1563
+ preformance: performance.now() - tick,
1564
+ tracking: this.getTracking({ vtec: getVTEC, wmoidentifier: getWmo, ugc: getUgc ? getUgc.join(`,`) : null }),
1565
+ header: getHeader,
1566
+ vtec: getVTEC || `N/A`,
1567
+ history: [{
1568
+ description: (_v = (_u = feature == null ? void 0 : feature.properties) == null ? void 0 : _u.description) != null ? _v : `N/A`,
1569
+ action: (_x = (_w = feature == null ? void 0 : feature.properties) == null ? void 0 : _w.messageType) != null ? _x : `N/A`,
1570
+ time: ((_y = feature == null ? void 0 : feature.properties) == null ? void 0 : _y.sent) ? new Date((_z = feature == null ? void 0 : feature.properties) == null ? void 0 : _z.sent).toLocaleString() : `N/A`
1571
+ }],
1572
+ properties: {
1573
+ locations: (_B = (_A = feature == null ? void 0 : feature.properties) == null ? void 0 : _A.areaDesc) != null ? _B : `N/A`,
1574
+ event: (_D = (_C = feature == null ? void 0 : feature.properties) == null ? void 0 : _C.event) != null ? _D : `N/A`,
1575
+ issued: ((_E = feature == null ? void 0 : feature.properties) == null ? void 0 : _E.sent) ? new Date((_F = feature == null ? void 0 : feature.properties) == null ? void 0 : _F.sent).toLocaleString() : `N/A`,
1576
+ expires: ((_G = feature == null ? void 0 : feature.properties) == null ? void 0 : _G.expires) ? new Date((_H = feature == null ? void 0 : feature.properties) == null ? void 0 : _H.expires).toLocaleString() : `N/A`,
1577
+ parent: (_J = (_I = feature == null ? void 0 : feature.properties) == null ? void 0 : _I.event) != null ? _J : `N/A`,
1578
+ action_type: (_L = (_K = feature == null ? void 0 : feature.properties) == null ? void 0 : _K.messageType) != null ? _L : `N/A`,
1579
+ description: (_N = (_M = feature == null ? void 0 : feature.properties) == null ? void 0 : _M.description) != null ? _N : `N/A`,
1580
+ sender_name: getOffice.name || `N/A`,
1581
+ sender_icao: getOffice.icao || `N/A`,
1582
+ attributes: validated.attributes,
1583
+ geocode: {
1584
+ UGC: (_Q = (_P = (_O = feature == null ? void 0 : feature.properties) == null ? void 0 : _O.geocode) == null ? void 0 : _P.UGC) != null ? _Q : [`XX000`]
1585
+ },
1586
+ parameters: {
1587
+ wmo: ((_T = (_S = (_R = feature == null ? void 0 : feature.properties) == null ? void 0 : _R.parameters) == null ? void 0 : _S.WMOidentifier) == null ? void 0 : _T[0]) || getWmo || `N/A`,
1588
+ source: getSource,
1589
+ max_hail_size: ((_V = (_U = feature == null ? void 0 : feature.properties) == null ? void 0 : _U.parameters) == null ? void 0 : _V.maxHailSize) || `N/A`,
1590
+ max_wind_gust: ((_X = (_W = feature == null ? void 0 : feature.properties) == null ? void 0 : _W.parameters) == null ? void 0 : _X.maxWindGust) || `N/A`,
1591
+ damage_threat: ((_Z = (_Y = feature == null ? void 0 : feature.properties) == null ? void 0 : _Y.parameters) == null ? void 0 : _Z.thunderstormDamageThreat) || [`N/A`],
1592
+ tornado_detection: ((_$ = (__ = feature == null ? void 0 : feature.properties) == null ? void 0 : __.parameters) == null ? void 0 : _$.tornadoDetection) || [`N/A`],
1593
+ flood_detection: ((_ba = (_aa = feature == null ? void 0 : feature.properties) == null ? void 0 : _aa.parameters) == null ? void 0 : _ba.floodDetection) || [`N/A`],
1594
+ discussion_tornado_intensity: "N/A",
1595
+ peakWindGust: `N/A`,
1596
+ peakHailSize: `N/A`
1597
+ },
1598
+ geometry: (_ca = feature == null ? void 0 : feature.geometry) != null ? _ca : null
1599
+ }
1600
+ });
1601
+ }
1602
+ events_default.validateEvents(processed);
1603
+ });
1604
+ }
1605
+ };
1606
+ var api_default = APIAlerts;
1607
+
1608
+ // src/parsers/stanza.ts
1609
+ var StanzaParser = class {
1610
+ /**
1611
+ * validate handles the validation of incoming XMPP stanzas to ensure they contain valid alert data.
1612
+ * You can also feed debug / cache data directly into this function by specifying the second parameter
1613
+ * which is the attributes object that would normally be parsed from the XMPP stanza.
1614
+ *
1615
+ * @public
1616
+ * @static
1617
+ * @param {*} stanza
1618
+ * @param {(boolean | types.TypeAttributes)} [isDebug=false]
1619
+ * @returns {{ message: any; attributes: types.TypeAttributes; isCap: any; isVtec: boolean; isCapDescription: any; awipsType: any; isApi: boolean; ignore: boolean; }}
1620
+ */
1621
+ static validate(stanza, isDebug = false) {
1622
+ var _a;
1623
+ if (isDebug !== false) {
1624
+ const vTypes = isDebug;
1625
+ const message = stanza;
1626
+ const attributes = vTypes;
1627
+ const isCap = (_a = vTypes.isCap) != null ? _a : message.includes(`<?xml`);
1628
+ const isCapDescription = message.includes(`<areaDesc>`);
1629
+ const isVtec = message.match(definitions.expressions.vtec) != null;
1630
+ const isUGC = message.match(definitions.expressions.ugc1) != null;
1631
+ const awipsType = this.getType(attributes);
1632
+ return { message, attributes, isCap, isVtec, isUGC, isCapDescription, awipsType, isApi: false, ignore: false };
1633
+ }
1634
+ if (stanza.is(`message`)) {
1635
+ let cb = stanza.getChild(`x`);
1636
+ if (cb && cb.children) {
1637
+ let message = unescape(cb.children[0]);
1638
+ let attributes = cb.attrs;
1639
+ if (attributes.awipsid && attributes.awipsid.length > 1) {
1640
+ const isCap = message.includes(`<?xml`);
1641
+ const isCapDescription = message.includes(`<areaDesc>`);
1642
+ const isVtec = message.match(definitions.expressions.vtec) != null;
1643
+ const isUGC = message.match(definitions.expressions.ugc1) != null;
1644
+ const awipsType = this.getType(attributes);
1645
+ const isApi = false;
1646
+ this.cache({ message, attributes, isCap, isVtec, awipsType: awipsType.type, awipsPrefix: awipsType.prefix });
1647
+ return { message, attributes, isCap, isApi, isVtec, isUGC, isCapDescription, awipsType, ignore: false };
1648
+ }
1649
+ }
1650
+ }
1651
+ return { message: null, attributes: null, isApi: null, isCap: null, isVtec: null, isUGC: null, isCapDescription: null, awipsType: null, ignore: true };
1652
+ }
1653
+ /**
1654
+ * getType determines the AWIPS type of the alert based on its attributes, specifically the awipsid.
1655
+ * If no matching type is found, it defaults to 'default'.
1656
+ *
1657
+ * @private
1658
+ * @static
1659
+ * @param {unknown} attributes
1660
+ * @returns {*}
1661
+ */
1662
+ static getType(attributes) {
1663
+ const attrs = attributes;
1664
+ if (!attrs || !attrs.awipsid) return { type: `XX`, prefix: `XX` };
1665
+ for (const [prefix, type] of Object.entries(definitions.awips)) {
1666
+ if (attrs.awipsid.startsWith(prefix)) {
1667
+ return { type, prefix };
1668
+ }
1669
+ }
1670
+ return { type: `XX`, prefix: `XX` };
1671
+ }
1672
+ /**
1673
+ * cache stores the compiled alert data into a cache file if caching is enabled in the settings.
1674
+ *
1675
+ * @private
1676
+ * @static
1677
+ * @param {unknown} compiled
1678
+ */
1679
+ static cache(compiled) {
1680
+ const data = compiled;
1681
+ const settings2 = settings;
1682
+ if (!settings2.NoaaWeatherWireService.cache.directory) return;
1683
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) {
1684
+ packages.fs.mkdirSync(settings2.NoaaWeatherWireService.cache.directory, { recursive: true });
1685
+ }
1686
+ data.message = data.message.replace(/\$\$/g, `
1687
+ STANZA ATTRIBUTES...${JSON.stringify(data.attributes)}
1688
+ ISSUED TIME...${(/* @__PURE__ */ new Date()).toISOString()}
1689
+ $$$
1690
+ `);
1691
+ if (!data.message.includes(`STANZA ATTRIBUTES...`)) {
1692
+ data.message += `
1693
+ STANZA ATTRIBUTES...${JSON.stringify(data.attributes)}
1694
+ ISSUED TIME...${(/* @__PURE__ */ new Date()).toISOString()}
1695
+ $$
1696
+ `;
1697
+ }
1698
+ packages.fs.appendFileSync(`${settings2.NoaaWeatherWireService.cache.directory}/category-${data.awipsPrefix}-${data.awipsType}s-${data.isCap ? `cap` : `raw`}${data.isVtec ? `-vtec` : ``}.bin`, `=================================================
1699
+ ${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}
1700
+ =================================================
1701
+ ${data.message}`, "utf8");
1702
+ packages.fs.appendFileSync(`${settings2.NoaaWeatherWireService.cache.directory}/cache-${data.isCap ? `cap` : `raw`}${data.isVtec ? `-vtec` : ``}.bin`, `=================================================
1703
+ ${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}
1704
+ =================================================
1705
+ ${data.message}`, "utf8");
1706
+ }
1707
+ };
1708
+ var stanza_default = StanzaParser;
1709
+
1710
+ // src/database.ts
1711
+ var Database = class {
1712
+ /**
1713
+ * handleAlertCache stores a unique alert in the SQLite database and ensures the total number of alerts does not exceed 5000.
1714
+ *
1715
+ * @public
1716
+ * @static
1717
+ * @async
1718
+ * @param {*} alert
1719
+ * @returns {*}
1720
+ */
1721
+ static stanzaCacheImport(stanza) {
1722
+ return __async(this, null, function* () {
1723
+ const settings2 = settings;
1724
+ cache.db.prepare(`INSERT OR IGNORE INTO stanzas (stanza) VALUES (?)`).run(stanza);
1725
+ const count = cache.db.prepare(`SELECT COUNT(*) as total FROM stanzas`).get();
1726
+ if (count.total > settings2.NoaaWeatherWireService.cache.maxHistory) {
1727
+ cache.db.prepare(`DELETE FROM stanzas WHERE rowid IN (SELECT rowid FROM stanzas ORDER BY rowid ASC LIMIT ?)`).run(count.total - settings2.NoaaWeatherWireService.cache.maxHistory / 2);
1728
+ }
1729
+ });
1730
+ }
1731
+ /**
1732
+ * loadDatabase initializes the SQLite database and imports shapefile data if the database or table does not exist.
1733
+ *
1734
+ * @public
1735
+ * @static
1736
+ * @async
1737
+ * @returns {Promise<void>}
1738
+ */
1739
+ static loadDatabase() {
1740
+ return __async(this, null, function* () {
1741
+ const settings2 = settings;
1742
+ try {
1743
+ if (!packages.fs.existsSync(settings2.database)) {
1744
+ packages.fs.writeFileSync(settings2.database, "");
1745
+ }
1746
+ cache.db = new packages.sqlite3(settings2.database);
1747
+ const shapfileTable = cache.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='shapefiles'`).get();
1748
+ const stanzaTable = cache.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='stanzas'`).get();
1749
+ if (!stanzaTable) {
1750
+ cache.db.prepare(`CREATE TABLE stanzas (id INTEGER PRIMARY KEY AUTOINCREMENT, stanza TEXT)`).run();
1751
+ }
1752
+ if (!shapfileTable) {
1753
+ cache.db.prepare(`CREATE TABLE shapefiles (id TEXT PRIMARY KEY, location TEXT, geometry TEXT)`).run();
1754
+ console.log(definitions.messages.shapefile_creation);
1755
+ for (const shape of definitions.shapefiles) {
1756
+ const { id, file } = shape;
1757
+ const filepath = packages.path.join(__dirname, `../../shapefiles`, file);
1758
+ const { features } = yield packages.shapefile.read(filepath, filepath);
1759
+ console.log(`Importing ${features.length} entries from ${file}...`);
1760
+ const insertStmt = cache.db.prepare(`INSERT OR REPLACE INTO shapefiles (id, location, geometry)VALUES (?, ?, ?)`);
1761
+ const insertTransaction = cache.db.transaction((entries) => {
1762
+ for (const feature of entries) {
1763
+ const { properties, geometry } = feature;
1764
+ let final, location;
1765
+ switch (true) {
1766
+ case !!properties.FIPS:
1767
+ final = `${properties.STATE}${id}${properties.FIPS.substring(2)}`;
1768
+ location = `${properties.COUNTYNAME}, ${properties.STATE}`;
1769
+ break;
1770
+ case !!properties.FULLSTAID:
1771
+ final = `${properties.ST}${id}${properties.WFO}`;
1772
+ location = `${properties.CITY}, ${properties.STATE}`;
1773
+ break;
1774
+ case !!properties.STATE:
1775
+ final = `${properties.STATE}${id}${properties.ZONE}`;
1776
+ location = `${properties.NAME}, ${properties.STATE}`;
1777
+ break;
1778
+ default:
1779
+ final = properties.ID;
1780
+ location = properties.NAME;
1781
+ break;
1782
+ }
1783
+ insertStmt.run(final, location, JSON.stringify(geometry));
1784
+ }
1785
+ });
1786
+ yield insertTransaction(features);
1787
+ }
1788
+ console.log(definitions.messages.shapefile_creation_finished);
1789
+ }
1790
+ } catch (error) {
1791
+ cache.events.emit("onError", { code: "error-load-database", message: `Failed to load database: ${error.message}` });
1792
+ }
1793
+ });
1794
+ }
1795
+ };
1796
+ var database_default = Database;
1797
+
1798
+ // src/xmpp.ts
1799
+ var Xmpp = class {
1800
+ /**
1801
+ * isSessionReconnectionEligible checks if the XMPP session is eligible for reconnection based on the last
1802
+ * received stanza time and current interval.
1803
+ *
1804
+ * @public
1805
+ * @static
1806
+ * @async
1807
+ * @param {number} currentInterval
1808
+ * @returns {Promise<void>}
1809
+ */
1810
+ static isSessionReconnectionEligible(currentInterval) {
1811
+ return __async(this, null, function* () {
1812
+ const settings2 = settings;
1813
+ if ((cache.isConnected || cache.sigHalt) && cache.session) {
1814
+ const lastStanza = Date.now() - cache.lastStanza;
1815
+ if (lastStanza >= currentInterval * 1e3) {
1816
+ if (!cache.attemptingReconnect) {
1817
+ cache.attemptingReconnect = true;
1818
+ cache.isConnected = false;
1819
+ cache.totalReconnects += 1;
1820
+ cache.events.emit(`onReconnect`, { reconnects: cache.totalReconnects, lastStanza, lastName: settings2.NoaaWeatherWireService.clientCredentials.nickname });
1821
+ yield cache.session.stop().catch(() => {
1822
+ });
1823
+ yield cache.session.start().catch(() => {
1824
+ });
1825
+ }
1826
+ }
1827
+ }
1828
+ });
1829
+ }
1830
+ /**
1831
+ * deploySession initializes and starts the XMPP client session, setting up event listeners for
1832
+ * connection management and message handling. This function is specifically tailored for
1833
+ * NoaaWeatherWireService and connects to their XMPP server.
1834
+ *
1835
+ * @public
1836
+ * @static
1837
+ * @async
1838
+ * @returns {Promise<void>}
1839
+ */
1840
+ static deploySession() {
1841
+ return __async(this, null, function* () {
1842
+ var _a, _b;
1843
+ const settings2 = settings;
1844
+ cache.session = packages.xmpp.client({
1845
+ service: `xmpp://nwws-oi.weather.gov`,
1846
+ domain: `nwws-oi.weather.gov`,
1847
+ username: settings2.NoaaWeatherWireService.clientCredentials.username,
1848
+ password: settings2.NoaaWeatherWireService.clientCredentials.password
1849
+ });
1850
+ (_b = (_a = settings2.NoaaWeatherWireService.clientCredentials).nickname) != null ? _b : _a.nickname = settings2.NoaaWeatherWireService.clientCredentials.username;
1851
+ cache.session.on(`online`, (address) => __async(null, null, function* () {
1852
+ if (cache.lastConnect && Date.now() - cache.lastConnect < 10 * 1e3) {
1853
+ cache.sigHalt = true;
1854
+ utils_default.sleep(2 * 1e3).then(() => __async(null, null, function* () {
1855
+ yield cache.session.stop();
1856
+ }));
1857
+ cache.events.emit(`onError`, { code: `error-reconnecting-too-fast`, message: `The client is attempting to reconnect too fast. Please wait a few seconds before trying again.` });
1858
+ return;
1859
+ }
1860
+ cache.isConnected = true;
1861
+ cache.sigHalt = false;
1862
+ cache.lastConnect = Date.now();
1863
+ cache.session.send(packages.xmpp.xml("presence", { to: `nwws@conference.nwws-oi.weather.gov/${settings2.NoaaWeatherWireService.clientCredentials.nickname}`, xmlns: "http://jabber.org/protocol/muc" }));
1864
+ cache.session.send(packages.xmpp.xml("presence", { to: `nwws@conference.nwws-oi.weather.gov`, type: "available" }));
1865
+ cache.events.emit(`onConnection`, settings2.NoaaWeatherWireService.clientCredentials.nickname);
1866
+ if (cache.attemptingReconnect) {
1867
+ utils_default.sleep(15 * 1e3).then(() => {
1868
+ cache.attemptingReconnect = false;
1869
+ });
1870
+ }
1871
+ }));
1872
+ cache.session.on(`offline`, () => __async(null, null, function* () {
1873
+ cache.isConnected = false;
1874
+ cache.sigHalt = true;
1875
+ cache.events.emit(`onError`, { code: `connection-lost`, message: `XMPP connection went offline` });
1876
+ }));
1877
+ cache.session.on(`error`, (error) => __async(null, null, function* () {
1878
+ cache.isConnected = false;
1879
+ cache.sigHalt = true;
1880
+ cache.events.emit(`onError`, { code: `connection-error`, message: error.message });
1881
+ }));
1882
+ cache.session.on(`stanza`, (stanza) => __async(null, null, function* () {
1883
+ try {
1884
+ cache.lastStanza = Date.now();
1885
+ if (stanza.is(`message`)) {
1886
+ const validate = stanza_default.validate(stanza);
1887
+ if (validate.ignore || validate.isCap && !settings2.NoaaWeatherWireService.alertPreferences.isCapOnly || !validate.isCap && settings2.NoaaWeatherWireService.alertPreferences.isCapOnly || validate.isCap && !validate.isCapDescription) return;
1888
+ events_default.eventHandler(validate);
1889
+ cache.events.emit(`onMessage`, validate);
1890
+ database_default.stanzaCacheImport(JSON.stringify(validate));
1891
+ }
1892
+ if (stanza.is(`presence`) && stanza.attrs.from && stanza.attrs.from.startsWith("nwws@conference.nwws-oi.weather.gov/")) {
1893
+ const occupant = stanza.attrs.from.split("/").slice(1).join("/");
1894
+ cache.events.emit("onOccupant", { occupant, type: stanza.attrs.type === "unavailable" ? "unavailable" : "available" });
1895
+ }
1896
+ } catch (e) {
1897
+ cache.events.emit(`onError`, { code: `error-processing-stanza`, message: e.message });
1898
+ }
1899
+ }));
1900
+ yield cache.session.start();
1901
+ });
1902
+ }
1903
+ };
1904
+ var xmpp_default = Xmpp;
1905
+
1906
+ // src/utils.ts
1907
+ var Utils = class {
1908
+ /**
1909
+ * Zzzzzzz... yeah not much to explain here. Simple sleep function that returns a promise after the specified milliseconds.
1910
+ *
1911
+ * @public
1912
+ * @static
1913
+ * @async
1914
+ * @param {number} ms
1915
+ * @returns {Promise<void>}
1916
+ */
1917
+ static sleep(ms) {
1918
+ return __async(this, null, function* () {
1919
+ return new Promise((resolve) => setTimeout(resolve, ms));
1920
+ });
1921
+ }
1922
+ /**
1923
+ * loadCollectionCache reads cached alert files from the specified cache directory and processes them.
1924
+ *
1925
+ * @public
1926
+ * @static
1927
+ * @async
1928
+ * @returns {Promise<void>}
1929
+ */
1930
+ static loadCollectionCache() {
1931
+ return __async(this, null, function* () {
1932
+ try {
1933
+ const settings2 = settings;
1934
+ if (settings2.NoaaWeatherWireService.cache.read && settings2.NoaaWeatherWireService.cache.directory) {
1935
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) return;
1936
+ const cacheDir = settings2.NoaaWeatherWireService.cache.directory;
1937
+ const getAllFiles = packages.fs.readdirSync(cacheDir).filter((file) => file.endsWith(".bin") && file.startsWith("cache-"));
1938
+ for (const file of getAllFiles) {
1939
+ const start = Date.now();
1940
+ const filepath = packages.path.join(cacheDir, file);
1941
+ const readFile = packages.fs.readFileSync(filepath, { encoding: "utf-8" });
1942
+ const isCap = readFile.includes(`<?xml`);
1943
+ if (isCap && !settings2.NoaaWeatherWireService.alertPreferences.isCapOnly) continue;
1944
+ if (!isCap && settings2.NoaaWeatherWireService.alertPreferences.isCapOnly) continue;
1945
+ const validate = stanza_default.validate(readFile, { awipsid: file, isCap, raw: true, issue: void 0 });
1946
+ yield events_default.eventHandler(validate);
1947
+ }
1948
+ }
1949
+ } catch (error) {
1950
+ cache.events.emit("onError", { code: "error-load-cache", message: `Failed to load cache: ${error.message}` });
1951
+ }
1952
+ });
1953
+ }
1954
+ /**
1955
+ * loadGeoJsonData fetches GeoJSON data from the National Weather Service endpoint and processes each alert.
1956
+ *
1957
+ * @public
1958
+ * @static
1959
+ * @async
1960
+ * @returns {Promise<void>}
1961
+ */
1962
+ static loadGeoJsonData() {
1963
+ return __async(this, null, function* () {
1964
+ try {
1965
+ const settings2 = settings;
1966
+ const response = yield this.createHttpRequest(settings2.NationalWeatherService.endpoint);
1967
+ if (!response.error) {
1968
+ events_default.eventHandler({ message: JSON.stringify(response.message), attributes: {}, isCap: true, isApi: true, isVtec: false, isUGC: false, isCapDescription: false, awipsType: { type: "api", prefix: "AP" }, ignore: false });
1969
+ }
1970
+ } catch (error) {
1971
+ cache.events.emit("onError", { code: "error-fetching-nws-data", message: `Failed to fetch NWS data: ${error.message}` });
1972
+ }
1973
+ });
1974
+ }
1975
+ /**
1976
+ * detectUncaughtExceptions sets up a global handler for uncaught exceptions in the Node.js process,
1977
+ *
1978
+ * @public
1979
+ * @static
1980
+ */
1981
+ static detectUncaughtExceptions() {
1982
+ if (process.listeners("uncaughtException").some((l) => l.name === "uncaughtExceptionHandler")) return;
1983
+ process.on(`uncaughtException`, (error) => {
1984
+ cache.events.emit(`onError`, { message: `Uncaught Exception: ${error.message}`, code: `error-uncaught-exception`, stack: error.stack });
1985
+ });
1986
+ }
1987
+ /**
1988
+ * createHttpRequest performs an HTTP GET request to the specified URL with optional settings.
1989
+ *
1990
+ * @public
1991
+ * @static
1992
+ * @async
1993
+ * @param {string} url
1994
+ * @param {?types.HTTPSettings} [options]
1995
+ * @returns {unknown}
1996
+ */
1997
+ static createHttpRequest(url, options) {
1998
+ return __async(this, null, function* () {
1999
+ var _a, _b;
2000
+ const defaultOptions = {
2001
+ timeout: 1e4,
2002
+ headers: {
2003
+ "User-Agent": "AtmosphericX",
2004
+ "Accept": "application/geo+json, text/plain, */*; q=0.9",
2005
+ "Accept-Language": "en-US,en;q=0.9"
2006
+ }
2007
+ };
2008
+ const requestOptions = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), options), {
2009
+ headers: __spreadValues(__spreadValues({}, defaultOptions.headers), (_a = options == null ? void 0 : options.headers) != null ? _a : {})
2010
+ });
2011
+ try {
2012
+ const resp = yield packages.axios.get(url, {
2013
+ headers: requestOptions.headers,
2014
+ timeout: requestOptions.timeout,
2015
+ maxRedirects: 0,
2016
+ validateStatus: (status) => status === 200 || status === 500
2017
+ });
2018
+ return { error: false, message: resp.data };
2019
+ } catch (err) {
2020
+ return { error: true, message: (_b = err == null ? void 0 : err.message) != null ? _b : String(err) };
2021
+ }
2022
+ });
2023
+ }
2024
+ /**
2025
+ * garbageCollectionCache removes files from the cache directory that exceed the specified maximum file size in megabytes.
2026
+ *
2027
+ * @public
2028
+ * @static
2029
+ * @param {number} maxFileMegabytes
2030
+ */
2031
+ static garbageCollectionCache(maxFileMegabytes) {
2032
+ try {
2033
+ const settings2 = settings;
2034
+ if (!settings2.NoaaWeatherWireService.cache.directory) return;
2035
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) return;
2036
+ const maxBytes = maxFileMegabytes * 1024 * 1024;
2037
+ const cacheDirectory = settings2.NoaaWeatherWireService.cache.directory;
2038
+ const stackFiles = [cacheDirectory], files = [];
2039
+ while (stackFiles.length) {
2040
+ const currentDirectory = stackFiles.pop();
2041
+ packages.fs.readdirSync(currentDirectory).forEach((file) => {
2042
+ const fullPath = packages.path.join(currentDirectory, file);
2043
+ const stat = packages.fs.statSync(fullPath);
2044
+ if (stat.isDirectory()) stackFiles.push(fullPath);
2045
+ else files.push({ file: fullPath, size: stat.size });
2046
+ });
2047
+ }
2048
+ if (!files.length) return;
2049
+ files.forEach((f) => {
2050
+ if (f.size > maxBytes) packages.fs.unlinkSync(f.file);
2051
+ });
2052
+ } catch (error) {
2053
+ cache.events.emit("onError", { code: "error-garbage-collection", message: `Failed to perform garbage collection: ${error.message}` });
2054
+ }
2055
+ }
2056
+ /**
2057
+ * handleCronJob performs periodic tasks based on whether the client is connected to NWWS or fetching data from NWS.
2058
+ *
2059
+ * @public
2060
+ * @static
2061
+ * @param {boolean} isNwws
2062
+ */
2063
+ static handleCronJob(isNwws) {
2064
+ try {
2065
+ const settings2 = settings;
2066
+ if (isNwws) {
2067
+ if (settings2.NoaaWeatherWireService.cache.read) void this.garbageCollectionCache(settings2.NoaaWeatherWireService.cache.maxSizeMB);
2068
+ if (settings2.NoaaWeatherWireService.clientReconnections.canReconnect) void xmpp_default.isSessionReconnectionEligible(settings2.NoaaWeatherWireService.clientReconnections.currentInterval);
2069
+ } else {
2070
+ void this.loadGeoJsonData();
2071
+ }
2072
+ } catch (error) {
2073
+ cache.events.emit("onError", { code: "error-cron-job", message: `Failed to perform scheduled tasks: ${error.message}` });
2074
+ }
2075
+ }
2076
+ /**
2077
+ * mergeClientSettings merges user-provided settings into the existing client settings, allowing for nested objects to be merged correctly.
2078
+ *
2079
+ * @public
2080
+ * @static
2081
+ * @param {Record<string, any>} target
2082
+ * @param {Record<string, any>} settings
2083
+ */
2084
+ static mergeClientSettings(target, settings2) {
2085
+ for (const key in settings2) {
2086
+ if (settings2.hasOwnProperty(key)) {
2087
+ if (typeof settings2[key] === "object" && settings2[key] !== null && !Array.isArray(settings2[key])) {
2088
+ if (!target[key] || typeof target[key] !== "object") {
2089
+ target[key] = {};
2090
+ }
2091
+ this.mergeClientSettings(target[key], settings2[key]);
2092
+ } else {
2093
+ target[key] = settings2[key];
2094
+ }
2095
+ }
2096
+ }
2097
+ }
2098
+ };
2099
+ var utils_default = Utils;
2100
+
2101
+ // src/eas.ts
2102
+ var EAS = class {
2103
+ /**
2104
+ * generateEASAudio creates an EAS-compliant audio file in WAV format containing the provided message and VTEC header.
2105
+ *
2106
+ * @public
2107
+ * @static
2108
+ * @param {string} message
2109
+ * @param {string} vtec
2110
+ * @returns {*}
2111
+ */
2112
+ static generateEASAudio(message, vtec) {
2113
+ return new Promise((resolve) => __async(this, null, function* () {
2114
+ const settings2 = settings;
2115
+ for (const { regex, replacement } of definitions.messageSignatures) {
2116
+ message = message.replace(regex, replacement);
2117
+ }
2118
+ const assetsDir = settings2.global.easSettings.easDirectory;
2119
+ if (!assetsDir) {
2120
+ console.warn(definitions.messages.eas_no_directory);
2121
+ return resolve(null);
2122
+ }
2123
+ const rngFile = `${vtec.replace(/[^a-zA-Z0-9]/g, `_`)}`.substring(0, 32).replace(/^_+|_+$/g, "");
2124
+ if (!packages.fs.existsSync(assetsDir)) {
2125
+ packages.fs.mkdirSync(assetsDir);
2126
+ }
2127
+ const tmpTTS = packages.path.join(assetsDir, `/tmp/${rngFile}.wav`);
2128
+ const outTTS = packages.path.join(assetsDir, `/output/${rngFile}.wav`);
2129
+ const voice = process.platform === "win32" ? "Microsoft David Desktop" : "en-US-GuyNeural";
2130
+ if (!packages.fs.existsSync(packages.path.join(assetsDir, `/tmp`))) {
2131
+ packages.fs.mkdirSync(packages.path.join(assetsDir, `/tmp`), { recursive: true });
2132
+ }
2133
+ if (!packages.fs.existsSync(packages.path.join(assetsDir, `/output`))) {
2134
+ packages.fs.mkdirSync(packages.path.join(assetsDir, `/output`), { recursive: true });
2135
+ }
2136
+ packages.say.export(message, voice, 1, tmpTTS);
2137
+ yield utils_default.sleep(2500);
2138
+ let ttsBuffer = null;
2139
+ while (!packages.fs.existsSync(tmpTTS) || (ttsBuffer = packages.fs.readFileSync(tmpTTS)).length === 0) {
2140
+ yield utils_default.sleep(500);
2141
+ }
2142
+ const ttsWav = this.parseWavPCM16(ttsBuffer);
2143
+ const ttsSamples = this.resamplePCM16(ttsWav.samples, ttsWav.sampleRate, 8e3);
2144
+ const ttsRadio = this.applyNWREffect(ttsSamples, 8e3);
2145
+ let toneRadio = null;
2146
+ if (packages.fs.existsSync(settings2.global.easSettings.easIntroWav)) {
2147
+ const toneBuffer = packages.fs.readFileSync(settings2.global.easSettings.easIntroWav);
2148
+ const toneWav = this.parseWavPCM16(toneBuffer);
2149
+ const toneSamples = toneWav.sampleRate !== 8e3 ? this.resamplePCM16(toneWav.samples, toneWav.sampleRate, 8e3) : toneWav.samples;
2150
+ toneRadio = this.applyNWREffect(toneSamples, 8e3);
2151
+ }
2152
+ let build = toneRadio != null ? [toneRadio, this.generateSilence(0.5, 8e3)] : [];
2153
+ build.push(this.generateSAMEHeader(vtec, 3, 8e3, { preMarkSec: 1.1, gapSec: 0.5 }), this.generateSilence(0.5, 8e3), this.generateAttentionTone(8, 8e3), this.generateSilence(0.5, 8e3), ttsRadio);
2154
+ for (let i = 0; i < 3; i++) {
2155
+ build.push(this.generateSAMEHeader(vtec, 1, 8e3, { preMarkSec: 0.5, gapSec: 0.1 }));
2156
+ build.push(this.generateSilence(0.5, 8e3));
2157
+ }
2158
+ const allSamples = this.concatPCM16(build);
2159
+ const finalSamples = this.addNoise(allSamples, 2e-3);
2160
+ const outBuffer = this.encodeWavPCM16(Array.from(finalSamples).map((v) => ({ value: v })), 8e3);
2161
+ packages.fs.writeFileSync(outTTS, outBuffer);
2162
+ try {
2163
+ packages.fs.unlinkSync(tmpTTS);
2164
+ } catch (error) {
2165
+ if (error.code !== "EBUSY") {
2166
+ throw error;
2167
+ }
2168
+ }
2169
+ return Promise.resolve(outTTS);
2170
+ }));
2171
+ }
2172
+ /**
2173
+ * encodeWavPCM16 encodes an array of samples into a WAV PCM 16-bit Buffer.
2174
+ *
2175
+ * @private
2176
+ * @static
2177
+ * @param {Record<string, number>[]} samples
2178
+ * @param {number} [sampleRate=8000]
2179
+ * @returns {Buffer}
2180
+ */
2181
+ static encodeWavPCM16(samples, sampleRate = 8e3) {
2182
+ const bytesPerSample = 2;
2183
+ const blockAlign = 1 * bytesPerSample;
2184
+ const byteRate = sampleRate * blockAlign;
2185
+ const subchunk2Size = samples.length * bytesPerSample;
2186
+ const chunkSize = 36 + subchunk2Size;
2187
+ const buffer = Buffer.alloc(44 + subchunk2Size);
2188
+ let o = 0;
2189
+ buffer.write("RIFF", o);
2190
+ o += 4;
2191
+ buffer.writeUInt32LE(chunkSize, o);
2192
+ o += 4;
2193
+ buffer.write("WAVE", o);
2194
+ o += 4;
2195
+ buffer.write("fmt ", o);
2196
+ o += 4;
2197
+ buffer.writeUInt32LE(16, o);
2198
+ o += 4;
2199
+ buffer.writeUInt16LE(1, o);
2200
+ o += 2;
2201
+ buffer.writeUInt16LE(1, o);
2202
+ o += 2;
2203
+ buffer.writeUInt32LE(sampleRate, o);
2204
+ o += 4;
2205
+ buffer.writeUInt32LE(byteRate, o);
2206
+ o += 4;
2207
+ buffer.writeUInt16LE(blockAlign, o);
2208
+ o += 2;
2209
+ buffer.writeUInt16LE(16, o);
2210
+ o += 2;
2211
+ buffer.write("data", o);
2212
+ o += 4;
2213
+ buffer.writeUInt32LE(subchunk2Size, o);
2214
+ o += 4;
2215
+ for (let i = 0; i < samples.length; i++, o += 2) {
2216
+ buffer.writeInt16LE(samples[i].value, o);
2217
+ }
2218
+ return buffer;
2219
+ }
2220
+ /**
2221
+ * parseWavPCM16 decodes a WAV PCM 16-bit Buffer into its sample data and format information.
2222
+ *
2223
+ * @private
2224
+ * @static
2225
+ * @param {Buffer} buffer
2226
+ * @returns {{ samples: any; sampleRate: any; channels: any; bitsPerSample: any; }}
2227
+ */
2228
+ static parseWavPCM16(buffer) {
2229
+ if (buffer.toString("ascii", 0, 4) !== "RIFF" || buffer.toString("ascii", 8, 12) !== "WAVE") {
2230
+ return null;
2231
+ }
2232
+ let fmt = null;
2233
+ let data = null;
2234
+ let i = 12;
2235
+ while (i + 8 <= buffer.length) {
2236
+ const id = buffer.toString("ascii", i, i + 4);
2237
+ const size = buffer.readUInt32LE(i + 4);
2238
+ const start = i + 8;
2239
+ const end = start + size;
2240
+ if (id === "fmt ") fmt = buffer.slice(start, end);
2241
+ if (id === "data") data = buffer.slice(start, end);
2242
+ i = end + size % 2;
2243
+ }
2244
+ if (!fmt || !data) return null;
2245
+ const audioFormat = fmt.readUInt16LE(0);
2246
+ const channels = fmt.readUInt16LE(2);
2247
+ const sampleRate = fmt.readUInt32LE(4);
2248
+ const bitsPerSample = fmt.readUInt16LE(14);
2249
+ if (audioFormat !== 1 || bitsPerSample !== 16 || channels !== 1) {
2250
+ return null;
2251
+ }
2252
+ const samples = new Int16Array(data.buffer, data.byteOffset, data.length / 2);
2253
+ return { samples: new Int16Array(samples), sampleRate, channels, bitsPerSample };
2254
+ }
2255
+ /**
2256
+ * concatPCM16 concatenates multiple Int16Array buffers into a single Int16Array buffer.
2257
+ *
2258
+ * @private
2259
+ * @static
2260
+ * @param {Int16Array[]} arrays
2261
+ * @returns {*}
2262
+ */
2263
+ static concatPCM16(arrays) {
2264
+ let total = 0;
2265
+ for (const a of arrays) total += a.length;
2266
+ const out = new Int16Array(total);
2267
+ let o = 0;
2268
+ for (const a of arrays) {
2269
+ out.set(a, o);
2270
+ o += a.length;
2271
+ }
2272
+ return out;
2273
+ }
2274
+ /**
2275
+ * pcm16toFloat converts an Int16Array of PCM 16-bit samples to a Float32Array of normalized float samples.
2276
+ *
2277
+ * @private
2278
+ * @static
2279
+ * @param {Int16Array} int16
2280
+ * @returns {*}
2281
+ */
2282
+ static pcm16toFloat(int16) {
2283
+ const out = new Float32Array(int16.length);
2284
+ for (let i = 0; i < int16.length; i++) out[i] = int16[i] / 32768;
2285
+ return out;
2286
+ }
2287
+ /**
2288
+ * floatToPcm16 converts a Float32Array of normalized float samples to an Int16Array of PCM 16-bit samples.
2289
+ *
2290
+ * @private
2291
+ * @static
2292
+ * @param {Float32Array} float32
2293
+ * @returns {*}
2294
+ */
2295
+ static floatToPcm16(float32) {
2296
+ const out = new Int16Array(float32.length);
2297
+ for (let i = 0; i < float32.length; i++) {
2298
+ let v = Math.max(-1, Math.min(1, float32[i]));
2299
+ out[i] = Math.round(v * 32767);
2300
+ }
2301
+ return out;
2302
+ }
2303
+ /**
2304
+ * resamplePCM16 resamples an Int16Array of PCM 16-bit samples from the original sample rate to the target sample rate using linear interpolation.
2305
+ *
2306
+ * @private
2307
+ * @static
2308
+ * @param {Int16Array} int16
2309
+ * @param {number} originalRate
2310
+ * @param {number} targetRate
2311
+ * @returns {*}
2312
+ */
2313
+ static resamplePCM16(int16, originalRate, targetRate) {
2314
+ if (originalRate === targetRate) return int16;
2315
+ const ratio = targetRate / originalRate;
2316
+ const outLen = Math.max(1, Math.round(int16.length * ratio));
2317
+ const out = new Int16Array(outLen);
2318
+ for (let i = 0; i < outLen; i++) {
2319
+ const pos = i / ratio;
2320
+ const i0 = Math.floor(pos);
2321
+ const i1 = Math.min(i0 + 1, int16.length - 1);
2322
+ const frac = pos - i0;
2323
+ const v = int16[i0] * (1 - frac) + int16[i1] * frac;
2324
+ out[i] = Math.round(v);
2325
+ }
2326
+ return out;
2327
+ }
2328
+ /**
2329
+ * generateSilence creates an Int16Array of PCM 16-bit samples representing silence for the specified duration in milliseconds.
2330
+ *
2331
+ * @private
2332
+ * @static
2333
+ * @param {number} ms
2334
+ * @param {number} [sampleRate=8000]
2335
+ * @returns {*}
2336
+ */
2337
+ static generateSilence(ms, sampleRate = 8e3) {
2338
+ return new Int16Array(Math.floor(ms * sampleRate));
2339
+ }
2340
+ /**
2341
+ * generateAttentionTone creates an Int16Array of PCM 16-bit samples representing the EAS attention tone for the specified duration in milliseconds.
2342
+ *
2343
+ * @private
2344
+ * @static
2345
+ * @param {*} ms
2346
+ * @param {number} [sampleRate=8000]
2347
+ * @returns {*}
2348
+ */
2349
+ static generateAttentionTone(ms, sampleRate = 8e3) {
2350
+ const len = Math.floor(ms * sampleRate);
2351
+ const out = new Int16Array(len);
2352
+ const f1 = 853;
2353
+ const f2 = 960;
2354
+ const twoPi = Math.PI * 2;
2355
+ const amp = 0.1;
2356
+ const fadeLen = Math.floor(sampleRate * 0);
2357
+ for (let i = 0; i < len; i++) {
2358
+ const t = i / sampleRate;
2359
+ const s = Math.sin(twoPi * f1 * t) + Math.sin(twoPi * f2 * t);
2360
+ let gain = 1;
2361
+ if (i < fadeLen) gain = i / fadeLen;
2362
+ else if (i > len - fadeLen) gain = (len - i) / fadeLen;
2363
+ const v = Math.max(-1, Math.min(1, s / 2 * amp * gain));
2364
+ out[i] = Math.round(v * 32767);
2365
+ }
2366
+ return out;
2367
+ }
2368
+ /**
2369
+ * applyNWREffect applies a series of audio processing effects to simulate the sound characteristics of NOAA Weather Radio broadcasts.
2370
+ *
2371
+ * @private
2372
+ * @static
2373
+ * @param {Int16Array} int16
2374
+ * @param {number} [sampleRate=8000]
2375
+ * @returns {*}
2376
+ */
2377
+ static applyNWREffect(int16, sampleRate = 8e3) {
2378
+ const hpCut = 3555;
2379
+ const lpCut = 1600;
2380
+ const noiseLevel = 0;
2381
+ const crushBits = 8;
2382
+ const x = this.pcm16toFloat(int16);
2383
+ const dt = 1 / sampleRate;
2384
+ const rcHP = 1 / (2 * Math.PI * hpCut);
2385
+ const aHP = rcHP / (rcHP + dt);
2386
+ let yHP = 0, xPrev = 0;
2387
+ for (let i = 0; i < x.length; i++) {
2388
+ const xi = x[i];
2389
+ yHP = aHP * (yHP + xi - xPrev);
2390
+ xPrev = xi;
2391
+ x[i] = yHP;
2392
+ }
2393
+ const rcLP = 1 / (2 * Math.PI * lpCut);
2394
+ const aLP = dt / (rcLP + dt);
2395
+ let yLP = 0;
2396
+ for (let i = 0; i < x.length; i++) {
2397
+ yLP = yLP + aLP * (x[i] - yLP);
2398
+ x[i] = yLP;
2399
+ }
2400
+ const compGain = 2;
2401
+ const norm = Math.tanh(compGain);
2402
+ for (let i = 0; i < x.length; i++) x[i] = Math.tanh(x[i] * compGain) / norm;
2403
+ const levels = Math.pow(2, crushBits) - 1;
2404
+ return this.floatToPcm16(x);
2405
+ }
2406
+ /**
2407
+ * addNoise adds low-level white noise to an Int16Array of PCM 16-bit samples to simulate analog broadcast imperfections.
2408
+ *
2409
+ * @private
2410
+ * @static
2411
+ * @param {Int16Array} int16
2412
+ * @param {number} [noiseLevel=0.02]
2413
+ * @returns {*}
2414
+ */
2415
+ static addNoise(int16, noiseLevel = 0.02) {
2416
+ const x = this.pcm16toFloat(int16);
2417
+ for (let i = 0; i < x.length; i++) x[i] += (Math.random() * 2 - 1) * noiseLevel;
2418
+ let peak = 0;
2419
+ for (let i = 0; i < x.length; i++) peak = Math.max(peak, Math.abs(x[i]));
2420
+ if (peak > 1) for (let i = 0; i < x.length; i++) x[i] *= 0.98 / peak;
2421
+ return this.floatToPcm16(x);
2422
+ }
2423
+ /**
2424
+ * asciiTo8N1Bits converts an ASCII string to a sequence of bits using 8-N-1 encoding (8 data bits, no parity, 1 stop bit).
2425
+ *
2426
+ * @private
2427
+ * @static
2428
+ * @param {string} str
2429
+ * @returns {{}}
2430
+ */
2431
+ static asciiTo8N1Bits(str) {
2432
+ const bits = [];
2433
+ for (let i = 0; i < str.length; i++) {
2434
+ const c = str.charCodeAt(i) & 255;
2435
+ bits.push(0);
2436
+ for (let b = 0; b < 8; b++) bits.push(c >> b & 1);
2437
+ bits.push(1, 1);
2438
+ }
2439
+ return bits;
2440
+ }
2441
+ /**
2442
+ * generateAFSK generates an Int16Array of PCM 16-bit samples representing AFSK modulation of the provided bit sequence.
2443
+ *
2444
+ * @private
2445
+ * @static
2446
+ * @param {number[]} bits
2447
+ * @param {number} [sampleRate=8000]
2448
+ * @returns {*}
2449
+ */
2450
+ static generateAFSK(bits, sampleRate = 8e3) {
2451
+ const baud = 520.83;
2452
+ const markFreq = 2083.3;
2453
+ const spaceFreq = 1562.5;
2454
+ const amplitude = 0.6;
2455
+ const twoPi = Math.PI * 2;
2456
+ const result = [];
2457
+ let phase = 0;
2458
+ let frac = 0;
2459
+ for (let b = 0; b < bits.length; b++) {
2460
+ const bit = bits[b];
2461
+ const freq = bit ? markFreq : spaceFreq;
2462
+ const samplesPerBit = sampleRate / baud + frac;
2463
+ const n = Math.round(samplesPerBit);
2464
+ frac = samplesPerBit - n;
2465
+ const inc = twoPi * freq / sampleRate;
2466
+ for (let i = 0; i < n; i++) {
2467
+ result.push(Math.round(Math.sin(phase) * amplitude * 32767));
2468
+ phase += inc;
2469
+ if (phase > twoPi) phase -= twoPi;
2470
+ }
2471
+ }
2472
+ const fadeSamples = Math.floor(sampleRate * 2e-3);
2473
+ for (let i = 0; i < fadeSamples; i++) {
2474
+ const gain = i / fadeSamples;
2475
+ result[i] = Math.round(result[i] * gain);
2476
+ result[result.length - 1 - i] = Math.round(result[result.length - 1 - i] * gain);
2477
+ }
2478
+ return Int16Array.from(result);
2479
+ }
2480
+ /**
2481
+ * generateSAMEHeader generates an Int16Array of PCM 16-bit samples representing the SAME header repeated the specified number of times.
2482
+ *
2483
+ * @private
2484
+ * @static
2485
+ * @param {string} vtec
2486
+ * @param {number} repeats
2487
+ * @param {number} [sampleRate=8000]
2488
+ * @param {{preMarkSec?: number, gapSec?: number}} [options={}]
2489
+ * @returns {*}
2490
+ */
2491
+ static generateSAMEHeader(vtec, repeats, sampleRate = 8e3, options = {}) {
2492
+ var _a, _b;
2493
+ const preMarkSec = (_a = options.preMarkSec) != null ? _a : 0.3;
2494
+ const gapSec = (_b = options.gapSec) != null ? _b : 0.1;
2495
+ const bursts = [];
2496
+ const gap = this.generateSilence(gapSec, sampleRate);
2497
+ for (let i = 0; i < repeats; i++) {
2498
+ const bodyBits = this.asciiTo8N1Bits(vtec);
2499
+ const body = this.generateAFSK(bodyBits, sampleRate);
2500
+ const extendedBodyDuration = Math.round(preMarkSec * sampleRate);
2501
+ const extendedBody = new Int16Array(extendedBodyDuration + gap.length);
2502
+ for (let j = 0; j < extendedBodyDuration; j++) {
2503
+ extendedBody[j] = Math.round(body[j % body.length] * 0.2);
2504
+ }
2505
+ extendedBody.set(gap, extendedBodyDuration);
2506
+ bursts.push(extendedBody);
2507
+ if (i !== repeats - 1) bursts.push(gap);
2508
+ }
2509
+ return this.concatPCM16(bursts);
2510
+ }
2511
+ };
2512
+ var eas_default = EAS;
2513
+
2514
+ // src/parsers/events.ts
2515
+ var EventParser = class {
2516
+ /**
2517
+ * getBaseProperties extracts and compiles the base properties of an alert message, including location, timing, description, sender information, and various parameters.
2518
+ *
2519
+ * @public
2520
+ * @static
2521
+ * @async
2522
+ * @param {string} message
2523
+ * @param {types.TypeCompiled} validated
2524
+ * @param {types.UGCParsed} [ugc=null]
2525
+ * @param {types.VTECParsed} [vtec=null]
2526
+ * @returns {Promise<types.BaseProperties>}
2527
+ */
2528
+ static getBaseProperties(message, validated, ugc = null, vtec = null) {
2529
+ return __async(this, null, function* () {
2530
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2531
+ const settings2 = settings;
2532
+ const definitions2 = {
2533
+ tornado: text_default.textProductToString(message, `TORNADO...`) || text_default.textProductToString(message, `WATERSPOUT...`) || `N/A`,
2534
+ hail: text_default.textProductToString(message, `MAX HAIL SIZE...`, [`IN`]) || text_default.textProductToString(message, `HAIL...`, [`IN`]) || `N/A`,
2535
+ gusts: text_default.textProductToString(message, `MAX WIND GUST...`) || text_default.textProductToString(message, `WIND...`) || `N/A`,
2536
+ flood: text_default.textProductToString(message, `FLASH FLOOD...`) || `N/A`,
2537
+ damage: text_default.textProductToString(message, `DAMAGE THREAT...`) || `N/A`,
2538
+ source: text_default.textProductToString(message, `SOURCE...`, [`.`]) || `N/A`,
2539
+ attributes: text_default.textProductToString(message, `STANZA ATTRIBUTES...`) ? JSON.parse(text_default.textProductToString(message, `STANZA ATTRIBUTES...`)) : null,
2540
+ polygon: text_default.textProductToPolygon(message),
2541
+ description: text_default.textProductToDescription(message, (_a = vtec == null ? void 0 : vtec.raw) != null ? _a : null),
2542
+ wmo: message.match(new RegExp(definitions.expressions.wmo, "imu")),
2543
+ mdTorIntensity: text_default.textProductToString(message, `MOST PROBABLE PEAK TORNADO INTENSITY...`) || `N/A`,
2544
+ mdWindGusts: text_default.textProductToString(message, `MOST PROBABLE PEAK WIND GUST...`) || `N/A`,
2545
+ mdHailSize: text_default.textProductToString(message, `MOST PROBABLE PEAK HAIL SIZE...`) || `N/A`
2546
+ };
2547
+ const getOffice = this.getICAO(vtec, (_c = (_b = validated.attributes) != null ? _b : definitions2.attributes) != null ? _c : {}, definitions2.wmo);
2548
+ const getCorrectIssued = this.getCorrectIssuedDate((_e = (_d = definitions2.attributes) != null ? _d : validated.attributes) != null ? _e : {});
2549
+ const getCorrectExpiry = this.getCorrectExpiryDate(vtec, ugc);
2550
+ const getAwip = text_default.awipTextToEvent((_g = (_f = definitions2.attributes) == null ? void 0 : _f.awipsid) != null ? _g : validated.awipsType.prefix);
2551
+ const base = {
2552
+ locations: (ugc == null ? void 0 : ugc.locations.join(`; `)) || `No Location Specified (UGC Missing)`,
2553
+ issued: getCorrectIssued,
2554
+ expires: getCorrectExpiry,
2555
+ geocode: { UGC: (ugc == null ? void 0 : ugc.zones) || [`XX000`] },
2556
+ description: definitions2.description,
2557
+ sender_name: getOffice.name,
2558
+ sender_icao: getOffice.icao,
2559
+ attributes: __spreadProps(__spreadValues(__spreadValues({}, validated.attributes), definitions2.attributes), {
2560
+ getAwip
2561
+ }),
2562
+ parameters: {
2563
+ wmo: Array.isArray(definitions2.wmo) ? definitions2.wmo[0] : (_h = definitions2.wmo) != null ? _h : `N/A`,
2564
+ source: definitions2.source,
2565
+ max_hail_size: definitions2.hail,
2566
+ max_wind_gust: definitions2.gusts,
2567
+ damage_threat: definitions2.damage,
2568
+ tornado_detection: definitions2.tornado,
2569
+ flood_detection: definitions2.flood,
2570
+ discussion_tornado_intensity: definitions2.mdTorIntensity,
2571
+ discussion_wind_intensity: definitions2.mdWindGusts,
2572
+ discussion_hail_intensity: definitions2.mdHailSize
2573
+ },
2574
+ geometry: definitions2.polygon.length > 0 ? { type: "Polygon", coordinates: definitions2.polygon } : null
2575
+ };
2576
+ if (settings2.NoaaWeatherWireService.alertPreferences.isShapefileUGC && base.geometry == null && ugc != null) {
2577
+ const coordinates = yield ugc_default.getCoordinates(ugc.zones);
2578
+ base.geometry = { type: "Polygon", coordinates };
2579
+ }
2580
+ return base;
2581
+ });
2582
+ }
2583
+ /**
2584
+ * enhanceEvent refines the event name based on specific conditions and tags found in the event's description and parameters.
2585
+ *
2586
+ * @public
2587
+ * @static
2588
+ * @param {types.TypeAlert} event
2589
+ * @returns {{ eventName: any; tags: any; }}
2590
+ */
2591
+ static enhanceEvent(event) {
2592
+ var _a, _b, _c, _d, _e;
2593
+ let eventName = (_b = (_a = event == null ? void 0 : event.properties) == null ? void 0 : _a.event) != null ? _b : `Unknown Event`;
2594
+ const defEventTable = definitions.enhancedEvents;
2595
+ const defEventTags = definitions.tags;
2596
+ const properties = event == null ? void 0 : event.properties;
2597
+ const parameters = properties == null ? void 0 : properties.parameters;
2598
+ const description = (_c = properties == null ? void 0 : properties.description) != null ? _c : `Unknown Description`;
2599
+ const damageThreatTag = (_d = parameters == null ? void 0 : parameters.damage_threat) != null ? _d : `N/A`;
2600
+ const tornadoThreatTag = (_e = parameters == null ? void 0 : parameters.tornado_detection) != null ? _e : `N/A`;
2601
+ for (const eventGroup of defEventTable) {
2602
+ const [baseEvent, conditions] = Object.entries(eventGroup)[0];
2603
+ if (eventName === baseEvent) {
2604
+ for (const [specificEvent, condition] of Object.entries(conditions)) {
2605
+ const conditionMet = condition.description && description.includes(condition.description.toLowerCase()) || condition.condition && condition.condition(damageThreatTag || tornadoThreatTag);
2606
+ if (conditionMet) {
2607
+ eventName = specificEvent;
2608
+ break;
2609
+ }
2610
+ }
2611
+ if (baseEvent === "Severe Thunderstorm Warning" && damageThreatTag === "POSSIBLE" && !eventName.includes("(TPROB)")) eventName += " (TPROB)";
2612
+ break;
2613
+ }
2614
+ }
2615
+ const tags = Object.entries(defEventTags).filter(([key]) => description.includes(key.toLowerCase())).map(([, value]) => value);
2616
+ return { eventName, tags: tags.length > 0 ? tags : [`N/A`] };
2617
+ }
2618
+ /**
2619
+ * getCorrectExpiryDate determines the correct expiration date for an alert based on VTEC information or UGC zones.
2620
+ *
2621
+ * @public
2622
+ * @static
2623
+ * @param {unknown[]} events
2624
+ */
2625
+ static validateEvents(events2) {
2626
+ var _a, _b, _c, _d, _e;
2627
+ if (events2.length == 0) return;
2628
+ const settings2 = settings;
2629
+ const filteringSettings = (_b = (_a = settings) == null ? void 0 : _a.global) == null ? void 0 : _b.alertFiltering;
2630
+ const easSettings = (_d = (_c = settings) == null ? void 0 : _c.global) == null ? void 0 : _d.easSettings;
2631
+ const globalSettings = (_e = settings) == null ? void 0 : _e.global;
2632
+ const sets = {};
2633
+ const bools = {};
2634
+ const megered = __spreadValues(__spreadValues(__spreadValues({}, filteringSettings), easSettings), globalSettings);
2635
+ for (const key in megered) {
2636
+ const setting = megered[key];
2637
+ if (Array.isArray(setting)) {
2638
+ sets[key] = new Set(setting.map((item) => item.toLowerCase()));
2639
+ }
2640
+ if (typeof setting === "boolean") {
2641
+ bools[key] = setting;
2642
+ }
2643
+ }
2644
+ const filtered = events2.filter((alert) => {
2645
+ var _a2, _b2, _c2, _d2;
2646
+ const originalEvent = alert;
2647
+ const props = originalEvent == null ? void 0 : originalEvent.properties;
2648
+ const ugcs = (_b2 = (_a2 = props == null ? void 0 : props.geocode) == null ? void 0 : _a2.UGC) != null ? _b2 : [];
2649
+ if (bools == null ? void 0 : bools.betterEventParsing) {
2650
+ const { eventName, tags } = this.enhanceEvent(originalEvent);
2651
+ originalEvent.properties.event = eventName;
2652
+ originalEvent.properties.tags = tags;
2653
+ }
2654
+ const eventCheck = (bools == null ? void 0 : bools.useParentEvents) ? (_c2 = props.parent) == null ? void 0 : _c2.toLowerCase() : (_d2 = props.event) == null ? void 0 : _d2.toLowerCase();
2655
+ const statusCorrelation = definitions.correlations.find((c) => c.type === originalEvent.properties.action_type);
2656
+ for (const key in sets) {
2657
+ const setting = sets[key];
2658
+ if (key === "filteredEvents" && setting.size > 0 && eventCheck != null && !setting.has(eventCheck)) return false;
2659
+ if (key === "ignoredEvents" && setting.size > 0 && eventCheck != null && setting.has(eventCheck)) return false;
2660
+ if (key === "filteredICOAs" && setting.size > 0 && props.sender_icao != null && !setting.has(props.sender_icao.toLowerCase())) return false;
2661
+ if (key === "ignoredICOAs" && setting.size > 0 && props.sender_icao != null && setting.has(props.sender_icao.toLowerCase())) return false;
2662
+ if (key === "ugcFilter" && setting.size > 0 && ugcs.length > 0 && !ugcs.some((ugc) => setting.has(ugc.toLowerCase()))) return false;
2663
+ if (key === "stateFilter" && setting.size > 0 && ugcs.length > 0 && !ugcs.some((ugc) => setting.has(ugc.substring(0, 2).toLowerCase()))) return false;
2664
+ if (key === "easAlerts" && setting.size > 0 && eventCheck != null && setting.has(eventCheck) && settings2.isNWWS) {
2665
+ eas_default.generateEASAudio(props.description, alert.header);
2666
+ }
2667
+ }
2668
+ for (const key in bools) {
2669
+ const setting = bools[key];
2670
+ if (key === "checkExpired" && setting && new Date(props == null ? void 0 : props.expires).getTime() < (/* @__PURE__ */ new Date()).getTime()) return false;
2671
+ }
2672
+ originalEvent.properties.action_type = statusCorrelation ? statusCorrelation.forward : originalEvent.properties.action_type;
2673
+ originalEvent.properties.is_cancelled = statusCorrelation ? statusCorrelation.cancel == true && bools.checkExpired : false;
2674
+ if (props.description) {
2675
+ const detectedPhrase = definitions.cancelSignatures.find((sig) => props.description.toLowerCase().includes(sig.toLowerCase()));
2676
+ if (detectedPhrase && bools.checkExpired) {
2677
+ originalEvent.properties.action_type = "Cancel";
2678
+ originalEvent.properties.is_cancelled = true;
2679
+ return false;
2680
+ }
2681
+ }
2682
+ if (originalEvent.vtec) {
2683
+ const getType = originalEvent.vtec.split(`.`)[0];
2684
+ const isTestProduct = definitions.productTypes[getType] == `Test Product`;
2685
+ if (isTestProduct) {
2686
+ return false;
2687
+ }
2688
+ }
2689
+ cache.events.emit(`on${originalEvent.properties.parent.replace(/\s+/g, "")}`);
2690
+ return true;
2691
+ });
2692
+ if (filtered.length > 0) {
2693
+ cache.events.emit(`onAlerts`, filtered);
2694
+ }
2695
+ }
2696
+ /**
2697
+ * getHeader constructs a standardized alert header string based on provided attributes, properties, and VTEC information.
2698
+ *
2699
+ * @public
2700
+ * @static
2701
+ * @param {types.TypeAttributes} attributes
2702
+ * @param {?types.BaseProperties} [properties]
2703
+ * @param {?types.VTECParsed} [vtec]
2704
+ * @returns {string}
2705
+ */
2706
+ static getHeader(attributes, properties, vtec) {
2707
+ var _a, _b, _c, _d, _e, _f, _g;
2708
+ const parent = `ATSX`;
2709
+ const alertType = (_d = (_c = (_a = attributes == null ? void 0 : attributes.awipsType) == null ? void 0 : _a.type) != null ? _c : (_b = attributes == null ? void 0 : attributes.getAwip) == null ? void 0 : _b.prefix) != null ? _d : `XX`;
2710
+ const ugc = ((_e = properties == null ? void 0 : properties.geocode) == null ? void 0 : _e.UGC) != null ? (_f = properties == null ? void 0 : properties.geocode) == null ? void 0 : _f.UGC.join(`-`) : `000000`;
2711
+ const status = (vtec == null ? void 0 : vtec.status) || "Issued";
2712
+ const issued = (properties == null ? void 0 : properties.issued) != null ? (_g = new Date(properties == null ? void 0 : properties.issued)) == null ? void 0 : _g.toISOString().replace(/[-:]/g, "").split(".")[0] : (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").split(".")[0];
2713
+ const sender = (properties == null ? void 0 : properties.sender_icao) || `XXXX`;
2714
+ const header = `ZCZC-${parent}-${alertType}-${ugc}-${status}-${issued}-${sender}-`;
2715
+ return header;
2716
+ }
2717
+ /**
2718
+ * eventHandler routes the validated alert message to the appropriate event parser based on its type (API, CAP, VTEC, UGC, or plain text).
2719
+ *
2720
+ * @public
2721
+ * @static
2722
+ * @param {types.TypeCompiled} validated
2723
+ * @returns {*}
2724
+ */
2725
+ static eventHandler(validated) {
2726
+ if (validated.isApi) return api_default.event(validated);
2727
+ if (validated.isCap) return cap_default.event(validated);
2728
+ if (!validated.isCap && validated.isVtec && validated.isUGC) return vtec_default2.event(validated);
2729
+ if (!validated.isCap && !validated.isVtec && validated.isUGC) return ugc_default2.event(validated);
2730
+ if (!validated.isCap && !validated.isVtec && !validated.isUGC) return text_default2.event(validated);
2731
+ }
2732
+ /**
2733
+ * getICAO retrieves the ICAO code and corresponding office name based on VTEC tracking information, message attributes, or WMO code.
2734
+ *
2735
+ * @private
2736
+ * @static
2737
+ * @param {types.VTECParsed} vtec
2738
+ * @param {Record<string, string>} attributes
2739
+ * @param {(RegExpMatchArray | string | null)} WMO
2740
+ * @returns {{ icao: any; name: any; }}
2741
+ */
2742
+ static getICAO(vtec, attributes, WMO) {
2743
+ var _a, _b, _c;
2744
+ const icao = vtec != null ? vtec == null ? void 0 : vtec.tracking.split(`-`)[0] : (_a = attributes == null ? void 0 : attributes.cccc) != null ? _a : WMO != null ? Array.isArray(WMO) ? WMO[0] : WMO : `N/A`;
2745
+ const name = (_c = (_b = definitions.ICAO) == null ? void 0 : _b[icao]) != null ? _c : `N/A`;
2746
+ return { icao, name };
2747
+ }
2748
+ /**
2749
+ * getCorrectIssuedDate ensures the issued date is valid and falls back to the current date if not.
2750
+ *
2751
+ * @private
2752
+ * @static
2753
+ * @param {Record<string, string>} attributes
2754
+ * @returns {*}
2755
+ */
2756
+ static getCorrectIssuedDate(attributes) {
2757
+ const time = attributes.issue != null ? new Date(attributes.issue).toLocaleString() : (attributes == null ? void 0 : attributes.issue) != null ? new Date(attributes.issue).toLocaleString() : (/* @__PURE__ */ new Date()).toLocaleString();
2758
+ if (time == `Invalid Date`) return (/* @__PURE__ */ new Date()).toLocaleString();
2759
+ return time;
2760
+ }
2761
+ /**
2762
+ * getCorrectExpiryDate determines the correct expiration date for an alert based on VTEC information or UGC zones.
2763
+ *
2764
+ * @private
2765
+ * @static
2766
+ * @param {types.VTECParsed} vtec
2767
+ * @param {types.UGCParsed} ugc
2768
+ * @returns {*}
2769
+ */
2770
+ static getCorrectExpiryDate(vtec, ugc) {
2771
+ const time = (vtec == null ? void 0 : vtec.expires) && !isNaN(new Date(vtec.expires).getTime()) ? new Date(vtec.expires).toLocaleString() : (ugc == null ? void 0 : ugc.expiry) != null ? new Date(ugc.expiry).toLocaleString() : new Date((/* @__PURE__ */ new Date()).getTime() + 1 * 60 * 60 * 1e3).toLocaleString();
2772
+ if (time == `Invalid Date`) return new Date((/* @__PURE__ */ new Date()).getTime() + 1 * 60 * 60 * 1e3).toLocaleString();
2773
+ return time;
2774
+ }
2775
+ };
2776
+ var events_default = EventParser;
2777
+
2778
+ // src/parsers/types/vtec.ts
2779
+ var VTECAlerts = class {
2780
+ /**
2781
+ * event processes validated VTEC alert messages, extracting relevant information and compiling it into structured event objects.
2782
+ *
2783
+ * @public
2784
+ * @static
2785
+ * @async
2786
+ * @param {types.TypeCompiled} validated
2787
+ * @returns {*}
2788
+ */
2789
+ static event(validated) {
2790
+ return __async(this, null, function* () {
2791
+ var _a;
2792
+ let processed = [];
2793
+ const messages = (_a = validated.message.split(/(?=\$\$)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
2794
+ if (!messages || messages.length == 0) return;
2795
+ for (let i = 0; i < messages.length; i++) {
2796
+ const tick = performance.now();
2797
+ const message = messages[i];
2798
+ const getVTEC = yield vtec_default.vtecExtractor(message);
2799
+ const getUGC = yield ugc_default.ugcExtractor(message);
2800
+ if (getVTEC != null && getUGC != null) {
2801
+ for (let j = 0; j < getVTEC.length; j++) {
2802
+ const vtec = getVTEC[j];
2803
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated, getUGC, vtec);
2804
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties, vtec);
2805
+ processed.push({
2806
+ preformance: performance.now() - tick,
2807
+ tracking: vtec.tracking,
2808
+ header: getHeader,
2809
+ vtec: vtec.raw,
2810
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: vtec.status }],
2811
+ properties: __spreadValues({ event: vtec.event, parent: vtec.event, action_type: vtec.status }, getBaseProperties)
2812
+ });
2813
+ }
2814
+ }
2815
+ }
2816
+ events_default.validateEvents(processed);
2817
+ });
2818
+ }
2819
+ };
2820
+ var vtec_default2 = VTECAlerts;
2821
+ export {
2822
+ VTECAlerts,
2823
+ vtec_default2 as default
2824
+ };