UNPKG

@botpress/webchat-client

Version:
106 lines (105 loc) 2.66 kB
class E extends Error { constructor(d, i) { super(d), this.name = "ParseError", this.type = i.type, this.field = i.field, this.value = i.value, this.line = i.line; } } function x(n) { } function w(n) { if (typeof n == "function") throw new TypeError( "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" ); const { onEvent: d = x, onError: i = x, onRetry: r = x, onComment: c } = n; let o = "", s = !0, f, a = "", p = ""; function b(e) { const t = s ? e.replace(/^\xEF\xBB\xBF/, "") : e, [l, u] = g(`${o}${t}`); for (const h of l) y(h); o = u, s = !1; } function y(e) { if (e === "") { v(); return; } if (e.startsWith(":")) { c && c(e.slice(e.startsWith(": ") ? 2 : 1)); return; } const t = e.indexOf(":"); if (t !== -1) { const l = e.slice(0, t), u = e[t + 1] === " " ? 2 : 1, h = e.slice(t + u); m(l, h, e); return; } m(e, "", e); } function m(e, t, l) { switch (e) { case "event": p = t; break; case "data": a = `${a}${t} `; break; case "id": f = t.includes("\0") ? void 0 : t; break; case "retry": /^\d+$/.test(t) ? r(parseInt(t, 10)) : i( new E(`Invalid \`retry\` value: "${t}"`, { type: "invalid-retry", value: t, line: l }) ); break; default: i( new E( `Unknown field "${e.length > 20 ? `${e.slice(0, 20)}…` : e}"`, { type: "unknown-field", field: e, value: t, line: l } ) ); break; } } function v() { a.length > 0 && d({ id: f, event: p || void 0, // If the data buffer's last character is a U+000A LINE FEED (LF) character, // then remove the last character from the data buffer. data: a.endsWith(` `) ? a.slice(0, -1) : a }), f = void 0, a = "", p = ""; } function $(e = {}) { o && e.consume && y(o), s = !0, f = void 0, a = "", p = "", o = ""; } return { feed: b, reset: $ }; } function g(n) { const d = []; let i = "", r = 0; for (; r < n.length; ) { const c = n.indexOf("\r", r), o = n.indexOf(` `, r); let s = -1; if (c !== -1 && o !== -1 ? s = Math.min(c, o) : c !== -1 ? c === n.length - 1 ? s = -1 : s = c : o !== -1 && (s = o), s === -1) { i = n.slice(r); break; } else { const f = n.slice(r, s); d.push(f), r = s + 1, n[r - 1] === "\r" && n[r] === ` ` && r++; } } return [d, i]; } export { E as ParseError, w as createParser };