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/stanza.ts
1009
+ var StanzaParser = class {
1010
+ /**
1011
+ * validate handles the validation of incoming XMPP stanzas to ensure they contain valid alert data.
1012
+ * You can also feed debug / cache data directly into this function by specifying the second parameter
1013
+ * which is the attributes object that would normally be parsed from the XMPP stanza.
1014
+ *
1015
+ * @public
1016
+ * @static
1017
+ * @param {*} stanza
1018
+ * @param {(boolean | types.TypeAttributes)} [isDebug=false]
1019
+ * @returns {{ message: any; attributes: types.TypeAttributes; isCap: any; isVtec: boolean; isCapDescription: any; awipsType: any; isApi: boolean; ignore: boolean; }}
1020
+ */
1021
+ static validate(stanza, isDebug = false) {
1022
+ var _a;
1023
+ if (isDebug !== false) {
1024
+ const vTypes = isDebug;
1025
+ const message = stanza;
1026
+ const attributes = vTypes;
1027
+ const isCap = (_a = vTypes.isCap) != null ? _a : message.includes(`<?xml`);
1028
+ const isCapDescription = message.includes(`<areaDesc>`);
1029
+ const isVtec = message.match(definitions.expressions.vtec) != null;
1030
+ const isUGC = message.match(definitions.expressions.ugc1) != null;
1031
+ const awipsType = this.getType(attributes);
1032
+ return { message, attributes, isCap, isVtec, isUGC, isCapDescription, awipsType, isApi: false, ignore: false };
1033
+ }
1034
+ if (stanza.is(`message`)) {
1035
+ let cb = stanza.getChild(`x`);
1036
+ if (cb && cb.children) {
1037
+ let message = unescape(cb.children[0]);
1038
+ let attributes = cb.attrs;
1039
+ if (attributes.awipsid && attributes.awipsid.length > 1) {
1040
+ const isCap = message.includes(`<?xml`);
1041
+ const isCapDescription = message.includes(`<areaDesc>`);
1042
+ const isVtec = message.match(definitions.expressions.vtec) != null;
1043
+ const isUGC = message.match(definitions.expressions.ugc1) != null;
1044
+ const awipsType = this.getType(attributes);
1045
+ const isApi = false;
1046
+ this.cache({ message, attributes, isCap, isVtec, awipsType: awipsType.type, awipsPrefix: awipsType.prefix });
1047
+ return { message, attributes, isCap, isApi, isVtec, isUGC, isCapDescription, awipsType, ignore: false };
1048
+ }
1049
+ }
1050
+ }
1051
+ return { message: null, attributes: null, isApi: null, isCap: null, isVtec: null, isUGC: null, isCapDescription: null, awipsType: null, ignore: true };
1052
+ }
1053
+ /**
1054
+ * getType determines the AWIPS type of the alert based on its attributes, specifically the awipsid.
1055
+ * If no matching type is found, it defaults to 'default'.
1056
+ *
1057
+ * @private
1058
+ * @static
1059
+ * @param {unknown} attributes
1060
+ * @returns {*}
1061
+ */
1062
+ static getType(attributes) {
1063
+ const attrs = attributes;
1064
+ if (!attrs || !attrs.awipsid) return { type: `XX`, prefix: `XX` };
1065
+ for (const [prefix, type] of Object.entries(definitions.awips)) {
1066
+ if (attrs.awipsid.startsWith(prefix)) {
1067
+ return { type, prefix };
1068
+ }
1069
+ }
1070
+ return { type: `XX`, prefix: `XX` };
1071
+ }
1072
+ /**
1073
+ * cache stores the compiled alert data into a cache file if caching is enabled in the settings.
1074
+ *
1075
+ * @private
1076
+ * @static
1077
+ * @param {unknown} compiled
1078
+ */
1079
+ static cache(compiled) {
1080
+ const data = compiled;
1081
+ const settings2 = settings;
1082
+ if (!settings2.NoaaWeatherWireService.cache.directory) return;
1083
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) {
1084
+ packages.fs.mkdirSync(settings2.NoaaWeatherWireService.cache.directory, { recursive: true });
1085
+ }
1086
+ data.message = data.message.replace(/\$\$/g, `
1087
+ STANZA ATTRIBUTES...${JSON.stringify(data.attributes)}
1088
+ ISSUED TIME...${(/* @__PURE__ */ new Date()).toISOString()}
1089
+ $$$
1090
+ `);
1091
+ if (!data.message.includes(`STANZA ATTRIBUTES...`)) {
1092
+ data.message += `
1093
+ STANZA ATTRIBUTES...${JSON.stringify(data.attributes)}
1094
+ ISSUED TIME...${(/* @__PURE__ */ new Date()).toISOString()}
1095
+ $$
1096
+ `;
1097
+ }
1098
+ packages.fs.appendFileSync(`${settings2.NoaaWeatherWireService.cache.directory}/category-${data.awipsPrefix}-${data.awipsType}s-${data.isCap ? `cap` : `raw`}${data.isVtec ? `-vtec` : ``}.bin`, `=================================================
1099
+ ${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}
1100
+ =================================================
1101
+ ${data.message}`, "utf8");
1102
+ packages.fs.appendFileSync(`${settings2.NoaaWeatherWireService.cache.directory}/cache-${data.isCap ? `cap` : `raw`}${data.isVtec ? `-vtec` : ``}.bin`, `=================================================
1103
+ ${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}
1104
+ =================================================
1105
+ ${data.message}`, "utf8");
1106
+ }
1107
+ };
1108
+ var stanza_default = StanzaParser;
1109
+
1110
+ // src/parsers/text.ts
1111
+ var TextParser = class {
1112
+ /**
1113
+ * textProductToString extracts a specific value from a text-based weather product message based on a given key and optional removal strings.
1114
+ *
1115
+ * @public
1116
+ * @static
1117
+ * @param {string} message
1118
+ * @param {string} value
1119
+ * @param {string[]} [removal=[]]
1120
+ * @returns {(string | null)}
1121
+ */
1122
+ static textProductToString(message, value, removal = []) {
1123
+ const lines = message.split("\n");
1124
+ for (const line of lines) {
1125
+ if (line.includes(value)) {
1126
+ let result = line.slice(line.indexOf(value) + value.length).trim();
1127
+ for (const str of removal) {
1128
+ result = result.split(str).join("");
1129
+ }
1130
+ result = result.replace(value, "").replace("<", "").trim();
1131
+ return result || null;
1132
+ }
1133
+ }
1134
+ return null;
1135
+ }
1136
+ /**
1137
+ * textProductToPolygon extracts geographical coordinates from a text-based weather product message and returns them as an array of [longitude, latitude] pairs.
1138
+ *
1139
+ * @public
1140
+ * @static
1141
+ * @param {string} message
1142
+ * @returns {[number, number][]}
1143
+ */
1144
+ static textProductToPolygon(message) {
1145
+ const coordinates = [];
1146
+ const latLonMatch = message.match(/LAT\.{3}LON\s+([\d\s]+)/i);
1147
+ if (!latLonMatch || !latLonMatch[1]) return coordinates;
1148
+ const coordStrings = latLonMatch[1].replace(/\n/g, " ").trim().split(/\s+/);
1149
+ for (let i = 0; i < coordStrings.length - 1; i += 2) {
1150
+ const lat = parseFloat(coordStrings[i]) / 100;
1151
+ const lon = -parseFloat(coordStrings[i + 1]) / 100;
1152
+ if (!isNaN(lat) && !isNaN(lon)) {
1153
+ coordinates.push([lon, lat]);
1154
+ }
1155
+ }
1156
+ if (coordinates.length > 2) {
1157
+ coordinates.push(coordinates[0]);
1158
+ }
1159
+ return coordinates;
1160
+ }
1161
+ /**
1162
+ * textProductToDescription extracts the main description from a text-based weather product message.
1163
+ *
1164
+ * @public
1165
+ * @static
1166
+ * @param {string} message
1167
+ * @param {string} [handle=null]
1168
+ * @returns {string}
1169
+ */
1170
+ static textProductToDescription(message, handle = null) {
1171
+ const original = message;
1172
+ 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;
1173
+ const discoveredDates = Array.from(message.matchAll(dateRegex));
1174
+ if (discoveredDates.length) {
1175
+ const lastMatch = discoveredDates[discoveredDates.length - 1][0];
1176
+ const startIdx = message.lastIndexOf(lastMatch);
1177
+ if (startIdx !== -1) {
1178
+ const endIdx = message.indexOf("&&", startIdx);
1179
+ message = message.substring(startIdx + lastMatch.length, endIdx !== -1 ? endIdx : void 0).trimStart();
1180
+ if (message.startsWith("/")) message = message.slice(1).trimStart();
1181
+ if (handle && message.includes(handle)) {
1182
+ const handleIdx = message.indexOf(handle);
1183
+ message = message.substring(handleIdx + handle.length).trimStart();
1184
+ if (message.startsWith("/")) message = message.slice(1).trimStart();
1185
+ }
1186
+ }
1187
+ } else if (handle) {
1188
+ const handleIdx = message.indexOf(handle);
1189
+ if (handleIdx !== -1) {
1190
+ let afterHandle = message.substring(handleIdx + handle.length).trimStart();
1191
+ if (afterHandle.startsWith("/")) afterHandle = afterHandle.slice(1).trimStart();
1192
+ const latEnd = afterHandle.indexOf("&&");
1193
+ message = latEnd !== -1 ? afterHandle.substring(0, latEnd).trim() : afterHandle.trim();
1194
+ }
1195
+ }
1196
+ return message.replace(/\s+/g, " ").trim().startsWith("ISSUED TIME...") ? original : message.trim();
1197
+ }
1198
+ /**
1199
+ * awipTextToEvent converts an AWIPS ID prefix from a text-based weather product message to its corresponding event type and prefix.
1200
+ *
1201
+ * @public
1202
+ * @static
1203
+ * @param {string} message
1204
+ * @returns {{ type: any; prefix: any; }}
1205
+ */
1206
+ static awipTextToEvent(message) {
1207
+ for (const [prefix, type] of Object.entries(definitions.awips)) {
1208
+ if (message.startsWith(prefix)) {
1209
+ return { type, prefix };
1210
+ }
1211
+ }
1212
+ return { type: `XX`, prefix: `XX` };
1213
+ }
1214
+ /**
1215
+ * getXmlValues recursively searches a parsed XML object for specified keys and extracts their values.
1216
+ *
1217
+ * @public
1218
+ * @static
1219
+ * @param {*} parsed
1220
+ * @param {string[]} valuesToExtract
1221
+ * @returns {Record<string, any>}
1222
+ */
1223
+ static getXmlValues(parsed, valuesToExtract) {
1224
+ const extracted = {};
1225
+ const findValueByKey = (obj, searchKey) => {
1226
+ const results = [];
1227
+ if (obj === null || typeof obj !== "object") {
1228
+ return results;
1229
+ }
1230
+ const searchKeyLower = searchKey.toLowerCase();
1231
+ for (const key in obj) {
1232
+ if (obj.hasOwnProperty(key) && key.toLowerCase() === searchKeyLower) {
1233
+ results.push(obj[key]);
1234
+ }
1235
+ }
1236
+ if (Array.isArray(obj)) {
1237
+ for (const item of obj) {
1238
+ if (item.valueName && item.valueName.toLowerCase() === searchKeyLower && item.value !== void 0) {
1239
+ results.push(item.value);
1240
+ }
1241
+ const nestedResults = findValueByKey(item, searchKey);
1242
+ results.push(...nestedResults);
1243
+ }
1244
+ }
1245
+ for (const key in obj) {
1246
+ if (obj.hasOwnProperty(key)) {
1247
+ const nestedResults = findValueByKey(obj[key], searchKey);
1248
+ results.push(...nestedResults);
1249
+ }
1250
+ }
1251
+ return results;
1252
+ };
1253
+ for (const key of valuesToExtract) {
1254
+ const values = findValueByKey(parsed.alert, key);
1255
+ const uniqueValues = [...new Set(values)];
1256
+ extracted[key] = uniqueValues.length === 0 ? null : uniqueValues.length === 1 ? uniqueValues[0] : uniqueValues;
1257
+ }
1258
+ return extracted;
1259
+ }
1260
+ };
1261
+ var text_default = TextParser;
1262
+
1263
+ // src/parsers/ugc.ts
1264
+ var UGCParser = class {
1265
+ /**
1266
+ * ugcExtractor extracts and parses UGC codes from a given message string.
1267
+ *
1268
+ * @public
1269
+ * @static
1270
+ * @async
1271
+ * @param {string} message
1272
+ * @returns {unknown}
1273
+ */
1274
+ static ugcExtractor(message) {
1275
+ return __async(this, null, function* () {
1276
+ const header = this.getHeader(message);
1277
+ const zones = this.getZones(header);
1278
+ const expiry = this.getExpiry(message);
1279
+ const locations = yield this.getLocations(zones);
1280
+ const ugc = zones.length > 0 ? { zones, locations, expiry } : null;
1281
+ return ugc;
1282
+ });
1283
+ }
1284
+ /**
1285
+ * getHeader extracts the UGC header from a UGC message string.
1286
+ *
1287
+ * @public
1288
+ * @static
1289
+ * @param {string} message
1290
+ * @returns {*}
1291
+ */
1292
+ static getHeader(message) {
1293
+ const start = message.search(new RegExp(definitions.expressions.ugc1, "gimu"));
1294
+ const end = message.substring(start).search(new RegExp(definitions.expressions.ugc2, "gimu"));
1295
+ const full = message.substring(start, start + end).replace(/\s+/g, "").slice(0, -1);
1296
+ return full;
1297
+ }
1298
+ /**
1299
+ * getExpiry extracts the expiry date and time from a UGC message and returns it as a Date object.
1300
+ *
1301
+ * @public
1302
+ * @static
1303
+ * @param {string} message
1304
+ * @returns {*}
1305
+ */
1306
+ static getExpiry(message) {
1307
+ const start = message.match(new RegExp(definitions.expressions.ugc3, "gimu"));
1308
+ if (start != null) {
1309
+ const day = parseInt(start[0].substring(0, 2), 10);
1310
+ const hour = parseInt(start[0].substring(2, 4), 10);
1311
+ const minute = parseInt(start[0].substring(4, 6), 10);
1312
+ const now = /* @__PURE__ */ new Date();
1313
+ const expires = new Date(now.getUTCFullYear(), now.getUTCMonth(), day, hour, minute, 0);
1314
+ return expires;
1315
+ }
1316
+ return null;
1317
+ }
1318
+ /**
1319
+ * getLocations retrieves unique location names for the provided UGC zone codes from the database.
1320
+ *
1321
+ * @public
1322
+ * @static
1323
+ * @async
1324
+ * @param {String[]} zones
1325
+ * @returns {unknown}
1326
+ */
1327
+ static getLocations(zones) {
1328
+ return __async(this, null, function* () {
1329
+ const locations = [];
1330
+ for (let i = 0; i < zones.length; i++) {
1331
+ const id = zones[i].trim();
1332
+ const located = yield cache.db.prepare(`SELECT location FROM shapefiles WHERE id = ?`).get(id);
1333
+ located != void 0 ? locations.push(located.location) : locations.push(id);
1334
+ }
1335
+ return Array.from(new Set(locations)).sort();
1336
+ });
1337
+ }
1338
+ /**
1339
+ * getCoordinates retrieves geographical coordinates for the provided UGC zone codes from the database.
1340
+ *
1341
+ * @public
1342
+ * @static
1343
+ * @param {String[]} zones
1344
+ * @returns {{}}
1345
+ */
1346
+ static getCoordinates(zones) {
1347
+ let coordinates = [];
1348
+ for (let i = 0; i < zones.length; i++) {
1349
+ const id = zones[i].trim();
1350
+ let located = cache.db.prepare(`SELECT geometry FROM shapefiles WHERE id = ?`).get(id);
1351
+ if (located != void 0) {
1352
+ let geometry = JSON.parse(located.geometry);
1353
+ if ((geometry == null ? void 0 : geometry.type) === "Polygon") {
1354
+ coordinates.push(...geometry.coordinates[0].map((coord) => [coord[0], coord[1]]));
1355
+ break;
1356
+ }
1357
+ }
1358
+ }
1359
+ return coordinates;
1360
+ }
1361
+ /**
1362
+ * getZones parses a UGC header string and returns an array of individual UGC zone codes.
1363
+ *
1364
+ * @public
1365
+ * @static
1366
+ * @param {string} header
1367
+ * @returns {*}
1368
+ */
1369
+ static getZones(header) {
1370
+ const ugcSplit = header.split("-");
1371
+ const zones = [];
1372
+ let state = ugcSplit[0].substring(0, 2);
1373
+ let format = ugcSplit[0].substring(2, 3);
1374
+ for (let i = 0; i < ugcSplit.length; i++) {
1375
+ if (/^[A-Z]/.test(ugcSplit[i])) {
1376
+ state = ugcSplit[i].substring(0, 2);
1377
+ if (ugcSplit[i].includes(">")) {
1378
+ let [start, end] = ugcSplit[i].split(">"), startNum = parseInt(start.substring(3), 10), endNum = parseInt(end, 10);
1379
+ for (let j = startNum; j <= endNum; j++) zones.push(`${state}${format}${j.toString().padStart(3, "0")}`);
1380
+ } else zones.push(ugcSplit[i]);
1381
+ continue;
1382
+ }
1383
+ if (ugcSplit[i].includes(">")) {
1384
+ let [start, end] = ugcSplit[i].split(">"), startNum = parseInt(start, 10), endNum = parseInt(end, 10);
1385
+ for (let j = startNum; j <= endNum; j++) zones.push(`${state}${format}${j.toString().padStart(3, "0")}`);
1386
+ } else zones.push(`${state}${format}${ugcSplit[i]}`);
1387
+ }
1388
+ return zones.filter((item) => item !== "");
1389
+ }
1390
+ };
1391
+ var ugc_default = UGCParser;
1392
+
1393
+ // src/parsers/vtec.ts
1394
+ var VtecParser = class {
1395
+ /**
1396
+ * vtecExtractor extracts and parses VTEC codes from a given message string.
1397
+ *
1398
+ * @public
1399
+ * @static
1400
+ * @async
1401
+ * @param {string} message
1402
+ * @returns {unknown}
1403
+ */
1404
+ static vtecExtractor(message) {
1405
+ return __async(this, null, function* () {
1406
+ const vtecs = [];
1407
+ const matches = message.match(new RegExp(definitions.expressions.vtec, "g"));
1408
+ if (!matches) return null;
1409
+ for (let i = 0; i < matches.length; i++) {
1410
+ const vtec = matches[i];
1411
+ const parts = vtec.split(`.`);
1412
+ const dates = parts[6].split(`-`);
1413
+ vtecs.push({
1414
+ raw: vtec,
1415
+ type: definitions.productTypes[parts[0]],
1416
+ tracking: `${parts[2]}-${parts[3]}-${parts[4]}-${parts[5]}`,
1417
+ event: `${definitions.events[parts[3]]} ${definitions.actions[parts[4]]}`,
1418
+ status: definitions.status[parts[1]],
1419
+ wmo: message.match(new RegExp(definitions.expressions.wmo, "gimu")),
1420
+ expires: this.parseExpiryDate(dates)
1421
+ });
1422
+ }
1423
+ return vtecs;
1424
+ });
1425
+ }
1426
+ /**
1427
+ * parseExpiryDate converts VTEC expiry date format to a standard ISO 8601 format with timezone adjustment.
1428
+ *
1429
+ * @private
1430
+ * @static
1431
+ * @param {String[]} args
1432
+ * @returns {string}
1433
+ */
1434
+ static parseExpiryDate(args) {
1435
+ if (args[1] == `000000T0000Z`) return `Invalid Date Format`;
1436
+ 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`;
1437
+ const local = new Date(new Date(expires).getTime() - 4 * 60 * 6e4);
1438
+ const pad = (n) => n.toString().padStart(2, "0");
1439
+ return `${local.getFullYear()}-${pad(local.getMonth() + 1)}-${pad(local.getDate())}T${pad(local.getHours())}:${pad(local.getMinutes())}:00.000-04:00`;
1440
+ }
1441
+ };
1442
+ var vtec_default = VtecParser;
1443
+
1444
+ // src/parsers/types/vtec.ts
1445
+ var VTECAlerts = class {
1446
+ /**
1447
+ * event processes validated VTEC alert messages, extracting relevant information and compiling it into structured event objects.
1448
+ *
1449
+ * @public
1450
+ * @static
1451
+ * @async
1452
+ * @param {types.TypeCompiled} validated
1453
+ * @returns {*}
1454
+ */
1455
+ static event(validated) {
1456
+ return __async(this, null, function* () {
1457
+ var _a;
1458
+ let processed = [];
1459
+ const messages = (_a = validated.message.split(/(?=\$\$)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1460
+ if (!messages || messages.length == 0) return;
1461
+ for (let i = 0; i < messages.length; i++) {
1462
+ const tick = performance.now();
1463
+ const message = messages[i];
1464
+ const getVTEC = yield vtec_default.vtecExtractor(message);
1465
+ const getUGC = yield ugc_default.ugcExtractor(message);
1466
+ if (getVTEC != null && getUGC != null) {
1467
+ for (let j = 0; j < getVTEC.length; j++) {
1468
+ const vtec = getVTEC[j];
1469
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated, getUGC, vtec);
1470
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties, vtec);
1471
+ processed.push({
1472
+ preformance: performance.now() - tick,
1473
+ tracking: vtec.tracking,
1474
+ header: getHeader,
1475
+ vtec: vtec.raw,
1476
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: vtec.status }],
1477
+ properties: __spreadValues({ event: vtec.event, parent: vtec.event, action_type: vtec.status }, getBaseProperties)
1478
+ });
1479
+ }
1480
+ }
1481
+ }
1482
+ events_default.validateEvents(processed);
1483
+ });
1484
+ }
1485
+ };
1486
+ var vtec_default2 = VTECAlerts;
1487
+
1488
+ // src/parsers/types/ugc.ts
1489
+ var UGCAlerts = class {
1490
+ /**
1491
+ * getTracking generates a unique tracking identifier based on the sender's ICAO code and a hash of the UGC zones.
1492
+ *
1493
+ * @private
1494
+ * @static
1495
+ * @param {types.BaseProperties} baseProperties
1496
+ * @param {string[]} zones
1497
+ * @returns {string}
1498
+ */
1499
+ static getTracking(baseProperties, zones) {
1500
+ return `${baseProperties.sender_icao} (${packages.crypto.createHash("md5").update(zones.join(``)).digest("hex")}})`;
1501
+ }
1502
+ /**
1503
+ * getEvent determines the event name based on offshore definitions or formats it from the attributes.
1504
+ *
1505
+ * @private
1506
+ * @static
1507
+ * @param {string} message
1508
+ * @param {Record<string, any>} attributes
1509
+ * @returns {*}
1510
+ */
1511
+ static getEvent(message, attributes) {
1512
+ const offshoreEvent = Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1513
+ if (offshoreEvent != void 0) return Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1514
+ return attributes.type.split(`-`).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(` `);
1515
+ }
1516
+ /**
1517
+ * event processes validated UGC alert messages, extracting relevant information and compiling it into structured event objects.
1518
+ *
1519
+ * @public
1520
+ * @static
1521
+ * @async
1522
+ * @param {types.TypeCompiled} validated
1523
+ * @returns {*}
1524
+ */
1525
+ static event(validated) {
1526
+ return __async(this, null, function* () {
1527
+ var _a;
1528
+ let processed = [];
1529
+ const messages = (_a = validated.message.split(/(?=\$\$|ISSUED TIME...|=================================================)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1530
+ if (!messages || messages.length == 0) return;
1531
+ for (let i = 0; i < messages.length; i++) {
1532
+ const tick = performance.now();
1533
+ const message = messages[i];
1534
+ const getUGC = yield ugc_default.ugcExtractor(message);
1535
+ if (getUGC != null) {
1536
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated, getUGC);
1537
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties);
1538
+ const getEvent = this.getEvent(message, getBaseProperties.attributes.getAwip);
1539
+ processed.push({
1540
+ preformance: performance.now() - tick,
1541
+ tracking: this.getTracking(getBaseProperties, getUGC.zones),
1542
+ header: getHeader,
1543
+ vtec: `N/A`,
1544
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: `Issued` }],
1545
+ properties: __spreadValues({ event: getEvent, parent: getEvent, action_type: `Issued` }, getBaseProperties)
1546
+ });
1547
+ }
1548
+ }
1549
+ events_default.validateEvents(processed);
1550
+ });
1551
+ }
1552
+ };
1553
+ var ugc_default2 = UGCAlerts;
1554
+
1555
+ // src/parsers/types/text.ts
1556
+ var UGCAlerts2 = class {
1557
+ static getTracking(baseProperties) {
1558
+ return `${baseProperties.sender_icao}`;
1559
+ }
1560
+ static getEvent(message, attributes) {
1561
+ const offshoreEvent = Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1562
+ if (offshoreEvent) return Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1563
+ return attributes.type.split(`-`).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(` `);
1564
+ }
1565
+ static event(validated) {
1566
+ return __async(this, null, function* () {
1567
+ var _a;
1568
+ let processed = [];
1569
+ const messages = (_a = validated.message.split(/(?=\$\$|ISSUED TIME...|=================================================)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1570
+ if (!messages || messages.length == 0) return;
1571
+ for (let i = 0; i < messages.length; i++) {
1572
+ const tick = performance.now();
1573
+ const message = messages[i];
1574
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated);
1575
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties);
1576
+ const getEvent = this.getEvent(message, getBaseProperties.attributes.getAwip);
1577
+ processed.push({
1578
+ preformance: performance.now() - tick,
1579
+ tracking: this.getTracking(getBaseProperties),
1580
+ header: getHeader,
1581
+ vtec: `N/A`,
1582
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: `Issued` }],
1583
+ properties: __spreadValues({ event: getEvent, parent: getEvent, action_type: `Issued` }, getBaseProperties)
1584
+ });
1585
+ }
1586
+ events_default.validateEvents(processed);
1587
+ });
1588
+ }
1589
+ };
1590
+ var text_default2 = UGCAlerts2;
1591
+
1592
+ // src/parsers/types/cap.ts
1593
+ var CapAlerts = class {
1594
+ static getTracking(extracted) {
1595
+ return extracted.vtec ? (() => {
1596
+ const vtecValue = Array.isArray(extracted.vtec) ? extracted.vtec[0] : extracted.vtec;
1597
+ const splitVTEC = vtecValue.split(".");
1598
+ return `${splitVTEC[2]}-${splitVTEC[3]}-${splitVTEC[4]}-${splitVTEC[5]}`;
1599
+ })() : `${extracted.wmoidentifier} (${extracted.ugc})`;
1600
+ }
1601
+ static event(validated) {
1602
+ return __async(this, null, function* () {
1603
+ var _a;
1604
+ let processed = [];
1605
+ const messages = (_a = validated.message.match(/<\?xml[\s\S]*?<\/alert>/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1606
+ if (messages == null || messages.length === 0) return;
1607
+ for (let message of messages) {
1608
+ const tick = performance.now();
1609
+ message = message.substring(message.indexOf(`<?xml version="1.0"`), message.lastIndexOf(`>`) + 1);
1610
+ const parser = new packages.xml2js.Parser({ explicitArray: false, mergeAttrs: true, trim: true });
1611
+ const parsed = yield parser.parseStringPromise(message);
1612
+ if (parsed == null || parsed.alert == null) continue;
1613
+ const extracted = text_default.getXmlValues(parsed, [
1614
+ `vtec`,
1615
+ `wmoidentifier`,
1616
+ `ugc`,
1617
+ `areadesc`,
1618
+ `expires`,
1619
+ `sent`,
1620
+ `msgtype`,
1621
+ `description`,
1622
+ `event`,
1623
+ `sendername`,
1624
+ `tornadodetection`,
1625
+ `polygon`,
1626
+ `maxHailSize`,
1627
+ `maxWindGust`,
1628
+ `thunderstormdamagethreat`,
1629
+ `tornadodamagethreat`,
1630
+ `waterspoutdetection`,
1631
+ `flooddetection`
1632
+ ]);
1633
+ const getHeader = events_default.getHeader(__spreadValues({}, validated.attributes));
1634
+ const getSource = text_default.textProductToString(extracted.description, `SOURCE...`, [`.`]) || `N/A`;
1635
+ processed.push({
1636
+ preformance: performance.now() - tick,
1637
+ tracking: this.getTracking(extracted),
1638
+ header: getHeader,
1639
+ vtec: extracted.vtec || `N/A`,
1640
+ history: [{ description: extracted.description || `N/A`, issued: extracted.sent ? new Date(extracted.sent).toLocaleString() : `N/A`, type: extracted.msgtype || `N/A` }],
1641
+ properties: {
1642
+ locations: extracted.areadesc || `N/A`,
1643
+ event: extracted.event || `N/A`,
1644
+ issued: extracted.sent ? new Date(extracted.sent).toLocaleString() : `N/A`,
1645
+ expires: extracted.expires ? new Date(extracted.expires).toLocaleString() : `N/A`,
1646
+ parent: extracted.event || `N/A`,
1647
+ action_type: extracted.msgtype || `N/A`,
1648
+ description: extracted.description || `N/A`,
1649
+ sender_name: extracted.sendername || `N/A`,
1650
+ sender_icao: extracted.wmoidentifier ? extracted.wmoidentifier.substring(extracted.wmoidentifier.length - 4) : `N/A`,
1651
+ attributes: validated.attributes,
1652
+ geocode: {
1653
+ UGC: [extracted.ugc]
1654
+ },
1655
+ parameters: {
1656
+ wmo: extracted.wmoidentifier || `N/A`,
1657
+ source: getSource,
1658
+ max_hail_size: extracted.maxHailSize || `N/A`,
1659
+ max_wind_gust: extracted.maxWindGust || `N/A`,
1660
+ damage_threat: extracted.thunderstormdamagethreat || `N/A`,
1661
+ tornado_detection: extracted.tornadodetection || extracted.waterspoutdetection || `N/A`,
1662
+ flood_detection: extracted.flooddetection || `N/A`,
1663
+ discussion_tornado_intensity: `N/A`,
1664
+ discussion_wind_intensity: `N/A`,
1665
+ discussion_hail_intensity: `N/A`
1666
+ },
1667
+ geometry: extracted.polygon ? { type: `Polygon`, coordinates: extracted.polygon.split(` `).map((coord) => coord.split(`,`).map((num) => parseFloat(num))) } : null
1668
+ }
1669
+ });
1670
+ }
1671
+ events_default.validateEvents(processed);
1672
+ });
1673
+ }
1674
+ };
1675
+ var cap_default = CapAlerts;
1676
+
1677
+ // src/parsers/types/api.ts
1678
+ var APIAlerts = class {
1679
+ static getTracking(extracted) {
1680
+ return extracted.vtec ? (() => {
1681
+ const vtecValue = Array.isArray(extracted.vtec) ? extracted.vtec[0] : extracted.vtec;
1682
+ const splitVTEC = vtecValue.split(".");
1683
+ return `${splitVTEC[2]}-${splitVTEC[3]}-${splitVTEC[4]}-${splitVTEC[5]}`;
1684
+ })() : `${extracted.wmoidentifier} (${extracted.ugc})`;
1685
+ }
1686
+ static getICAO(vtec) {
1687
+ var _a, _b;
1688
+ const icao = vtec ? vtec.split(`.`)[2] : `N/A`;
1689
+ const name = (_b = (_a = definitions.ICAO) == null ? void 0 : _a[icao]) != null ? _b : `N/A`;
1690
+ return { icao, name };
1691
+ }
1692
+ static event(validated) {
1693
+ return __async(this, null, function* () {
1694
+ 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;
1695
+ let processed = [];
1696
+ const messages = Object.values(JSON.parse(validated.message).features);
1697
+ for (let feature of messages) {
1698
+ const tick = performance.now();
1699
+ 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;
1700
+ 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;
1701
+ const getUgc = (_j = (_i = (_h = feature == null ? void 0 : feature.properties) == null ? void 0 : _h.geocode) == null ? void 0 : _i.UGC) != null ? _j : null;
1702
+ 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 : "";
1703
+ const getDescription = `${getHeadline} ${(_p = (_o = feature == null ? void 0 : feature.properties) == null ? void 0 : _o.description) != null ? _p : ``}`;
1704
+ 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;
1705
+ const getHeader = events_default.getHeader(__spreadValues({}, { getAwip: { prefix: getAWIP == null ? void 0 : getAWIP.slice(0, -3) } }));
1706
+ const getSource = text_default.textProductToString(getDescription, `SOURCE...`, [`.`]) || `N/A`;
1707
+ const getOffice = this.getICAO(getVTEC || ``);
1708
+ processed.push({
1709
+ preformance: performance.now() - tick,
1710
+ tracking: this.getTracking({ vtec: getVTEC, wmoidentifier: getWmo, ugc: getUgc ? getUgc.join(`,`) : null }),
1711
+ header: getHeader,
1712
+ vtec: getVTEC || `N/A`,
1713
+ history: [{
1714
+ description: (_v = (_u = feature == null ? void 0 : feature.properties) == null ? void 0 : _u.description) != null ? _v : `N/A`,
1715
+ action: (_x = (_w = feature == null ? void 0 : feature.properties) == null ? void 0 : _w.messageType) != null ? _x : `N/A`,
1716
+ 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`
1717
+ }],
1718
+ properties: {
1719
+ locations: (_B = (_A = feature == null ? void 0 : feature.properties) == null ? void 0 : _A.areaDesc) != null ? _B : `N/A`,
1720
+ event: (_D = (_C = feature == null ? void 0 : feature.properties) == null ? void 0 : _C.event) != null ? _D : `N/A`,
1721
+ 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`,
1722
+ 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`,
1723
+ parent: (_J = (_I = feature == null ? void 0 : feature.properties) == null ? void 0 : _I.event) != null ? _J : `N/A`,
1724
+ action_type: (_L = (_K = feature == null ? void 0 : feature.properties) == null ? void 0 : _K.messageType) != null ? _L : `N/A`,
1725
+ description: (_N = (_M = feature == null ? void 0 : feature.properties) == null ? void 0 : _M.description) != null ? _N : `N/A`,
1726
+ sender_name: getOffice.name || `N/A`,
1727
+ sender_icao: getOffice.icao || `N/A`,
1728
+ attributes: validated.attributes,
1729
+ geocode: {
1730
+ UGC: (_Q = (_P = (_O = feature == null ? void 0 : feature.properties) == null ? void 0 : _O.geocode) == null ? void 0 : _P.UGC) != null ? _Q : [`XX000`]
1731
+ },
1732
+ parameters: {
1733
+ 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`,
1734
+ source: getSource,
1735
+ max_hail_size: ((_V = (_U = feature == null ? void 0 : feature.properties) == null ? void 0 : _U.parameters) == null ? void 0 : _V.maxHailSize) || `N/A`,
1736
+ max_wind_gust: ((_X = (_W = feature == null ? void 0 : feature.properties) == null ? void 0 : _W.parameters) == null ? void 0 : _X.maxWindGust) || `N/A`,
1737
+ damage_threat: ((_Z = (_Y = feature == null ? void 0 : feature.properties) == null ? void 0 : _Y.parameters) == null ? void 0 : _Z.thunderstormDamageThreat) || [`N/A`],
1738
+ tornado_detection: ((_$ = (__ = feature == null ? void 0 : feature.properties) == null ? void 0 : __.parameters) == null ? void 0 : _$.tornadoDetection) || [`N/A`],
1739
+ flood_detection: ((_ba = (_aa = feature == null ? void 0 : feature.properties) == null ? void 0 : _aa.parameters) == null ? void 0 : _ba.floodDetection) || [`N/A`],
1740
+ discussion_tornado_intensity: "N/A",
1741
+ peakWindGust: `N/A`,
1742
+ peakHailSize: `N/A`
1743
+ },
1744
+ geometry: (_ca = feature == null ? void 0 : feature.geometry) != null ? _ca : null
1745
+ }
1746
+ });
1747
+ }
1748
+ events_default.validateEvents(processed);
1749
+ });
1750
+ }
1751
+ };
1752
+ var api_default = APIAlerts;
1753
+
1754
+ // src/eas.ts
1755
+ var EAS = class {
1756
+ /**
1757
+ * generateEASAudio creates an EAS-compliant audio file in WAV format containing the provided message and VTEC header.
1758
+ *
1759
+ * @public
1760
+ * @static
1761
+ * @param {string} message
1762
+ * @param {string} vtec
1763
+ * @returns {*}
1764
+ */
1765
+ static generateEASAudio(message, vtec) {
1766
+ return new Promise((resolve) => __async(this, null, function* () {
1767
+ const settings2 = settings;
1768
+ for (const { regex, replacement } of definitions.messageSignatures) {
1769
+ message = message.replace(regex, replacement);
1770
+ }
1771
+ const assetsDir = settings2.global.easSettings.easDirectory;
1772
+ if (!assetsDir) {
1773
+ console.warn(definitions.messages.eas_no_directory);
1774
+ return resolve(null);
1775
+ }
1776
+ const rngFile = `${vtec.replace(/[^a-zA-Z0-9]/g, `_`)}`.substring(0, 32).replace(/^_+|_+$/g, "");
1777
+ if (!packages.fs.existsSync(assetsDir)) {
1778
+ packages.fs.mkdirSync(assetsDir);
1779
+ }
1780
+ const tmpTTS = packages.path.join(assetsDir, `/tmp/${rngFile}.wav`);
1781
+ const outTTS = packages.path.join(assetsDir, `/output/${rngFile}.wav`);
1782
+ const voice = process.platform === "win32" ? "Microsoft David Desktop" : "en-US-GuyNeural";
1783
+ if (!packages.fs.existsSync(packages.path.join(assetsDir, `/tmp`))) {
1784
+ packages.fs.mkdirSync(packages.path.join(assetsDir, `/tmp`), { recursive: true });
1785
+ }
1786
+ if (!packages.fs.existsSync(packages.path.join(assetsDir, `/output`))) {
1787
+ packages.fs.mkdirSync(packages.path.join(assetsDir, `/output`), { recursive: true });
1788
+ }
1789
+ packages.say.export(message, voice, 1, tmpTTS);
1790
+ yield utils_default.sleep(2500);
1791
+ let ttsBuffer = null;
1792
+ while (!packages.fs.existsSync(tmpTTS) || (ttsBuffer = packages.fs.readFileSync(tmpTTS)).length === 0) {
1793
+ yield utils_default.sleep(500);
1794
+ }
1795
+ const ttsWav = this.parseWavPCM16(ttsBuffer);
1796
+ const ttsSamples = this.resamplePCM16(ttsWav.samples, ttsWav.sampleRate, 8e3);
1797
+ const ttsRadio = this.applyNWREffect(ttsSamples, 8e3);
1798
+ let toneRadio = null;
1799
+ if (packages.fs.existsSync(settings2.global.easSettings.easIntroWav)) {
1800
+ const toneBuffer = packages.fs.readFileSync(settings2.global.easSettings.easIntroWav);
1801
+ const toneWav = this.parseWavPCM16(toneBuffer);
1802
+ const toneSamples = toneWav.sampleRate !== 8e3 ? this.resamplePCM16(toneWav.samples, toneWav.sampleRate, 8e3) : toneWav.samples;
1803
+ toneRadio = this.applyNWREffect(toneSamples, 8e3);
1804
+ }
1805
+ let build = toneRadio != null ? [toneRadio, this.generateSilence(0.5, 8e3)] : [];
1806
+ 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);
1807
+ for (let i = 0; i < 3; i++) {
1808
+ build.push(this.generateSAMEHeader(vtec, 1, 8e3, { preMarkSec: 0.5, gapSec: 0.1 }));
1809
+ build.push(this.generateSilence(0.5, 8e3));
1810
+ }
1811
+ const allSamples = this.concatPCM16(build);
1812
+ const finalSamples = this.addNoise(allSamples, 2e-3);
1813
+ const outBuffer = this.encodeWavPCM16(Array.from(finalSamples).map((v) => ({ value: v })), 8e3);
1814
+ packages.fs.writeFileSync(outTTS, outBuffer);
1815
+ try {
1816
+ packages.fs.unlinkSync(tmpTTS);
1817
+ } catch (error) {
1818
+ if (error.code !== "EBUSY") {
1819
+ throw error;
1820
+ }
1821
+ }
1822
+ return Promise.resolve(outTTS);
1823
+ }));
1824
+ }
1825
+ /**
1826
+ * encodeWavPCM16 encodes an array of samples into a WAV PCM 16-bit Buffer.
1827
+ *
1828
+ * @private
1829
+ * @static
1830
+ * @param {Record<string, number>[]} samples
1831
+ * @param {number} [sampleRate=8000]
1832
+ * @returns {Buffer}
1833
+ */
1834
+ static encodeWavPCM16(samples, sampleRate = 8e3) {
1835
+ const bytesPerSample = 2;
1836
+ const blockAlign = 1 * bytesPerSample;
1837
+ const byteRate = sampleRate * blockAlign;
1838
+ const subchunk2Size = samples.length * bytesPerSample;
1839
+ const chunkSize = 36 + subchunk2Size;
1840
+ const buffer = Buffer.alloc(44 + subchunk2Size);
1841
+ let o = 0;
1842
+ buffer.write("RIFF", o);
1843
+ o += 4;
1844
+ buffer.writeUInt32LE(chunkSize, o);
1845
+ o += 4;
1846
+ buffer.write("WAVE", o);
1847
+ o += 4;
1848
+ buffer.write("fmt ", o);
1849
+ o += 4;
1850
+ buffer.writeUInt32LE(16, o);
1851
+ o += 4;
1852
+ buffer.writeUInt16LE(1, o);
1853
+ o += 2;
1854
+ buffer.writeUInt16LE(1, o);
1855
+ o += 2;
1856
+ buffer.writeUInt32LE(sampleRate, o);
1857
+ o += 4;
1858
+ buffer.writeUInt32LE(byteRate, o);
1859
+ o += 4;
1860
+ buffer.writeUInt16LE(blockAlign, o);
1861
+ o += 2;
1862
+ buffer.writeUInt16LE(16, o);
1863
+ o += 2;
1864
+ buffer.write("data", o);
1865
+ o += 4;
1866
+ buffer.writeUInt32LE(subchunk2Size, o);
1867
+ o += 4;
1868
+ for (let i = 0; i < samples.length; i++, o += 2) {
1869
+ buffer.writeInt16LE(samples[i].value, o);
1870
+ }
1871
+ return buffer;
1872
+ }
1873
+ /**
1874
+ * parseWavPCM16 decodes a WAV PCM 16-bit Buffer into its sample data and format information.
1875
+ *
1876
+ * @private
1877
+ * @static
1878
+ * @param {Buffer} buffer
1879
+ * @returns {{ samples: any; sampleRate: any; channels: any; bitsPerSample: any; }}
1880
+ */
1881
+ static parseWavPCM16(buffer) {
1882
+ if (buffer.toString("ascii", 0, 4) !== "RIFF" || buffer.toString("ascii", 8, 12) !== "WAVE") {
1883
+ return null;
1884
+ }
1885
+ let fmt = null;
1886
+ let data = null;
1887
+ let i = 12;
1888
+ while (i + 8 <= buffer.length) {
1889
+ const id = buffer.toString("ascii", i, i + 4);
1890
+ const size = buffer.readUInt32LE(i + 4);
1891
+ const start = i + 8;
1892
+ const end = start + size;
1893
+ if (id === "fmt ") fmt = buffer.slice(start, end);
1894
+ if (id === "data") data = buffer.slice(start, end);
1895
+ i = end + size % 2;
1896
+ }
1897
+ if (!fmt || !data) return null;
1898
+ const audioFormat = fmt.readUInt16LE(0);
1899
+ const channels = fmt.readUInt16LE(2);
1900
+ const sampleRate = fmt.readUInt32LE(4);
1901
+ const bitsPerSample = fmt.readUInt16LE(14);
1902
+ if (audioFormat !== 1 || bitsPerSample !== 16 || channels !== 1) {
1903
+ return null;
1904
+ }
1905
+ const samples = new Int16Array(data.buffer, data.byteOffset, data.length / 2);
1906
+ return { samples: new Int16Array(samples), sampleRate, channels, bitsPerSample };
1907
+ }
1908
+ /**
1909
+ * concatPCM16 concatenates multiple Int16Array buffers into a single Int16Array buffer.
1910
+ *
1911
+ * @private
1912
+ * @static
1913
+ * @param {Int16Array[]} arrays
1914
+ * @returns {*}
1915
+ */
1916
+ static concatPCM16(arrays) {
1917
+ let total = 0;
1918
+ for (const a of arrays) total += a.length;
1919
+ const out = new Int16Array(total);
1920
+ let o = 0;
1921
+ for (const a of arrays) {
1922
+ out.set(a, o);
1923
+ o += a.length;
1924
+ }
1925
+ return out;
1926
+ }
1927
+ /**
1928
+ * pcm16toFloat converts an Int16Array of PCM 16-bit samples to a Float32Array of normalized float samples.
1929
+ *
1930
+ * @private
1931
+ * @static
1932
+ * @param {Int16Array} int16
1933
+ * @returns {*}
1934
+ */
1935
+ static pcm16toFloat(int16) {
1936
+ const out = new Float32Array(int16.length);
1937
+ for (let i = 0; i < int16.length; i++) out[i] = int16[i] / 32768;
1938
+ return out;
1939
+ }
1940
+ /**
1941
+ * floatToPcm16 converts a Float32Array of normalized float samples to an Int16Array of PCM 16-bit samples.
1942
+ *
1943
+ * @private
1944
+ * @static
1945
+ * @param {Float32Array} float32
1946
+ * @returns {*}
1947
+ */
1948
+ static floatToPcm16(float32) {
1949
+ const out = new Int16Array(float32.length);
1950
+ for (let i = 0; i < float32.length; i++) {
1951
+ let v = Math.max(-1, Math.min(1, float32[i]));
1952
+ out[i] = Math.round(v * 32767);
1953
+ }
1954
+ return out;
1955
+ }
1956
+ /**
1957
+ * resamplePCM16 resamples an Int16Array of PCM 16-bit samples from the original sample rate to the target sample rate using linear interpolation.
1958
+ *
1959
+ * @private
1960
+ * @static
1961
+ * @param {Int16Array} int16
1962
+ * @param {number} originalRate
1963
+ * @param {number} targetRate
1964
+ * @returns {*}
1965
+ */
1966
+ static resamplePCM16(int16, originalRate, targetRate) {
1967
+ if (originalRate === targetRate) return int16;
1968
+ const ratio = targetRate / originalRate;
1969
+ const outLen = Math.max(1, Math.round(int16.length * ratio));
1970
+ const out = new Int16Array(outLen);
1971
+ for (let i = 0; i < outLen; i++) {
1972
+ const pos = i / ratio;
1973
+ const i0 = Math.floor(pos);
1974
+ const i1 = Math.min(i0 + 1, int16.length - 1);
1975
+ const frac = pos - i0;
1976
+ const v = int16[i0] * (1 - frac) + int16[i1] * frac;
1977
+ out[i] = Math.round(v);
1978
+ }
1979
+ return out;
1980
+ }
1981
+ /**
1982
+ * generateSilence creates an Int16Array of PCM 16-bit samples representing silence for the specified duration in milliseconds.
1983
+ *
1984
+ * @private
1985
+ * @static
1986
+ * @param {number} ms
1987
+ * @param {number} [sampleRate=8000]
1988
+ * @returns {*}
1989
+ */
1990
+ static generateSilence(ms, sampleRate = 8e3) {
1991
+ return new Int16Array(Math.floor(ms * sampleRate));
1992
+ }
1993
+ /**
1994
+ * generateAttentionTone creates an Int16Array of PCM 16-bit samples representing the EAS attention tone for the specified duration in milliseconds.
1995
+ *
1996
+ * @private
1997
+ * @static
1998
+ * @param {*} ms
1999
+ * @param {number} [sampleRate=8000]
2000
+ * @returns {*}
2001
+ */
2002
+ static generateAttentionTone(ms, sampleRate = 8e3) {
2003
+ const len = Math.floor(ms * sampleRate);
2004
+ const out = new Int16Array(len);
2005
+ const f1 = 853;
2006
+ const f2 = 960;
2007
+ const twoPi = Math.PI * 2;
2008
+ const amp = 0.1;
2009
+ const fadeLen = Math.floor(sampleRate * 0);
2010
+ for (let i = 0; i < len; i++) {
2011
+ const t = i / sampleRate;
2012
+ const s = Math.sin(twoPi * f1 * t) + Math.sin(twoPi * f2 * t);
2013
+ let gain = 1;
2014
+ if (i < fadeLen) gain = i / fadeLen;
2015
+ else if (i > len - fadeLen) gain = (len - i) / fadeLen;
2016
+ const v = Math.max(-1, Math.min(1, s / 2 * amp * gain));
2017
+ out[i] = Math.round(v * 32767);
2018
+ }
2019
+ return out;
2020
+ }
2021
+ /**
2022
+ * applyNWREffect applies a series of audio processing effects to simulate the sound characteristics of NOAA Weather Radio broadcasts.
2023
+ *
2024
+ * @private
2025
+ * @static
2026
+ * @param {Int16Array} int16
2027
+ * @param {number} [sampleRate=8000]
2028
+ * @returns {*}
2029
+ */
2030
+ static applyNWREffect(int16, sampleRate = 8e3) {
2031
+ const hpCut = 3555;
2032
+ const lpCut = 1600;
2033
+ const noiseLevel = 0;
2034
+ const crushBits = 8;
2035
+ const x = this.pcm16toFloat(int16);
2036
+ const dt = 1 / sampleRate;
2037
+ const rcHP = 1 / (2 * Math.PI * hpCut);
2038
+ const aHP = rcHP / (rcHP + dt);
2039
+ let yHP = 0, xPrev = 0;
2040
+ for (let i = 0; i < x.length; i++) {
2041
+ const xi = x[i];
2042
+ yHP = aHP * (yHP + xi - xPrev);
2043
+ xPrev = xi;
2044
+ x[i] = yHP;
2045
+ }
2046
+ const rcLP = 1 / (2 * Math.PI * lpCut);
2047
+ const aLP = dt / (rcLP + dt);
2048
+ let yLP = 0;
2049
+ for (let i = 0; i < x.length; i++) {
2050
+ yLP = yLP + aLP * (x[i] - yLP);
2051
+ x[i] = yLP;
2052
+ }
2053
+ const compGain = 2;
2054
+ const norm = Math.tanh(compGain);
2055
+ for (let i = 0; i < x.length; i++) x[i] = Math.tanh(x[i] * compGain) / norm;
2056
+ const levels = Math.pow(2, crushBits) - 1;
2057
+ return this.floatToPcm16(x);
2058
+ }
2059
+ /**
2060
+ * addNoise adds low-level white noise to an Int16Array of PCM 16-bit samples to simulate analog broadcast imperfections.
2061
+ *
2062
+ * @private
2063
+ * @static
2064
+ * @param {Int16Array} int16
2065
+ * @param {number} [noiseLevel=0.02]
2066
+ * @returns {*}
2067
+ */
2068
+ static addNoise(int16, noiseLevel = 0.02) {
2069
+ const x = this.pcm16toFloat(int16);
2070
+ for (let i = 0; i < x.length; i++) x[i] += (Math.random() * 2 - 1) * noiseLevel;
2071
+ let peak = 0;
2072
+ for (let i = 0; i < x.length; i++) peak = Math.max(peak, Math.abs(x[i]));
2073
+ if (peak > 1) for (let i = 0; i < x.length; i++) x[i] *= 0.98 / peak;
2074
+ return this.floatToPcm16(x);
2075
+ }
2076
+ /**
2077
+ * asciiTo8N1Bits converts an ASCII string to a sequence of bits using 8-N-1 encoding (8 data bits, no parity, 1 stop bit).
2078
+ *
2079
+ * @private
2080
+ * @static
2081
+ * @param {string} str
2082
+ * @returns {{}}
2083
+ */
2084
+ static asciiTo8N1Bits(str) {
2085
+ const bits = [];
2086
+ for (let i = 0; i < str.length; i++) {
2087
+ const c = str.charCodeAt(i) & 255;
2088
+ bits.push(0);
2089
+ for (let b = 0; b < 8; b++) bits.push(c >> b & 1);
2090
+ bits.push(1, 1);
2091
+ }
2092
+ return bits;
2093
+ }
2094
+ /**
2095
+ * generateAFSK generates an Int16Array of PCM 16-bit samples representing AFSK modulation of the provided bit sequence.
2096
+ *
2097
+ * @private
2098
+ * @static
2099
+ * @param {number[]} bits
2100
+ * @param {number} [sampleRate=8000]
2101
+ * @returns {*}
2102
+ */
2103
+ static generateAFSK(bits, sampleRate = 8e3) {
2104
+ const baud = 520.83;
2105
+ const markFreq = 2083.3;
2106
+ const spaceFreq = 1562.5;
2107
+ const amplitude = 0.6;
2108
+ const twoPi = Math.PI * 2;
2109
+ const result = [];
2110
+ let phase = 0;
2111
+ let frac = 0;
2112
+ for (let b = 0; b < bits.length; b++) {
2113
+ const bit = bits[b];
2114
+ const freq = bit ? markFreq : spaceFreq;
2115
+ const samplesPerBit = sampleRate / baud + frac;
2116
+ const n = Math.round(samplesPerBit);
2117
+ frac = samplesPerBit - n;
2118
+ const inc = twoPi * freq / sampleRate;
2119
+ for (let i = 0; i < n; i++) {
2120
+ result.push(Math.round(Math.sin(phase) * amplitude * 32767));
2121
+ phase += inc;
2122
+ if (phase > twoPi) phase -= twoPi;
2123
+ }
2124
+ }
2125
+ const fadeSamples = Math.floor(sampleRate * 2e-3);
2126
+ for (let i = 0; i < fadeSamples; i++) {
2127
+ const gain = i / fadeSamples;
2128
+ result[i] = Math.round(result[i] * gain);
2129
+ result[result.length - 1 - i] = Math.round(result[result.length - 1 - i] * gain);
2130
+ }
2131
+ return Int16Array.from(result);
2132
+ }
2133
+ /**
2134
+ * generateSAMEHeader generates an Int16Array of PCM 16-bit samples representing the SAME header repeated the specified number of times.
2135
+ *
2136
+ * @private
2137
+ * @static
2138
+ * @param {string} vtec
2139
+ * @param {number} repeats
2140
+ * @param {number} [sampleRate=8000]
2141
+ * @param {{preMarkSec?: number, gapSec?: number}} [options={}]
2142
+ * @returns {*}
2143
+ */
2144
+ static generateSAMEHeader(vtec, repeats, sampleRate = 8e3, options = {}) {
2145
+ var _a, _b;
2146
+ const preMarkSec = (_a = options.preMarkSec) != null ? _a : 0.3;
2147
+ const gapSec = (_b = options.gapSec) != null ? _b : 0.1;
2148
+ const bursts = [];
2149
+ const gap = this.generateSilence(gapSec, sampleRate);
2150
+ for (let i = 0; i < repeats; i++) {
2151
+ const bodyBits = this.asciiTo8N1Bits(vtec);
2152
+ const body = this.generateAFSK(bodyBits, sampleRate);
2153
+ const extendedBodyDuration = Math.round(preMarkSec * sampleRate);
2154
+ const extendedBody = new Int16Array(extendedBodyDuration + gap.length);
2155
+ for (let j = 0; j < extendedBodyDuration; j++) {
2156
+ extendedBody[j] = Math.round(body[j % body.length] * 0.2);
2157
+ }
2158
+ extendedBody.set(gap, extendedBodyDuration);
2159
+ bursts.push(extendedBody);
2160
+ if (i !== repeats - 1) bursts.push(gap);
2161
+ }
2162
+ return this.concatPCM16(bursts);
2163
+ }
2164
+ };
2165
+ var eas_default = EAS;
2166
+
2167
+ // src/parsers/events.ts
2168
+ var EventParser = class {
2169
+ /**
2170
+ * getBaseProperties extracts and compiles the base properties of an alert message, including location, timing, description, sender information, and various parameters.
2171
+ *
2172
+ * @public
2173
+ * @static
2174
+ * @async
2175
+ * @param {string} message
2176
+ * @param {types.TypeCompiled} validated
2177
+ * @param {types.UGCParsed} [ugc=null]
2178
+ * @param {types.VTECParsed} [vtec=null]
2179
+ * @returns {Promise<types.BaseProperties>}
2180
+ */
2181
+ static getBaseProperties(message, validated, ugc = null, vtec = null) {
2182
+ return __async(this, null, function* () {
2183
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2184
+ const settings2 = settings;
2185
+ const definitions2 = {
2186
+ tornado: text_default.textProductToString(message, `TORNADO...`) || text_default.textProductToString(message, `WATERSPOUT...`) || `N/A`,
2187
+ hail: text_default.textProductToString(message, `MAX HAIL SIZE...`, [`IN`]) || text_default.textProductToString(message, `HAIL...`, [`IN`]) || `N/A`,
2188
+ gusts: text_default.textProductToString(message, `MAX WIND GUST...`) || text_default.textProductToString(message, `WIND...`) || `N/A`,
2189
+ flood: text_default.textProductToString(message, `FLASH FLOOD...`) || `N/A`,
2190
+ damage: text_default.textProductToString(message, `DAMAGE THREAT...`) || `N/A`,
2191
+ source: text_default.textProductToString(message, `SOURCE...`, [`.`]) || `N/A`,
2192
+ attributes: text_default.textProductToString(message, `STANZA ATTRIBUTES...`) ? JSON.parse(text_default.textProductToString(message, `STANZA ATTRIBUTES...`)) : null,
2193
+ polygon: text_default.textProductToPolygon(message),
2194
+ description: text_default.textProductToDescription(message, (_a = vtec == null ? void 0 : vtec.raw) != null ? _a : null),
2195
+ wmo: message.match(new RegExp(definitions.expressions.wmo, "imu")),
2196
+ mdTorIntensity: text_default.textProductToString(message, `MOST PROBABLE PEAK TORNADO INTENSITY...`) || `N/A`,
2197
+ mdWindGusts: text_default.textProductToString(message, `MOST PROBABLE PEAK WIND GUST...`) || `N/A`,
2198
+ mdHailSize: text_default.textProductToString(message, `MOST PROBABLE PEAK HAIL SIZE...`) || `N/A`
2199
+ };
2200
+ const getOffice = this.getICAO(vtec, (_c = (_b = validated.attributes) != null ? _b : definitions2.attributes) != null ? _c : {}, definitions2.wmo);
2201
+ const getCorrectIssued = this.getCorrectIssuedDate((_e = (_d = definitions2.attributes) != null ? _d : validated.attributes) != null ? _e : {});
2202
+ const getCorrectExpiry = this.getCorrectExpiryDate(vtec, ugc);
2203
+ const getAwip = text_default.awipTextToEvent((_g = (_f = definitions2.attributes) == null ? void 0 : _f.awipsid) != null ? _g : validated.awipsType.prefix);
2204
+ const base = {
2205
+ locations: (ugc == null ? void 0 : ugc.locations.join(`; `)) || `No Location Specified (UGC Missing)`,
2206
+ issued: getCorrectIssued,
2207
+ expires: getCorrectExpiry,
2208
+ geocode: { UGC: (ugc == null ? void 0 : ugc.zones) || [`XX000`] },
2209
+ description: definitions2.description,
2210
+ sender_name: getOffice.name,
2211
+ sender_icao: getOffice.icao,
2212
+ attributes: __spreadProps(__spreadValues(__spreadValues({}, validated.attributes), definitions2.attributes), {
2213
+ getAwip
2214
+ }),
2215
+ parameters: {
2216
+ wmo: Array.isArray(definitions2.wmo) ? definitions2.wmo[0] : (_h = definitions2.wmo) != null ? _h : `N/A`,
2217
+ source: definitions2.source,
2218
+ max_hail_size: definitions2.hail,
2219
+ max_wind_gust: definitions2.gusts,
2220
+ damage_threat: definitions2.damage,
2221
+ tornado_detection: definitions2.tornado,
2222
+ flood_detection: definitions2.flood,
2223
+ discussion_tornado_intensity: definitions2.mdTorIntensity,
2224
+ discussion_wind_intensity: definitions2.mdWindGusts,
2225
+ discussion_hail_intensity: definitions2.mdHailSize
2226
+ },
2227
+ geometry: definitions2.polygon.length > 0 ? { type: "Polygon", coordinates: definitions2.polygon } : null
2228
+ };
2229
+ if (settings2.NoaaWeatherWireService.alertPreferences.isShapefileUGC && base.geometry == null && ugc != null) {
2230
+ const coordinates = yield ugc_default.getCoordinates(ugc.zones);
2231
+ base.geometry = { type: "Polygon", coordinates };
2232
+ }
2233
+ return base;
2234
+ });
2235
+ }
2236
+ /**
2237
+ * enhanceEvent refines the event name based on specific conditions and tags found in the event's description and parameters.
2238
+ *
2239
+ * @public
2240
+ * @static
2241
+ * @param {types.TypeAlert} event
2242
+ * @returns {{ eventName: any; tags: any; }}
2243
+ */
2244
+ static enhanceEvent(event) {
2245
+ var _a, _b, _c, _d, _e;
2246
+ let eventName = (_b = (_a = event == null ? void 0 : event.properties) == null ? void 0 : _a.event) != null ? _b : `Unknown Event`;
2247
+ const defEventTable = definitions.enhancedEvents;
2248
+ const defEventTags = definitions.tags;
2249
+ const properties = event == null ? void 0 : event.properties;
2250
+ const parameters = properties == null ? void 0 : properties.parameters;
2251
+ const description = (_c = properties == null ? void 0 : properties.description) != null ? _c : `Unknown Description`;
2252
+ const damageThreatTag = (_d = parameters == null ? void 0 : parameters.damage_threat) != null ? _d : `N/A`;
2253
+ const tornadoThreatTag = (_e = parameters == null ? void 0 : parameters.tornado_detection) != null ? _e : `N/A`;
2254
+ for (const eventGroup of defEventTable) {
2255
+ const [baseEvent, conditions] = Object.entries(eventGroup)[0];
2256
+ if (eventName === baseEvent) {
2257
+ for (const [specificEvent, condition] of Object.entries(conditions)) {
2258
+ const conditionMet = condition.description && description.includes(condition.description.toLowerCase()) || condition.condition && condition.condition(damageThreatTag || tornadoThreatTag);
2259
+ if (conditionMet) {
2260
+ eventName = specificEvent;
2261
+ break;
2262
+ }
2263
+ }
2264
+ if (baseEvent === "Severe Thunderstorm Warning" && damageThreatTag === "POSSIBLE" && !eventName.includes("(TPROB)")) eventName += " (TPROB)";
2265
+ break;
2266
+ }
2267
+ }
2268
+ const tags = Object.entries(defEventTags).filter(([key]) => description.includes(key.toLowerCase())).map(([, value]) => value);
2269
+ return { eventName, tags: tags.length > 0 ? tags : [`N/A`] };
2270
+ }
2271
+ /**
2272
+ * getCorrectExpiryDate determines the correct expiration date for an alert based on VTEC information or UGC zones.
2273
+ *
2274
+ * @public
2275
+ * @static
2276
+ * @param {unknown[]} events
2277
+ */
2278
+ static validateEvents(events2) {
2279
+ var _a, _b, _c, _d, _e;
2280
+ if (events2.length == 0) return;
2281
+ const settings2 = settings;
2282
+ const filteringSettings = (_b = (_a = settings) == null ? void 0 : _a.global) == null ? void 0 : _b.alertFiltering;
2283
+ const easSettings = (_d = (_c = settings) == null ? void 0 : _c.global) == null ? void 0 : _d.easSettings;
2284
+ const globalSettings = (_e = settings) == null ? void 0 : _e.global;
2285
+ const sets = {};
2286
+ const bools = {};
2287
+ const megered = __spreadValues(__spreadValues(__spreadValues({}, filteringSettings), easSettings), globalSettings);
2288
+ for (const key in megered) {
2289
+ const setting = megered[key];
2290
+ if (Array.isArray(setting)) {
2291
+ sets[key] = new Set(setting.map((item) => item.toLowerCase()));
2292
+ }
2293
+ if (typeof setting === "boolean") {
2294
+ bools[key] = setting;
2295
+ }
2296
+ }
2297
+ const filtered = events2.filter((alert) => {
2298
+ var _a2, _b2, _c2, _d2;
2299
+ const originalEvent = alert;
2300
+ const props = originalEvent == null ? void 0 : originalEvent.properties;
2301
+ const ugcs = (_b2 = (_a2 = props == null ? void 0 : props.geocode) == null ? void 0 : _a2.UGC) != null ? _b2 : [];
2302
+ if (bools == null ? void 0 : bools.betterEventParsing) {
2303
+ const { eventName, tags } = this.enhanceEvent(originalEvent);
2304
+ originalEvent.properties.event = eventName;
2305
+ originalEvent.properties.tags = tags;
2306
+ }
2307
+ const eventCheck = (bools == null ? void 0 : bools.useParentEvents) ? (_c2 = props.parent) == null ? void 0 : _c2.toLowerCase() : (_d2 = props.event) == null ? void 0 : _d2.toLowerCase();
2308
+ const statusCorrelation = definitions.correlations.find((c) => c.type === originalEvent.properties.action_type);
2309
+ for (const key in sets) {
2310
+ const setting = sets[key];
2311
+ if (key === "filteredEvents" && setting.size > 0 && eventCheck != null && !setting.has(eventCheck)) return false;
2312
+ if (key === "ignoredEvents" && setting.size > 0 && eventCheck != null && setting.has(eventCheck)) return false;
2313
+ if (key === "filteredICOAs" && setting.size > 0 && props.sender_icao != null && !setting.has(props.sender_icao.toLowerCase())) return false;
2314
+ if (key === "ignoredICOAs" && setting.size > 0 && props.sender_icao != null && setting.has(props.sender_icao.toLowerCase())) return false;
2315
+ if (key === "ugcFilter" && setting.size > 0 && ugcs.length > 0 && !ugcs.some((ugc) => setting.has(ugc.toLowerCase()))) return false;
2316
+ if (key === "stateFilter" && setting.size > 0 && ugcs.length > 0 && !ugcs.some((ugc) => setting.has(ugc.substring(0, 2).toLowerCase()))) return false;
2317
+ if (key === "easAlerts" && setting.size > 0 && eventCheck != null && setting.has(eventCheck) && settings2.isNWWS) {
2318
+ eas_default.generateEASAudio(props.description, alert.header);
2319
+ }
2320
+ }
2321
+ for (const key in bools) {
2322
+ const setting = bools[key];
2323
+ if (key === "checkExpired" && setting && new Date(props == null ? void 0 : props.expires).getTime() < (/* @__PURE__ */ new Date()).getTime()) return false;
2324
+ }
2325
+ originalEvent.properties.action_type = statusCorrelation ? statusCorrelation.forward : originalEvent.properties.action_type;
2326
+ originalEvent.properties.is_cancelled = statusCorrelation ? statusCorrelation.cancel == true && bools.checkExpired : false;
2327
+ if (props.description) {
2328
+ const detectedPhrase = definitions.cancelSignatures.find((sig) => props.description.toLowerCase().includes(sig.toLowerCase()));
2329
+ if (detectedPhrase && bools.checkExpired) {
2330
+ originalEvent.properties.action_type = "Cancel";
2331
+ originalEvent.properties.is_cancelled = true;
2332
+ return false;
2333
+ }
2334
+ }
2335
+ if (originalEvent.vtec) {
2336
+ const getType = originalEvent.vtec.split(`.`)[0];
2337
+ const isTestProduct = definitions.productTypes[getType] == `Test Product`;
2338
+ if (isTestProduct) {
2339
+ return false;
2340
+ }
2341
+ }
2342
+ cache.events.emit(`on${originalEvent.properties.parent.replace(/\s+/g, "")}`);
2343
+ return true;
2344
+ });
2345
+ if (filtered.length > 0) {
2346
+ cache.events.emit(`onAlerts`, filtered);
2347
+ }
2348
+ }
2349
+ /**
2350
+ * getHeader constructs a standardized alert header string based on provided attributes, properties, and VTEC information.
2351
+ *
2352
+ * @public
2353
+ * @static
2354
+ * @param {types.TypeAttributes} attributes
2355
+ * @param {?types.BaseProperties} [properties]
2356
+ * @param {?types.VTECParsed} [vtec]
2357
+ * @returns {string}
2358
+ */
2359
+ static getHeader(attributes, properties, vtec) {
2360
+ var _a, _b, _c, _d, _e, _f, _g;
2361
+ const parent = `ATSX`;
2362
+ 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`;
2363
+ 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`;
2364
+ const status = (vtec == null ? void 0 : vtec.status) || "Issued";
2365
+ 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];
2366
+ const sender = (properties == null ? void 0 : properties.sender_icao) || `XXXX`;
2367
+ const header = `ZCZC-${parent}-${alertType}-${ugc}-${status}-${issued}-${sender}-`;
2368
+ return header;
2369
+ }
2370
+ /**
2371
+ * eventHandler routes the validated alert message to the appropriate event parser based on its type (API, CAP, VTEC, UGC, or plain text).
2372
+ *
2373
+ * @public
2374
+ * @static
2375
+ * @param {types.TypeCompiled} validated
2376
+ * @returns {*}
2377
+ */
2378
+ static eventHandler(validated) {
2379
+ if (validated.isApi) return api_default.event(validated);
2380
+ if (validated.isCap) return cap_default.event(validated);
2381
+ if (!validated.isCap && validated.isVtec && validated.isUGC) return vtec_default2.event(validated);
2382
+ if (!validated.isCap && !validated.isVtec && validated.isUGC) return ugc_default2.event(validated);
2383
+ if (!validated.isCap && !validated.isVtec && !validated.isUGC) return text_default2.event(validated);
2384
+ }
2385
+ /**
2386
+ * getICAO retrieves the ICAO code and corresponding office name based on VTEC tracking information, message attributes, or WMO code.
2387
+ *
2388
+ * @private
2389
+ * @static
2390
+ * @param {types.VTECParsed} vtec
2391
+ * @param {Record<string, string>} attributes
2392
+ * @param {(RegExpMatchArray | string | null)} WMO
2393
+ * @returns {{ icao: any; name: any; }}
2394
+ */
2395
+ static getICAO(vtec, attributes, WMO) {
2396
+ var _a, _b, _c;
2397
+ 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`;
2398
+ const name = (_c = (_b = definitions.ICAO) == null ? void 0 : _b[icao]) != null ? _c : `N/A`;
2399
+ return { icao, name };
2400
+ }
2401
+ /**
2402
+ * getCorrectIssuedDate ensures the issued date is valid and falls back to the current date if not.
2403
+ *
2404
+ * @private
2405
+ * @static
2406
+ * @param {Record<string, string>} attributes
2407
+ * @returns {*}
2408
+ */
2409
+ static getCorrectIssuedDate(attributes) {
2410
+ 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();
2411
+ if (time == `Invalid Date`) return (/* @__PURE__ */ new Date()).toLocaleString();
2412
+ return time;
2413
+ }
2414
+ /**
2415
+ * getCorrectExpiryDate determines the correct expiration date for an alert based on VTEC information or UGC zones.
2416
+ *
2417
+ * @private
2418
+ * @static
2419
+ * @param {types.VTECParsed} vtec
2420
+ * @param {types.UGCParsed} ugc
2421
+ * @returns {*}
2422
+ */
2423
+ static getCorrectExpiryDate(vtec, ugc) {
2424
+ 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();
2425
+ if (time == `Invalid Date`) return new Date((/* @__PURE__ */ new Date()).getTime() + 1 * 60 * 60 * 1e3).toLocaleString();
2426
+ return time;
2427
+ }
2428
+ };
2429
+ var events_default = EventParser;
2430
+
2431
+ // src/utils.ts
2432
+ var Utils = class {
2433
+ /**
2434
+ * Zzzzzzz... yeah not much to explain here. Simple sleep function that returns a promise after the specified milliseconds.
2435
+ *
2436
+ * @public
2437
+ * @static
2438
+ * @async
2439
+ * @param {number} ms
2440
+ * @returns {Promise<void>}
2441
+ */
2442
+ static sleep(ms) {
2443
+ return __async(this, null, function* () {
2444
+ return new Promise((resolve) => setTimeout(resolve, ms));
2445
+ });
2446
+ }
2447
+ /**
2448
+ * loadCollectionCache reads cached alert files from the specified cache directory and processes them.
2449
+ *
2450
+ * @public
2451
+ * @static
2452
+ * @async
2453
+ * @returns {Promise<void>}
2454
+ */
2455
+ static loadCollectionCache() {
2456
+ return __async(this, null, function* () {
2457
+ try {
2458
+ const settings2 = settings;
2459
+ if (settings2.NoaaWeatherWireService.cache.read && settings2.NoaaWeatherWireService.cache.directory) {
2460
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) return;
2461
+ const cacheDir = settings2.NoaaWeatherWireService.cache.directory;
2462
+ const getAllFiles = packages.fs.readdirSync(cacheDir).filter((file) => file.endsWith(".bin") && file.startsWith("cache-"));
2463
+ for (const file of getAllFiles) {
2464
+ const start = Date.now();
2465
+ const filepath = packages.path.join(cacheDir, file);
2466
+ const readFile = packages.fs.readFileSync(filepath, { encoding: "utf-8" });
2467
+ const isCap = readFile.includes(`<?xml`);
2468
+ if (isCap && !settings2.NoaaWeatherWireService.alertPreferences.isCapOnly) continue;
2469
+ if (!isCap && settings2.NoaaWeatherWireService.alertPreferences.isCapOnly) continue;
2470
+ const validate = stanza_default.validate(readFile, { awipsid: file, isCap, raw: true, issue: void 0 });
2471
+ yield events_default.eventHandler(validate);
2472
+ }
2473
+ }
2474
+ } catch (error) {
2475
+ cache.events.emit("onError", { code: "error-load-cache", message: `Failed to load cache: ${error.message}` });
2476
+ }
2477
+ });
2478
+ }
2479
+ /**
2480
+ * loadGeoJsonData fetches GeoJSON data from the National Weather Service endpoint and processes each alert.
2481
+ *
2482
+ * @public
2483
+ * @static
2484
+ * @async
2485
+ * @returns {Promise<void>}
2486
+ */
2487
+ static loadGeoJsonData() {
2488
+ return __async(this, null, function* () {
2489
+ try {
2490
+ const settings2 = settings;
2491
+ const response = yield this.createHttpRequest(settings2.NationalWeatherService.endpoint);
2492
+ if (!response.error) {
2493
+ 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 });
2494
+ }
2495
+ } catch (error) {
2496
+ cache.events.emit("onError", { code: "error-fetching-nws-data", message: `Failed to fetch NWS data: ${error.message}` });
2497
+ }
2498
+ });
2499
+ }
2500
+ /**
2501
+ * detectUncaughtExceptions sets up a global handler for uncaught exceptions in the Node.js process,
2502
+ *
2503
+ * @public
2504
+ * @static
2505
+ */
2506
+ static detectUncaughtExceptions() {
2507
+ if (process.listeners("uncaughtException").some((l) => l.name === "uncaughtExceptionHandler")) return;
2508
+ process.on(`uncaughtException`, (error) => {
2509
+ cache.events.emit(`onError`, { message: `Uncaught Exception: ${error.message}`, code: `error-uncaught-exception`, stack: error.stack });
2510
+ });
2511
+ }
2512
+ /**
2513
+ * createHttpRequest performs an HTTP GET request to the specified URL with optional settings.
2514
+ *
2515
+ * @public
2516
+ * @static
2517
+ * @async
2518
+ * @param {string} url
2519
+ * @param {?types.HTTPSettings} [options]
2520
+ * @returns {unknown}
2521
+ */
2522
+ static createHttpRequest(url, options) {
2523
+ return __async(this, null, function* () {
2524
+ var _a, _b;
2525
+ const defaultOptions = {
2526
+ timeout: 1e4,
2527
+ headers: {
2528
+ "User-Agent": "AtmosphericX",
2529
+ "Accept": "application/geo+json, text/plain, */*; q=0.9",
2530
+ "Accept-Language": "en-US,en;q=0.9"
2531
+ }
2532
+ };
2533
+ const requestOptions = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), options), {
2534
+ headers: __spreadValues(__spreadValues({}, defaultOptions.headers), (_a = options == null ? void 0 : options.headers) != null ? _a : {})
2535
+ });
2536
+ try {
2537
+ const resp = yield packages.axios.get(url, {
2538
+ headers: requestOptions.headers,
2539
+ timeout: requestOptions.timeout,
2540
+ maxRedirects: 0,
2541
+ validateStatus: (status) => status === 200 || status === 500
2542
+ });
2543
+ return { error: false, message: resp.data };
2544
+ } catch (err) {
2545
+ return { error: true, message: (_b = err == null ? void 0 : err.message) != null ? _b : String(err) };
2546
+ }
2547
+ });
2548
+ }
2549
+ /**
2550
+ * garbageCollectionCache removes files from the cache directory that exceed the specified maximum file size in megabytes.
2551
+ *
2552
+ * @public
2553
+ * @static
2554
+ * @param {number} maxFileMegabytes
2555
+ */
2556
+ static garbageCollectionCache(maxFileMegabytes) {
2557
+ try {
2558
+ const settings2 = settings;
2559
+ if (!settings2.NoaaWeatherWireService.cache.directory) return;
2560
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) return;
2561
+ const maxBytes = maxFileMegabytes * 1024 * 1024;
2562
+ const cacheDirectory = settings2.NoaaWeatherWireService.cache.directory;
2563
+ const stackFiles = [cacheDirectory], files = [];
2564
+ while (stackFiles.length) {
2565
+ const currentDirectory = stackFiles.pop();
2566
+ packages.fs.readdirSync(currentDirectory).forEach((file) => {
2567
+ const fullPath = packages.path.join(currentDirectory, file);
2568
+ const stat = packages.fs.statSync(fullPath);
2569
+ if (stat.isDirectory()) stackFiles.push(fullPath);
2570
+ else files.push({ file: fullPath, size: stat.size });
2571
+ });
2572
+ }
2573
+ if (!files.length) return;
2574
+ files.forEach((f) => {
2575
+ if (f.size > maxBytes) packages.fs.unlinkSync(f.file);
2576
+ });
2577
+ } catch (error) {
2578
+ cache.events.emit("onError", { code: "error-garbage-collection", message: `Failed to perform garbage collection: ${error.message}` });
2579
+ }
2580
+ }
2581
+ /**
2582
+ * handleCronJob performs periodic tasks based on whether the client is connected to NWWS or fetching data from NWS.
2583
+ *
2584
+ * @public
2585
+ * @static
2586
+ * @param {boolean} isNwws
2587
+ */
2588
+ static handleCronJob(isNwws) {
2589
+ try {
2590
+ const settings2 = settings;
2591
+ if (isNwws) {
2592
+ if (settings2.NoaaWeatherWireService.cache.read) void this.garbageCollectionCache(settings2.NoaaWeatherWireService.cache.maxSizeMB);
2593
+ if (settings2.NoaaWeatherWireService.clientReconnections.canReconnect) void xmpp_default.isSessionReconnectionEligible(settings2.NoaaWeatherWireService.clientReconnections.currentInterval);
2594
+ } else {
2595
+ void this.loadGeoJsonData();
2596
+ }
2597
+ } catch (error) {
2598
+ cache.events.emit("onError", { code: "error-cron-job", message: `Failed to perform scheduled tasks: ${error.message}` });
2599
+ }
2600
+ }
2601
+ /**
2602
+ * mergeClientSettings merges user-provided settings into the existing client settings, allowing for nested objects to be merged correctly.
2603
+ *
2604
+ * @public
2605
+ * @static
2606
+ * @param {Record<string, any>} target
2607
+ * @param {Record<string, any>} settings
2608
+ */
2609
+ static mergeClientSettings(target, settings2) {
2610
+ for (const key in settings2) {
2611
+ if (settings2.hasOwnProperty(key)) {
2612
+ if (typeof settings2[key] === "object" && settings2[key] !== null && !Array.isArray(settings2[key])) {
2613
+ if (!target[key] || typeof target[key] !== "object") {
2614
+ target[key] = {};
2615
+ }
2616
+ this.mergeClientSettings(target[key], settings2[key]);
2617
+ } else {
2618
+ target[key] = settings2[key];
2619
+ }
2620
+ }
2621
+ }
2622
+ }
2623
+ };
2624
+ var utils_default = Utils;
2625
+
2626
+ // src/database.ts
2627
+ var Database = class {
2628
+ /**
2629
+ * handleAlertCache stores a unique alert in the SQLite database and ensures the total number of alerts does not exceed 5000.
2630
+ *
2631
+ * @public
2632
+ * @static
2633
+ * @async
2634
+ * @param {*} alert
2635
+ * @returns {*}
2636
+ */
2637
+ static stanzaCacheImport(stanza) {
2638
+ return __async(this, null, function* () {
2639
+ const settings2 = settings;
2640
+ cache.db.prepare(`INSERT OR IGNORE INTO stanzas (stanza) VALUES (?)`).run(stanza);
2641
+ const count = cache.db.prepare(`SELECT COUNT(*) as total FROM stanzas`).get();
2642
+ if (count.total > settings2.NoaaWeatherWireService.cache.maxHistory) {
2643
+ 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);
2644
+ }
2645
+ });
2646
+ }
2647
+ /**
2648
+ * loadDatabase initializes the SQLite database and imports shapefile data if the database or table does not exist.
2649
+ *
2650
+ * @public
2651
+ * @static
2652
+ * @async
2653
+ * @returns {Promise<void>}
2654
+ */
2655
+ static loadDatabase() {
2656
+ return __async(this, null, function* () {
2657
+ const settings2 = settings;
2658
+ try {
2659
+ if (!packages.fs.existsSync(settings2.database)) {
2660
+ packages.fs.writeFileSync(settings2.database, "");
2661
+ }
2662
+ cache.db = new packages.sqlite3(settings2.database);
2663
+ const shapfileTable = cache.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='shapefiles'`).get();
2664
+ const stanzaTable = cache.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='stanzas'`).get();
2665
+ if (!stanzaTable) {
2666
+ cache.db.prepare(`CREATE TABLE stanzas (id INTEGER PRIMARY KEY AUTOINCREMENT, stanza TEXT)`).run();
2667
+ }
2668
+ if (!shapfileTable) {
2669
+ cache.db.prepare(`CREATE TABLE shapefiles (id TEXT PRIMARY KEY, location TEXT, geometry TEXT)`).run();
2670
+ console.log(definitions.messages.shapefile_creation);
2671
+ for (const shape of definitions.shapefiles) {
2672
+ const { id, file } = shape;
2673
+ const filepath = packages.path.join(__dirname, `../../shapefiles`, file);
2674
+ const { features } = yield packages.shapefile.read(filepath, filepath);
2675
+ console.log(`Importing ${features.length} entries from ${file}...`);
2676
+ const insertStmt = cache.db.prepare(`INSERT OR REPLACE INTO shapefiles (id, location, geometry)VALUES (?, ?, ?)`);
2677
+ const insertTransaction = cache.db.transaction((entries) => {
2678
+ for (const feature of entries) {
2679
+ const { properties, geometry } = feature;
2680
+ let final, location;
2681
+ switch (true) {
2682
+ case !!properties.FIPS:
2683
+ final = `${properties.STATE}${id}${properties.FIPS.substring(2)}`;
2684
+ location = `${properties.COUNTYNAME}, ${properties.STATE}`;
2685
+ break;
2686
+ case !!properties.FULLSTAID:
2687
+ final = `${properties.ST}${id}${properties.WFO}`;
2688
+ location = `${properties.CITY}, ${properties.STATE}`;
2689
+ break;
2690
+ case !!properties.STATE:
2691
+ final = `${properties.STATE}${id}${properties.ZONE}`;
2692
+ location = `${properties.NAME}, ${properties.STATE}`;
2693
+ break;
2694
+ default:
2695
+ final = properties.ID;
2696
+ location = properties.NAME;
2697
+ break;
2698
+ }
2699
+ insertStmt.run(final, location, JSON.stringify(geometry));
2700
+ }
2701
+ });
2702
+ yield insertTransaction(features);
2703
+ }
2704
+ console.log(definitions.messages.shapefile_creation_finished);
2705
+ }
2706
+ } catch (error) {
2707
+ cache.events.emit("onError", { code: "error-load-database", message: `Failed to load database: ${error.message}` });
2708
+ }
2709
+ });
2710
+ }
2711
+ };
2712
+ var database_default = Database;
2713
+
2714
+ // src/xmpp.ts
2715
+ var Xmpp = class {
2716
+ /**
2717
+ * isSessionReconnectionEligible checks if the XMPP session is eligible for reconnection based on the last
2718
+ * received stanza time and current interval.
2719
+ *
2720
+ * @public
2721
+ * @static
2722
+ * @async
2723
+ * @param {number} currentInterval
2724
+ * @returns {Promise<void>}
2725
+ */
2726
+ static isSessionReconnectionEligible(currentInterval) {
2727
+ return __async(this, null, function* () {
2728
+ const settings2 = settings;
2729
+ if ((cache.isConnected || cache.sigHalt) && cache.session) {
2730
+ const lastStanza = Date.now() - cache.lastStanza;
2731
+ if (lastStanza >= currentInterval * 1e3) {
2732
+ if (!cache.attemptingReconnect) {
2733
+ cache.attemptingReconnect = true;
2734
+ cache.isConnected = false;
2735
+ cache.totalReconnects += 1;
2736
+ cache.events.emit(`onReconnect`, { reconnects: cache.totalReconnects, lastStanza, lastName: settings2.NoaaWeatherWireService.clientCredentials.nickname });
2737
+ yield cache.session.stop().catch(() => {
2738
+ });
2739
+ yield cache.session.start().catch(() => {
2740
+ });
2741
+ }
2742
+ }
2743
+ }
2744
+ });
2745
+ }
2746
+ /**
2747
+ * deploySession initializes and starts the XMPP client session, setting up event listeners for
2748
+ * connection management and message handling. This function is specifically tailored for
2749
+ * NoaaWeatherWireService and connects to their XMPP server.
2750
+ *
2751
+ * @public
2752
+ * @static
2753
+ * @async
2754
+ * @returns {Promise<void>}
2755
+ */
2756
+ static deploySession() {
2757
+ return __async(this, null, function* () {
2758
+ var _a, _b;
2759
+ const settings2 = settings;
2760
+ cache.session = packages.xmpp.client({
2761
+ service: `xmpp://nwws-oi.weather.gov`,
2762
+ domain: `nwws-oi.weather.gov`,
2763
+ username: settings2.NoaaWeatherWireService.clientCredentials.username,
2764
+ password: settings2.NoaaWeatherWireService.clientCredentials.password
2765
+ });
2766
+ (_b = (_a = settings2.NoaaWeatherWireService.clientCredentials).nickname) != null ? _b : _a.nickname = settings2.NoaaWeatherWireService.clientCredentials.username;
2767
+ cache.session.on(`online`, (address) => __async(null, null, function* () {
2768
+ if (cache.lastConnect && Date.now() - cache.lastConnect < 10 * 1e3) {
2769
+ cache.sigHalt = true;
2770
+ utils_default.sleep(2 * 1e3).then(() => __async(null, null, function* () {
2771
+ yield cache.session.stop();
2772
+ }));
2773
+ 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.` });
2774
+ return;
2775
+ }
2776
+ cache.isConnected = true;
2777
+ cache.sigHalt = false;
2778
+ cache.lastConnect = Date.now();
2779
+ cache.session.send(packages.xmpp.xml("presence", { to: `nwws@conference.nwws-oi.weather.gov/${settings2.NoaaWeatherWireService.clientCredentials.nickname}`, xmlns: "http://jabber.org/protocol/muc" }));
2780
+ cache.session.send(packages.xmpp.xml("presence", { to: `nwws@conference.nwws-oi.weather.gov`, type: "available" }));
2781
+ cache.events.emit(`onConnection`, settings2.NoaaWeatherWireService.clientCredentials.nickname);
2782
+ if (cache.attemptingReconnect) {
2783
+ utils_default.sleep(15 * 1e3).then(() => {
2784
+ cache.attemptingReconnect = false;
2785
+ });
2786
+ }
2787
+ }));
2788
+ cache.session.on(`offline`, () => __async(null, null, function* () {
2789
+ cache.isConnected = false;
2790
+ cache.sigHalt = true;
2791
+ cache.events.emit(`onError`, { code: `connection-lost`, message: `XMPP connection went offline` });
2792
+ }));
2793
+ cache.session.on(`error`, (error) => __async(null, null, function* () {
2794
+ cache.isConnected = false;
2795
+ cache.sigHalt = true;
2796
+ cache.events.emit(`onError`, { code: `connection-error`, message: error.message });
2797
+ }));
2798
+ cache.session.on(`stanza`, (stanza) => __async(null, null, function* () {
2799
+ try {
2800
+ cache.lastStanza = Date.now();
2801
+ if (stanza.is(`message`)) {
2802
+ const validate = stanza_default.validate(stanza);
2803
+ if (validate.ignore || validate.isCap && !settings2.NoaaWeatherWireService.alertPreferences.isCapOnly || !validate.isCap && settings2.NoaaWeatherWireService.alertPreferences.isCapOnly || validate.isCap && !validate.isCapDescription) return;
2804
+ events_default.eventHandler(validate);
2805
+ cache.events.emit(`onMessage`, validate);
2806
+ database_default.stanzaCacheImport(JSON.stringify(validate));
2807
+ }
2808
+ if (stanza.is(`presence`) && stanza.attrs.from && stanza.attrs.from.startsWith("nwws@conference.nwws-oi.weather.gov/")) {
2809
+ const occupant = stanza.attrs.from.split("/").slice(1).join("/");
2810
+ cache.events.emit("onOccupant", { occupant, type: stanza.attrs.type === "unavailable" ? "unavailable" : "available" });
2811
+ }
2812
+ } catch (e) {
2813
+ cache.events.emit(`onError`, { code: `error-processing-stanza`, message: e.message });
2814
+ }
2815
+ }));
2816
+ yield cache.session.start();
2817
+ });
2818
+ }
2819
+ };
2820
+ var xmpp_default = Xmpp;
2821
+ export {
2822
+ Xmpp,
2823
+ xmpp_default as default
2824
+ };