@mmote/niimbluelib
Version:
Library for the communication with NIIMBOT printers
1,216 lines (1,210 loc) • 204 kB
JavaScript
"use strict";
var niimbluelib = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// node_modules/eventemitter3/index.js
var require_eventemitter3 = __commonJS({
"node_modules/eventemitter3/index.js"(exports, module) {
"use strict";
var has = Object.prototype.hasOwnProperty;
var prefix = "~";
function Events() {
}
if (Object.create) {
Events.prototype = /* @__PURE__ */ Object.create(null);
if (!new Events().__proto__) prefix = false;
}
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== "function") {
throw new TypeError("The listener must be a function");
}
var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
function EventEmitter2() {
this._events = new Events();
this._eventsCount = 0;
}
EventEmitter2.prototype.eventNames = function eventNames() {
var names = [], events, name;
if (this._eventsCount === 0) return names;
for (name in events = this._events) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
EventEmitter2.prototype.listeners = function listeners(event) {
var evt = prefix ? prefix + event : event, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
};
EventEmitter2.prototype.listenerCount = function listenerCount(event) {
var evt = prefix ? prefix + event : event, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
};
EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt], len = arguments.length, args, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
switch (len) {
case 1:
return listeners.fn.call(listeners.context), true;
case 2:
return listeners.fn.call(listeners.context, a1), true;
case 3:
return listeners.fn.call(listeners.context, a1, a2), true;
case 4:
return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5:
return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6:
return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len - 1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
switch (len) {
case 1:
listeners[i].fn.call(listeners[i].context);
break;
case 2:
listeners[i].fn.call(listeners[i].context, a1);
break;
case 3:
listeners[i].fn.call(listeners[i].context, a1, a2);
break;
case 4:
listeners[i].fn.call(listeners[i].context, a1, a2, a3);
break;
default:
if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
EventEmitter2.prototype.on = function on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
EventEmitter2.prototype.once = function once(event, fn, context) {
return addListener(this, event, fn, context, true);
};
EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
events.push(listeners[i]);
}
}
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else clearEvent(this, evt);
}
return this;
};
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
EventEmitter2.prefixed = prefix;
EventEmitter2.EventEmitter = EventEmitter2;
if ("undefined" !== typeof module) {
module.exports = EventEmitter2;
}
}
});
// node_modules/@capacitor/core/dist/index.js
var ExceptionCode, CapacitorException, getPlatformId, createCapacitor, initCapacitorGlobal, Capacitor, registerPlugin, WebPlugin, encode, decode, CapacitorCookiesPluginWeb, CapacitorCookies, readBlobAsBase64, normalizeHttpHeaders, buildUrlParams, buildRequestInit, CapacitorHttpPluginWeb, CapacitorHttp;
var init_dist = __esm({
"node_modules/@capacitor/core/dist/index.js"() {
(function(ExceptionCode2) {
ExceptionCode2["Unimplemented"] = "UNIMPLEMENTED";
ExceptionCode2["Unavailable"] = "UNAVAILABLE";
})(ExceptionCode || (ExceptionCode = {}));
CapacitorException = class extends Error {
constructor(message, code, data) {
super(message);
this.message = message;
this.code = code;
this.data = data;
}
};
getPlatformId = (win) => {
var _a, _b;
if (win === null || win === void 0 ? void 0 : win.androidBridge) {
return "android";
} else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {
return "ios";
} else {
return "web";
}
};
createCapacitor = (win) => {
const capCustomPlatform = win.CapacitorCustomPlatform || null;
const cap = win.Capacitor || {};
const Plugins = cap.Plugins = cap.Plugins || {};
const getPlatform = () => {
return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win);
};
const isNativePlatform = () => getPlatform() !== "web";
const isPluginAvailable = (pluginName) => {
const plugin = registeredPlugins.get(pluginName);
if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) {
return true;
}
if (getPluginHeader(pluginName)) {
return true;
}
return false;
};
const getPluginHeader = (pluginName) => {
var _a;
return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find((h) => h.name === pluginName);
};
const handleError = (err) => win.console.error(err);
const registeredPlugins = /* @__PURE__ */ new Map();
const registerPlugin2 = (pluginName, jsImplementations = {}) => {
const registeredPlugin = registeredPlugins.get(pluginName);
if (registeredPlugin) {
console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`);
return registeredPlugin.proxy;
}
const platform = getPlatform();
const pluginHeader = getPluginHeader(pluginName);
let jsImplementation;
const loadPluginImplementation = () => __async(null, null, function* () {
if (!jsImplementation && platform in jsImplementations) {
jsImplementation = typeof jsImplementations[platform] === "function" ? jsImplementation = yield jsImplementations[platform]() : jsImplementation = jsImplementations[platform];
} else if (capCustomPlatform !== null && !jsImplementation && "web" in jsImplementations) {
jsImplementation = typeof jsImplementations["web"] === "function" ? jsImplementation = yield jsImplementations["web"]() : jsImplementation = jsImplementations["web"];
}
return jsImplementation;
});
const createPluginMethod = (impl, prop) => {
var _a, _b;
if (pluginHeader) {
const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find((m) => prop === m.name);
if (methodHeader) {
if (methodHeader.rtype === "promise") {
return (options) => cap.nativePromise(pluginName, prop.toString(), options);
} else {
return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback);
}
} else if (impl) {
return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl);
}
} else if (impl) {
return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl);
} else {
throw new CapacitorException(`"${pluginName}" plugin is not implemented on ${platform}`, ExceptionCode.Unimplemented);
}
};
const createPluginMethodWrapper = (prop) => {
let remove;
const wrapper = (...args) => {
const p = loadPluginImplementation().then((impl) => {
const fn = createPluginMethod(impl, prop);
if (fn) {
const p2 = fn(...args);
remove = p2 === null || p2 === void 0 ? void 0 : p2.remove;
return p2;
} else {
throw new CapacitorException(`"${pluginName}.${prop}()" is not implemented on ${platform}`, ExceptionCode.Unimplemented);
}
});
if (prop === "addListener") {
p.remove = () => __async(null, null, function* () {
return remove();
});
}
return p;
};
wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`;
Object.defineProperty(wrapper, "name", {
value: prop,
writable: false,
configurable: false
});
return wrapper;
};
const addListener = createPluginMethodWrapper("addListener");
const removeListener = createPluginMethodWrapper("removeListener");
const addListenerNative = (eventName, callback) => {
const call = addListener({ eventName }, callback);
const remove = () => __async(null, null, function* () {
const callbackId = yield call;
removeListener({
eventName,
callbackId
}, callback);
});
const p = new Promise((resolve) => call.then(() => resolve({ remove })));
p.remove = () => __async(null, null, function* () {
console.warn(`Using addListener() without 'await' is deprecated.`);
yield remove();
});
return p;
};
const proxy = new Proxy({}, {
get(_, prop) {
switch (prop) {
// https://github.com/facebook/react/issues/20030
case "$$typeof":
return void 0;
case "toJSON":
return () => ({});
case "addListener":
return pluginHeader ? addListenerNative : addListener;
case "removeListener":
return removeListener;
default:
return createPluginMethodWrapper(prop);
}
}
});
Plugins[pluginName] = proxy;
registeredPlugins.set(pluginName, {
name: pluginName,
proxy,
platforms: /* @__PURE__ */ new Set([...Object.keys(jsImplementations), ...pluginHeader ? [platform] : []])
});
return proxy;
};
if (!cap.convertFileSrc) {
cap.convertFileSrc = (filePath) => filePath;
}
cap.getPlatform = getPlatform;
cap.handleError = handleError;
cap.isNativePlatform = isNativePlatform;
cap.isPluginAvailable = isPluginAvailable;
cap.registerPlugin = registerPlugin2;
cap.Exception = CapacitorException;
cap.DEBUG = !!cap.DEBUG;
cap.isLoggingEnabled = !!cap.isLoggingEnabled;
return cap;
};
initCapacitorGlobal = (win) => win.Capacitor = createCapacitor(win);
Capacitor = /* @__PURE__ */ initCapacitorGlobal(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {});
registerPlugin = Capacitor.registerPlugin;
WebPlugin = class {
constructor() {
this.listeners = {};
this.retainedEventArguments = {};
this.windowListeners = {};
}
addListener(eventName, listenerFunc) {
let firstListener = false;
const listeners = this.listeners[eventName];
if (!listeners) {
this.listeners[eventName] = [];
firstListener = true;
}
this.listeners[eventName].push(listenerFunc);
const windowListener = this.windowListeners[eventName];
if (windowListener && !windowListener.registered) {
this.addWindowListener(windowListener);
}
if (firstListener) {
this.sendRetainedArgumentsForEvent(eventName);
}
const remove = () => __async(this, null, function* () {
return this.removeListener(eventName, listenerFunc);
});
const p = Promise.resolve({ remove });
return p;
}
removeAllListeners() {
return __async(this, null, function* () {
this.listeners = {};
for (const listener in this.windowListeners) {
this.removeWindowListener(this.windowListeners[listener]);
}
this.windowListeners = {};
});
}
notifyListeners(eventName, data, retainUntilConsumed) {
const listeners = this.listeners[eventName];
if (!listeners) {
if (retainUntilConsumed) {
let args = this.retainedEventArguments[eventName];
if (!args) {
args = [];
}
args.push(data);
this.retainedEventArguments[eventName] = args;
}
return;
}
listeners.forEach((listener) => listener(data));
}
hasListeners(eventName) {
return !!this.listeners[eventName].length;
}
registerWindowListener(windowEventName, pluginEventName) {
this.windowListeners[pluginEventName] = {
registered: false,
windowEventName,
pluginEventName,
handler: (event) => {
this.notifyListeners(pluginEventName, event);
}
};
}
unimplemented(msg = "not implemented") {
return new Capacitor.Exception(msg, ExceptionCode.Unimplemented);
}
unavailable(msg = "not available") {
return new Capacitor.Exception(msg, ExceptionCode.Unavailable);
}
removeListener(eventName, listenerFunc) {
return __async(this, null, function* () {
const listeners = this.listeners[eventName];
if (!listeners) {
return;
}
const index = listeners.indexOf(listenerFunc);
this.listeners[eventName].splice(index, 1);
if (!this.listeners[eventName].length) {
this.removeWindowListener(this.windowListeners[eventName]);
}
});
}
addWindowListener(handle) {
window.addEventListener(handle.windowEventName, handle.handler);
handle.registered = true;
}
removeWindowListener(handle) {
if (!handle) {
return;
}
window.removeEventListener(handle.windowEventName, handle.handler);
handle.registered = false;
}
sendRetainedArgumentsForEvent(eventName) {
const args = this.retainedEventArguments[eventName];
if (!args) {
return;
}
delete this.retainedEventArguments[eventName];
args.forEach((arg) => {
this.notifyListeners(eventName, arg);
});
}
};
encode = (str) => encodeURIComponent(str).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
decode = (str) => str.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
CapacitorCookiesPluginWeb = class extends WebPlugin {
getCookies() {
return __async(this, null, function* () {
const cookies = document.cookie;
const cookieMap = {};
cookies.split(";").forEach((cookie) => {
if (cookie.length <= 0)
return;
let [key, value] = cookie.replace(/=/, "CAP_COOKIE").split("CAP_COOKIE");
key = decode(key).trim();
value = decode(value).trim();
cookieMap[key] = value;
});
return cookieMap;
});
}
setCookie(options) {
return __async(this, null, function* () {
try {
const encodedKey = encode(options.key);
const encodedValue = encode(options.value);
const expires = `; expires=${(options.expires || "").replace("expires=", "")}`;
const path = (options.path || "/").replace("path=", "");
const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : "";
document.cookie = `${encodedKey}=${encodedValue || ""}${expires}; path=${path}; ${domain};`;
} catch (error) {
return Promise.reject(error);
}
});
}
deleteCookie(options) {
return __async(this, null, function* () {
try {
document.cookie = `${options.key}=; Max-Age=0`;
} catch (error) {
return Promise.reject(error);
}
});
}
clearCookies() {
return __async(this, null, function* () {
try {
const cookies = document.cookie.split(";") || [];
for (const cookie of cookies) {
document.cookie = cookie.replace(/^ +/, "").replace(/=.*/, `=;expires=${(/* @__PURE__ */ new Date()).toUTCString()};path=/`);
}
} catch (error) {
return Promise.reject(error);
}
});
}
clearAllCookies() {
return __async(this, null, function* () {
try {
yield this.clearCookies();
} catch (error) {
return Promise.reject(error);
}
});
}
};
CapacitorCookies = registerPlugin("CapacitorCookies", {
web: () => new CapacitorCookiesPluginWeb()
});
readBlobAsBase64 = (blob) => __async(null, null, function* () {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const base64String = reader.result;
resolve(base64String.indexOf(",") >= 0 ? base64String.split(",")[1] : base64String);
};
reader.onerror = (error) => reject(error);
reader.readAsDataURL(blob);
});
});
normalizeHttpHeaders = (headers = {}) => {
const originalKeys = Object.keys(headers);
const loweredKeys = Object.keys(headers).map((k) => k.toLocaleLowerCase());
const normalized = loweredKeys.reduce((acc, key, index) => {
acc[key] = headers[originalKeys[index]];
return acc;
}, {});
return normalized;
};
buildUrlParams = (params, shouldEncode = true) => {
if (!params)
return null;
const output = Object.entries(params).reduce((accumulator, entry) => {
const [key, value] = entry;
let encodedValue;
let item;
if (Array.isArray(value)) {
item = "";
value.forEach((str) => {
encodedValue = shouldEncode ? encodeURIComponent(str) : str;
item += `${key}=${encodedValue}&`;
});
item.slice(0, -1);
} else {
encodedValue = shouldEncode ? encodeURIComponent(value) : value;
item = `${key}=${encodedValue}`;
}
return `${accumulator}&${item}`;
}, "");
return output.substr(1);
};
buildRequestInit = (options, extra = {}) => {
const output = Object.assign({ method: options.method || "GET", headers: options.headers }, extra);
const headers = normalizeHttpHeaders(options.headers);
const type = headers["content-type"] || "";
if (typeof options.data === "string") {
output.body = options.data;
} else if (type.includes("application/x-www-form-urlencoded")) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(options.data || {})) {
params.set(key, value);
}
output.body = params.toString();
} else if (type.includes("multipart/form-data") || options.data instanceof FormData) {
const form = new FormData();
if (options.data instanceof FormData) {
options.data.forEach((value, key) => {
form.append(key, value);
});
} else {
for (const key of Object.keys(options.data)) {
form.append(key, options.data[key]);
}
}
output.body = form;
const headers2 = new Headers(output.headers);
headers2.delete("content-type");
output.headers = headers2;
} else if (type.includes("application/json") || typeof options.data === "object") {
output.body = JSON.stringify(options.data);
}
return output;
};
CapacitorHttpPluginWeb = class extends WebPlugin {
/**
* Perform an Http request given a set of options
* @param options Options to build the HTTP request
*/
request(options) {
return __async(this, null, function* () {
const requestInit = buildRequestInit(options, options.webFetchExtra);
const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams);
const url = urlParams ? `${options.url}?${urlParams}` : options.url;
const response = yield fetch(url, requestInit);
const contentType = response.headers.get("content-type") || "";
let { responseType = "text" } = response.ok ? options : {};
if (contentType.includes("application/json")) {
responseType = "json";
}
let data;
let blob;
switch (responseType) {
case "arraybuffer":
case "blob":
blob = yield response.blob();
data = yield readBlobAsBase64(blob);
break;
case "json":
data = yield response.json();
break;
case "document":
case "text":
default:
data = yield response.text();
}
const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
return {
data,
headers,
status: response.status,
url: response.url
};
});
}
/**
* Perform an Http GET request given a set of options
* @param options Options to build the HTTP request
*/
get(options) {
return __async(this, null, function* () {
return this.request(Object.assign(Object.assign({}, options), { method: "GET" }));
});
}
/**
* Perform an Http POST request given a set of options
* @param options Options to build the HTTP request
*/
post(options) {
return __async(this, null, function* () {
return this.request(Object.assign(Object.assign({}, options), { method: "POST" }));
});
}
/**
* Perform an Http PUT request given a set of options
* @param options Options to build the HTTP request
*/
put(options) {
return __async(this, null, function* () {
return this.request(Object.assign(Object.assign({}, options), { method: "PUT" }));
});
}
/**
* Perform an Http PATCH request given a set of options
* @param options Options to build the HTTP request
*/
patch(options) {
return __async(this, null, function* () {
return this.request(Object.assign(Object.assign({}, options), { method: "PATCH" }));
});
}
/**
* Perform an Http DELETE request given a set of options
* @param options Options to build the HTTP request
*/
delete(options) {
return __async(this, null, function* () {
return this.request(Object.assign(Object.assign({}, options), { method: "DELETE" }));
});
}
};
CapacitorHttp = registerPlugin("CapacitorHttp", {
web: () => new CapacitorHttpPluginWeb()
});
}
});
// node_modules/crc-32/crc32.js
var require_crc32 = __commonJS({
"node_modules/crc-32/crc32.js"(exports) {
var CRC323;
(function(factory) {
if (typeof DO_NOT_EXPORT_CRC === "undefined") {
if ("object" === typeof exports) {
factory(exports);
} else if ("function" === typeof define && define.amd) {
define(function() {
var module2 = {};
factory(module2);
return module2;
});
} else {
factory(CRC323 = {});
}
} else {
factory(CRC323 = {});
}
})(function(CRC324) {
CRC324.version = "1.2.2";
function signed_crc_table() {
var c = 0, table = new Array(256);
for (var n = 0; n != 256; ++n) {
c = n;
c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
table[n] = c;
}
return typeof Int32Array !== "undefined" ? new Int32Array(table) : table;
}
var T0 = signed_crc_table();
function slice_by_16_tables(T) {
var c = 0, v = 0, n = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096);
for (n = 0; n != 256; ++n) table[n] = T[n];
for (n = 0; n != 256; ++n) {
v = T[n];
for (c = 256 + n; c < 4096; c += 256) v = table[c] = v >>> 8 ^ T[v & 255];
}
var out = [];
for (n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== "undefined" ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256);
return out;
}
var TT = slice_by_16_tables(T0);
var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];
function crc32_bstr(bstr, seed) {
var C = seed ^ -1;
for (var i = 0, L = bstr.length; i < L; ) C = C >>> 8 ^ T0[(C ^ bstr.charCodeAt(i++)) & 255];
return ~C;
}
function crc32_buf(B, seed) {
var C = seed ^ -1, L = B.length - 15, i = 0;
for (; i < L; ) C = Tf[B[i++] ^ C & 255] ^ Te[B[i++] ^ C >> 8 & 255] ^ Td[B[i++] ^ C >> 16 & 255] ^ Tc[B[i++] ^ C >>> 24] ^ Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];
L += 15;
while (i < L) C = C >>> 8 ^ T0[(C ^ B[i++]) & 255];
return ~C;
}
function crc32_str(str, seed) {
var C = seed ^ -1;
for (var i = 0, L = str.length, c = 0, d = 0; i < L; ) {
c = str.charCodeAt(i++);
if (c < 128) {
C = C >>> 8 ^ T0[(C ^ c) & 255];
} else if (c < 2048) {
C = C >>> 8 ^ T0[(C ^ (192 | c >> 6 & 31)) & 255];
C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
} else if (c >= 55296 && c < 57344) {
c = (c & 1023) + 64;
d = str.charCodeAt(i++) & 1023;
C = C >>> 8 ^ T0[(C ^ (240 | c >> 8 & 7)) & 255];
C = C >>> 8 ^ T0[(C ^ (128 | c >> 2 & 63)) & 255];
C = C >>> 8 ^ T0[(C ^ (128 | d >> 6 & 15 | (c & 3) << 4)) & 255];
C = C >>> 8 ^ T0[(C ^ (128 | d & 63)) & 255];
} else {
C = C >>> 8 ^ T0[(C ^ (224 | c >> 12 & 15)) & 255];
C = C >>> 8 ^ T0[(C ^ (128 | c >> 6 & 63)) & 255];
C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
}
}
return ~C;
}
CRC324.table = T0;
CRC324.bstr = crc32_bstr;
CRC324.buf = crc32_buf;
CRC324.str = crc32_str;
});
}
});
// node_modules/@capacitor-community/bluetooth-le/dist/esm/conversion.js
function numbersToDataView(value) {
return new DataView(Uint8Array.from(value).buffer);
}
function dataViewToNumbers(value) {
return Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
}
function numberToUUID(value) {
return `0000${value.toString(16).padStart(4, "0")}-0000-1000-8000-00805f9b34fb`;
}
function hexStringToDataView(hex) {
const bin = [];
let i, c, isEmpty = 1, buffer = 0;
for (i = 0; i < hex.length; i++) {
c = hex.charCodeAt(i);
if (c > 47 && c < 58 || c > 64 && c < 71 || c > 96 && c < 103) {
buffer = buffer << 4 ^ (c > 64 ? c + 9 : c) & 15;
if (isEmpty ^= 1) {
bin.push(buffer & 255);
}
}
}
return numbersToDataView(bin);
}
function dataViewToHexString(value) {
return dataViewToNumbers(value).map((n) => {
let s = n.toString(16);
if (s.length == 1) {
s = "0" + s;
}
return s;
}).join("");
}
function webUUIDToString(uuid) {
if (typeof uuid === "string") {
return uuid;
} else if (typeof uuid === "number") {
return numberToUUID(uuid);
} else {
throw new Error("Invalid UUID");
}
}
function mapToObject(map) {
const obj = {};
if (!map) {
return void 0;
}
map.forEach((value, key) => {
obj[key.toString()] = value;
});
return obj;
}
var init_conversion = __esm({
"node_modules/@capacitor-community/bluetooth-le/dist/esm/conversion.js"() {
}
});
// node_modules/@capacitor-community/bluetooth-le/dist/esm/timeout.js
function runWithTimeout(promise, time, exception) {
return __async(this, null, function* () {
let timer;
return Promise.race([
promise,
new Promise((_, reject) => {
timer = setTimeout(() => reject(exception), time);
})
]).finally(() => clearTimeout(timer));
});
}
var init_timeout = __esm({
"node_modules/@capacitor-community/bluetooth-le/dist/esm/timeout.js"() {
}
});
// node_modules/@capacitor-community/bluetooth-le/dist/esm/web.js
var web_exports = {};
__export(web_exports, {
BluetoothLeWeb: () => BluetoothLeWeb
});
var BluetoothLeWeb;
var init_web = __esm({
"node_modules/@capacitor-community/bluetooth-le/dist/esm/web.js"() {
init_dist();
init_conversion();
init_timeout();
BluetoothLeWeb = class extends WebPlugin {
constructor() {
super(...arguments);
this.deviceMap = /* @__PURE__ */ new Map();
this.discoveredDevices = /* @__PURE__ */ new Map();
this.scan = null;
this.DEFAULT_CONNECTION_TIMEOUT = 1e4;
this.onAdvertisementReceivedCallback = this.onAdvertisementReceived.bind(this);
this.onDisconnectedCallback = this.onDisconnected.bind(this);
this.onCharacteristicValueChangedCallback = this.onCharacteristicValueChanged.bind(this);
}
initialize() {
return __async(this, null, function* () {
if (typeof navigator === "undefined" || !navigator.bluetooth) {
throw this.unavailable("Web Bluetooth API not available in this browser.");
}
const isAvailable = yield navigator.bluetooth.getAvailability();
if (!isAvailable) {
throw this.unavailable("No Bluetooth radio available.");
}
});
}
isEnabled() {
return __async(this, null, function* () {
return { value: true };
});
}
requestEnable() {
return __async(this, null, function* () {
throw this.unavailable("requestEnable is not available on web.");
});
}
enable() {
return __async(this, null, function* () {
throw this.unavailable("enable is not available on web.");
});
}
disable() {
return __async(this, null, function* () {
throw this.unavailable("disable is not available on web.");
});
}
startEnabledNotifications() {
return __async(this, null, function* () {
});
}
stopEnabledNotifications() {
return __async(this, null, function* () {
});
}
isLocationEnabled() {
return __async(this, null, function* () {
throw this.unavailable("isLocationEnabled is not available on web.");
});
}
openLocationSettings() {
return __async(this, null, function* () {
throw this.unavailable("openLocationSettings is not available on web.");
});
}
openBluetoothSettings() {
return __async(this, null, function* () {
throw this.unavailable("openBluetoothSettings is not available on web.");
});
}
openAppSettings() {
return __async(this, null, function* () {
throw this.unavailable("openAppSettings is not available on web.");
});
}
setDisplayStrings() {
return __async(this, null, function* () {
});
}
requestDevice(options) {
return __async(this, null, function* () {
const filters = this.getFilters(options);
const device = yield navigator.bluetooth.requestDevice({
filters: filters.length ? filters : void 0,
optionalServices: options === null || options === void 0 ? void 0 : options.optionalServices,
acceptAllDevices: filters.length === 0
});
this.deviceMap.set(device.id, device);
const bleDevice = this.getBleDevice(device);
return bleDevice;
});
}
requestLEScan(options) {
return __async(this, null, function* () {
this.requestBleDeviceOptions = options;
const filters = this.getFilters(options);
yield this.stopLEScan();
this.discoveredDevices = /* @__PURE__ */ new Map();
navigator.bluetooth.removeEventListener("advertisementreceived", this.onAdvertisementReceivedCallback);
navigator.bluetooth.addEventListener("advertisementreceived", this.onAdvertisementReceivedCallback);
this.scan = yield navigator.bluetooth.requestLEScan({
filters: filters.length ? filters : void 0,
acceptAllAdvertisements: filters.length === 0,
keepRepeatedDevices: options === null || options === void 0 ? void 0 : options.allowDuplicates
});
});
}
onAdvertisementReceived(event) {
var _a, _b;
const deviceId = event.device.id;
this.deviceMap.set(deviceId, event.device);
const isNew = !this.discoveredDevices.has(deviceId);
if (isNew || ((_a = this.requestBleDeviceOptions) === null || _a === void 0 ? void 0 : _a.allowDuplicates)) {
this.discoveredDevices.set(deviceId, true);
const device = this.getBleDevice(event.device);
const result = {
device,
localName: device.name,
rssi: event.rssi,
txPower: event.txPower,
manufacturerData: mapToObject(event.manufacturerData),
serviceData: mapToObject(event.serviceData),
uuids: (_b = event.uuids) === null || _b === void 0 ? void 0 : _b.map(webUUIDToString)
};
this.notifyListeners("onScanResult", result);
}
}
stopLEScan() {
return __async(this, null, function* () {
var _a;
if ((_a = this.scan) === null || _a === void 0 ? void 0 : _a.active) {
this.scan.stop();
}
this.scan = null;
});
}
getDevices(options) {
return __async(this, null, function* () {
const devices = yield navigator.bluetooth.getDevices();
const bleDevices = devices.filter((device) => options.deviceIds.includes(device.id)).map((device) => {
this.deviceMap.set(device.id, device);
const bleDevice = this.getBleDevice(device);
return bleDevice;
});
return { devices: bleDevices };
});
}
getConnectedDevices(_options) {
return __async(this, null, function* () {
const devices = yield navigator.bluetooth.getDevices();
const bleDevices = devices.filter((device) => {
var _a;
return (_a = device.gatt) === null || _a === void 0 ? void 0 : _a.connected;
}).map((device) => {
this.deviceMap.set(device.id, device);
const bleDevice = this.getBleDevice(device);
return bleDevice;
});
return { devices: bleDevices };
});
}
getBondedDevices() {
return __async(this, null, function* () {
return {};
});
}
connect(options) {
return __async(this, null, function* () {
var _a, _b;
const device = this.getDeviceFromMap(options.deviceId);
device.removeEventListener("gattserverdisconnected", this.onDisconnectedCallback);
device.addEventListener("gattserverdisconnected", this.onDisconnectedCallback);
const timeoutError = Symbol();
if (device.gatt === void 0) {
throw new Error("No gatt server available.");
}
try {
const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.DEFAULT_CONNECTION_TIMEOUT;
yield runWithTimeout(device.gatt.connect(), timeout, timeoutError);
} catch (error) {
yield (_b = device.gatt) === null || _b === void 0 ? void 0 : _b.disconnect();
if (error === timeoutError) {
throw new Error("Connection timeout");
} else {
throw error;
}
}
});
}
onDisconnected(event) {
const deviceId = event.target.id;
const key = `disconnected|${deviceId}`;
this.notifyListeners(key, null);
}
createBond(_options) {
return __async(this, null, function* () {
throw this.unavailable("createBond is not available on web.");
});
}
isBonded(_options) {
return __async(this, null, function* () {
throw this.unavailable("isBonded is not available on web.");
});
}
disconnect(options) {
return __async(this, null, function* () {
var _a;
(_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === void 0 ? void 0 : _a.disconnect();
});
}
getServices(options) {
return __async(this, null, function* () {
var _a, _b;
const services = (_b = yield (_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === void 0 ? void 0 : _a.getPrimaryServices()) !== null && _b !== void 0 ? _b : [];
const bleServices = [];
for (const service of services) {
const characteristics = yield service.getCharacteristics();
const bleCharacteristics = [];
for (const characteristic of characteristics) {
bleCharacteristics.push({
uuid: characteristic.uuid,
properties: this.getProperties(characteristic),
descriptors: yield this.getDescriptors(characteristic)
});
}
bleServices.push({ uuid: service.uuid, characteristics: bleCharacteristics });
}
return { services: bleServices };
});
}
getDescriptors(characteristic) {
return __async(this, null, function* () {
try {
const descriptors = yield characteristic.getDescriptors();
return descriptors.map((descriptor) => ({
uuid: descriptor.uuid
}));
} catch (_a) {
return [];
}
});
}
getProperties(characteristic) {
return {
broadcast: characteristic.properties.broadcast,
read: characteristic.properties.read,
writeWithoutResponse: characteristic.properties.writeWithoutResponse,
write: characteristic.properties.write,
notify: characteristic.properties.notify,
indicate: characteristic.properties.indicate,
authenticatedSignedWrites: characteristic.properties.authenticatedSignedWrites,
reliableWrite: characteristic.properties.reliableWrite,
writableAuxiliaries: characteristic.properties.writableAuxiliaries
};
}
getCharacteristic(options) {
return __async(this, null, function* () {
var _a;
const service = yield (_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === void 0 ? void 0 : _a.getPrimaryService(options === null || options === void 0 ? void 0 : options.service);
return service === null || service === void 0 ? void 0 : service.getCharacteristic(options === null || options === void 0 ? void 0 : options.characteristic);
});
}
getDescriptor(options) {
return __async(this, null, function* () {
const characteristic = yield this.getCharacteristic(options);
return characteristic === null || characteristic === void 0 ? void 0 : characteristic.getDescriptor(options === null || options === void 0 ? void 0 : options.descriptor);
});
}
discoverServices(_options) {
return __async(this, null, function* () {
throw this.unavailable("discoverServices is not available on web.");
});
}
getMtu(_options) {
return __async(this, null, function* () {
throw this.unavailable("getMtu is not available on web.");
});
}
requestConnectionPriority(_options) {
return __async(this, null, function* () {
throw this.unavailable("requestConnectionPriority is not available on web.");
});
}
readRssi(_options) {
return __async(this, null, function* () {
throw this.unavailable("readRssi is not available on web.");
});
}
read(options) {
return __async(this, null, function* () {
const characteristic = yield this.getCharacteristic(options);
const value = yield characte