@dataemergencia/emergency 0.2.1 → 0.3.0
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.
- package/README.md +16 -9
- package/dist/iife/emergency.iife.global.js +5 -5
- package/dist/index.cjs +44 -23
- package/dist/index.d.cts +22 -14
- package/dist/index.d.ts +22 -14
- package/dist/index.js +44 -23
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -84,13 +84,8 @@ function isFiniteNumber(value) {
|
|
|
84
84
|
function isArrayOf(value, guard) {
|
|
85
85
|
return Array.isArray(value) && value.every(guard);
|
|
86
86
|
}
|
|
87
|
-
function isRealtimeConfig(value) {
|
|
88
|
-
if (!isRecord(value) || value["mode"] !== "public" || !isRecord(value["pusher"])) return false;
|
|
89
|
-
const pusher = value["pusher"];
|
|
90
|
-
return isString(pusher["key"]) && isString(pusher["cluster"]) && isString(pusher["channel_pattern"]);
|
|
91
|
-
}
|
|
92
87
|
function isConfigResponse(value) {
|
|
93
|
-
return isRecord(value) && isString(value["route_prefix"]) && isString(value["csrf_token"])
|
|
88
|
+
return isRecord(value) && isString(value["route_prefix"]) && isString(value["csrf_token"]);
|
|
94
89
|
}
|
|
95
90
|
function isSessionResponse(value) {
|
|
96
91
|
return isRecord(value) && isString(value["code"]) && isString(value["csrf_token"]) && isFiniteNumber(value["expires_in"]);
|
|
@@ -108,7 +103,7 @@ function isEmergencyResultPayload(value) {
|
|
|
108
103
|
return (value["emergency_id"] === null || isString(value["emergency_id"])) && isBoolean(value["simulated"]) && isArrayOf(value["responders"], isResponderPayload) && isArrayOf(value["failures"], isFailurePayload);
|
|
109
104
|
}
|
|
110
105
|
function isCurrentResponse(value) {
|
|
111
|
-
if (!isRecord(value) || !isBoolean(value["active"])
|
|
106
|
+
if (!isRecord(value) || !isBoolean(value["active"])) return false;
|
|
112
107
|
return value["emergency"] === null || isRecord(value["emergency"]) && !Array.isArray(value["emergency"]);
|
|
113
108
|
}
|
|
114
109
|
function isRefreshResponse(value) {
|
|
@@ -634,8 +629,9 @@ function themeToCssVariables(theme) {
|
|
|
634
629
|
}
|
|
635
630
|
|
|
636
631
|
// src/core/realtime.ts
|
|
632
|
+
const DEFAULT_CHANNEL_PATTERN = "whatsapp.{phone}";
|
|
637
633
|
function channelForPhone(pattern, phone) {
|
|
638
|
-
return pattern.replace("{phone}", phone.replace(
|
|
634
|
+
return pattern.replace("{phone}", phone.replace(/\D/g, ""));
|
|
639
635
|
}
|
|
640
636
|
function toStatus(state) {
|
|
641
637
|
switch (state) {
|
|
@@ -650,11 +646,11 @@ function toStatus(state) {
|
|
|
650
646
|
}
|
|
651
647
|
function createPusherRealtimeProvider() {
|
|
652
648
|
return { subscribe(config, phones, handlers) {
|
|
653
|
-
if (typeof window === "undefined" || !config.
|
|
649
|
+
if (typeof window === "undefined" || !config.key || !config.cluster) return null;
|
|
654
650
|
let pusher;
|
|
655
651
|
try {
|
|
656
|
-
pusher = new pusher_js.default(config.
|
|
657
|
-
cluster: config.
|
|
652
|
+
pusher = new pusher_js.default(config.key, {
|
|
653
|
+
cluster: config.cluster,
|
|
658
654
|
forceTLS: true
|
|
659
655
|
});
|
|
660
656
|
} catch {
|
|
@@ -666,7 +662,7 @@ function createPusherRealtimeProvider() {
|
|
|
666
662
|
handlers.onStatus(toStatus(change.current));
|
|
667
663
|
});
|
|
668
664
|
const channels = [...new Set(phones.filter((phone) => phone !== ""))].map((phone) => {
|
|
669
|
-
const channelName = channelForPhone(config.
|
|
665
|
+
const channelName = channelForPhone(config.channelPattern ?? DEFAULT_CHANNEL_PATTERN, phone);
|
|
670
666
|
pusher.subscribe(channelName).bind_global((eventName, data) => {
|
|
671
667
|
handlers.onEvent(channelName, eventName, data);
|
|
672
668
|
});
|
|
@@ -795,7 +791,6 @@ function createEmergencyController(deps) {
|
|
|
795
791
|
let sessionPromise = null;
|
|
796
792
|
let refreshing = false;
|
|
797
793
|
let realtimeSubscription = null;
|
|
798
|
-
let realtimeConfig = null;
|
|
799
794
|
let subscribedPhones = [];
|
|
800
795
|
let messageSequence = 0;
|
|
801
796
|
let lastReconcileAt = 0;
|
|
@@ -853,9 +848,12 @@ function createEmergencyController(deps) {
|
|
|
853
848
|
realtimeSubscription = null;
|
|
854
849
|
subscribedPhones = [];
|
|
855
850
|
}
|
|
856
|
-
function startRealtime(
|
|
857
|
-
|
|
858
|
-
|
|
851
|
+
function startRealtime(responders) {
|
|
852
|
+
const realtime = config.realtime ?? null;
|
|
853
|
+
if (!realtime) {
|
|
854
|
+
if (responders.length > 0) patch({ realtimeStatus: "unavailable" });
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
859
857
|
const phones = [...new Set(responders.map((responder) => responder.phone))];
|
|
860
858
|
if (realtimeSubscription && phones.length === subscribedPhones.length && phones.every((phone, index) => phone === subscribedPhones[index])) return;
|
|
861
859
|
realtimeSubscription?.disconnect();
|
|
@@ -889,7 +887,7 @@ function createEmergencyController(deps) {
|
|
|
889
887
|
const phase = get().phase.kind;
|
|
890
888
|
if (phase === "idle" || phase === "error") transition({ kind: "initializing" });
|
|
891
889
|
try {
|
|
892
|
-
|
|
890
|
+
await bff.config();
|
|
893
891
|
const session = await bff.session(config.code);
|
|
894
892
|
patch({
|
|
895
893
|
sessionReady: true,
|
|
@@ -919,7 +917,6 @@ function createEmergencyController(deps) {
|
|
|
919
917
|
async function hydrateCurrent() {
|
|
920
918
|
try {
|
|
921
919
|
const current = await bff.current();
|
|
922
|
-
realtimeConfig = current.realtime;
|
|
923
920
|
if (current.active && current.emergency) {
|
|
924
921
|
const snapshot = payloadToSnapshot(current.emergency, { code: config.code });
|
|
925
922
|
patch({
|
|
@@ -935,7 +932,7 @@ function createEmergencyController(deps) {
|
|
|
935
932
|
emergencyId: snapshot.emergencyId,
|
|
936
933
|
simulated: snapshot.simulated
|
|
937
934
|
});
|
|
938
|
-
startRealtime(
|
|
935
|
+
startRealtime(snapshot.responders);
|
|
939
936
|
events.emit("emergency:resumed", { snapshot });
|
|
940
937
|
return;
|
|
941
938
|
}
|
|
@@ -1017,7 +1014,7 @@ function createEmergencyController(deps) {
|
|
|
1017
1014
|
});
|
|
1018
1015
|
pushMessage(failures.length > 0 ? "warning" : "success", failures.length > 0 ? copy.partialFailure : copy.activeBanner);
|
|
1019
1016
|
events.emit("emergency:activated", { snapshot: hydrated });
|
|
1020
|
-
startRealtime(
|
|
1017
|
+
startRealtime(responders);
|
|
1021
1018
|
} catch (error) {
|
|
1022
1019
|
const normalized = toEmergencyError(error, "network");
|
|
1023
1020
|
if (normalized.code === "emergency_already_active") {
|
|
@@ -1109,7 +1106,7 @@ function createEmergencyController(deps) {
|
|
|
1109
1106
|
emergencyId: updated.emergencyId,
|
|
1110
1107
|
simulated: updated.simulated
|
|
1111
1108
|
});
|
|
1112
|
-
startRealtime(
|
|
1109
|
+
startRealtime(responders);
|
|
1113
1110
|
events.emit("emergency:updated", { snapshot: updated });
|
|
1114
1111
|
} catch (error) {
|
|
1115
1112
|
const normalized = toEmergencyError(error, "network");
|
|
@@ -1242,7 +1239,6 @@ function createEmergencyController(deps) {
|
|
|
1242
1239
|
bff.destroy();
|
|
1243
1240
|
realtimeSubscription?.disconnect();
|
|
1244
1241
|
realtimeSubscription = null;
|
|
1245
|
-
realtimeConfig = null;
|
|
1246
1242
|
subscribedPhones = [];
|
|
1247
1243
|
patch({
|
|
1248
1244
|
destroyed: true,
|
|
@@ -1373,6 +1369,24 @@ function installEmergencyFonts(input) {
|
|
|
1373
1369
|
|
|
1374
1370
|
// src/core/config.ts
|
|
1375
1371
|
const EMERGENCY_CODE_PATTERN = /^[A-Za-z][A-Za-z0-9]{5}$/;
|
|
1372
|
+
const DEFAULT_REALTIME_CHANNEL_PATTERN = "whatsapp.{phone}";
|
|
1373
|
+
/**
|
|
1374
|
+
* Validates the host-supplied realtime block. Returns `null` when the value is
|
|
1375
|
+
* present but invalid; callers treat `undefined` as "realtime not requested".
|
|
1376
|
+
*/
|
|
1377
|
+
function normalizeRealtimeConfig(value) {
|
|
1378
|
+
if (!isRecord(value)) return null;
|
|
1379
|
+
const key = value["key"];
|
|
1380
|
+
const cluster = value["cluster"];
|
|
1381
|
+
const channelPattern = value["channelPattern"];
|
|
1382
|
+
if (typeof key !== "string" || key.trim() === "" || typeof cluster !== "string" || cluster.trim() === "") return null;
|
|
1383
|
+
if (channelPattern !== void 0 && (typeof channelPattern !== "string" || channelPattern.trim() === "" || !channelPattern.includes("{phone}"))) return null;
|
|
1384
|
+
return {
|
|
1385
|
+
key,
|
|
1386
|
+
cluster,
|
|
1387
|
+
channelPattern: channelPattern ?? "whatsapp.{phone}"
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1376
1390
|
const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
1377
1391
|
"localhost",
|
|
1378
1392
|
"127.0.0.1",
|
|
@@ -1433,6 +1447,12 @@ function validateConfig(config) {
|
|
|
1433
1447
|
config: null,
|
|
1434
1448
|
error: createEmergencyError("configuration", "The fallback requires a non-empty phone and label.")
|
|
1435
1449
|
};
|
|
1450
|
+
const realtime = config.realtime === void 0 ? void 0 : normalizeRealtimeConfig(config.realtime);
|
|
1451
|
+
if (realtime === null) return {
|
|
1452
|
+
ok: false,
|
|
1453
|
+
config: null,
|
|
1454
|
+
error: createEmergencyError("configuration", "The realtime configuration requires a non-empty key and cluster, and a channel pattern containing {phone}.")
|
|
1455
|
+
};
|
|
1436
1456
|
return {
|
|
1437
1457
|
ok: true,
|
|
1438
1458
|
error: null,
|
|
@@ -1443,7 +1463,8 @@ function validateConfig(config) {
|
|
|
1443
1463
|
locale: config.locale ?? "es",
|
|
1444
1464
|
geolocationTimeoutMs: config.geolocationTimeoutMs ?? 8e3,
|
|
1445
1465
|
requestTimeoutMs: config.requestTimeoutMs ?? 15e3,
|
|
1446
|
-
fontLoading: normalizeFontLoading(config.fontLoading)
|
|
1466
|
+
fontLoading: normalizeFontLoading(config.fontLoading),
|
|
1467
|
+
realtime
|
|
1447
1468
|
}
|
|
1448
1469
|
};
|
|
1449
1470
|
}
|
package/dist/index.d.cts
CHANGED
|
@@ -101,6 +101,17 @@ interface EmergencyGeolocation {
|
|
|
101
101
|
readonly longitude: number;
|
|
102
102
|
readonly accuracy?: number;
|
|
103
103
|
}
|
|
104
|
+
interface EmergencyRealtimeConfig {
|
|
105
|
+
/** Public Pusher app key supplied by the host. */
|
|
106
|
+
readonly key: string;
|
|
107
|
+
/** Pusher cluster that serves the app key. */
|
|
108
|
+
readonly cluster: string;
|
|
109
|
+
/**
|
|
110
|
+
* Channel name pattern. `{phone}` is replaced with the responder phone in
|
|
111
|
+
* digits-only form. Defaults to `whatsapp.{phone}`.
|
|
112
|
+
*/
|
|
113
|
+
readonly channelPattern?: string;
|
|
114
|
+
}
|
|
104
115
|
interface EmergencyConfig {
|
|
105
116
|
/** Full BFF route prefix, for example `https://example.com/de-bff/emergency`. */
|
|
106
117
|
readonly bffBaseUrl: string;
|
|
@@ -122,6 +133,11 @@ interface EmergencyConfig {
|
|
|
122
133
|
readonly geolocationTimeoutMs?: number;
|
|
123
134
|
/** Request timeout in milliseconds. Defaults to 15000. */
|
|
124
135
|
readonly requestTimeoutMs?: number;
|
|
136
|
+
/**
|
|
137
|
+
* Public Pusher values supplied by the host. When omitted, the client stays
|
|
138
|
+
* in pull mode and never opens a realtime connection.
|
|
139
|
+
*/
|
|
140
|
+
readonly realtime?: EmergencyRealtimeConfig;
|
|
125
141
|
}
|
|
126
142
|
interface EmergencySnapshot {
|
|
127
143
|
readonly emergencyId: string;
|
|
@@ -239,18 +255,8 @@ interface EmergencyMountOptions extends EmergencyConfig {
|
|
|
239
255
|
* message, and an inert client.
|
|
240
256
|
*/
|
|
241
257
|
export declare function mount(options: EmergencyMountOptions): EmergencyClient;
|
|
242
|
-
interface RealtimePusherConfig {
|
|
243
|
-
readonly key: string;
|
|
244
|
-
readonly cluster: string;
|
|
245
|
-
readonly channel_pattern: string;
|
|
246
|
-
}
|
|
247
|
-
interface RealtimePublicConfig {
|
|
248
|
-
readonly mode: 'public';
|
|
249
|
-
readonly pusher: RealtimePusherConfig;
|
|
250
|
-
}
|
|
251
258
|
interface ConfigResponse {
|
|
252
259
|
readonly route_prefix: string;
|
|
253
|
-
readonly realtime: RealtimePublicConfig;
|
|
254
260
|
readonly csrf_token: string;
|
|
255
261
|
}
|
|
256
262
|
interface SessionResponse {
|
|
@@ -292,7 +298,6 @@ type EmergencyPayload = Readonly<Record<string, unknown>>;
|
|
|
292
298
|
interface CurrentResponse {
|
|
293
299
|
readonly active: boolean;
|
|
294
300
|
readonly emergency: EmergencyPayload | null;
|
|
295
|
-
readonly realtime: RealtimePublicConfig;
|
|
296
301
|
}
|
|
297
302
|
interface GeolocationRequest {
|
|
298
303
|
readonly latitude: number;
|
|
@@ -377,7 +382,7 @@ interface RealtimeProvider {
|
|
|
377
382
|
* Returns `null` when the realtime configuration is unusable, in which case
|
|
378
383
|
* the client keeps working in pull mode.
|
|
379
384
|
*/
|
|
380
|
-
subscribe(config:
|
|
385
|
+
subscribe(config: EmergencyRealtimeConfig, phones: readonly string[], handlers: RealtimeHandlers): RealtimeSubscription | null;
|
|
381
386
|
}
|
|
382
387
|
export declare function createPusherRealtimeProvider(): RealtimeProvider;
|
|
383
388
|
type EmergencyStore = StoreApi<EmergencyClientState>;
|
|
@@ -409,7 +414,10 @@ interface ConfigValidationResult {
|
|
|
409
414
|
readonly error: EmergencyError | null;
|
|
410
415
|
readonly config: EmergencyConfig | null;
|
|
411
416
|
}
|
|
412
|
-
|
|
417
|
+
type EmergencyConfigInput = Omit<EmergencyConfig, 'realtime'> & {
|
|
418
|
+
readonly realtime?: unknown;
|
|
419
|
+
};
|
|
420
|
+
export declare function validateConfig(config: EmergencyConfigInput): ConfigValidationResult;
|
|
413
421
|
export declare function themeToCssVariables(theme: EmergencyTheme | undefined): Record<string, string>;
|
|
414
422
|
interface EmergencyErrorOptions {
|
|
415
423
|
status?: number | null;
|
|
@@ -428,5 +436,5 @@ export declare class EmergencyClientError extends Error {
|
|
|
428
436
|
readonly error: EmergencyError;
|
|
429
437
|
constructor(error: EmergencyError);
|
|
430
438
|
}
|
|
431
|
-
export type { AbortResponse, AbortResult, ActivateRequest, BffClient, BffClientOptions, ConfigResponse, CsrfStrategy, CurrentResponse, EmergencyClient, EmergencyClientState, EmergencyConfig, EmergencyController, EmergencyControllerDeps, EmergencyError, EmergencyErrorCode, EmergencyEventEmitter, EmergencyEventMap, EmergencyEventName, EmergencyFailure, EmergencyFallback, EmergencyFontFamilyFlags, EmergencyFontLoading, EmergencyGeolocation, EmergencyMountOptions, EmergencyOperation, EmergencyPhase, EmergencyPhaseName, EmergencyResultPayload, EmergencySnapshot, EmergencyStore, EmergencyTheme, EmergencyTrigger, FailurePayload, Message, MessageKind, PanelCloseReason, PanelOpenReason, RealtimeStatus, RefreshResponse, Responder, ResponderPayload, ResponderStatus, SessionResponse, SimulationResult };
|
|
439
|
+
export type { AbortResponse, AbortResult, ActivateRequest, BffClient, BffClientOptions, ConfigResponse, CsrfStrategy, CurrentResponse, EmergencyClient, EmergencyClientState, EmergencyConfig, EmergencyConfigInput, EmergencyController, EmergencyControllerDeps, EmergencyError, EmergencyErrorCode, EmergencyEventEmitter, EmergencyEventMap, EmergencyEventName, EmergencyFailure, EmergencyFallback, EmergencyFontFamilyFlags, EmergencyFontLoading, EmergencyGeolocation, EmergencyMountOptions, EmergencyOperation, EmergencyPhase, EmergencyPhaseName, EmergencyRealtimeConfig, EmergencyResultPayload, EmergencySnapshot, EmergencyStore, EmergencyTheme, EmergencyTrigger, FailurePayload, Message, MessageKind, PanelCloseReason, PanelOpenReason, RealtimeStatus, RefreshResponse, Responder, ResponderPayload, ResponderStatus, SessionResponse, SimulationResult };
|
|
432
440
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -101,6 +101,17 @@ interface EmergencyGeolocation {
|
|
|
101
101
|
readonly longitude: number;
|
|
102
102
|
readonly accuracy?: number;
|
|
103
103
|
}
|
|
104
|
+
interface EmergencyRealtimeConfig {
|
|
105
|
+
/** Public Pusher app key supplied by the host. */
|
|
106
|
+
readonly key: string;
|
|
107
|
+
/** Pusher cluster that serves the app key. */
|
|
108
|
+
readonly cluster: string;
|
|
109
|
+
/**
|
|
110
|
+
* Channel name pattern. `{phone}` is replaced with the responder phone in
|
|
111
|
+
* digits-only form. Defaults to `whatsapp.{phone}`.
|
|
112
|
+
*/
|
|
113
|
+
readonly channelPattern?: string;
|
|
114
|
+
}
|
|
104
115
|
interface EmergencyConfig {
|
|
105
116
|
/** Full BFF route prefix, for example `https://example.com/de-bff/emergency`. */
|
|
106
117
|
readonly bffBaseUrl: string;
|
|
@@ -122,6 +133,11 @@ interface EmergencyConfig {
|
|
|
122
133
|
readonly geolocationTimeoutMs?: number;
|
|
123
134
|
/** Request timeout in milliseconds. Defaults to 15000. */
|
|
124
135
|
readonly requestTimeoutMs?: number;
|
|
136
|
+
/**
|
|
137
|
+
* Public Pusher values supplied by the host. When omitted, the client stays
|
|
138
|
+
* in pull mode and never opens a realtime connection.
|
|
139
|
+
*/
|
|
140
|
+
readonly realtime?: EmergencyRealtimeConfig;
|
|
125
141
|
}
|
|
126
142
|
interface EmergencySnapshot {
|
|
127
143
|
readonly emergencyId: string;
|
|
@@ -239,18 +255,8 @@ interface EmergencyMountOptions extends EmergencyConfig {
|
|
|
239
255
|
* message, and an inert client.
|
|
240
256
|
*/
|
|
241
257
|
export declare function mount(options: EmergencyMountOptions): EmergencyClient;
|
|
242
|
-
interface RealtimePusherConfig {
|
|
243
|
-
readonly key: string;
|
|
244
|
-
readonly cluster: string;
|
|
245
|
-
readonly channel_pattern: string;
|
|
246
|
-
}
|
|
247
|
-
interface RealtimePublicConfig {
|
|
248
|
-
readonly mode: 'public';
|
|
249
|
-
readonly pusher: RealtimePusherConfig;
|
|
250
|
-
}
|
|
251
258
|
interface ConfigResponse {
|
|
252
259
|
readonly route_prefix: string;
|
|
253
|
-
readonly realtime: RealtimePublicConfig;
|
|
254
260
|
readonly csrf_token: string;
|
|
255
261
|
}
|
|
256
262
|
interface SessionResponse {
|
|
@@ -292,7 +298,6 @@ type EmergencyPayload = Readonly<Record<string, unknown>>;
|
|
|
292
298
|
interface CurrentResponse {
|
|
293
299
|
readonly active: boolean;
|
|
294
300
|
readonly emergency: EmergencyPayload | null;
|
|
295
|
-
readonly realtime: RealtimePublicConfig;
|
|
296
301
|
}
|
|
297
302
|
interface GeolocationRequest {
|
|
298
303
|
readonly latitude: number;
|
|
@@ -377,7 +382,7 @@ interface RealtimeProvider {
|
|
|
377
382
|
* Returns `null` when the realtime configuration is unusable, in which case
|
|
378
383
|
* the client keeps working in pull mode.
|
|
379
384
|
*/
|
|
380
|
-
subscribe(config:
|
|
385
|
+
subscribe(config: EmergencyRealtimeConfig, phones: readonly string[], handlers: RealtimeHandlers): RealtimeSubscription | null;
|
|
381
386
|
}
|
|
382
387
|
export declare function createPusherRealtimeProvider(): RealtimeProvider;
|
|
383
388
|
type EmergencyStore = StoreApi<EmergencyClientState>;
|
|
@@ -409,7 +414,10 @@ interface ConfigValidationResult {
|
|
|
409
414
|
readonly error: EmergencyError | null;
|
|
410
415
|
readonly config: EmergencyConfig | null;
|
|
411
416
|
}
|
|
412
|
-
|
|
417
|
+
type EmergencyConfigInput = Omit<EmergencyConfig, 'realtime'> & {
|
|
418
|
+
readonly realtime?: unknown;
|
|
419
|
+
};
|
|
420
|
+
export declare function validateConfig(config: EmergencyConfigInput): ConfigValidationResult;
|
|
413
421
|
export declare function themeToCssVariables(theme: EmergencyTheme | undefined): Record<string, string>;
|
|
414
422
|
interface EmergencyErrorOptions {
|
|
415
423
|
status?: number | null;
|
|
@@ -428,5 +436,5 @@ export declare class EmergencyClientError extends Error {
|
|
|
428
436
|
readonly error: EmergencyError;
|
|
429
437
|
constructor(error: EmergencyError);
|
|
430
438
|
}
|
|
431
|
-
export type { AbortResponse, AbortResult, ActivateRequest, BffClient, BffClientOptions, ConfigResponse, CsrfStrategy, CurrentResponse, EmergencyClient, EmergencyClientState, EmergencyConfig, EmergencyController, EmergencyControllerDeps, EmergencyError, EmergencyErrorCode, EmergencyEventEmitter, EmergencyEventMap, EmergencyEventName, EmergencyFailure, EmergencyFallback, EmergencyFontFamilyFlags, EmergencyFontLoading, EmergencyGeolocation, EmergencyMountOptions, EmergencyOperation, EmergencyPhase, EmergencyPhaseName, EmergencyResultPayload, EmergencySnapshot, EmergencyStore, EmergencyTheme, EmergencyTrigger, FailurePayload, Message, MessageKind, PanelCloseReason, PanelOpenReason, RealtimeStatus, RefreshResponse, Responder, ResponderPayload, ResponderStatus, SessionResponse, SimulationResult };
|
|
439
|
+
export type { AbortResponse, AbortResult, ActivateRequest, BffClient, BffClientOptions, ConfigResponse, CsrfStrategy, CurrentResponse, EmergencyClient, EmergencyClientState, EmergencyConfig, EmergencyConfigInput, EmergencyController, EmergencyControllerDeps, EmergencyError, EmergencyErrorCode, EmergencyEventEmitter, EmergencyEventMap, EmergencyEventName, EmergencyFailure, EmergencyFallback, EmergencyFontFamilyFlags, EmergencyFontLoading, EmergencyGeolocation, EmergencyMountOptions, EmergencyOperation, EmergencyPhase, EmergencyPhaseName, EmergencyRealtimeConfig, EmergencyResultPayload, EmergencySnapshot, EmergencyStore, EmergencyTheme, EmergencyTrigger, FailurePayload, Message, MessageKind, PanelCloseReason, PanelOpenReason, RealtimeStatus, RefreshResponse, Responder, ResponderPayload, ResponderStatus, SessionResponse, SimulationResult };
|
|
432
440
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -55,13 +55,8 @@ function isFiniteNumber(value) {
|
|
|
55
55
|
function isArrayOf(value, guard) {
|
|
56
56
|
return Array.isArray(value) && value.every(guard);
|
|
57
57
|
}
|
|
58
|
-
function isRealtimeConfig(value) {
|
|
59
|
-
if (!isRecord(value) || value["mode"] !== "public" || !isRecord(value["pusher"])) return false;
|
|
60
|
-
const pusher = value["pusher"];
|
|
61
|
-
return isString(pusher["key"]) && isString(pusher["cluster"]) && isString(pusher["channel_pattern"]);
|
|
62
|
-
}
|
|
63
58
|
function isConfigResponse(value) {
|
|
64
|
-
return isRecord(value) && isString(value["route_prefix"]) && isString(value["csrf_token"])
|
|
59
|
+
return isRecord(value) && isString(value["route_prefix"]) && isString(value["csrf_token"]);
|
|
65
60
|
}
|
|
66
61
|
function isSessionResponse(value) {
|
|
67
62
|
return isRecord(value) && isString(value["code"]) && isString(value["csrf_token"]) && isFiniteNumber(value["expires_in"]);
|
|
@@ -79,7 +74,7 @@ function isEmergencyResultPayload(value) {
|
|
|
79
74
|
return (value["emergency_id"] === null || isString(value["emergency_id"])) && isBoolean(value["simulated"]) && isArrayOf(value["responders"], isResponderPayload) && isArrayOf(value["failures"], isFailurePayload);
|
|
80
75
|
}
|
|
81
76
|
function isCurrentResponse(value) {
|
|
82
|
-
if (!isRecord(value) || !isBoolean(value["active"])
|
|
77
|
+
if (!isRecord(value) || !isBoolean(value["active"])) return false;
|
|
83
78
|
return value["emergency"] === null || isRecord(value["emergency"]) && !Array.isArray(value["emergency"]);
|
|
84
79
|
}
|
|
85
80
|
function isRefreshResponse(value) {
|
|
@@ -605,8 +600,9 @@ function themeToCssVariables(theme) {
|
|
|
605
600
|
}
|
|
606
601
|
|
|
607
602
|
// src/core/realtime.ts
|
|
603
|
+
const DEFAULT_CHANNEL_PATTERN = "whatsapp.{phone}";
|
|
608
604
|
function channelForPhone(pattern, phone) {
|
|
609
|
-
return pattern.replace("{phone}", phone.replace(
|
|
605
|
+
return pattern.replace("{phone}", phone.replace(/\D/g, ""));
|
|
610
606
|
}
|
|
611
607
|
function toStatus(state) {
|
|
612
608
|
switch (state) {
|
|
@@ -621,11 +617,11 @@ function toStatus(state) {
|
|
|
621
617
|
}
|
|
622
618
|
function createPusherRealtimeProvider() {
|
|
623
619
|
return { subscribe(config, phones, handlers) {
|
|
624
|
-
if (typeof window === "undefined" || !config.
|
|
620
|
+
if (typeof window === "undefined" || !config.key || !config.cluster) return null;
|
|
625
621
|
let pusher;
|
|
626
622
|
try {
|
|
627
|
-
pusher = new Pusher(config.
|
|
628
|
-
cluster: config.
|
|
623
|
+
pusher = new Pusher(config.key, {
|
|
624
|
+
cluster: config.cluster,
|
|
629
625
|
forceTLS: true
|
|
630
626
|
});
|
|
631
627
|
} catch {
|
|
@@ -637,7 +633,7 @@ function createPusherRealtimeProvider() {
|
|
|
637
633
|
handlers.onStatus(toStatus(change.current));
|
|
638
634
|
});
|
|
639
635
|
const channels = [...new Set(phones.filter((phone) => phone !== ""))].map((phone) => {
|
|
640
|
-
const channelName = channelForPhone(config.
|
|
636
|
+
const channelName = channelForPhone(config.channelPattern ?? DEFAULT_CHANNEL_PATTERN, phone);
|
|
641
637
|
pusher.subscribe(channelName).bind_global((eventName, data) => {
|
|
642
638
|
handlers.onEvent(channelName, eventName, data);
|
|
643
639
|
});
|
|
@@ -766,7 +762,6 @@ function createEmergencyController(deps) {
|
|
|
766
762
|
let sessionPromise = null;
|
|
767
763
|
let refreshing = false;
|
|
768
764
|
let realtimeSubscription = null;
|
|
769
|
-
let realtimeConfig = null;
|
|
770
765
|
let subscribedPhones = [];
|
|
771
766
|
let messageSequence = 0;
|
|
772
767
|
let lastReconcileAt = 0;
|
|
@@ -824,9 +819,12 @@ function createEmergencyController(deps) {
|
|
|
824
819
|
realtimeSubscription = null;
|
|
825
820
|
subscribedPhones = [];
|
|
826
821
|
}
|
|
827
|
-
function startRealtime(
|
|
828
|
-
|
|
829
|
-
|
|
822
|
+
function startRealtime(responders) {
|
|
823
|
+
const realtime = config.realtime ?? null;
|
|
824
|
+
if (!realtime) {
|
|
825
|
+
if (responders.length > 0) patch({ realtimeStatus: "unavailable" });
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
830
828
|
const phones = [...new Set(responders.map((responder) => responder.phone))];
|
|
831
829
|
if (realtimeSubscription && phones.length === subscribedPhones.length && phones.every((phone, index) => phone === subscribedPhones[index])) return;
|
|
832
830
|
realtimeSubscription?.disconnect();
|
|
@@ -860,7 +858,7 @@ function createEmergencyController(deps) {
|
|
|
860
858
|
const phase = get().phase.kind;
|
|
861
859
|
if (phase === "idle" || phase === "error") transition({ kind: "initializing" });
|
|
862
860
|
try {
|
|
863
|
-
|
|
861
|
+
await bff.config();
|
|
864
862
|
const session = await bff.session(config.code);
|
|
865
863
|
patch({
|
|
866
864
|
sessionReady: true,
|
|
@@ -890,7 +888,6 @@ function createEmergencyController(deps) {
|
|
|
890
888
|
async function hydrateCurrent() {
|
|
891
889
|
try {
|
|
892
890
|
const current = await bff.current();
|
|
893
|
-
realtimeConfig = current.realtime;
|
|
894
891
|
if (current.active && current.emergency) {
|
|
895
892
|
const snapshot = payloadToSnapshot(current.emergency, { code: config.code });
|
|
896
893
|
patch({
|
|
@@ -906,7 +903,7 @@ function createEmergencyController(deps) {
|
|
|
906
903
|
emergencyId: snapshot.emergencyId,
|
|
907
904
|
simulated: snapshot.simulated
|
|
908
905
|
});
|
|
909
|
-
startRealtime(
|
|
906
|
+
startRealtime(snapshot.responders);
|
|
910
907
|
events.emit("emergency:resumed", { snapshot });
|
|
911
908
|
return;
|
|
912
909
|
}
|
|
@@ -988,7 +985,7 @@ function createEmergencyController(deps) {
|
|
|
988
985
|
});
|
|
989
986
|
pushMessage(failures.length > 0 ? "warning" : "success", failures.length > 0 ? copy.partialFailure : copy.activeBanner);
|
|
990
987
|
events.emit("emergency:activated", { snapshot: hydrated });
|
|
991
|
-
startRealtime(
|
|
988
|
+
startRealtime(responders);
|
|
992
989
|
} catch (error) {
|
|
993
990
|
const normalized = toEmergencyError(error, "network");
|
|
994
991
|
if (normalized.code === "emergency_already_active") {
|
|
@@ -1080,7 +1077,7 @@ function createEmergencyController(deps) {
|
|
|
1080
1077
|
emergencyId: updated.emergencyId,
|
|
1081
1078
|
simulated: updated.simulated
|
|
1082
1079
|
});
|
|
1083
|
-
startRealtime(
|
|
1080
|
+
startRealtime(responders);
|
|
1084
1081
|
events.emit("emergency:updated", { snapshot: updated });
|
|
1085
1082
|
} catch (error) {
|
|
1086
1083
|
const normalized = toEmergencyError(error, "network");
|
|
@@ -1213,7 +1210,6 @@ function createEmergencyController(deps) {
|
|
|
1213
1210
|
bff.destroy();
|
|
1214
1211
|
realtimeSubscription?.disconnect();
|
|
1215
1212
|
realtimeSubscription = null;
|
|
1216
|
-
realtimeConfig = null;
|
|
1217
1213
|
subscribedPhones = [];
|
|
1218
1214
|
patch({
|
|
1219
1215
|
destroyed: true,
|
|
@@ -1344,6 +1340,24 @@ function installEmergencyFonts(input) {
|
|
|
1344
1340
|
|
|
1345
1341
|
// src/core/config.ts
|
|
1346
1342
|
const EMERGENCY_CODE_PATTERN = /^[A-Za-z][A-Za-z0-9]{5}$/;
|
|
1343
|
+
const DEFAULT_REALTIME_CHANNEL_PATTERN = "whatsapp.{phone}";
|
|
1344
|
+
/**
|
|
1345
|
+
* Validates the host-supplied realtime block. Returns `null` when the value is
|
|
1346
|
+
* present but invalid; callers treat `undefined` as "realtime not requested".
|
|
1347
|
+
*/
|
|
1348
|
+
function normalizeRealtimeConfig(value) {
|
|
1349
|
+
if (!isRecord(value)) return null;
|
|
1350
|
+
const key = value["key"];
|
|
1351
|
+
const cluster = value["cluster"];
|
|
1352
|
+
const channelPattern = value["channelPattern"];
|
|
1353
|
+
if (typeof key !== "string" || key.trim() === "" || typeof cluster !== "string" || cluster.trim() === "") return null;
|
|
1354
|
+
if (channelPattern !== void 0 && (typeof channelPattern !== "string" || channelPattern.trim() === "" || !channelPattern.includes("{phone}"))) return null;
|
|
1355
|
+
return {
|
|
1356
|
+
key,
|
|
1357
|
+
cluster,
|
|
1358
|
+
channelPattern: channelPattern ?? "whatsapp.{phone}"
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1347
1361
|
const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
1348
1362
|
"localhost",
|
|
1349
1363
|
"127.0.0.1",
|
|
@@ -1404,6 +1418,12 @@ function validateConfig(config) {
|
|
|
1404
1418
|
config: null,
|
|
1405
1419
|
error: createEmergencyError("configuration", "The fallback requires a non-empty phone and label.")
|
|
1406
1420
|
};
|
|
1421
|
+
const realtime = config.realtime === void 0 ? void 0 : normalizeRealtimeConfig(config.realtime);
|
|
1422
|
+
if (realtime === null) return {
|
|
1423
|
+
ok: false,
|
|
1424
|
+
config: null,
|
|
1425
|
+
error: createEmergencyError("configuration", "The realtime configuration requires a non-empty key and cluster, and a channel pattern containing {phone}.")
|
|
1426
|
+
};
|
|
1407
1427
|
return {
|
|
1408
1428
|
ok: true,
|
|
1409
1429
|
error: null,
|
|
@@ -1414,7 +1434,8 @@ function validateConfig(config) {
|
|
|
1414
1434
|
locale: config.locale ?? "es",
|
|
1415
1435
|
geolocationTimeoutMs: config.geolocationTimeoutMs ?? 8e3,
|
|
1416
1436
|
requestTimeoutMs: config.requestTimeoutMs ?? 15e3,
|
|
1417
|
-
fontLoading: normalizeFontLoading(config.fontLoading)
|
|
1437
|
+
fontLoading: normalizeFontLoading(config.fontLoading),
|
|
1438
|
+
realtime
|
|
1418
1439
|
}
|
|
1419
1440
|
};
|
|
1420
1441
|
}
|
package/package.json
CHANGED