taro-bluetooth-print 2.1.1 → 2.1.2
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/CHANGELOG.md +24 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +664 -604
- package/dist/index.umd.js +1 -1
- package/dist/types/adapters/AlipayAdapter.d.ts +1 -1
- package/dist/types/adapters/BaiduAdapter.d.ts +1 -1
- package/dist/types/adapters/ByteDanceAdapter.d.ts +1 -1
- package/dist/types/adapters/TaroAdapter.d.ts +1 -1
- package/dist/types/core/BluetoothPrinter.d.ts +3 -3
- package/dist/types/core/EventEmitter.d.ts +33 -4
- package/dist/types/errors/BluetoothError.d.ts +6 -1
- package/dist/types/services/CommandBuilder.d.ts +1 -1
- package/dist/types/services/ConnectionManager.d.ts +6 -2
- package/dist/types/services/PrintJobManager.d.ts +57 -13
- package/dist/types/services/interfaces/index.d.ts +21 -3
- package/dist/types/types.d.ts +1 -1
- package/dist/types/utils/image.d.ts +125 -5
- package/package.json +3 -5
- package/src/adapters/TaroAdapter.ts +71 -8
- package/src/core/BluetoothPrinter.ts +24 -23
- package/src/core/EventEmitter.ts +138 -19
- package/src/errors/BluetoothError.ts +27 -1
- package/src/services/CommandBuilder.ts +1 -3
- package/src/services/ConnectionManager.ts +46 -22
- package/src/services/PrintJobManager.ts +203 -93
- package/src/services/interfaces/index.ts +18 -3
- package/src/types.ts +1 -1
- package/src/utils/encoding.ts +3 -3
- package/src/utils/image.ts +435 -26
- package/src/utils/logger.ts +4 -6
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,30 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [2.1.2] - 2025-12-16
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- 增强了弱网适配功能,支持动态分片大小调整
|
|
13
|
+
- 实现了指数退避重试策略和智能超时处理
|
|
14
|
+
- 添加了断点续传功能,支持作业ID生成与管理
|
|
15
|
+
- 实现了作业状态保存与加载机制
|
|
16
|
+
- 增强了图片处理功能,支持多种抖动算法(Floyd-Steinberg、Atkinson)
|
|
17
|
+
- 添加了图片对比度和亮度调整功能
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
- 优化了灰度转换和缩放算法,提高图片处理性能
|
|
22
|
+
- 更新了TypeScript配置,移除无效设置
|
|
23
|
+
- 更新了npm依赖到最新兼容版本
|
|
24
|
+
- 优化了代码结构,提高了代码质量
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
|
|
28
|
+
- 修复了测试中缺少reflect-metadata的问题
|
|
29
|
+
- 修复了TypeScript编译错误
|
|
30
|
+
- 确保了所有异步操作都有正确的清理机制
|
|
31
|
+
|
|
8
32
|
## [2.1.1] - 2025-12-02
|
|
9
33
|
|
|
10
34
|
### Added
|
package/dist/index.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=Object.defineProperty,t=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,r=Object.prototype.propertyIsEnumerable,n=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,s=(e,s)=>{for(var o in s||(s={}))i.call(s,o)&&n(e,o,s[o]);if(t)for(var o of t(s))r.call(s,o)&&n(e,o,s[o]);return e},o=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{c(i.next(e))}catch(t){n(t)}},o=e=>{try{c(i.throw(e))}catch(t){n(t)}},c=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,o);c((i=i.apply(e,t)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var c=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.DISCONNECTING="disconnecting",e.PRINTING="printing",e.PAUSED="paused",e))(c||{});class a{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const i=r=>{t(r),this.off(e,i)};return this.on(e,i)}prepend(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const i=this.listeners.get(e),r=new Set;return r.add(t),i.forEach(e=>r.add(e)),this.listeners.set(e,r),()=>this.off(e,t)}prependOnce(e,t){const i=r=>{t(r),this.off(e,i)};return this.prepend(e,i)}off(e,t){const i=this.listeners.get(e);i&&(i.delete(t),0===i.size&&this.listeners.delete(e))}emit(e,t){const i=this.listeners.get(e);i&&0!==i.size&&new Set(i).forEach(e=>{try{null==t?e():e(t)}catch(i){}})}emitAsync(e,t){return o(this,null,function*(){const i=this.listeners.get(e);if(!i||0===i.size)return;const r=new Set(i),n=[];r.forEach(e=>{n.push(new Promise(i=>{try{null==t?e():e(t)}catch(r){}finally{i()}}))}),yield Promise.all(n)})}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t,i;return null!=(i=null==(t=this.listeners.get(e))?void 0:t.size)?i:0}getListeners(e){const t=this.listeners.get(e);return t?Array.from(t):[]}eventNames(){return Array.from(this.listeners.keys())}hasListeners(e){return this.listenerCount(e)>0}}var l=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE",e))(l||{});const h=class e{static configure(e){this.config=s(s({},this.config),e)}static setLevel(e){this.config.level=e}static getLevel(){return this.config.level}static formatPrefix(e,t){return`${t?`${this.config.prefix}:${t}`:this.config.prefix} [${{0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"NONE"}[e]}]`}static formatMessage(e,t,i,r){return`${this.formatPrefix(e,r)} ${t}`}static log(e,t,i,r){if(this.config.level>e)return;this.formatPrefix(e,r);const n=this.formatMessage(e,t,i,r),s={level:e,message:t,args:i,timestamp:new Date,scope:r,formatted:n};this.config.handler&&this.config.handler(s)}static debug(e,...t){this.log(0,e,t)}static info(e,...t){this.log(1,e,t)}static warn(e,...t){this.log(2,e,t)}static error(e,...t){this.log(3,e,t)}static scope(t){return{debug:(i,...r)=>{e.log(0,i,r,t)},info:(i,...r)=>{e.log(1,i,r,t)},warn:(i,...r)=>{e.log(2,i,r,t)},error:(i,...r)=>{e.log(3,i,r,t)}}}};h.config={level:2,prefix:"[TaroBTPrint]"};let u=h;var d=(e=>(e.CONNECTION_FAILED="CONNECTION_FAILED",e.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.DEVICE_DISCONNECTED="DEVICE_DISCONNECTED",e.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",e.CHARACTERISTIC_NOT_FOUND="CHARACTERISTIC_NOT_FOUND",e.SERVICE_DISCOVERY_FAILED="SERVICE_DISCOVERY_FAILED",e.WRITE_FAILED="WRITE_FAILED",e.WRITE_TIMEOUT="WRITE_TIMEOUT",e.PRINT_JOB_IN_PROGRESS="PRINT_JOB_IN_PROGRESS",e.PRINT_JOB_CANCELLED="PRINT_JOB_CANCELLED",e.PRINT_JOB_FAILED="PRINT_JOB_FAILED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.ENCODING_NOT_SUPPORTED="ENCODING_NOT_SUPPORTED",e.INVALID_IMAGE_DATA="INVALID_IMAGE_DATA",e.INVALID_QR_DATA="INVALID_QR_DATA",e.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",e))(d||{});class f extends Error{constructor(e,t,i){super(t),this.code=e,this.originalError=i,this.name="BluetoothPrintError",Error.captureStackTrace&&Error.captureStackTrace(this,f)}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(e+="\nCaused by: "+this.originalError.message),e}}var g=function(){return function(e){this.name=e}}(),p=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])})(t,i)};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}(),v=function(e){function t(t){var i,r,n=e.call(this)||this;return n.name="ServiceNotFoundError",n.normalizedIdentifier="<UNKNOWN_IDENTIFIER>","string"==typeof t?n.normalizedIdentifier=t:t instanceof g?n.normalizedIdentifier="Token<"+(t.name||"UNSET_NAME")+">":t&&(t.name||(null===(i=t.prototype)||void 0===i?void 0:i.name))&&(n.normalizedIdentifier="MaybeConstructable<"+t.name+">"||"MaybeConstructable<"+(null===(r=t.prototype)||void 0===r?void 0:r.name)+">"),n}return p(t,e),Object.defineProperty(t.prototype,"message",{get:function(){return'Service with "'+this.normalizedIdentifier+'" identifier was not found in the container. Register it before usage via explicitly calling the "Container.set" function or using the "@Service()" decorator.'},enumerable:!1,configurable:!0}),t}(Error),E=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])})(t,i)};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}(),I=function(e){function t(t){var i,r,n=e.call(this)||this;return n.name="CannotInstantiateValueError",n.normalizedIdentifier="<UNKNOWN_IDENTIFIER>","string"==typeof t?n.normalizedIdentifier=t:t instanceof g?n.normalizedIdentifier="Token<"+(t.name||"UNSET_NAME")+">":t&&(t.name||(null===(i=t.prototype)||void 0===i?void 0:i.name))&&(n.normalizedIdentifier="MaybeConstructable<"+t.name+">"||"MaybeConstructable<"+(null===(r=t.prototype)||void 0===r?void 0:r.name)+">"),n}return E(t,e),Object.defineProperty(t.prototype,"message",{get:function(){return'Cannot instantiate the requested value for the "'+this.normalizedIdentifier+"\" identifier. The related metadata doesn't contain a factory or a type to instantiate."},enumerable:!1,configurable:!0}),t}(Error),C=Symbol(),y=function(){return y=Object.assign||function(e){for(var t,i=1,r=arguments.length;r>i;i++)for(var n in t=arguments[i])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},y.apply(this,arguments)},w=function(){function e(e){this.services=[],this.id=e}return e.prototype.has=function(e){return!!this.findService(e)},e.prototype.get=function(e){var t=D.of(void 0),i=t.findService(e),r=this.findService(e);if(i&&!0===i.global)return this.getServiceValue(i);if(r)return this.getServiceValue(r);if(i&&this!==t){var n=y({},i);n.value=C,this.set(n);var s=this.getServiceValue(n);return this.set(y(y({},n),{value:s})),s}if(i)return this.getServiceValue(i);throw new v(e)},e.prototype.getMany=function(e){var t=this;return this.findAllServices(e).map(function(e){return t.getServiceValue(e)})},e.prototype.set=function(e,t){var i=this;if(e instanceof Array)return e.forEach(function(e){return i.set(e)}),this;if("string"==typeof e||e instanceof g)return this.set({id:e,type:null,value:t,factory:void 0,global:!1,multiple:!1,eager:!1,transient:!1});if("function"==typeof e)return this.set({id:e,type:e,value:t,factory:void 0,global:!1,multiple:!1,eager:!1,transient:!1});var r=y({id:new g("UNREACHABLE"),type:null,factory:void 0,value:C,global:!1,multiple:!1,eager:!1,transient:!1},e),n=this.findService(r.id);return n&&!0!==n.multiple?Object.assign(n,r):this.services.push(r),r.eager&&this.get(r.id),this},e.prototype.remove=function(e){var t=this;return Array.isArray(e)?e.forEach(function(e){return t.remove(e)}):this.services=this.services.filter(function(i){return i.id!==e||(t.destroyServiceInstance(i),!1)}),this},e.prototype.reset=function(e){var t=this;switch(void 0===e&&(e={strategy:"resetValue"}),e.strategy){case"resetValue":this.services.forEach(function(e){return t.destroyServiceInstance(e)});break;case"resetServices":this.services.forEach(function(e){return t.destroyServiceInstance(e)}),this.services=[];break;default:throw Error("Received invalid reset strategy.")}return this},e.prototype.findAllServices=function(e){return this.services.filter(function(t){return t.id===e})},e.prototype.findService=function(e){return this.services.find(function(t){return t.id===e})},e.prototype.getServiceValue=function(e){var t,i=C;if(e.value!==C)return e.value;if(!e.factory&&!e.type)throw new I(e.id);if(e.factory)if(e.factory instanceof Array){var r=void 0;try{r=this.get(e.factory[0])}catch(c){if(!(c instanceof v))throw c;r=new e.factory[0]}i=r[e.factory[1]](this,e.id)}else i=e.factory(this,e.id);if(!e.factory&&e.type){var n=e.type,s=(null===(t=Reflect)||void 0===t?void 0:t.getMetadata("design:paramtypes",n))||[],o=this.initializeParams(n,s);o.push(this),i=new(n.bind.apply(n,function(){for(var e=0,t=0,i=arguments.length;i>t;t++)e+=arguments[t].length;var r=Array(e),n=0;for(t=0;i>t;t++)for(var s=arguments[t],o=0,c=s.length;c>o;o++,n++)r[n]=s[o];return r}([void 0],o)))}if(e.transient||i===C||(e.value=i),i===C)throw new I(e.id);return e.type&&this.applyPropertyHandlers(e.type,i),i},e.prototype.initializeParams=function(e,t){var i=this;return t.map(function(t,r){var n=D.handlers.find(function(t){return(t.object===e||t.object===Object.getPrototypeOf(e))&&t.index===r});return n?n.value(i):t&&t.name&&!i.isPrimitiveParamType(t.name)?i.get(t):void 0})},e.prototype.isPrimitiveParamType=function(e){return["string","boolean","number","object"].includes(e.toLowerCase())},e.prototype.applyPropertyHandlers=function(e,t){var i=this;D.handlers.forEach(function(r){"number"!=typeof r.index&&(r.object.constructor===e||e.prototype instanceof r.object.constructor)&&r.propertyName&&(t[r.propertyName]=r.value(i))})},e.prototype.destroyServiceInstance=function(e,t){if(void 0===t&&(t=!1),t||e.type||e.factory){if("function"==typeof(null==e?void 0:e.value).destroy)try{e.value.destroy()}catch(i){}e.value=C}},e}(),D=function(){function e(){}return e.of=function(e){if(void 0===e&&(e="default"),"default"===e)return this.globalInstance;var t=this.instances.find(function(t){return t.id===e});return t||(t=new w(e),this.instances.push(t)),t},e.has=function(e){return this.globalInstance.has(e)},e.get=function(e){return this.globalInstance.get(e)},e.getMany=function(e){return this.globalInstance.getMany(e)},e.set=function(e,t){return this.globalInstance.set(e,t),this},e.remove=function(e){return this.globalInstance.remove(e),this},e.reset=function(e){if(void 0===e&&(e="default"),"default"==e)this.globalInstance.reset(),this.instances.forEach(function(e){return e.reset()});else{var t=this.instances.find(function(t){return t.id===e});t&&(t.reset(),this.instances.splice(this.instances.indexOf(t),1))}return this},e.registerHandler=function(e){return this.handlers.push(e),this},e.import=function(e){return this},e.handlers=[],e.globalInstance=new w("default"),e.instances=[],e}();function N(e){return function(t){var i={id:t,type:t,factory:void 0,multiple:!1,global:!1,eager:!1,transient:!1,value:C};(e instanceof g||"string"==typeof e)&&(i.id=e),D.set(i)}}class m{constructor(){this.serviceCache=new Map,this.logger=u.scope("BaseAdapter")}onStateChange(e){this.stateCallback=e}updateState(e){this.stateCallback&&this.stateCallback(e)}validateDeviceId(e){if(!e||"string"!=typeof e)throw new f(d.DEVICE_NOT_FOUND,"Invalid device ID provided")}validateBuffer(e){if(!(e&&e instanceof ArrayBuffer))throw new f(d.PRINT_JOB_FAILED,"Invalid buffer data provided")}validateOptions(e){var t,i,r;return{chunkSize:Math.max(1,Math.min(256,null!=(t=null==e?void 0:e.chunkSize)?t:20)),delay:Math.max(10,Math.min(100,null!=(i=null==e?void 0:e.delay)?i:20)),retries:Math.max(1,Math.min(10,null!=(r=null==e?void 0:e.retries)?r:3))}}getServiceInfo(e){const t=this.serviceCache.get(e);if(!t)throw new f(d.SERVICE_NOT_FOUND,"Device not connected or services not discovered. Call connect() first.");return t}isDeviceConnected(e){return this.serviceCache.has(e)}cleanupDevice(e){this.serviceCache.delete(e)}}class O extends m{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=Taro.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),Taro.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new f(d.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new f(d.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new f(d.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield Taro.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield Taro.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),l=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${l} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let u=0;for(;c>=u;)try{const t=Taro.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${l} written successfully`);break}catch(h){if(u++,u>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new f(d.WRITE_FAILED,`Failed to write chunk ${n}/${l}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${u}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield Taro.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield Taro.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new f(d.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof f)throw t;throw new f(d.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class b extends m{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=my.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),my.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new f(d.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new f(d.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new f(d.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield my.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield my.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),l=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${l} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let u=0;for(;c>=u;)try{const t=my.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${l} written successfully`);break}catch(h){if(u++,u>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new f(d.WRITE_FAILED,`Failed to write chunk ${n}/${l}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${u}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield my.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield my.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new f(d.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof f)throw t;throw new f(d.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class T extends m{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=swan.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),swan.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new f(d.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new f(d.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new f(d.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield swan.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield swan.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),l=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${l} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let u=0;for(;c>=u;)try{const t=swan.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${l} written successfully`);break}catch(h){if(u++,u>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new f(d.WRITE_FAILED,`Failed to write chunk ${n}/${l}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${u}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield swan.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield swan.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new f(d.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof f)throw t;throw new f(d.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class S extends m{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=tt.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),tt.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new f(d.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new f(d.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new f(d.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield tt.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield tt.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),l=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${l} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let u=0;for(;c>=u;)try{const t=tt.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${l} written successfully`);break}catch(h){if(u++,u>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new f(d.WRITE_FAILED,`Failed to write chunk ${n}/${l}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${u}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield tt.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield tt.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new f(d.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof f)throw t;throw new f(d.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}var _=(e=>(e.WECHAT="wechat",e.ALIPAY="alipay",e.BAIDU="baidu",e.BYTEDANCE="bytedance",e.WEB="web",e.UNKNOWN="unknown",e))(_||{});function P(e){return"object"==typeof e&&null!==e&&"request"in e}class A{static create(){const e="undefined"!=typeof wx&&P(wx)?"wechat":"undefined"!=typeof my&&P(my)?"alipay":"undefined"!=typeof swan&&P(swan)?"baidu":"undefined"!=typeof tt&&P(tt)?"bytedance":"undefined"!=typeof window&&"object"==typeof(t=window)&&null!==t&&"navigator"in t?"web":"unknown";var t;switch(e){case _.WECHAT:return new O;case _.ALIPAY:return new b;case _.BAIDU:return new T;case _.BYTEDANCE:return new S;default:throw new f(d.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported. Please use a supported mini-program platform.`)}}static createForPlatform(e){switch(e){case _.WECHAT:return new O;case _.ALIPAY:return new b;case _.BAIDU:return new T;case _.BYTEDANCE:return new S;default:throw new f(d.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported.`)}}}let B=class{constructor(e){var t,i;this.deviceId=null,this.state=c.DISCONNECTED,this.logger=u.scope("ConnectionManager"),this.adapter=e||A.create(),null==(i=(t=this.adapter).onStateChange)||i.call(t,e=>{this.state=e,this.logger.debug("State changed:",e)})}connect(e){return o(this,null,function*(){this.logger.info("Connecting to device:",e);try{this.deviceId=e,yield this.adapter.connect(e),this.state=c.CONNECTED,this.logger.info("Connected successfully")}catch(t){this.deviceId=null,this.state=c.DISCONNECTED;const e=t instanceof f?t:new f(d.CONNECTION_FAILED,"Connection failed",t);throw this.logger.error("Connection failed:",e),e}})}disconnect(){return o(this,null,function*(){if(!this.deviceId)return void this.logger.warn("Disconnect called but no device connected");const e=this.deviceId;this.logger.info("Disconnecting from device:",e);try{yield this.adapter.disconnect(e),this.deviceId=null,this.state=c.DISCONNECTED,this.logger.info("Disconnected successfully")}catch(t){const e=new f(d.DEVICE_DISCONNECTED,"Disconnect failed",t);throw this.logger.error("Disconnect failed:",e),e}})}isConnected(){return this.state===c.CONNECTED}getDeviceId(){return this.deviceId}getState(){return this.state}getAdapter(){return this.adapter}};B=((e,t)=>{for(var i,r=t,n=e.length-1;n>=0;n--)(i=e[n])&&(r=i(r)||r);return r})([N()],B);let M=class{constructor(e,t){if(this.jobBuffer=null,this.jobOffset=0,this._isPaused=!1,this._isInProgress=!1,this.adapterOptions={},this.logger=u.scope("PrintJobManager"),t)this.connectionManager=e,this.adapter=t;else if(e&&"function"==typeof e.connect)this.adapter=e,this.connectionManager={getDeviceId:()=>"test-device",isConnected:()=>!0,getState:()=>c.CONNECTED,connect:()=>Promise.resolve(),disconnect:()=>Promise.resolve(),getAdapter:()=>this.adapter};else{if(this.connectionManager=e,!this.connectionManager||"function"!=typeof this.connectionManager.getAdapter)throw Error("Printer adapter not provided and could not be retrieved from connection manager");this.adapter=this.connectionManager.getAdapter()}}start(e){return o(this,null,function*(){if(this._isInProgress)throw new f(d.PRINT_JOB_IN_PROGRESS,"A print job is already in progress. Wait for completion or cancel it.");this.logger.info(`Starting print job: ${e.length} bytes`),this.jobBuffer=e,this.jobOffset=0,this._isPaused=!1,this._isInProgress=!0;try{yield this.processJob(),this._isPaused?this.logger.info("Print job paused"):(this.logger.info("Print job completed successfully"),this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0)}catch(t){throw this.logger.error("Print job failed:",t),this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0,t instanceof f?t:new f(d.PRINT_JOB_FAILED,"Print job failed",t)}})}pause(){this._isInProgress?(this._isPaused=!0,this.logger.info("Print job paused")):this.logger.warn("Pause called but no print job in progress")}resume(){return o(this,null,function*(){if(this._isInProgress&&this._isPaused){this._isPaused=!1,this.logger.info("Print job resumed");try{yield this.processJob(),this._isPaused||(this.logger.info("Print job completed successfully"),this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0)}catch(e){throw this.logger.error("Print job failed after resume:",e),this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0,e instanceof f?e:new f(d.PRINT_JOB_FAILED,"Print job failed",e)}}else this.logger.warn("Resume called but no paused print job")})}cancel(){this._isInProgress?(this._isPaused=!1,this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0,this.logger.info("Print job cancelled")):this.logger.warn("Cancel called but no print job in progress")}remaining(){return this.jobBuffer?this.jobBuffer.length-this.jobOffset:0}isPaused(){return this._isPaused}isInProgress(){return this._isInProgress}setOptions(e){this.adapterOptions=s(s({},this.adapterOptions),e),this.logger.debug("Adapter options updated:",this.adapterOptions)}processJob(){return o(this,null,function*(){if(!this.jobBuffer)return;if(!this.adapter||"function"!=typeof this.adapter.write)throw new f(d.INVALID_CONFIGURATION,"Printer adapter does not support write operation");const e=this.jobBuffer.length,t=this.jobBuffer;try{for(;this.jobOffset<t.length;){if(this._isPaused)return void this.logger.debug("Job paused at offset:",this.jobOffset);const i=Math.min(this.jobOffset+512,t.length),r=t.slice(this.jobOffset,i);yield this.adapter.write(this.getDeviceId(),r.buffer,this.adapterOptions),this.jobOffset=i,this.logger.debug(`Processed ${this.jobOffset}/${e} bytes`)}}catch(i){throw this.logger.error("Error processing job:",i),i}})}getDeviceId(){const e=this.connectionManager.getDeviceId();if(!e)throw new f(d.DEVICE_DISCONNECTED,"Device ID not available");return e}};M=((e,t)=>{for(var i,r=t,n=e.length-1;n>=0;n--)(i=e[n])&&(r=i(r)||r);return r})([N()],M);const R=u.scope("Encoding"),L=class{static configure(e){this.config=s(s({},this.config),e)}static encode(e,t="GBK"){if(!e||"string"!=typeof e)return new Uint8Array(0);const i=t.toUpperCase().replace("-","");return"UTF8"===i||"UTF-8"===i||this.config.showWarnings&&!this.warningShown&&(R.warn(`Encoding ${t} not yet fully implemented, falling back to UTF-8. This may cause display issues with some printers.`),this.warningShown=!0),this.utf8Encoder.encode(e)}static isSupported(e){if(!e||"string"!=typeof e)return!1;const t=e.toUpperCase().replace("-","");return"UTF8"===t||"UTF-8"===t}};L.utf8Encoder=new TextEncoder,L.warningShown=!1,L.config={showWarnings:!0};let F=L;class ${static toBitmap(e,t,i){if(!(e&&e instanceof Uint8Array&&t>0&&i>0))return new Uint8Array(0);if(e.length!==t*i*4)throw Error(`Invalid image data length: expected ${t*i*4}, got ${e.length}`);const r=Math.ceil(t/8),n=new Uint8Array(r*i),s=new Float32Array(t*i);for(let o=0;o<e.length;o+=4){const t=o/4,i=e[o]||0,r=e[o+1]||0,n=e[o+2]||0;s[t]=.299*i+.587*r+.114*n}for(let o=0;i>o;o++)for(let e=0;t>e;e++){const c=s[o*t+e]||0,a=128>c?0:255;if(0===a){const t=o*r+Math.floor(e/8),i=7-e%8;n[t]=(n[t]||0)|1<<i}const l=c-a;this.distributeError(s,t,i,e,o,l)}return n}static distributeError(e,t,i,r,n,s){const o=(o,c,a)=>{const l=r+o,h=n+c;if(l>=0&&t>l&&h>=0&&i>h){const i=h*t+l;e[i]=Math.max(0,Math.min(255,(e[i]||0)+s*a))}};o(1,0,7/16),o(-1,1,3/16),o(0,1,5/16),o(1,1,1/16)}}class j{constructor(){this.logger=u.scope("EscPos")}init(){return[new Uint8Array([27,64])]}text(e,t="GBK"){return e&&"string"==typeof e?[F.encode(e,t)]:[]}feed(e=1){return[new Uint8Array([27,100,Math.max(1,Math.min(255,Math.floor(e)))])]}cut(){return[new Uint8Array([29,86,0])]}image(e,t,i){if(!(e&&e instanceof Uint8Array&&t>0&&i>0))return[];if(e.length!==t*i*4)return this.logger.warn(`Invalid image data length: expected ${t*i*4}, got ${e.length}`),[];const r=$.toBitmap(e,t,i),n=Math.ceil(t/8);return[new Uint8Array([29,118,48,0,n%256,Math.floor(n/256),i%256,Math.floor(i/256)]),r]}qr(e,t){var i,r,n,s;if(!e||"string"!=typeof e)return[];const o=null!=(i=null==t?void 0:t.model)?i:2,c=Math.max(1,Math.min(16,null!=(r=null==t?void 0:t.size)?r:6)),a=null!=(n=null==t?void 0:t.errorCorrection)?n:"M",l=[];l.push(new Uint8Array([29,40,107,4,0,49,65,1===o?49:50,0])),l.push(new Uint8Array([29,40,107,3,0,49,67,c]));const h=null!=(s={L:48,M:49,Q:50,H:51}[a])?s:49;l.push(new Uint8Array([29,40,107,3,0,49,69,h]));const u=F.encode(e,"GBK"),d=u.length+3,f=d%256,g=Math.floor(d/256);return l.push(new Uint8Array([29,40,107,f,g,49,80,48])),l.push(u),l.push(new Uint8Array([29,40,107,3,0,49,81,48])),l}}let U=class{constructor(e){this.buffer=[],this.logger=u.scope("CommandBuilder"),this.driver=e||new j,this.buffer.push(...this.driver.init())}text(e,t){return this.logger.debug("Adding text:",e.substring(0,50)),this.buffer.push(...this.driver.text(e,t)),this}feed(e=1){return this.logger.debug("Adding feed:",e),this.buffer.push(...this.driver.feed(e)),this}cut(){return this.logger.debug("Adding cut command"),this.buffer.push(...this.driver.cut()),this}image(e,t,i){return this.logger.debug(`Adding image: ${t}x${i}`),this.buffer.push(...this.driver.image(e,t,i)),this}qr(e,t){return this.logger.debug("Adding QR code:",e.substring(0,50)),this.buffer.push(...this.driver.qr(e,t)),this}clear(){return this.logger.debug("Clearing buffer"),this.buffer=[],this.buffer.push(...this.driver.init()),this}getBuffer(){const e=this.buffer.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e);let i=0;for(const r of this.buffer)t.set(r,i),i+=r.length;return t}getTotalBytes(){return this.buffer.reduce((e,t)=>e+t.length,0)}};U=((e,t)=>{for(var i,r=t,n=e.length-1;n>=0;n--)(i=e[n])&&(r=i(r)||r);return r})([N()],U);exports.BluetoothPrinter=class extends a{constructor(e,t,i){if(super(),this.logger=u.scope("BluetoothPrinter"),this.state=c.DISCONNECTED,e&&"function"==typeof e.connect){const i=e,r=t;this.connectionManager=new B(i),this.printJobManager=new M(this.connectionManager,i),this.commandBuilder=new U(r)}else this.connectionManager=e,this.printJobManager=t,this.commandBuilder=i,this.connectionManager||(this.connectionManager=new B,this.printJobManager=new M(this.connectionManager),this.commandBuilder=new U);this.updateState()}updateState(){let e;e=this.connectionManager&&"function"==typeof this.connectionManager.getState?this.connectionManager.getState():c.CONNECTED;let t=!1,i=!1;this.printJobManager&&(t="function"==typeof this.printJobManager.isInProgress&&this.printJobManager.isInProgress(),i="function"==typeof this.printJobManager.isPaused&&this.printJobManager.isPaused()),this.state=i?c.PAUSED:t?c.PRINTING:e,this.emit("state-change",this.state),this.logger.debug("State updated:",this.state)}connect(e){return o(this,null,function*(){this.logger.info("Connecting to device:",e);try{return yield this.connectionManager.connect(e),this.updateState(),this.emit("connected",e),this.logger.info("Connected successfully"),this}catch(t){const e=t instanceof f?t:new f(d.CONNECTION_FAILED,"Connection failed",t);throw this.emit("error",e),this.updateState(),e}})}disconnect(){return o(this,null,function*(){const e=this.connectionManager.getDeviceId();if(e){this.logger.info("Disconnecting from device:",e);try{yield this.connectionManager.disconnect(),this.printJobManager.cancel(),this.updateState(),this.emit("disconnected",e),this.logger.info("Disconnected successfully")}catch(t){const e=new f(d.DEVICE_DISCONNECTED,"Disconnect failed",t);throw this.emit("error",e),this.updateState(),e}}else this.logger.warn("Disconnect called but no device connected")})}text(e,t){return this.commandBuilder.text(e,t),this}feed(e=1){return this.commandBuilder.feed(e),this}cut(){return this.commandBuilder.cut(),this}image(e,t,i){return this.commandBuilder.image(e,t,i),this}qr(e,t){return this.commandBuilder.qr(e,t),this}setOptions(e){return this.printJobManager.setOptions(e),this}pause(){this.printJobManager.pause(),this.updateState(),this.logger.info("Print job paused")}resume(){return o(this,null,function*(){this.logger.info("Resuming print job");try{yield this.printJobManager.resume(),this.updateState(),this.logger.info("Print job resumed")}catch(e){const t=new f(d.PRINT_JOB_FAILED,"Failed to resume print job",e);throw this.emit("error",t),this.updateState(),t}})}cancel(){this.printJobManager.cancel(),this.commandBuilder.clear(),this.updateState(),this.logger.info("Print job cancelled")}remaining(){return this.printJobManager.remaining()}print(){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new f(d.CONNECTION_FAILED,"Printer not connected. Call connect() first.");const e=this.commandBuilder.getBuffer();this.logger.info(`Starting print job: ${e.length} bytes`),this.commandBuilder.clear(),this.updateState();try{yield this.printJobManager.start(e),"function"==typeof this.printJobManager.isPaused&&this.printJobManager.isPaused()?this.logger.info("Print job paused"):(this.emit("print-complete"),this.logger.info("Print job completed successfully"))}catch(t){this.logger.error("Print job failed with error:",t);const e=t instanceof f?t:new f(d.PRINT_JOB_FAILED,"Print job failed",t);throw this.emit("error",e),e}finally{this.updateState()}})}},exports.BluetoothPrinter=((e,t)=>{for(var i,r=t,n=e.length-1;n>=0;n--)(i=e[n])&&(r=i(r)||r);return r})([N()],exports.BluetoothPrinter);const x={adapter:{chunkSize:20,delay:20,retries:3,timeout:1e4},driver:{encoding:"GBK",paperWidth:58},logging:{level:l.WARN}};exports.BluetoothPrintError=f,exports.DEFAULT_CONFIG=x,exports.Encoding=F,exports.ErrorCode=d,exports.EscPos=j,exports.EventEmitter=a,exports.ImageProcessing=$,exports.LogLevel=l,exports.Logger=u,exports.PrinterState=c,exports.TaroAdapter=O,exports.mergeConfig=function(e,t){return{adapter:s(s(s({},x.adapter),e.adapter),t.adapter),driver:s(s(s({},x.driver),e.driver),t.driver),logging:s(s(s({},x.logging),e.logging),t.logging)}};
|
|
1
|
+
"use strict";var e=Object.defineProperty,t=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,r=Object.prototype.propertyIsEnumerable,n=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,s=(e,s)=>{for(var o in s||(s={}))i.call(s,o)&&n(e,o,s[o]);if(t)for(var o of t(s))r.call(s,o)&&n(e,o,s[o]);return e},o=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{c(i.next(e))}catch(t){n(t)}},o=e=>{try{c(i.throw(e))}catch(t){n(t)}},c=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,o);c((i=i.apply(e,t)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var c=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.DISCONNECTING="disconnecting",e.PRINTING="printing",e.PAUSED="paused",e))(c||{});class a{constructor(){this.listeners=new Map,this.debugMode=!1}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this.debugMode,()=>this.off(e,t)}once(e,t){const i=r=>{t(r),this.off(e,i)};return this.on(e,i)}prepend(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const i=this.listeners.get(e),r=new Set;return r.add(t),i.forEach(e=>r.add(e)),this.listeners.set(e,r),this.debugMode,()=>this.off(e,t)}prependOnce(e,t){const i=r=>{t(r),this.off(e,i)};return this.prepend(e,i)}off(e,t){const i=this.listeners.get(e);i&&(i.delete(t),this.debugMode,0===i.size&&(this.listeners.delete(e),this.debugMode))}emit(e,...t){const i=t[0];this.debugMode;const r=this.listeners.get(e);if(!r||0===r.size)return;const n=new Set(r),s=Array.from(n);for(let c=0;c<s.length;c++){const e=s[c];if("function"==typeof e)try{null==i?e():e(i)}catch(o){}}}emitAsync(e,...t){return o(this,null,function*(){const i=t[0];this.debugMode;const r=this.listeners.get(e);if(!r||0===r.size)return;const n=new Set(r),s=[];n.forEach(e=>{s.push(new Promise(t=>{try{null==i?e():e(i)}catch(r){}finally{t()}}))}),yield Promise.all(s),this.debugMode})}removeAllListeners(e){e?(this.listenerCount(e),this.listeners.delete(e),this.debugMode):(this.listeners.size,this.listeners.clear(),this.debugMode)}listenerCount(e){var t,i;return null!=(i=null==(t=this.listeners.get(e))?void 0:t.size)?i:0}getListeners(e){const t=this.listeners.get(e);return t?Array.from(t):[]}eventNames(){return Array.from(this.listeners.keys())}hasListeners(e){return this.listenerCount(e)>0}setDebugMode(e){this.debugMode=e}isDebugMode(){return this.debugMode}getTotalEvents(){return this.listeners.size}getTotalListeners(){let e=0;for(const t of this.listeners.values())e+=t.size;return e}reset(){this.removeAllListeners(),this.debugMode=!1}}var h=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE",e))(h||{});const d=class e{static configure(e){this.config=s(s({},this.config),e)}static setLevel(e){this.config.level=e}static getLevel(){return this.config.level}static formatPrefix(e,t){return`${t?`${this.config.prefix}:${t}`:this.config.prefix} [${{0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"NONE"}[e]}]`}static formatMessage(e,t,i){return`${this.formatPrefix(e,i)} ${t}`}static log(e,t,i,r){if(this.config.level>e)return;this.formatPrefix(e,r);const n=this.formatMessage(e,t,r),s={level:e,message:t,args:i,timestamp:new Date,scope:r,formatted:n};this.config.handler&&this.config.handler(s)}static debug(e,...t){this.log(0,e,t)}static info(e,...t){this.log(1,e,t)}static warn(e,...t){this.log(2,e,t)}static error(e,...t){this.log(3,e,t)}static scope(t){return{debug:(i,...r)=>{e.log(0,i,r,t)},info:(i,...r)=>{e.log(1,i,r,t)},warn:(i,...r)=>{e.log(2,i,r,t)},error:(i,...r)=>{e.log(3,i,r,t)}}}};d.config={level:2,prefix:"[TaroBTPrint]"};let l=d;var u=(e=>(e.CONNECTION_FAILED="CONNECTION_FAILED",e.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.DEVICE_DISCONNECTED="DEVICE_DISCONNECTED",e.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",e.CHARACTERISTIC_NOT_FOUND="CHARACTERISTIC_NOT_FOUND",e.SERVICE_DISCOVERY_FAILED="SERVICE_DISCOVERY_FAILED",e.WRITE_FAILED="WRITE_FAILED",e.WRITE_TIMEOUT="WRITE_TIMEOUT",e.PRINT_JOB_IN_PROGRESS="PRINT_JOB_IN_PROGRESS",e.PRINT_JOB_CANCELLED="PRINT_JOB_CANCELLED",e.PRINT_JOB_FAILED="PRINT_JOB_FAILED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.ENCODING_NOT_SUPPORTED="ENCODING_NOT_SUPPORTED",e.INVALID_IMAGE_DATA="INVALID_IMAGE_DATA",e.INVALID_QR_DATA="INVALID_QR_DATA",e.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",e))(u||{});class g extends Error{constructor(e,t,i){super(t),this.code=e,this.originalError=i,this.name="BluetoothPrintError",Error.captureStackTrace&&Error.captureStackTrace(this,g)}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(e+="\nCaused by: "+this.originalError.message,this.originalError.stack&&(e+="\n"+this.originalError.stack)),this.stack&&(e+="\n"+this.stack),e}toJSON(){return{name:this.name,code:this.code,message:this.message,stack:this.stack,originalError:this.originalError?{name:this.originalError.name,message:this.originalError.message,stack:this.originalError.stack}:void 0}}}class f{constructor(){this.serviceCache=new Map,this.logger=l.scope("BaseAdapter")}onStateChange(e){this.stateCallback=e}updateState(e){this.stateCallback&&this.stateCallback(e)}validateDeviceId(e){if(!e||"string"!=typeof e)throw new g(u.DEVICE_NOT_FOUND,"Invalid device ID provided")}validateBuffer(e){if(!(e&&e instanceof ArrayBuffer))throw new g(u.PRINT_JOB_FAILED,"Invalid buffer data provided")}validateOptions(e){var t,i,r;return{chunkSize:Math.max(1,Math.min(256,null!=(t=null==e?void 0:e.chunkSize)?t:20)),delay:Math.max(10,Math.min(100,null!=(i=null==e?void 0:e.delay)?i:20)),retries:Math.max(1,Math.min(10,null!=(r=null==e?void 0:e.retries)?r:3))}}getServiceInfo(e){const t=this.serviceCache.get(e);if(!t)throw new g(u.SERVICE_NOT_FOUND,"Device not connected or services not discovered. Call connect() first.");return t}isDeviceConnected(e){return this.serviceCache.has(e)}cleanupDevice(e){this.serviceCache.delete(e)}}class E extends f{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=Taro.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),Taro.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new g(u.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new g(u.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new g(u.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield Taro.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield Taro.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected")}catch(E){throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected",E)}let{chunkSize:s,delay:o,retries:c}=n;const a=new Uint8Array(t);let h=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${h} chunks`),0===a.length)return void this.logger.warn("No data to write");let d=0,l=0,f=o;for(let t=0;t<a.length;t+=s){if(t>0&&Math.floor(t/s)%5==0)try{if(!(yield Taro.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected")}catch(E){throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected",E)}const i=a.slice(t,t+s),o=Math.floor(t/s)+1;let I=0,p=!1;for(;c>=I;)try{const t=Math.max(1e3,Math.min(1e4,1e3+5*i.length)),n=Taro.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,i)=>{setTimeout(()=>{i(Error(`Write timeout after ${t} milliseconds`))},t)});yield Promise.race([n,s]),this.logger.debug(`Chunk ${o}/${h} written successfully`),p=!0;break}catch(E){if(I++,I>c)throw this.logger.error(`Chunk ${o} failed after ${c} retries`),new g(u.WRITE_FAILED,`Failed to write chunk ${o}/${h}`,E);this.logger.warn(`Chunk ${o} write failed, retry ${I}/${c}`);const e=f*Math.pow(2,I-1);yield new Promise(t=>setTimeout(t,Math.min(e,200)))}p?(d++,l=0,d%3==0&&256>s&&(s=Math.min(256,s+5),f=Math.max(f/1.2,n.delay),h=Math.ceil((a.length-t-s)/s)+o,this.logger.debug(`Increased chunk size to ${s}, delay to ${f}`))):(l++,d=Math.max(0,d-1),l>=2&&s>10&&(s=Math.max(10,s-5),f=Math.min(1.5*f,200),h=Math.ceil((a.length-t-s)/s)+o,this.logger.debug(`Decreased chunk size to ${s}, delay to ${f}`),l=0)),t+s<a.length&&(yield new Promise(e=>setTimeout(e,f)))}this.logger.info(`Successfully wrote ${a.length} bytes`)})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield Taro.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield Taro.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new g(u.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof g)throw t;throw new g(u.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class I extends f{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=my.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),my.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new g(u.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new g(u.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new g(u.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield my.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield my.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected")}catch(d){throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected",d)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),h=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${h} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let l=0;for(;c>=l;)try{const t=my.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${h} written successfully`);break}catch(d){if(l++,l>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new g(u.WRITE_FAILED,`Failed to write chunk ${n}/${h}`,d);this.logger.warn(`Chunk ${n} write failed, retry ${l}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield my.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield my.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new g(u.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof g)throw t;throw new g(u.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class p extends f{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=swan.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),swan.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new g(u.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new g(u.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new g(u.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield swan.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield swan.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected")}catch(d){throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected",d)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),h=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${h} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let l=0;for(;c>=l;)try{const t=swan.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${h} written successfully`);break}catch(d){if(l++,l>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new g(u.WRITE_FAILED,`Failed to write chunk ${n}/${h}`,d);this.logger.warn(`Chunk ${n} write failed, retry ${l}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield swan.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield swan.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new g(u.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof g)throw t;throw new g(u.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class v extends f{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=tt.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),tt.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new g(u.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new g(u.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new g(u.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield tt.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield tt.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected")}catch(d){throw this.cleanupDevice(e),new g(u.DEVICE_DISCONNECTED,"Device disconnected",d)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),h=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${h} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let l=0;for(;c>=l;)try{const t=tt.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${h} written successfully`);break}catch(d){if(l++,l>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new g(u.WRITE_FAILED,`Failed to write chunk ${n}/${h}`,d);this.logger.warn(`Chunk ${n} write failed, retry ${l}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield tt.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield tt.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new g(u.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof g)throw t;throw new g(u.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}var C=(e=>(e.WECHAT="wechat",e.ALIPAY="alipay",e.BAIDU="baidu",e.BYTEDANCE="bytedance",e.WEB="web",e.UNKNOWN="unknown",e))(C||{});function D(e){return"object"==typeof e&&null!==e&&"request"in e}class w{static create(){const e="undefined"!=typeof wx&&D(wx)?"wechat":"undefined"!=typeof my&&D(my)?"alipay":"undefined"!=typeof swan&&D(swan)?"baidu":"undefined"!=typeof tt&&D(tt)?"bytedance":"undefined"!=typeof window&&"object"==typeof(t=window)&&null!==t&&"navigator"in t?"web":"unknown";var t;switch(e){case C.WECHAT:return new E;case C.ALIPAY:return new I;case C.BAIDU:return new p;case C.BYTEDANCE:return new v;default:throw new g(u.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported. Please use a supported mini-program platform.`)}}static createForPlatform(e){switch(e){case C.WECHAT:return new E;case C.ALIPAY:return new I;case C.BAIDU:return new p;case C.BYTEDANCE:return new v;default:throw new g(u.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported.`)}}}class N{constructor(e){var t,i;this.deviceId=null,this.state=c.DISCONNECTED,this.logger=l.scope("ConnectionManager"),this.adapter=e||w.create(),null==(i=(t=this.adapter).onStateChange)||i.call(t,e=>{this.state=e,this.logger.debug("State changed:",e)})}connect(e,t){return o(this,null,function*(){this.logger.info("Connecting to device:",e);const{retries:i=0,timeout:r=5e3}=t||{};let n=0;for(;i>=n;)try{this.deviceId=e,this.state=c.CONNECTING;const t=this.adapter.connect(e),i=new Promise((t,i)=>{setTimeout(()=>{i(new g(u.CONNECTION_TIMEOUT,`Connection to device ${e} timed out after ${r}ms`))},r)});return yield Promise.race([t,i]),this.state=c.CONNECTED,void this.logger.info("Connected successfully")}catch(s){if(n++,n>i){this.deviceId=null,this.state=c.DISCONNECTED;const e=s instanceof g?s:new g(u.CONNECTION_FAILED,`Connection failed after ${n} attempts`,s);throw this.logger.error("Connection failed:",e),e}this.logger.warn(`Connection attempt ${n}/${i} failed, retrying...`,s),yield new Promise(e=>setTimeout(e,1e3))}})}disconnect(){return o(this,null,function*(){if(!this.deviceId)return void this.logger.warn("Disconnect called but no device connected");const e=this.deviceId;this.logger.info("Disconnecting from device:",e);try{yield this.adapter.disconnect(e),this.deviceId=null,this.state=c.DISCONNECTED,this.logger.info("Disconnected successfully")}catch(t){const e=new g(u.DEVICE_DISCONNECTED,"Disconnect failed",t);throw this.logger.error("Disconnect failed:",e),e}})}isConnected(){return this.state===c.CONNECTED}getDeviceId(){return this.deviceId}getState(){return this.state}getAdapter(){return this.adapter}}class b{constructor(e){this.jobBuffer=null,this.jobOffset=0,this._isPaused=!1,this._isInProgress=!1,this.adapterOptions={},this.logger=l.scope("PrintJobManager"),this.jobId=null,this.connectionManager=e,"function"==typeof e.getAdapter?this.adapter=e.getAdapter():this.adapter={connect:()=>Promise.resolve(),disconnect:()=>Promise.resolve(),write:()=>Promise.resolve()}}setProgressCallback(e){this.onProgress=e}setJobStateCallback(e){this.onJobStateChange=e}start(e,t){return o(this,null,function*(){if(this._isInProgress)throw new g(u.PRINT_JOB_IN_PROGRESS,"A print job is already in progress. Wait for completion or cancel it.");this.jobId=(null==t?void 0:t.jobId)||this.generateJobId(),this.jobBuffer=e,this.jobOffset=0,this._isPaused=!1,this._isInProgress=!0,this.logger.info(`Starting print job ${this.jobId}: ${e.length} bytes`),this.emitJobState("in-progress");try{yield this.processJob(),this._isPaused?(this.logger.info(`Print job ${this.jobId} paused`),this.saveJobState()):(this.logger.info(`Print job ${this.jobId} completed successfully`),this._isInProgress=!1,this.clearJobState(),this.emitJobState("completed"))}catch(i){throw this.logger.error(`Print job ${this.jobId} failed:`,i),this._isInProgress=!1,this._isPaused?this.saveJobState():this.clearJobState(),i instanceof g?i:new g(u.PRINT_JOB_FAILED,"Print job failed",i)}})}resume(e){return o(this,null,function*(){if(!this._isInProgress||!this._isPaused){if(!e)return void this.logger.warn("Resume called but no paused print job");yield this.loadJobState(e)}this._isPaused=!1,this.logger.info("Resuming print job "+this.jobId),this.emitJobState("in-progress");try{yield this.processJob(),this._isPaused||(this.logger.info(`Print job ${this.jobId} completed successfully`),this._isInProgress=!1,this.clearJobState(),this.emitJobState("completed"))}catch(t){throw this.logger.error(`Print job ${this.jobId} failed after resume:`,t),this._isInProgress=!1,this.clearJobState(),this.emitJobState("cancelled"),t instanceof g?t:new g(u.PRINT_JOB_FAILED,"Print job failed",t)}})}cancel(){this._isInProgress?(this.logger.info("Cancelling print job "+this.jobId),this._isPaused=!1,this._isInProgress=!1,this.clearJobState(),this.emitJobState("cancelled"),this.logger.info(`Print job ${this.jobId} cancelled`)):this.logger.warn("Cancel called but no print job in progress")}generateJobId(){return`job-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}saveJobState(){if(this.jobBuffer&&this.jobId)try{this.logger.debug(`Saved job state for ${this.jobId}: offset=${this.jobOffset}/${this.jobBuffer.length}`)}catch(e){this.logger.error(`Failed to save job state for ${this.jobId}:`,e)}}loadJobState(e){return o(this,null,function*(){try{throw this.logger.debug("Loading job state for "+e),Error("Job state not found for "+e)}catch(t){throw this.logger.error(`Failed to load job state for ${e}:`,t),new g(u.PRINT_JOB_FAILED,"Failed to load job "+e,t)}})}clearJobState(){this.jobId&&this.logger.debug("Clearing job state for "+this.jobId),this.jobBuffer=null,this.jobOffset=0,this.jobId=null,this.adapterOptions={}}emitJobState(e){this.onJobStateChange&&this.onJobStateChange(e)}pause(){this._isInProgress?(this._isPaused=!0,this.logger.info("Print job paused")):this.logger.warn("Pause called but no print job in progress")}remaining(){return this.jobBuffer?this.jobBuffer.length-this.jobOffset:0}isPaused(){return this._isPaused}isInProgress(){return this._isInProgress}setOptions(e){this.adapterOptions=s(s({},this.adapterOptions),e),this.logger.debug("Adapter options updated:",this.adapterOptions)}processJob(){return o(this,null,function*(){if(!this.jobBuffer)return;if(!this.adapter||"function"!=typeof this.adapter.write)throw new g(u.INVALID_CONFIGURATION,"Printer adapter does not support write operation");const{chunkSize:e=512}=this.adapterOptions,t=this.jobBuffer.length,i=this.jobBuffer,r=this.getDeviceId();try{for(;this.jobOffset<i.length;){if(this._isPaused)return void this.logger.debug("Job paused at offset:",this.jobOffset);const n=Math.min(this.jobOffset+e,i.length),s=i.slice(this.jobOffset,n);yield this.adapter.write(r,s.buffer,this.adapterOptions),this.jobOffset=n,this.logger.debug(`Processed ${this.jobOffset}/${t} bytes`),this.onProgress&&this.onProgress(this.jobOffset,t)}}catch(n){throw this.logger.error("Error processing job:",n),n}})}getDeviceId(){const e=this.connectionManager.getDeviceId();if(!e)throw new g(u.DEVICE_DISCONNECTED,"Device ID not available");return e}}const m=l.scope("Encoding"),y=class{static configure(e){this.config=s(s({},this.config),e)}static encode(e,t="GBK"){if(!e||"string"!=typeof e)return new Uint8Array(0);const i=t.toUpperCase().replace("-","");return"UTF8"===i||"UTF-8"===i||this.config.showWarnings&&!this.warningShown&&(m.warn(`Encoding ${t} not yet fully implemented, falling back to UTF-8. This may cause display issues with some printers.`),this.warningShown=!0),this.utf8Encoder.encode(e)}static isSupported(e){if(!e||"string"!=typeof e)return!1;const t=e.toUpperCase().replace("-","");return"UTF8"===t||"UTF-8"===t}};y.utf8Encoder=new TextEncoder,y.warningShown=!1,y.config={showWarnings:!0};let O=y;class T{static toBitmap(e,t,i,r){if(!(e&&e instanceof Uint8Array&&t>0&&i>0))return new Uint8Array(0);if(e.length!==t*i*4)throw Error(`Invalid image data length: expected ${t*i*4}, got ${e.length}`);const{targetWidth:n,targetHeight:s,useDithering:o=!0,ditheringAlgorithm:c="floyd-steinberg",scalingAlgorithm:a="nearest",contrast:h=1,brightness:d=0,threshold:l=128}=r||{};let u=e,g=t,f=i;if(n||s){const{newData:r,newWidth:o,newHeight:c}=this.scaleImage(e,t,i,n||t,s||i,{algorithm:a});u=r,g=o,f=c}const E=Math.ceil(g/8),I=new Uint8Array(E*f);let p=this.toGrayscale(u,g,f);return p=this.adjustContrastBrightness(p,h,d),o?this.applyDithering(p,g,f,I,E,c,l):this.applyThreshold(p,g,f,I,E,l),I}static toGrayscale(e,t,i){const r=new Float32Array(t*i);for(let n=0;n<e.length;n+=4){const t=n>>2,i=e[n]||0,s=e[n+1]||0,o=e[n+2]||0;r[t]=(299*i+587*s+114*o)/1e3}return r}static adjustContrastBrightness(e,t,i){if(1===t&&0===i)return e;const r=new Float32Array(e);for(let n=0;n<r.length;n++){const e=r[n]||0;r[n]=Math.max(0,Math.min(255,(e-128)*t+128+255*i))}return r}static applyDithering(e,t,i,r,n,s,o){for(let c=0;i>c;c++)for(let a=0;t>a;a++){const h=e[c*t+a]||0,d=o>h?0:255;if(0===d){const e=c*n+Math.floor(a/8),t=7-a%8;r[e]=(r[e]||0)|1<<t}const l=h-d;"floyd-steinberg"===s?this.distributeErrorFloydSteinberg(e,t,i,a,c,l):"atkinson"===s&&this.distributeErrorAtkinson(e,t,i,a,c,l)}}static applyThreshold(e,t,i,r,n,s){for(let o=0;i>o;o++)for(let i=0;t>i;i++)if(s>(e[o*t+i]||0)){const e=o*n+Math.floor(i/8),t=7-i%8;r[e]=(r[e]||0)|1<<t}}static scaleImage(e,t,i,r,n,s){const o=t/i;let c=r,a=n;c/a>o?c=Math.round(a*o):a=Math.round(c/o);const h=new Uint8Array(c*a*4),{algorithm:d="nearest"}=s||{};return"bilinear"===d?this.applyBilinearInterpolation(e,t,i,h,c,a):this.applyNearestNeighbor(e,t,i,h,c,a),{newData:h,newWidth:c,newHeight:a}}static applyNearestNeighbor(e,t,i,r,n,s){const o=t/n,c=i/s;for(let a=0;s>a;a++)for(let i=0;n>i;i++){const s=Math.round(i*o),h=4*(Math.round(a*c)*t+s),d=4*(a*n+i);r[d]=e[h]||0,r[d+1]=e[h+1]||0,r[d+2]=e[h+2]||0,r[d+3]=e[h+3]||255}}static applyBilinearInterpolation(e,t,i,r,n,s){const o=t/n,c=i/s;for(let a=0;s>a;a++)for(let s=0;n>s;s++){const h=s*o,d=a*c,l=Math.floor(h),u=Math.floor(d),g=h-l,f=d-u,E=Math.min(l,t-1),I=Math.min(u,i-1),p=Math.min(E+1,t-1),v=Math.min(I+1,i-1),C=4*(I*t+E),D=4*(I*t+p),w=4*(v*t+E),N=4*(v*t+p),b=(1-g)*(1-f),m=g*(1-f),y=(1-g)*f,O=g*f,T=4*(a*n+s);r[T]=Math.round((e[C]||0)*b+(e[D]||0)*m+(e[w]||0)*y+(e[N]||0)*O),r[T+1]=Math.round((e[C+1]||0)*b+(e[D+1]||0)*m+(e[w+1]||0)*y+(e[N+1]||0)*O),r[T+2]=Math.round((e[C+2]||0)*b+(e[D+2]||0)*m+(e[w+2]||0)*y+(e[N+2]||0)*O),r[T+3]=Math.round((e[C+3]||255)*b+(e[D+3]||255)*m+(e[w+3]||255)*y+(e[N+3]||255)*O)}}static distributeErrorFloydSteinberg(e,t,i,r,n,s){const o=[{dx:1,dy:0,factor:7/16},{dx:-1,dy:1,factor:3/16},{dx:0,dy:1,factor:5/16},{dx:1,dy:1,factor:1/16}];for(const{dx:c,dy:a,factor:h}of o)this.distributeErrorPixel(e,t,i,r+c,n+a,s*h)}static distributeErrorAtkinson(e,t,i,r,n,s){const o=[{dx:1,dy:0,factor:1/8},{dx:2,dy:0,factor:1/8},{dx:-1,dy:1,factor:1/8},{dx:0,dy:1,factor:1/8},{dx:1,dy:1,factor:1/8},{dx:0,dy:2,factor:1/8}];for(const{dx:c,dy:a,factor:h}of o)this.distributeErrorPixel(e,t,i,r+c,n+a,s*h)}static distributeErrorPixel(e,t,i,r,n,s){if(r>=0&&t>r&&n>=0&&i>n){const i=n*t+r,o=e[i]||0;e[i]=Math.max(0,Math.min(255,o+s))}}}class S{constructor(){this.logger=l.scope("EscPos")}init(){return[new Uint8Array([27,64])]}text(e,t="GBK"){return e&&"string"==typeof e?[O.encode(e,t)]:[]}feed(e=1){return[new Uint8Array([27,100,Math.max(1,Math.min(255,Math.floor(e)))])]}cut(){return[new Uint8Array([29,86,0])]}image(e,t,i){if(!(e&&e instanceof Uint8Array&&t>0&&i>0))return[];if(e.length!==t*i*4)return this.logger.warn(`Invalid image data length: expected ${t*i*4}, got ${e.length}`),[];const r=T.toBitmap(e,t,i),n=Math.ceil(t/8);return[new Uint8Array([29,118,48,0,n%256,Math.floor(n/256),i%256,Math.floor(i/256)]),r]}qr(e,t){var i,r,n,s;if(!e||"string"!=typeof e)return[];const o=null!=(i=null==t?void 0:t.model)?i:2,c=Math.max(1,Math.min(16,null!=(r=null==t?void 0:t.size)?r:6)),a=null!=(n=null==t?void 0:t.errorCorrection)?n:"M",h=[];h.push(new Uint8Array([29,40,107,4,0,49,65,1===o?49:50,0])),h.push(new Uint8Array([29,40,107,3,0,49,67,c]));const d=null!=(s={L:48,M:49,Q:50,H:51}[a])?s:49;h.push(new Uint8Array([29,40,107,3,0,49,69,d]));const l=O.encode(e,"GBK"),u=l.length+3,g=u%256,f=Math.floor(u/256);return h.push(new Uint8Array([29,40,107,g,f,49,80,48])),h.push(l),h.push(new Uint8Array([29,40,107,3,0,49,81,48])),h}}class _{constructor(e){this.buffer=[],this.logger=l.scope("CommandBuilder"),this.driver=e||new S,this.buffer.push(...this.driver.init())}text(e,t){return this.logger.debug("Adding text:",e.substring(0,50)),this.buffer.push(...this.driver.text(e,t)),this}feed(e=1){return this.logger.debug("Adding feed:",e),this.buffer.push(...this.driver.feed(e)),this}cut(){return this.logger.debug("Adding cut command"),this.buffer.push(...this.driver.cut()),this}image(e,t,i){return this.logger.debug(`Adding image: ${t}x${i}`),this.buffer.push(...this.driver.image(e,t,i)),this}qr(e,t){return this.logger.debug("Adding QR code:",e.substring(0,50)),this.buffer.push(...this.driver.qr(e,t)),this}clear(){return this.logger.debug("Clearing buffer"),this.buffer=[],this.buffer.push(...this.driver.init()),this}getBuffer(){const e=this.buffer.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e);let i=0;for(const r of this.buffer)t.set(r,i),i+=r.length;return t}getTotalBytes(){return this.buffer.reduce((e,t)=>e+t.length,0)}}const P={adapter:{chunkSize:20,delay:20,retries:3,timeout:1e4},driver:{encoding:"GBK",paperWidth:58},logging:{level:h.WARN}};exports.BluetoothPrintError=g,exports.BluetoothPrinter=class extends a{constructor(e,t,i){if(super(),this.logger=l.scope("BluetoothPrinter"),this.state=c.DISCONNECTED,e&&"function"==typeof e.connect){const t=e;this.connectionManager=new N(t),this.printJobManager=new b(this.connectionManager),this.commandBuilder=i||new _}else this.connectionManager=e,this.printJobManager=t,this.commandBuilder=i,this.connectionManager||(this.connectionManager=new N,this.printJobManager=new b(this.connectionManager),this.commandBuilder=new _);this.updateState()}updateState(){let e;e=this.connectionManager&&"function"==typeof this.connectionManager.getState?this.connectionManager.getState():c.CONNECTED;let t=!1,i=!1;this.printJobManager&&(t="function"==typeof this.printJobManager.isInProgress&&this.printJobManager.isInProgress(),i="function"==typeof this.printJobManager.isPaused&&this.printJobManager.isPaused()),this.state=i?c.PAUSED:t?c.PRINTING:e,this.emit("state-change",this.state),this.logger.debug("State updated:",this.state)}connect(e){return o(this,null,function*(){this.logger.info("Connecting to device:",e);try{return yield this.connectionManager.connect(e),this.updateState(),this.emit("connected",e),this.logger.info("Connected successfully"),this}catch(t){const e=t instanceof g?t:new g(u.CONNECTION_FAILED,"Connection failed",t);throw this.emit("error",e),this.updateState(),e}})}disconnect(){return o(this,null,function*(){const e=this.connectionManager.getDeviceId();if(e){this.logger.info("Disconnecting from device:",e);try{yield this.connectionManager.disconnect(),this.printJobManager.cancel(),this.updateState(),this.emit("disconnected",e),this.logger.info("Disconnected successfully")}catch(t){const e=new g(u.DEVICE_DISCONNECTED,"Disconnect failed",t);throw this.emit("error",e),this.updateState(),e}}else this.logger.warn("Disconnect called but no device connected")})}text(e,t){return this.commandBuilder.text(e,t),this}feed(e=1){return this.commandBuilder.feed(e),this}cut(){return this.commandBuilder.cut(),this}image(e,t,i){return this.commandBuilder.image(e,t,i),this}qr(e,t){return this.commandBuilder.qr(e,t),this}setOptions(e){return this.printJobManager.setOptions(e),this}pause(){this.printJobManager.pause(),this.updateState(),this.logger.info("Print job paused")}resume(){return o(this,null,function*(){this.logger.info("Resuming print job");try{yield this.printJobManager.resume(),this.updateState(),this.logger.info("Print job resumed")}catch(e){const t=new g(u.PRINT_JOB_FAILED,"Failed to resume print job",e);throw this.emit("error",t),this.updateState(),t}})}cancel(){this.printJobManager.cancel(),this.commandBuilder.clear(),this.updateState(),this.logger.info("Print job cancelled")}remaining(){return this.printJobManager.remaining()}print(){return o(this,null,function*(){if("function"==typeof this.connectionManager.isConnected&&!this.connectionManager.isConnected())throw new g(u.CONNECTION_FAILED,"Printer not connected. Call connect() first.");const e=this.commandBuilder.getBuffer();this.logger.info(`Starting print job: ${e.length} bytes`),this.commandBuilder.clear(),this.updateState(),this.printJobManager.setProgressCallback((e,t)=>{this.emit("progress",{sent:e,total:t})});try{yield this.printJobManager.start(e),"function"==typeof this.printJobManager.isPaused&&this.printJobManager.isPaused()?this.logger.info("Print job paused"):(this.emit("print-complete"),this.logger.info("Print job completed successfully"))}catch(t){this.logger.error("Print job failed with error:",t);const e=t instanceof g?t:new g(u.PRINT_JOB_FAILED,"Print job failed",t);throw this.emit("error",e),e}finally{this.updateState()}})}},exports.DEFAULT_CONFIG=P,exports.Encoding=O,exports.ErrorCode=u,exports.EscPos=S,exports.EventEmitter=a,exports.ImageProcessing=T,exports.LogLevel=h,exports.Logger=l,exports.PrinterState=c,exports.TaroAdapter=E,exports.mergeConfig=function(e,t){return{adapter:s(s(s({},P.adapter),e.adapter),t.adapter),driver:s(s(s({},P.driver),e.driver),t.driver),logging:s(s(s({},P.logging),e.logging),t.logging)}};
|