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