UNPKG

1.46 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.listen = exports.log = void 0;
7
8/**
9 * A Log object
10 */
11let id = 0;
12const subscribers = [];
13/**
14 * log something
15 * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...)
16 * @param message a clear message of the log associated to the type
17 */
18
19const log = (type, message, data) => {
20 const obj = {
21 type,
22 id: String(++id),
23 date: new Date()
24 };
25 if (message) obj.message = message;
26 if (data) obj.data = data;
27 dispatch(obj);
28};
29/**
30 * listen to logs.
31 * @param cb that is called for each future log() with the Log object
32 * @return a function that can be called to unsubscribe the listener
33 */
34
35
36exports.log = log;
37
38const listen = cb => {
39 subscribers.push(cb);
40 return () => {
41 const i = subscribers.indexOf(cb);
42
43 if (i !== -1) {
44 // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952
45 subscribers[i] = subscribers[subscribers.length - 1];
46 subscribers.pop();
47 }
48 };
49};
50
51exports.listen = listen;
52
53function dispatch(log) {
54 for (let i = 0; i < subscribers.length; i++) {
55 try {
56 subscribers[i](log);
57 } catch (e) {
58 console.error(e);
59 }
60 }
61} // for debug purpose
62
63
64if (typeof window !== "undefined") {
65 window.__ledgerLogsListen = listen;
66}
67//# sourceMappingURL=index.js.map
\No newline at end of file