atmosx-nwws-parser 1.0.185 → 1.0.201

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