taro-bluetooth-print 2.15.2 → 2.15.4
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 +93 -0
- package/README.md +4 -4
- package/dist/adapters/index.cjs.js +1 -0
- package/dist/adapters/index.es.js +1 -0
- package/dist/chunks/AdapterFactory-CkjGKGZN.js +1 -0
- package/dist/chunks/AdapterFactory-DA4PnIrY.js +1 -0
- package/dist/chunks/EscPosDriver-BEwkA9KT.js +1 -0
- package/dist/chunks/EscPosDriver-ju4j3bXJ.js +1 -0
- package/dist/chunks/gbk-data-BhfiCGRq.js +1 -0
- package/dist/chunks/gbk-data-Cunq2WDW.js +1 -0
- package/dist/chunks/index-Cee15KIh.js +1 -0
- package/dist/chunks/index-DIquif_6.js +1 -0
- package/dist/chunks/shared-C7eA759x.js +1 -0
- package/dist/chunks/shared-CvHoYVGG.js +1 -0
- package/dist/core/index.cjs.js +1 -0
- package/dist/core/index.es.js +1 -0
- package/dist/drivers/index.cjs.js +1 -0
- package/dist/drivers/index.es.js +1 -0
- package/dist/encoding/index.cjs.js +1 -0
- package/dist/encoding/index.es.js +1 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +1 -1
- package/dist/types/config/PrinterConfigManager.d.ts +58 -7
- package/dist/types/core/BluetoothPrinter.d.ts +54 -0
- package/dist/types/encoding/GbkTable.d.ts +14 -5
- package/dist/types/index.d.ts +3 -3
- package/dist/types/plugins/builtin/RetryPlugin.d.ts +19 -1
- package/dist/types/plugins/index.d.ts +1 -0
- package/dist/types/services/BatchPrintManager.d.ts +48 -2
- package/package.json +7 -3
- package/src/config/PrinterConfigManager.ts +150 -45
- package/src/core/BluetoothPrinter.ts +115 -5
- package/src/encoding/GbkTable.ts +18 -7
- package/src/index.ts +15 -3
- package/src/plugins/builtin/RetryPlugin.ts +46 -12
- package/src/plugins/index.ts +1 -0
- package/src/services/BatchPrintManager.ts +126 -8
- package/dist/hero-illustration.svg +0 -44
- package/dist/index.umd.js +0 -1
- package/dist/logo.svg +0 -17
- package/dist/manifest.webmanifest +0 -17
- package/dist/offline.html +0 -146
- package/dist/service-worker.js +0 -161
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=Object.defineProperty,t=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,s=(t,n,i)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[n]=i,r=(e,r)=>{for(var o in r||(r={}))n.call(r,o)&&s(e,o,r[o]);if(t)for(var o of t(r))i.call(r,o)&&s(e,o,r[o]);return e},o=(e,t,n)=>new Promise((i,s)=>{var r=e=>{try{a(n.next(e))}catch(t){s(t)}},o=e=>{try{a(n.throw(e))}catch(t){s(t)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(r,o);a((n=n.apply(e,t)).next())});const a=require("./shared-CvHoYVGG.js"),h=require("./AdapterFactory-DA4PnIrY.js"),c=require("./EscPosDriver-BEwkA9KT.js");class l{constructor(){this.listeners={},this.debugMode=!1,this.logger=a.L.scope("EventEmitter")}ensureListeners(e){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e]}on(e,t){return this.ensureListeners(e).add(t),this.debugMode&&this.logger.debug(`EventEmitter: Added listener for "${e+""}"`,{listenerCount:this.listenerCount(e)}),()=>this.off(e,t)}once(e,t){const n=this.wrapOnceHandler(e,t);return this.on(e,n)}prepend(e,t){const n=this.ensureListeners(e),i=new Set;return i.add(t),n.forEach(e=>i.add(e)),this.listeners[e]=i,this.debugMode&&this.logger.debug(`EventEmitter: Prepend listener for "${e+""}"`,{listenerCount:this.listenerCount(e)}),()=>this.off(e,t)}prependOnce(e,t){const n=this.wrapOnceHandler(e,t);return this.prepend(e,n)}wrapOnceHandler(e,t){const n=i=>{t(i),this.off(e,n)};return n}off(e,t){const n=this.listeners[e];n&&(n.delete(t),this.debugMode&&this.logger.debug(`EventEmitter: Removed listener for "${e+""}"`,{listenerCount:n.size}),0===n.size&&(delete this.listeners[e],this.debugMode&&this.logger.debug(`EventEmitter: Removed event "${e+""}" (no more listeners)`)))}getHandlers(e){var t;return null!=(t=this.listeners[e])?t:new Set}emit(e,...t){const n=t[0],i=this.getHandlers(e);if(this.debugMode&&this.logger.debug(`EventEmitter: Emitting "${e+""}"`,{data:n,listenerCount:i.size}),0!==i.size)for(const r of i)if("function"==typeof r)try{r(n)}catch(s){this.logger.error(`Error in event handler for "${e+""}":`,s)}}emitAsync(e,...t){return o(this,null,function*(){const n=t[0],i=this.getHandlers(e);if(this.debugMode&&this.logger.debug(`EventEmitter: Emitting async "${e+""}"`,{data:n,listenerCount:i.size}),0===i.size)return;const s=[];i.forEach(t=>{s.push((()=>o(this,null,function*(){try{const e=t(n);null!=e&&"function"==typeof e.then&&(yield e)}catch(i){this.logger.error(`Error in event handler for "${e+""}":`,i)}}))())}),yield Promise.all(s),this.debugMode&&this.logger.debug(`EventEmitter: Finished emitting async "${e+""}"`)})}removeAllListeners(e){if(e){const t=this.listenerCount(e);delete this.listeners[e],this.debugMode&&this.logger.debug(`EventEmitter: Removed all ${t} listeners for "${e+""}"`)}else{const e=Object.keys(this.listeners).length;this.listeners={},this.debugMode&&this.logger.debug(`EventEmitter: Removed all ${e} events and their listeners`)}}listenerCount(e){var t,n;return null!=(n=null==(t=this.listeners[e])?void 0:t.size)?n:0}getListeners(e){const t=this.listeners[e];return t?Array.from(t):[]}eventNames(){return Object.keys(this.listeners)}hasListeners(e){return this.listenerCount(e)>0}setDebugMode(e){this.debugMode=e,this.logger.debug("EventEmitter: Debug mode "+(e?"enabled":"disabled"))}isDebugMode(){return this.debugMode}getTotalEvents(){return Object.keys(this.listeners).length}getTotalListeners(){var e,t;let n=0;for(const i of Object.keys(this.listeners))n+=null!=(t=null==(e=this.listeners[i])?void 0:e.size)?t:0;return n}reset(){this.removeAllListeners(),this.debugMode=!1}}const d={heartbeatEnabled:!0,heartbeatInterval:5e3,autoReconnect:!0,maxReconnectAttempts:3,reconnectInterval:2e3,connectionTimeout:1e4};class u extends l{constructor(e,t){var n,i;super(),this.deviceId=null,this.state=a.P.DISCONNECTED,this.connLogger=a.L.scope("ConnectionManager"),this.heartbeatTimer=null,this.reconnectAttempts=0,this.isReconnecting=!1,this.reconnectTimer=null,this.adapter=e||h.A.create(),this.config=r(r({},d),t),null==(i=(n=this.adapter).onStateChange)||i.call(n,e=>{this.handleStateChange(e)})}handleStateChange(e){const t=this.state;this.state=e,this.connLogger.debug("State changed:",{from:t,to:e}),this.emit("state-change",e),t===a.P.CONNECTED&&e===a.P.DISCONNECTED&&this.deviceId&&!this.isReconnecting&&(this.connLogger.warn("Unexpected disconnection detected"),this.emit("disconnected",this.deviceId),this.stopHeartbeat(),this.config.autoReconnect&&this.startReconnect())}connect(e,t){return o(this,null,function*(){this.connLogger.info("Connecting to device:",e);const{retries:n=0,timeout:i=this.config.connectionTimeout}=t||{};let s=0;for(this.reconnectAttempts=0,this.isReconnecting=!1,this.clearReconnectTimer();n>=s;)try{this.deviceId=e,this.state=a.P.CONNECTING,this.emit("state-change",a.P.CONNECTING);const t=this.adapter.connect(e);return yield a.w(t,i,`Connection to device ${e} timed out`),this.state=a.P.CONNECTED,this.emit("state-change",a.P.CONNECTED),this.emit("connected",e),this.connLogger.info("Connected successfully"),void(this.config.heartbeatEnabled&&this.startHeartbeat())}catch(r){if(s++,s>n){this.deviceId=null,this.state=a.P.DISCONNECTED,this.emit("state-change",a.P.DISCONNECTED);const t=this.classifyConnectError(r,e,s,i);throw this.connLogger.error("Connection failed:",t),this.emit("error",t),t}this.connLogger.warn(`Connection attempt ${s}/${n} failed, retrying...`,r),yield new Promise(e=>setTimeout(e,1e3))}})}classifyConnectError(e,t,n,i){if(e instanceof a.B)return e;const s=a.o(e).message.toLowerCase();return s.includes("timed out")||s.includes("timeout")?new a.B(a.n.CONNECTION_TIMEOUT,`Connection to device ${t} timed out after ${i}ms`):new a.B(a.n.CONNECTION_FAILED,`Connection failed after ${n} attempts`,a.o(e))}disconnect(){return o(this,null,function*(){if(this.stopHeartbeat(),this.clearReconnectTimer(),this.isReconnecting=!1,!this.deviceId)return void this.connLogger.warn("Disconnect called but no device connected");const e=this.deviceId;this.connLogger.info("Disconnecting from device:",e);try{yield this.adapter.disconnect(e),this.deviceId=null,this.state=a.P.DISCONNECTED,this.emit("state-change",a.P.DISCONNECTED),this.emit("disconnected",e),this.connLogger.info("Disconnected successfully")}catch(t){const e=new a.B(a.n.DEVICE_DISCONNECTED,"Disconnect failed",a.o(t));throw this.connLogger.error("Disconnect failed:",e),this.emit("error",e),e}})}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.checkHeartbeat()},this.config.heartbeatInterval),this.connLogger.debug("Heartbeat started with interval:",this.config.heartbeatInterval)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.connLogger.debug("Heartbeat stopped"))}checkHeartbeat(){if(this.deviceId&&this.state===a.P.CONNECTED)try{this.isConnected()?this.connLogger.debug("Heartbeat OK"):this.handleHeartbeatLost()}catch(e){this.connLogger.warn("Heartbeat check failed:",e),this.handleHeartbeatLost()}}handleHeartbeatLost(){this.deviceId&&(this.connLogger.warn("Heartbeat lost for device:",this.deviceId),this.emit("heartbeat-lost",this.deviceId),this.stopHeartbeat(),this.state=a.P.DISCONNECTED,this.emit("state-change",a.P.DISCONNECTED),this.emit("disconnected",this.deviceId),this.config.autoReconnect&&!this.isReconnecting&&this.startReconnect())}startReconnect(){this.deviceId&&!this.isReconnecting&&(this.isReconnecting=!0,this.reconnectAttempts=0,this.attemptReconnect())}attemptReconnect(){return o(this,null,function*(){if(!this.deviceId)return void(this.isReconnecting=!1);this.reconnectAttempts++;const e=this.deviceId;if(this.reconnectAttempts>this.config.maxReconnectAttempts)return this.connLogger.error("Max reconnect attempts reached"),this.isReconnecting=!1,this.emit("reconnect-failed",{deviceId:e,error:new a.B(a.n.CONNECTION_FAILED,`Reconnection failed after ${this.config.maxReconnectAttempts} attempts`)}),void(this.deviceId=null);this.connLogger.info(`Reconnect attempt ${this.reconnectAttempts}/${this.config.maxReconnectAttempts}`),this.emit("reconnecting",{deviceId:e,attempt:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}),this.state=a.P.CONNECTING,this.emit("state-change",a.P.CONNECTING);try{yield this.adapter.connect(e),this.connLogger.info("Reconnected successfully"),this.isReconnecting=!1,this.reconnectAttempts=0,this.state=a.P.CONNECTED,this.emit("state-change",a.P.CONNECTED),this.emit("reconnected",e),this.config.heartbeatEnabled&&this.startHeartbeat()}catch(t){this.connLogger.warn(`Reconnect attempt ${this.reconnectAttempts} failed:`,t);const e=this.config.reconnectInterval,n=Math.min(e*Math.pow(2,this.reconnectAttempts-1),3e4);this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},n)}})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}isConnected(){return this.state===a.P.CONNECTED}getDeviceId(){return this.deviceId}getState(){return this.state}getAdapter(){return this.adapter}getConfig(){return r({},this.config)}getReconnectStatus(){return{isReconnecting:this.isReconnecting,attempts:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}}reconnect(){if(!this.deviceId)throw new a.B(a.n.DEVICE_NOT_FOUND,"No device to reconnect to");this.isReconnecting?this.connLogger.warn("Reconnect already in progress"):this.startReconnect()}stopReconnect(){this.clearReconnectTimer(),this.isReconnecting=!1,this.reconnectAttempts=0,this.connLogger.info("Reconnect stopped")}destroy(){this.stopHeartbeat(),this.clearReconnectTimer(),this.removeAllListeners(),this.deviceId=null,this.state=a.P.DISCONNECTED}}const g=class e{constructor(e){this.instanceJobStateStore=new Map,this.jobBuffer=null,this.jobOffset=0,this.paused=!1,this.inProgress=!1,this.adapterOptions={},this.jobId=null,this.logger=a.L.scope("PrintJobManager"),this.connectionManager=e,this.adapter="function"==typeof e.getAdapter?e.getAdapter():{connect:()=>Promise.resolve(),disconnect:()=>Promise.resolve(),write:()=>{throw new a.B(a.n.INVALID_CONFIGURATION,"No adapter available for print job write")}}}setProgressCallback(e){this.onProgress=e}setJobStateCallback(e){this.onJobStateChange=e}wrapError(e,t,n){return e instanceof a.B?e:new a.B(t,n,a.o(e))}start(e,t){return o(this,null,function*(){var n;if(this.inProgress)throw new a.B(a.n.PRINT_JOB_IN_PROGRESS,"A print job is already in progress. Wait for completion or cancel it.");this.jobId=null!=(n=null==t?void 0:t.jobId)?n:this.generateJobId(),this.jobBuffer=e,this.jobOffset=0,this.paused=!1,this.inProgress=!0,this.logger.info(`Starting print job ${this.jobId}: ${e.length} bytes`),this.emitJobState("in-progress");try{yield this.processJob(),this.paused?(this.logger.info(`Print job ${this.jobId} paused`),this.saveJobState()):this.completeJob()}catch(i){throw this.logger.error(`Print job ${this.jobId} failed:`,i),this.inProgress=!1,this.paused?this.saveJobState():this.clearJobState(),this.wrapError(i,a.n.PRINT_JOB_FAILED,"Print job failed")}})}resume(e){return o(this,null,function*(){if(!this.inProgress||!this.paused){if(!e)return void this.logger.warn("Resume called but no paused print job");this.loadJobState(e)}this.paused=!1,this.logger.info("Resuming print job "+this.jobId),this.emitJobState("in-progress");try{yield this.processJob(),this.paused||this.completeJob()}catch(t){throw this.logger.error(`Print job ${this.jobId} failed after resume:`,t),this.inProgress=!1,this.clearJobState(),this.emitJobState("cancelled"),this.wrapError(t,a.n.PRINT_JOB_FAILED,"Print job failed")}})}cancel(){this.inProgress?(this.logger.info("Cancelling print job "+this.jobId),this.paused=!1,this.inProgress=!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")}pause(){this.inProgress?(this.paused=!0,this.logger.info("Print job paused")):this.logger.warn("Pause called but no print job in progress")}isPaused(){return this.paused}isInProgress(){return this.inProgress}remaining(){return this.jobBuffer?this.jobBuffer.length-this.jobOffset:0}setOptions(e){this.adapterOptions=r(r({},this.adapterOptions),e),this.logger.debug("Adapter options updated:",this.adapterOptions)}destroy(){this.cancel(),this.instanceJobStateStore.clear(),this.onProgress=void 0,this.onJobStateChange=void 0,this.logger.info("PrintJobManager destroyed")}generateJobId(){return`job-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}saveJobState(){if(this.jobBuffer&&this.jobId)try{const t={jobId:this.jobId,jobBuffer:Array.from(this.jobBuffer),jobOffset:this.jobOffset,adapterOptions:r({},this.adapterOptions),timestamp:Date.now()};this.instanceJobStateStore.set(this.jobId,t),e.staticJobStateStore.set(this.jobId,t),e.ensureCleanupTimer(),this.logger.debug(`Saved job state for ${this.jobId}: offset=${this.jobOffset}/${this.jobBuffer.length}`)}catch(t){this.logger.error(`Failed to save job state for ${this.jobId}:`,t)}}loadJobState(t){var n;try{this.logger.debug("Loading job state for "+t);const i=null!=(n=this.instanceJobStateStore.get(t))?n:e.staticJobStateStore.get(t);if(!i)throw new a.B(a.n.QUEUE_JOB_NOT_FOUND,"Job state not found for "+t);this.jobId=i.jobId,this.jobBuffer=new Uint8Array(i.jobBuffer),this.jobOffset=i.jobOffset,this.adapterOptions=r({},i.adapterOptions),this.paused=!0,this.inProgress=!0,this.logger.info(`Loaded job ${this.jobId}: offset=${this.jobOffset}/${this.jobBuffer.length}`)}catch(i){throw this.logger.error(`Failed to load job state for ${t}:`,i),new a.B(a.n.PRINT_JOB_FAILED,"Failed to load job "+t,a.o(i))}}clearJobState(){this.jobId&&(this.logger.debug("Clearing job state for "+this.jobId),this.instanceJobStateStore.delete(this.jobId),e.staticJobStateStore.delete(this.jobId)),this.jobBuffer=null,this.jobOffset=0,this.jobId=null,this.adapterOptions={}}static ensureCleanupTimer(){e.cleanupTimer||(e.cleanupTimer=setInterval(()=>{e.cleanupExpiredJobs()},3e5),"function"==typeof e.cleanupTimer.unref&&e.cleanupTimer.unref())}static cleanupExpiredJobs(t=36e5){const n=Date.now();let i=0;for(const[s,r]of e.staticJobStateStore.entries())n-r.timestamp>t&&(e.staticJobStateStore.delete(s),i++);return 0===e.staticJobStateStore.size&&e.cleanupTimer&&(clearInterval(e.cleanupTimer),e.cleanupTimer=null),i}static stopCleanupTimer(){e.cleanupTimer&&(clearInterval(e.cleanupTimer),e.cleanupTimer=null)}static getStaticStoreSize(){return e.staticJobStateStore.size}completeJob(){this.logger.info(`Print job ${this.jobId} completed successfully`),this.inProgress=!1,this.clearJobState(),this.emitJobState("completed")}emitJobState(e){var t;null==(t=this.onJobStateChange)||t.call(this,e)}processJob(){return o(this,null,function*(){var e;if(!this.jobBuffer||"function"!=typeof this.adapter.write)throw new a.B(a.n.INVALID_CONFIGURATION,"Printer adapter does not support write operation");const{chunkSize:t=512}=this.adapterOptions,n=this.jobBuffer,i=n.length,s=this.getDeviceId();for(;this.jobOffset<n.length;){if(this.paused)return void this.logger.debug("Job paused at offset:",this.jobOffset);const r=Math.min(this.jobOffset+t,n.length),o=n.slice(this.jobOffset,r);yield this.adapter.write(s,o.buffer,this.adapterOptions),this.jobOffset=r,this.logger.debug(`Processed ${this.jobOffset}/${i} bytes`),null==(e=this.onProgress)||e.call(this,this.jobOffset,i)}})}getDeviceId(){const e=this.connectionManager.getDeviceId();if(!e)throw new a.B(a.n.DEVICE_DISCONNECTED,"Device ID not available");return e}};g.staticJobStateStore=new Map,g.cleanupTimer=null;let p=g;var m=(e=>(e.LEFT="left",e.CENTER="center",e.RIGHT="right",e))(m||{});const f={align:"left",widthScale:1,heightScale:1,bold:!1,underline:!1,inverse:!1},b=27,C=29;class I{constructor(){this.currentStyle=r({},f)}setStyle(e){var t,n;const i=[];if(void 0!==e.align&&e.align!==this.currentStyle.align){const t=this.getAlignValue(e.align);i.push(new Uint8Array([b,97,t])),this.currentStyle.align=e.align}const s=this.clampScale(null!=(t=e.widthScale)?t:this.currentStyle.widthScale),r=this.clampScale(null!=(n=e.heightScale)?n:this.currentStyle.heightScale);if(s!==this.currentStyle.widthScale||r!==this.currentStyle.heightScale){const e=s-1<<4|r-1;i.push(new Uint8Array([C,33,e])),this.currentStyle.widthScale=s,this.currentStyle.heightScale=r}return void 0!==e.bold&&e.bold!==this.currentStyle.bold&&(i.push(new Uint8Array([b,69,e.bold?1:0])),this.currentStyle.bold=e.bold),void 0!==e.underline&&e.underline!==this.currentStyle.underline&&(i.push(new Uint8Array([b,45,e.underline?1:0])),this.currentStyle.underline=e.underline),void 0!==e.inverse&&e.inverse!==this.currentStyle.inverse&&(i.push(new Uint8Array([C,66,e.inverse?1:0])),this.currentStyle.inverse=e.inverse),i}resetStyle(){const e=[];return"left"!==this.currentStyle.align&&e.push(new Uint8Array([b,97,0])),1===this.currentStyle.widthScale&&1===this.currentStyle.heightScale||e.push(new Uint8Array([C,33,0])),this.currentStyle.bold&&e.push(new Uint8Array([b,69,0])),this.currentStyle.underline&&e.push(new Uint8Array([b,45,0])),this.currentStyle.inverse&&e.push(new Uint8Array([C,66,0])),this.currentStyle=r({},f),e}format(e,t){if(!e||"string"!=typeof e)return[];const n=[];return t&&n.push(...this.setStyle(t)),n}align(e){const t=this.getAlignValue(e);return this.currentStyle.align=e,[new Uint8Array([b,97,t])]}setSize(e,t){const n=this.clampScale(e),i=this.clampScale(t),s=n-1<<4|i-1;return this.currentStyle.widthScale=n,this.currentStyle.heightScale=i,[new Uint8Array([C,33,s])]}setBold(e){return this.currentStyle.bold=e,[new Uint8Array([b,69,e?1:0])]}setUnderline(e){return this.currentStyle.underline=e,[new Uint8Array([b,45,e?1:0])]}setInverse(e){return this.currentStyle.inverse=e,[new Uint8Array([C,66,e?1:0])]}getCurrentStyle(){return r({},this.currentStyle)}getAlignValue(e){switch(e){case"left":default:return 0;case"center":return 1;case"right":return 2}}clampScale(e){return Math.max(1,Math.min(8,Math.floor(e)))}}var E=(e=>(e.CODE128="CODE128",e.CODE39="CODE39",e.EAN13="EAN13",e.EAN8="EAN8",e.UPCA="UPCA",e.ITF="ITF",e.CODABAR="CODABAR",e.QR_CODE="QR_CODE",e.PDF417="PDF417",e))(E||{});const v=29,S={UPCA:65,EAN13:67,EAN8:68,CODE39:69,ITF:70,CODABAR:71,CODE128:73,QR_CODE:80,PDF417:81},A={L:48,M:49,Q:50,H:51},y={1:49,2:50},D={none:0,above:1,below:2,both:3},N={0:48,1:49,2:50,3:51};class w{generate(e,t){return this.validate(e,t.format).valid?"QR_CODE"===t.format?this.generateQRCode(e,t):"PDF417"===t.format?this.generatePDF417(e,t):this.generate1DBarcode(e,t):[]}generate1DBarcode(e,t){var n,i;const s=[],r=this.clampHeight(null!=(n=t.height)?n:80);s.push(new Uint8Array([v,104,r]));const o=this.clampWidth(null!=(i=t.width)?i:3);s.push(new Uint8Array([v,119,o]));const a=this.getTextPosition(t);s.push(new Uint8Array([v,72,a]));const h=S[t.format],c=this.encodeContent(e,t.format);return s.push(new Uint8Array([v,107,h,c.length,...c])),s}generateQRCode(e,t){var n,i,s,r,o;const a=[],h=null!=(n=t.qrModel)?n:2,c=this.clampQRSize(null!=(i=t.height)?i:6),l=null!=(s=t.errorCorrection)?s:"M",d=null!=(r=y[h])?r:50;a.push(new Uint8Array([v,40,107,4,0,49,65,80,d])),a.push(new Uint8Array([v,40,107,3,0,49,67,c]));const u=null!=(o=A[l])?o:49;a.push(new Uint8Array([v,40,107,3,0,49,69,u]));const g=this.encodeUTF8(e),p=g.length+3;return a.push(new Uint8Array([v,40,107,255&p,p>>8&255,49,80,48,...g])),a.push(new Uint8Array([v,40,107,3,0,49,81,48])),a}generatePDF417(e,t){var n,i,s,r;const o=[],a=null!=(n=t.pdf417Compression)?n:2,h=null!=(i=t.pdf417Security)?i:2,c=this.clampPDF417Columns(null!=(s=t.pdf417Columns)?s:2);o.push(new Uint8Array([v,40,107,7,0,49,48,c,h,0,0]));const l=null!=(r=N[a])?r:50;o.push(new Uint8Array([27,93,4,l]));const d=this.encodeUTF8(e),u=d.length+3;return o.push(new Uint8Array([v,107,81,255&u,u>>8&255,...d])),o.push(new Uint8Array([v,40,107,3,0,49,81,49])),o}validate(e,t){const n=[];if(null==e)return n.push({field:"content",message:"Barcode content is required",code:"REQUIRED"}),{valid:!1,errors:n};if("string"!=typeof e)return n.push({field:"content",message:"Barcode content must be a string",code:"INVALID_TYPE"}),{valid:!1,errors:n};if(0===e.length)return n.push({field:"content",message:"Barcode content cannot be empty",code:"REQUIRED"}),{valid:!1,errors:n};switch("QR_CODE"===t&&e.length>7089&&n.push({field:"content",message:"QR code content exceeds maximum length (7089 bytes for binary mode)",code:"CONTENT_TOO_LONG"}),"PDF417"===t&&e.length>1850&&n.push({field:"content",message:"PDF417 content exceeds maximum length (~1850 bytes)",code:"CONTENT_TOO_LONG"}),t){case"EAN13":this.validateEAN13(e,n);break;case"EAN8":this.validateEAN8(e,n);break;case"UPCA":this.validateUPCA(e,n);break;case"CODE39":this.validateCode39(e,n);break;case"CODE128":this.validateCode128(e,n);break;case"ITF":this.validateITF(e,n);break;case"CODABAR":this.validateCodabar(e,n);break;case"QR_CODE":this.validateQRCode(e,n);break;case"PDF417":this.validatePDF417(e,n);break;default:n.push({field:"format",message:"Unsupported barcode format: "+t,code:"UNSUPPORTED_FORMAT"})}return{valid:0===n.length,errors:n}}validateQRCode(e,t){0===e.length&&t.push({field:"content",message:"QR code content cannot be empty",code:"REQUIRED"}),e.length>7089&&t.push({field:"content",message:"QR code content exceeds maximum binary mode length",code:"CONTENT_TOO_LONG"})}validatePDF417(e,t){0===e.length&&t.push({field:"content",message:"PDF417 content cannot be empty",code:"REQUIRED"}),e.length>1850&&t.push({field:"content",message:"PDF417 content exceeds maximum length",code:"CONTENT_TOO_LONG"});let n=!1;for(let i=0;i<e.length;i++)if(e.charCodeAt(i)>127){n=!0;break}n&&t.push({field:"content",message:"PDF417 standard mode only supports ASCII characters. Consider using compression mode.",code:"INVALID_CHARACTERS"})}getSupportedFormats(){return Object.values(E)}validateEAN13(e,t){if(/^\d{12,13}$/.test(e)){if(13===e.length){const n=this.calculateEANCheckDigit(e.substring(0,12)),i=e[12];void 0!==i&&parseInt(i)!==n&&t.push({field:"content",message:"Invalid EAN-13 check digit",code:"INVALID_CHECK_DIGIT"})}}else t.push({field:"content",message:"EAN-13 must be 12 or 13 digits",code:"INVALID_LENGTH"})}validateEAN8(e,t){if(/^\d{7,8}$/.test(e)){if(8===e.length){const n=this.calculateEANCheckDigit(e.substring(0,7)),i=e[7];void 0!==i&&parseInt(i)!==n&&t.push({field:"content",message:"Invalid EAN-8 check digit",code:"INVALID_CHECK_DIGIT"})}}else t.push({field:"content",message:"EAN-8 must be 7 or 8 digits",code:"INVALID_LENGTH"})}validateUPCA(e,t){if(/^\d{11,12}$/.test(e)){if(12===e.length){const n=this.calculateUPCACheckDigit(e.substring(0,11)),i=e[11];void 0!==i&&parseInt(i)!==n&&t.push({field:"content",message:"Invalid UPC-A check digit",code:"INVALID_CHECK_DIGIT"})}}else t.push({field:"content",message:"UPC-A must be 11 or 12 digits",code:"INVALID_LENGTH"})}validateCode39(e,t){/^[0-9A-Z\s\-.$/+%]+$/.test(e.toUpperCase())||t.push({field:"content",message:"Code 39 only supports: 0-9, A-Z, space, - . $ / + %",code:"INVALID_CHARACTERS"}),(0===e.length||e.length>255)&&t.push({field:"content",message:"Code 39 content must be 1-255 characters",code:"INVALID_LENGTH"})}validateCode128(e,t){for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>127){t.push({field:"content",message:"Code 128 only supports ASCII characters (0-127)",code:"INVALID_CHARACTERS"});break}(0===e.length||e.length>255)&&t.push({field:"content",message:"Code 128 content must be 1-255 characters",code:"INVALID_LENGTH"})}validateITF(e,t){/^\d+$/.test(e)||t.push({field:"content",message:"ITF only supports numeric characters",code:"INVALID_CHARACTERS"}),e.length%2!=0&&t.push({field:"content",message:"ITF content must have even number of digits",code:"INVALID_LENGTH"}),(0===e.length||e.length>255)&&t.push({field:"content",message:"ITF content must be 2-254 digits (even)",code:"INVALID_LENGTH"})}validateCodabar(e,t){/^[ABCDabcd][0-9\-$:/.+]+[ABCDabcd]$/.test(e)||t.push({field:"content",message:"CODABAR must start and end with A/B/C/D and contain only 0-9, - $ : / . +",code:"INVALID_FORMAT"}),(3>e.length||e.length>255)&&t.push({field:"content",message:"CODABAR content must be 3-255 characters",code:"INVALID_LENGTH"})}calculateEANCheckDigit(e){let t=0;const n=e.length;for(let i=0;n>i;i++){const n=e[i];void 0!==n&&(t+=parseInt(n)*(i%2==0?1:3))}return(10-t%10)%10}calculateUPCACheckDigit(e){let t=0;for(let n=0;11>n;n++){const i=e[n];void 0!==i&&(t+=parseInt(i)*(n%2==0?3:1))}return(10-t%10)%10}encodeContent(e,t){return"CODE128"===t?[123,/^\d+$/.test(e)&&e.length>=4?67:66,...e.split("").map(e=>e.charCodeAt(0))]:e.split("").map(e=>e.charCodeAt(0))}encodeUTF8(e){const t=[];for(let n=0;n<e.length;n++){const i=e.charCodeAt(n);128>i?t.push(i):2048>i?(t.push(192|i>>6),t.push(128|63&i)):65536>i?(t.push(224|i>>12),t.push(128|i>>6&63),t.push(128|63&i)):(t.push(240|i>>18),t.push(128|i>>12&63),t.push(128|i>>6&63),t.push(128|63&i))}return t}getTextPosition(e){var t,n,i;if(!1===e.showText)return D.none;const s=null!=(t=e.textPosition)?t:"below";return null!=(i=null!=(n=D[s])?n:D.below)?i:2}clampHeight(e){return Math.max(1,Math.min(255,Math.floor(e)))}clampWidth(e){return Math.max(2,Math.min(6,Math.floor(e)))}clampQRSize(e){return Math.max(1,Math.min(16,Math.floor(e)))}clampPDF417Columns(e){return Math.max(1,Math.min(30,Math.floor(e)))}}class O{constructor(e){this.logger=a.L.scope("CommandBuilder"),this.buffer=[],this.cachedBuffer=null,this.driver=null!=e?e:new c.E,this.formatter=new I,this.barcodeGenerator=new w,this.buffer.push(...this.driver.init())}pushCommands(e){e.length>0&&(this.buffer.push(...e),this.cachedBuffer=null)}text(e,t){return this.logger.debug("Adding text:",e.substring(0,50)),this.pushCommands(this.driver.text(e,t)),this}feed(e=1){return this.logger.debug("Adding feed:",e),this.pushCommands(this.driver.feed(e)),this}cut(){return this.logger.debug("Adding cut command"),this.pushCommands(this.driver.cut()),this}image(e,t,n){return this.logger.debug(`Adding image: ${t}x${n}`),this.pushCommands(this.driver.image(e,t,n)),this}qr(e,t){return this.logger.debug("Adding QR code:",e.substring(0,50)),this.pushCommands(this.driver.qr(e,t)),this}clear(){return this.buffer=[],this.pushCommands(this.driver.init()),this}align(e){return this.logger.debug("Setting alignment:",e),this.pushCommands(this.formatter.align(e)),this}setSize(e,t){return this.logger.debug(`Setting size: ${e}x${t}`),this.pushCommands(this.formatter.setSize(e,t)),this}setBold(e){return this.logger.debug("Setting bold:",e),this.pushCommands(this.formatter.setBold(e)),this}setUnderline(e){return this.logger.debug("Setting underline:",e),this.pushCommands(this.formatter.setUnderline(e)),this}setInverse(e){return this.logger.debug("Setting inverse:",e),this.pushCommands(this.formatter.setInverse(e)),this}setStyle(e){return this.logger.debug("Setting style:",e),this.pushCommands(this.formatter.setStyle(e)),this}resetStyle(){return this.logger.debug("Resetting style"),this.pushCommands(this.formatter.resetStyle()),this}barcode(e,t){this.logger.debug(`Adding barcode: ${e} (${t.format})`);const n=this.barcodeGenerator.generate(e,t);return n.length>0?this.pushCommands(n):this.logger.warn("Failed to generate barcode for content: "+e),this}getBuffer(){if(this.cachedBuffer)return this.cachedBuffer;const e=this.buffer.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e);let n=0;for(const i of this.buffer)t.set(i,n),n+=i.length;return this.cachedBuffer=t,t}getTotalBytes(){return this.buffer.reduce((e,t)=>e+t.length,0)}}exports.B=class extends l{constructor(e,t,n){super(),this.printerLogger=a.L.scope("BluetoothPrinter"),this.state=a.P.DISCONNECTED,this.connectionManager=this.resolveConnectionManager(e),this.printJobManager=null!=t?t:new p(this.connectionManager),this.commandBuilder=null!=n?n:new O,this.updateState()}resolveConnectionManager(e){return e?"function"==typeof e.getState?e:new u(e):new u}handleError(e,t,n){const i=e instanceof a.B?e:new a.B(t,n,a.o(e));return this.emit("error",i),this.updateState(),i}updateState(){this.printJobManager.isPaused()?this.state=a.P.PAUSED:this.printJobManager.isInProgress()?this.state=a.P.PRINTING:this.state=this.connectionManager.getState(),this.emit("state-change",this.state),this.printerLogger.debug("State updated:",this.state)}connect(e){return o(this,null,function*(){this.printerLogger.info("Connecting to device:",e);try{return yield this.connectionManager.connect(e),this.updateState(),this.emit("connected",e),this.printerLogger.info("Connected successfully"),this}catch(t){throw this.handleError(t,a.n.CONNECTION_FAILED,"Connection failed")}})}disconnect(){return o(this,null,function*(){const e=this.connectionManager.getDeviceId();if(e){this.printerLogger.info("Disconnecting from device:",e);try{yield this.connectionManager.disconnect(),this.printJobManager.cancel(),this.updateState(),this.emit("disconnected",e),this.printerLogger.info("Disconnected successfully")}catch(t){throw this.handleError(t,a.n.DEVICE_DISCONNECTED,"Disconnect failed")}}else this.printerLogger.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,n){return this.commandBuilder.image(e,t,n),this}qr(e,t){return this.commandBuilder.qr(e,t),this}align(e){return this.commandBuilder.align(e),this}setSize(e,t){return this.commandBuilder.setSize(e,t),this}setBold(e){return this.commandBuilder.setBold(e),this}setUnderline(e){return this.commandBuilder.setUnderline(e),this}resetStyle(){return this.commandBuilder.resetStyle(),this}barcode(e,t,n){return this.commandBuilder.barcode(e,r({format:t},n)),this}setOptions(e){return this.printJobManager.setOptions(e),this}writeRaw(e,t){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new a.B(a.n.CONNECTION_FAILED,"Printer not connected. Call connect() first.");this.printerLogger.info(`writeRaw: ${e.length} bytes`),t&&this.printJobManager.setOptions(t),this.updateState(),this.printJobManager.setProgressCallback((e,t)=>{this.emit("progress",{sent:e,total:t})});const n=Date.now();try{yield this.printJobManager.start(e),this.printJobManager.isPaused()||(this.emit("print-complete"),this.emit("job-completed",{source:"writeRaw",bytes:e.length,completedAt:Date.now(),durationMs:Date.now()-n}))}catch(i){const t=this.handleError(i,a.n.PRINT_JOB_FAILED,"writeRaw failed");throw this.emit("job-failed",{source:"writeRaw",bytes:e.length,completedAt:Date.now(),durationMs:Date.now()-n,error:t}),t}finally{this.updateState()}})}pause(){this.printJobManager.pause(),this.updateState(),this.printerLogger.info("Print job paused")}resume(){return o(this,null,function*(){this.printerLogger.info("Resuming print job");try{yield this.printJobManager.resume(),this.updateState(),this.printerLogger.info("Print job resumed")}catch(e){throw this.handleError(e,a.n.PRINT_JOB_FAILED,"Failed to resume print job")}})}cancel(){this.printJobManager.cancel(),this.commandBuilder.clear(),this.updateState(),this.printerLogger.info("Print job cancelled")}remaining(){return this.printJobManager.remaining()}print(){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new a.B(a.n.CONNECTION_FAILED,"Printer not connected. Call connect() first.");const e=this.commandBuilder.getBuffer();this.printerLogger.info(`Starting print job: ${e.length} bytes`),this.commandBuilder.clear(),this.updateState(),this.printJobManager.setProgressCallback((e,t)=>{this.emit("progress",{sent:e,total:t})});const t=Date.now();try{yield this.printJobManager.start(e),this.printJobManager.isPaused()?this.printerLogger.info("Print job paused"):(this.emit("print-complete"),this.emit("job-completed",{source:"print",bytes:e.length,completedAt:Date.now(),durationMs:Date.now()-t}),this.printerLogger.info("Print job completed successfully"))}catch(n){this.printerLogger.error("Print job failed with error:",n);const i=this.handleError(n,a.n.PRINT_JOB_FAILED,"Print job failed");throw this.emit("job-failed",{source:"print",bytes:e.length,completedAt:Date.now(),durationMs:Date.now()-t,error:i}),i}finally{this.updateState()}})}getConnectionManager(){return this.connectionManager}getCommandBuilder(){return this.commandBuilder}destroy(){this.printerLogger.info("Destroying BluetoothPrinter instance"),this.printJobManager.cancel(),this.commandBuilder.clear(),this.connectionManager.isConnected()&&this.connectionManager.disconnect().catch(e=>{this.printerLogger.warn("Error during disconnect in destroy:",e)}),this.connectionManager.destroy(),this.removeAllListeners(),this.printerLogger.info("BluetoothPrinter instance destroyed")}},exports.C=u,exports.E=l,exports.P=p,exports.T=I,exports.a=w,exports.b=m,exports.c=E,exports.d=O;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t=Object.defineProperty,e=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,s=(e,n,i)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i,r=(t,r)=>{for(var o in r||(r={}))n.call(r,o)&&s(t,o,r[o]);if(e)for(var o of e(r))i.call(r,o)&&s(t,o,r[o]);return t},o=(t,e,n)=>new Promise((i,s)=>{var r=t=>{try{a(n.next(t))}catch(e){s(e)}},o=t=>{try{a(n.throw(t))}catch(e){s(e)}},a=t=>t.done?i(t.value):Promise.resolve(t.value).then(r,o);a((n=n.apply(t,e)).next())});import{L as a,P as h,w as c,B as l,o as d,n as u}from"./shared-C7eA759x.js";import{A as g}from"./AdapterFactory-CkjGKGZN.js";import{E as p}from"./EscPosDriver-ju4j3bXJ.js";class m{constructor(){this.listeners={},this.debugMode=!1,this.logger=a.scope("EventEmitter")}ensureListeners(t){return this.listeners[t]||(this.listeners[t]=/* @__PURE__ */new Set),this.listeners[t]}on(t,e){return this.ensureListeners(t).add(e),this.debugMode&&this.logger.debug(`EventEmitter: Added listener for "${t+""}"`,{listenerCount:this.listenerCount(t)}),()=>this.off(t,e)}once(t,e){const n=this.wrapOnceHandler(t,e);return this.on(t,n)}prepend(t,e){const n=this.ensureListeners(t),i=/* @__PURE__ */new Set;return i.add(e),n.forEach(t=>i.add(t)),this.listeners[t]=i,this.debugMode&&this.logger.debug(`EventEmitter: Prepend listener for "${t+""}"`,{listenerCount:this.listenerCount(t)}),()=>this.off(t,e)}prependOnce(t,e){const n=this.wrapOnceHandler(t,e);return this.prepend(t,n)}wrapOnceHandler(t,e){const n=i=>{e(i),this.off(t,n)};return n}off(t,e){const n=this.listeners[t];n&&(n.delete(e),this.debugMode&&this.logger.debug(`EventEmitter: Removed listener for "${t+""}"`,{listenerCount:n.size}),0===n.size&&(delete this.listeners[t],this.debugMode&&this.logger.debug(`EventEmitter: Removed event "${t+""}" (no more listeners)`)))}getHandlers(t){var e;return null!=(e=this.listeners[t])?e:/* @__PURE__ */new Set}emit(t,...e){const n=e[0],i=this.getHandlers(t);if(this.debugMode&&this.logger.debug(`EventEmitter: Emitting "${t+""}"`,{data:n,listenerCount:i.size}),0!==i.size)for(const r of i)if("function"==typeof r)try{r(n)}catch(s){this.logger.error(`Error in event handler for "${t+""}":`,s)}}emitAsync(t,...e){return o(this,null,function*(){const n=e[0],i=this.getHandlers(t);if(this.debugMode&&this.logger.debug(`EventEmitter: Emitting async "${t+""}"`,{data:n,listenerCount:i.size}),0===i.size)return;const s=[];i.forEach(e=>{s.push((()=>o(this,null,function*(){try{const t=e(n);null!=t&&"function"==typeof t.then&&(yield t)}catch(i){this.logger.error(`Error in event handler for "${t+""}":`,i)}}))())}),yield Promise.all(s),this.debugMode&&this.logger.debug(`EventEmitter: Finished emitting async "${t+""}"`)})}removeAllListeners(t){if(t){const e=this.listenerCount(t);delete this.listeners[t],this.debugMode&&this.logger.debug(`EventEmitter: Removed all ${e} listeners for "${t+""}"`)}else{const t=Object.keys(this.listeners).length;this.listeners={},this.debugMode&&this.logger.debug(`EventEmitter: Removed all ${t} events and their listeners`)}}listenerCount(t){var e,n;return null!=(n=null==(e=this.listeners[t])?void 0:e.size)?n:0}getListeners(t){const e=this.listeners[t];return e?Array.from(e):[]}eventNames(){return Object.keys(this.listeners)}hasListeners(t){return this.listenerCount(t)>0}setDebugMode(t){this.debugMode=t,this.logger.debug("EventEmitter: Debug mode "+(t?"enabled":"disabled"))}isDebugMode(){return this.debugMode}getTotalEvents(){return Object.keys(this.listeners).length}getTotalListeners(){var t,e;let n=0;for(const i of Object.keys(this.listeners))n+=null!=(e=null==(t=this.listeners[i])?void 0:t.size)?e:0;return n}reset(){this.removeAllListeners(),this.debugMode=!1}}const f={heartbeatEnabled:!0,heartbeatInterval:5e3,autoReconnect:!0,maxReconnectAttempts:3,reconnectInterval:2e3,connectionTimeout:1e4};class b extends m{constructor(t,e){var n,i;super(),this.deviceId=null,this.state=h.DISCONNECTED,this.connLogger=a.scope("ConnectionManager"),this.heartbeatTimer=null,this.reconnectAttempts=0,this.isReconnecting=!1,this.reconnectTimer=null,this.adapter=t||g.create(),this.config=r(r({},f),e),null==(i=(n=this.adapter).onStateChange)||i.call(n,t=>{this.handleStateChange(t)})}handleStateChange(t){const e=this.state;this.state=t,this.connLogger.debug("State changed:",{from:e,to:t}),this.emit("state-change",t),e===h.CONNECTED&&t===h.DISCONNECTED&&this.deviceId&&!this.isReconnecting&&(this.connLogger.warn("Unexpected disconnection detected"),this.emit("disconnected",this.deviceId),this.stopHeartbeat(),this.config.autoReconnect&&this.startReconnect())}connect(t,e){return o(this,null,function*(){this.connLogger.info("Connecting to device:",t);const{retries:n=0,timeout:i=this.config.connectionTimeout}=e||{};let s=0;for(this.reconnectAttempts=0,this.isReconnecting=!1,this.clearReconnectTimer();n>=s;)try{this.deviceId=t,this.state=h.CONNECTING,this.emit("state-change",h.CONNECTING);const e=this.adapter.connect(t);return yield c(e,i,`Connection to device ${t} timed out`),this.state=h.CONNECTED,this.emit("state-change",h.CONNECTED),this.emit("connected",t),this.connLogger.info("Connected successfully"),void(this.config.heartbeatEnabled&&this.startHeartbeat())}catch(r){if(s++,s>n){this.deviceId=null,this.state=h.DISCONNECTED,this.emit("state-change",h.DISCONNECTED);const e=this.classifyConnectError(r,t,s,i);throw this.connLogger.error("Connection failed:",e),this.emit("error",e),e}this.connLogger.warn(`Connection attempt ${s}/${n} failed, retrying...`,r),yield new Promise(t=>setTimeout(t,1e3))}})}classifyConnectError(t,e,n,i){if(t instanceof l)return t;const s=d(t).message.toLowerCase();return s.includes("timed out")||s.includes("timeout")?new l(u.CONNECTION_TIMEOUT,`Connection to device ${e} timed out after ${i}ms`):new l(u.CONNECTION_FAILED,`Connection failed after ${n} attempts`,d(t))}disconnect(){return o(this,null,function*(){if(this.stopHeartbeat(),this.clearReconnectTimer(),this.isReconnecting=!1,!this.deviceId)return void this.connLogger.warn("Disconnect called but no device connected");const t=this.deviceId;this.connLogger.info("Disconnecting from device:",t);try{yield this.adapter.disconnect(t),this.deviceId=null,this.state=h.DISCONNECTED,this.emit("state-change",h.DISCONNECTED),this.emit("disconnected",t),this.connLogger.info("Disconnected successfully")}catch(e){const t=new l(u.DEVICE_DISCONNECTED,"Disconnect failed",d(e));throw this.connLogger.error("Disconnect failed:",t),this.emit("error",t),t}})}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.checkHeartbeat()},this.config.heartbeatInterval),this.connLogger.debug("Heartbeat started with interval:",this.config.heartbeatInterval)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.connLogger.debug("Heartbeat stopped"))}checkHeartbeat(){if(this.deviceId&&this.state===h.CONNECTED)try{this.isConnected()?this.connLogger.debug("Heartbeat OK"):this.handleHeartbeatLost()}catch(t){this.connLogger.warn("Heartbeat check failed:",t),this.handleHeartbeatLost()}}handleHeartbeatLost(){this.deviceId&&(this.connLogger.warn("Heartbeat lost for device:",this.deviceId),this.emit("heartbeat-lost",this.deviceId),this.stopHeartbeat(),this.state=h.DISCONNECTED,this.emit("state-change",h.DISCONNECTED),this.emit("disconnected",this.deviceId),this.config.autoReconnect&&!this.isReconnecting&&this.startReconnect())}startReconnect(){this.deviceId&&!this.isReconnecting&&(this.isReconnecting=!0,this.reconnectAttempts=0,this.attemptReconnect())}attemptReconnect(){return o(this,null,function*(){if(!this.deviceId)return void(this.isReconnecting=!1);this.reconnectAttempts++;const t=this.deviceId;if(this.reconnectAttempts>this.config.maxReconnectAttempts)return this.connLogger.error("Max reconnect attempts reached"),this.isReconnecting=!1,this.emit("reconnect-failed",{deviceId:t,error:new l(u.CONNECTION_FAILED,`Reconnection failed after ${this.config.maxReconnectAttempts} attempts`)}),void(this.deviceId=null);this.connLogger.info(`Reconnect attempt ${this.reconnectAttempts}/${this.config.maxReconnectAttempts}`),this.emit("reconnecting",{deviceId:t,attempt:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}),this.state=h.CONNECTING,this.emit("state-change",h.CONNECTING);try{yield this.adapter.connect(t),this.connLogger.info("Reconnected successfully"),this.isReconnecting=!1,this.reconnectAttempts=0,this.state=h.CONNECTED,this.emit("state-change",h.CONNECTED),this.emit("reconnected",t),this.config.heartbeatEnabled&&this.startHeartbeat()}catch(e){this.connLogger.warn(`Reconnect attempt ${this.reconnectAttempts} failed:`,e);const t=this.config.reconnectInterval,n=Math.min(t*Math.pow(2,this.reconnectAttempts-1),3e4);this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},n)}})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}isConnected(){return this.state===h.CONNECTED}getDeviceId(){return this.deviceId}getState(){return this.state}getAdapter(){return this.adapter}getConfig(){return r({},this.config)}getReconnectStatus(){return{isReconnecting:this.isReconnecting,attempts:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}}reconnect(){if(!this.deviceId)throw new l(u.DEVICE_NOT_FOUND,"No device to reconnect to");this.isReconnecting?this.connLogger.warn("Reconnect already in progress"):this.startReconnect()}stopReconnect(){this.clearReconnectTimer(),this.isReconnecting=!1,this.reconnectAttempts=0,this.connLogger.info("Reconnect stopped")}destroy(){this.stopHeartbeat(),this.clearReconnectTimer(),this.removeAllListeners(),this.deviceId=null,this.state=h.DISCONNECTED}}const C=class t{constructor(t){this.instanceJobStateStore=/* @__PURE__ */new Map,this.jobBuffer=null,this.jobOffset=0,this.paused=!1,this.inProgress=!1,this.adapterOptions={},this.jobId=null,this.logger=a.scope("PrintJobManager"),this.connectionManager=t,this.adapter="function"==typeof t.getAdapter?t.getAdapter():{connect:()=>Promise.resolve(),disconnect:()=>Promise.resolve(),write:()=>{throw new l(u.INVALID_CONFIGURATION,"No adapter available for print job write")}}}setProgressCallback(t){this.onProgress=t}setJobStateCallback(t){this.onJobStateChange=t}wrapError(t,e,n){return t instanceof l?t:new l(e,n,d(t))}start(t,e){return o(this,null,function*(){var n;if(this.inProgress)throw new l(u.PRINT_JOB_IN_PROGRESS,"A print job is already in progress. Wait for completion or cancel it.");this.jobId=null!=(n=null==e?void 0:e.jobId)?n:this.generateJobId(),this.jobBuffer=t,this.jobOffset=0,this.paused=!1,this.inProgress=!0,this.logger.info(`Starting print job ${this.jobId}: ${t.length} bytes`),this.emitJobState("in-progress");try{yield this.processJob(),this.paused?(this.logger.info(`Print job ${this.jobId} paused`),this.saveJobState()):this.completeJob()}catch(i){throw this.logger.error(`Print job ${this.jobId} failed:`,i),this.inProgress=!1,this.paused?this.saveJobState():this.clearJobState(),this.wrapError(i,u.PRINT_JOB_FAILED,"Print job failed")}})}resume(t){return o(this,null,function*(){if(!this.inProgress||!this.paused){if(!t)return void this.logger.warn("Resume called but no paused print job");this.loadJobState(t)}this.paused=!1,this.logger.info("Resuming print job "+this.jobId),this.emitJobState("in-progress");try{yield this.processJob(),this.paused||this.completeJob()}catch(e){throw this.logger.error(`Print job ${this.jobId} failed after resume:`,e),this.inProgress=!1,this.clearJobState(),this.emitJobState("cancelled"),this.wrapError(e,u.PRINT_JOB_FAILED,"Print job failed")}})}cancel(){this.inProgress?(this.logger.info("Cancelling print job "+this.jobId),this.paused=!1,this.inProgress=!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")}pause(){this.inProgress?(this.paused=!0,this.logger.info("Print job paused")):this.logger.warn("Pause called but no print job in progress")}isPaused(){return this.paused}isInProgress(){return this.inProgress}remaining(){return this.jobBuffer?this.jobBuffer.length-this.jobOffset:0}setOptions(t){this.adapterOptions=r(r({},this.adapterOptions),t),this.logger.debug("Adapter options updated:",this.adapterOptions)}destroy(){this.cancel(),this.instanceJobStateStore.clear(),this.onProgress=void 0,this.onJobStateChange=void 0,this.logger.info("PrintJobManager destroyed")}generateJobId(){return`job-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}saveJobState(){if(this.jobBuffer&&this.jobId)try{const e={jobId:this.jobId,jobBuffer:Array.from(this.jobBuffer),jobOffset:this.jobOffset,adapterOptions:r({},this.adapterOptions),timestamp:Date.now()};this.instanceJobStateStore.set(this.jobId,e),t.staticJobStateStore.set(this.jobId,e),t.ensureCleanupTimer(),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){var n;try{this.logger.debug("Loading job state for "+e);const i=null!=(n=this.instanceJobStateStore.get(e))?n:t.staticJobStateStore.get(e);if(!i)throw new l(u.QUEUE_JOB_NOT_FOUND,"Job state not found for "+e);this.jobId=i.jobId,this.jobBuffer=new Uint8Array(i.jobBuffer),this.jobOffset=i.jobOffset,this.adapterOptions=r({},i.adapterOptions),this.paused=!0,this.inProgress=!0,this.logger.info(`Loaded job ${this.jobId}: offset=${this.jobOffset}/${this.jobBuffer.length}`)}catch(i){throw this.logger.error(`Failed to load job state for ${e}:`,i),new l(u.PRINT_JOB_FAILED,"Failed to load job "+e,d(i))}}clearJobState(){this.jobId&&(this.logger.debug("Clearing job state for "+this.jobId),this.instanceJobStateStore.delete(this.jobId),t.staticJobStateStore.delete(this.jobId)),this.jobBuffer=null,this.jobOffset=0,this.jobId=null,this.adapterOptions={}}static ensureCleanupTimer(){t.cleanupTimer||(t.cleanupTimer=setInterval(()=>{t.cleanupExpiredJobs()},3e5),"function"==typeof t.cleanupTimer.unref&&t.cleanupTimer.unref())}static cleanupExpiredJobs(e=36e5){const n=Date.now();let i=0;for(const[s,r]of t.staticJobStateStore.entries())n-r.timestamp>e&&(t.staticJobStateStore.delete(s),i++);return 0===t.staticJobStateStore.size&&t.cleanupTimer&&(clearInterval(t.cleanupTimer),t.cleanupTimer=null),i}static stopCleanupTimer(){t.cleanupTimer&&(clearInterval(t.cleanupTimer),t.cleanupTimer=null)}static getStaticStoreSize(){return t.staticJobStateStore.size}completeJob(){this.logger.info(`Print job ${this.jobId} completed successfully`),this.inProgress=!1,this.clearJobState(),this.emitJobState("completed")}emitJobState(t){var e;null==(e=this.onJobStateChange)||e.call(this,t)}processJob(){return o(this,null,function*(){var t;if(!this.jobBuffer||"function"!=typeof this.adapter.write)throw new l(u.INVALID_CONFIGURATION,"Printer adapter does not support write operation");const{chunkSize:e=512}=this.adapterOptions,n=this.jobBuffer,i=n.length,s=this.getDeviceId();for(;this.jobOffset<n.length;){if(this.paused)return void this.logger.debug("Job paused at offset:",this.jobOffset);const r=Math.min(this.jobOffset+e,n.length),o=n.slice(this.jobOffset,r);yield this.adapter.write(s,o.buffer,this.adapterOptions),this.jobOffset=r,this.logger.debug(`Processed ${this.jobOffset}/${i} bytes`),null==(t=this.onProgress)||t.call(this,this.jobOffset,i)}})}getDeviceId(){const t=this.connectionManager.getDeviceId();if(!t)throw new l(u.DEVICE_DISCONNECTED,"Device ID not available");return t}};C.staticJobStateStore=/* @__PURE__ */new Map,C.cleanupTimer=null;let I=C;var E=/* @__PURE__ */(t=>(t.LEFT="left",t.CENTER="center",t.RIGHT="right",t))(E||{});const v={align:"left",widthScale:1,heightScale:1,bold:!1,underline:!1,inverse:!1},S=27,A=29;class y{constructor(){this.currentStyle=r({},v)}setStyle(t){var e,n;const i=[];if(void 0!==t.align&&t.align!==this.currentStyle.align){const e=this.getAlignValue(t.align);i.push(new Uint8Array([S,97,e])),this.currentStyle.align=t.align}const s=this.clampScale(null!=(e=t.widthScale)?e:this.currentStyle.widthScale),r=this.clampScale(null!=(n=t.heightScale)?n:this.currentStyle.heightScale);if(s!==this.currentStyle.widthScale||r!==this.currentStyle.heightScale){const t=s-1<<4|r-1;i.push(new Uint8Array([A,33,t])),this.currentStyle.widthScale=s,this.currentStyle.heightScale=r}return void 0!==t.bold&&t.bold!==this.currentStyle.bold&&(i.push(new Uint8Array([S,69,t.bold?1:0])),this.currentStyle.bold=t.bold),void 0!==t.underline&&t.underline!==this.currentStyle.underline&&(i.push(new Uint8Array([S,45,t.underline?1:0])),this.currentStyle.underline=t.underline),void 0!==t.inverse&&t.inverse!==this.currentStyle.inverse&&(i.push(new Uint8Array([A,66,t.inverse?1:0])),this.currentStyle.inverse=t.inverse),i}resetStyle(){const t=[];return"left"!==this.currentStyle.align&&t.push(new Uint8Array([S,97,0])),1===this.currentStyle.widthScale&&1===this.currentStyle.heightScale||t.push(new Uint8Array([A,33,0])),this.currentStyle.bold&&t.push(new Uint8Array([S,69,0])),this.currentStyle.underline&&t.push(new Uint8Array([S,45,0])),this.currentStyle.inverse&&t.push(new Uint8Array([A,66,0])),this.currentStyle=r({},v),t}format(t,e){if(!t||"string"!=typeof t)return[];const n=[];return e&&n.push(...this.setStyle(e)),n}align(t){const e=this.getAlignValue(t);return this.currentStyle.align=t,[new Uint8Array([S,97,e])]}setSize(t,e){const n=this.clampScale(t),i=this.clampScale(e),s=n-1<<4|i-1;return this.currentStyle.widthScale=n,this.currentStyle.heightScale=i,[new Uint8Array([A,33,s])]}setBold(t){return this.currentStyle.bold=t,[new Uint8Array([S,69,t?1:0])]}setUnderline(t){return this.currentStyle.underline=t,[new Uint8Array([S,45,t?1:0])]}setInverse(t){return this.currentStyle.inverse=t,[new Uint8Array([A,66,t?1:0])]}getCurrentStyle(){return r({},this.currentStyle)}getAlignValue(t){switch(t){case"left":default:return 0;case"center":return 1;case"right":return 2}}clampScale(t){return Math.max(1,Math.min(8,Math.floor(t)))}}var D=/* @__PURE__ */(t=>(t.CODE128="CODE128",t.CODE39="CODE39",t.EAN13="EAN13",t.EAN8="EAN8",t.UPCA="UPCA",t.ITF="ITF",t.CODABAR="CODABAR",t.QR_CODE="QR_CODE",t.PDF417="PDF417",t))(D||{});const N=29,w={UPCA:65,EAN13:67,EAN8:68,CODE39:69,ITF:70,CODABAR:71,CODE128:73,QR_CODE:80,PDF417:81},O={L:48,M:49,Q:50,H:51},T={1:49,2:50},R={none:0,above:1,below:2,both:3},j={0:48,1:49,2:50,3:51};class P{generate(t,e){return this.validate(t,e.format).valid?"QR_CODE"===e.format?this.generateQRCode(t,e):"PDF417"===e.format?this.generatePDF417(t,e):this.generate1DBarcode(t,e):[]}generate1DBarcode(t,e){var n,i;const s=[],r=this.clampHeight(null!=(n=e.height)?n:80);s.push(new Uint8Array([N,104,r]));const o=this.clampWidth(null!=(i=e.width)?i:3);s.push(new Uint8Array([N,119,o]));const a=this.getTextPosition(e);s.push(new Uint8Array([N,72,a]));const h=w[e.format],c=this.encodeContent(t,e.format);return s.push(new Uint8Array([N,107,h,c.length,...c])),s}generateQRCode(t,e){var n,i,s,r,o;const a=[],h=null!=(n=e.qrModel)?n:2,c=this.clampQRSize(null!=(i=e.height)?i:6),l=null!=(s=e.errorCorrection)?s:"M",d=null!=(r=T[h])?r:50;a.push(new Uint8Array([N,40,107,4,0,49,65,80,d])),a.push(new Uint8Array([N,40,107,3,0,49,67,c]));const u=null!=(o=O[l])?o:49;a.push(new Uint8Array([N,40,107,3,0,49,69,u]));const g=this.encodeUTF8(t),p=g.length+3;return a.push(new Uint8Array([N,40,107,255&p,p>>8&255,49,80,48,...g])),a.push(new Uint8Array([N,40,107,3,0,49,81,48])),a}generatePDF417(t,e){var n,i,s,r;const o=[],a=null!=(n=e.pdf417Compression)?n:2,h=null!=(i=e.pdf417Security)?i:2,c=this.clampPDF417Columns(null!=(s=e.pdf417Columns)?s:2);o.push(new Uint8Array([N,40,107,7,0,49,48,c,h,0,0]));const l=null!=(r=j[a])?r:50;o.push(new Uint8Array([27,93,4,l]));const d=this.encodeUTF8(t),u=d.length+3;return o.push(new Uint8Array([N,107,81,255&u,u>>8&255,...d])),o.push(new Uint8Array([N,40,107,3,0,49,81,49])),o}validate(t,e){const n=[];if(null==t)return n.push({field:"content",message:"Barcode content is required",code:"REQUIRED"}),{valid:!1,errors:n};if("string"!=typeof t)return n.push({field:"content",message:"Barcode content must be a string",code:"INVALID_TYPE"}),{valid:!1,errors:n};if(0===t.length)return n.push({field:"content",message:"Barcode content cannot be empty",code:"REQUIRED"}),{valid:!1,errors:n};switch("QR_CODE"===e&&t.length>7089&&n.push({field:"content",message:"QR code content exceeds maximum length (7089 bytes for binary mode)",code:"CONTENT_TOO_LONG"}),"PDF417"===e&&t.length>1850&&n.push({field:"content",message:"PDF417 content exceeds maximum length (~1850 bytes)",code:"CONTENT_TOO_LONG"}),e){case"EAN13":this.validateEAN13(t,n);break;case"EAN8":this.validateEAN8(t,n);break;case"UPCA":this.validateUPCA(t,n);break;case"CODE39":this.validateCode39(t,n);break;case"CODE128":this.validateCode128(t,n);break;case"ITF":this.validateITF(t,n);break;case"CODABAR":this.validateCodabar(t,n);break;case"QR_CODE":this.validateQRCode(t,n);break;case"PDF417":this.validatePDF417(t,n);break;default:n.push({field:"format",message:"Unsupported barcode format: "+e,code:"UNSUPPORTED_FORMAT"})}return{valid:0===n.length,errors:n}}validateQRCode(t,e){0===t.length&&e.push({field:"content",message:"QR code content cannot be empty",code:"REQUIRED"}),t.length>7089&&e.push({field:"content",message:"QR code content exceeds maximum binary mode length",code:"CONTENT_TOO_LONG"})}validatePDF417(t,e){0===t.length&&e.push({field:"content",message:"PDF417 content cannot be empty",code:"REQUIRED"}),t.length>1850&&e.push({field:"content",message:"PDF417 content exceeds maximum length",code:"CONTENT_TOO_LONG"});let n=!1;for(let i=0;i<t.length;i++)if(t.charCodeAt(i)>127){n=!0;break}n&&e.push({field:"content",message:"PDF417 standard mode only supports ASCII characters. Consider using compression mode.",code:"INVALID_CHARACTERS"})}getSupportedFormats(){return Object.values(D)}validateEAN13(t,e){if(/^\d{12,13}$/.test(t)){if(13===t.length){const n=this.calculateEANCheckDigit(t.substring(0,12)),i=t[12];void 0!==i&&parseInt(i)!==n&&e.push({field:"content",message:"Invalid EAN-13 check digit",code:"INVALID_CHECK_DIGIT"})}}else e.push({field:"content",message:"EAN-13 must be 12 or 13 digits",code:"INVALID_LENGTH"})}validateEAN8(t,e){if(/^\d{7,8}$/.test(t)){if(8===t.length){const n=this.calculateEANCheckDigit(t.substring(0,7)),i=t[7];void 0!==i&&parseInt(i)!==n&&e.push({field:"content",message:"Invalid EAN-8 check digit",code:"INVALID_CHECK_DIGIT"})}}else e.push({field:"content",message:"EAN-8 must be 7 or 8 digits",code:"INVALID_LENGTH"})}validateUPCA(t,e){if(/^\d{11,12}$/.test(t)){if(12===t.length){const n=this.calculateUPCACheckDigit(t.substring(0,11)),i=t[11];void 0!==i&&parseInt(i)!==n&&e.push({field:"content",message:"Invalid UPC-A check digit",code:"INVALID_CHECK_DIGIT"})}}else e.push({field:"content",message:"UPC-A must be 11 or 12 digits",code:"INVALID_LENGTH"})}validateCode39(t,e){/^[0-9A-Z\s\-.$/+%]+$/.test(t.toUpperCase())||e.push({field:"content",message:"Code 39 only supports: 0-9, A-Z, space, - . $ / + %",code:"INVALID_CHARACTERS"}),(0===t.length||t.length>255)&&e.push({field:"content",message:"Code 39 content must be 1-255 characters",code:"INVALID_LENGTH"})}validateCode128(t,e){for(let n=0;n<t.length;n++)if(t.charCodeAt(n)>127){e.push({field:"content",message:"Code 128 only supports ASCII characters (0-127)",code:"INVALID_CHARACTERS"});break}(0===t.length||t.length>255)&&e.push({field:"content",message:"Code 128 content must be 1-255 characters",code:"INVALID_LENGTH"})}validateITF(t,e){/^\d+$/.test(t)||e.push({field:"content",message:"ITF only supports numeric characters",code:"INVALID_CHARACTERS"}),t.length%2!=0&&e.push({field:"content",message:"ITF content must have even number of digits",code:"INVALID_LENGTH"}),(0===t.length||t.length>255)&&e.push({field:"content",message:"ITF content must be 2-254 digits (even)",code:"INVALID_LENGTH"})}validateCodabar(t,e){/^[ABCDabcd][0-9\-$:/.+]+[ABCDabcd]$/.test(t)||e.push({field:"content",message:"CODABAR must start and end with A/B/C/D and contain only 0-9, - $ : / . +",code:"INVALID_FORMAT"}),(3>t.length||t.length>255)&&e.push({field:"content",message:"CODABAR content must be 3-255 characters",code:"INVALID_LENGTH"})}calculateEANCheckDigit(t){let e=0;const n=t.length;for(let i=0;n>i;i++){const n=t[i];void 0!==n&&(e+=parseInt(n)*(i%2==0?1:3))}return(10-e%10)%10}calculateUPCACheckDigit(t){let e=0;for(let n=0;11>n;n++){const i=t[n];void 0!==i&&(e+=parseInt(i)*(n%2==0?3:1))}return(10-e%10)%10}encodeContent(t,e){return"CODE128"===e?[123,/^\d+$/.test(t)&&t.length>=4?67:66,...t.split("").map(t=>t.charCodeAt(0))]:t.split("").map(t=>t.charCodeAt(0))}encodeUTF8(t){const e=[];for(let n=0;n<t.length;n++){const i=t.charCodeAt(n);128>i?e.push(i):2048>i?(e.push(192|i>>6),e.push(128|63&i)):65536>i?(e.push(224|i>>12),e.push(128|i>>6&63),e.push(128|63&i)):(e.push(240|i>>18),e.push(128|i>>12&63),e.push(128|i>>6&63),e.push(128|63&i))}return e}getTextPosition(t){var e,n,i;if(!1===t.showText)return R.none;const s=null!=(e=t.textPosition)?e:"below";return null!=(i=null!=(n=R[s])?n:R.below)?i:2}clampHeight(t){return Math.max(1,Math.min(255,Math.floor(t)))}clampWidth(t){return Math.max(2,Math.min(6,Math.floor(t)))}clampQRSize(t){return Math.max(1,Math.min(16,Math.floor(t)))}clampPDF417Columns(t){return Math.max(1,Math.min(30,Math.floor(t)))}}class L{constructor(t){this.logger=a.scope("CommandBuilder"),this.buffer=[],this.cachedBuffer=null,this.driver=null!=t?t:new p,this.formatter=new y,this.barcodeGenerator=new P,this.buffer.push(...this.driver.init())}pushCommands(t){t.length>0&&(this.buffer.push(...t),this.cachedBuffer=null)}text(t,e){return this.logger.debug("Adding text:",t.substring(0,50)),this.pushCommands(this.driver.text(t,e)),this}feed(t=1){return this.logger.debug("Adding feed:",t),this.pushCommands(this.driver.feed(t)),this}cut(){return this.logger.debug("Adding cut command"),this.pushCommands(this.driver.cut()),this}image(t,e,n){return this.logger.debug(`Adding image: ${e}x${n}`),this.pushCommands(this.driver.image(t,e,n)),this}qr(t,e){return this.logger.debug("Adding QR code:",t.substring(0,50)),this.pushCommands(this.driver.qr(t,e)),this}clear(){return this.buffer=[],this.pushCommands(this.driver.init()),this}align(t){return this.logger.debug("Setting alignment:",t),this.pushCommands(this.formatter.align(t)),this}setSize(t,e){return this.logger.debug(`Setting size: ${t}x${e}`),this.pushCommands(this.formatter.setSize(t,e)),this}setBold(t){return this.logger.debug("Setting bold:",t),this.pushCommands(this.formatter.setBold(t)),this}setUnderline(t){return this.logger.debug("Setting underline:",t),this.pushCommands(this.formatter.setUnderline(t)),this}setInverse(t){return this.logger.debug("Setting inverse:",t),this.pushCommands(this.formatter.setInverse(t)),this}setStyle(t){return this.logger.debug("Setting style:",t),this.pushCommands(this.formatter.setStyle(t)),this}resetStyle(){return this.logger.debug("Resetting style"),this.pushCommands(this.formatter.resetStyle()),this}barcode(t,e){this.logger.debug(`Adding barcode: ${t} (${e.format})`);const n=this.barcodeGenerator.generate(t,e);return n.length>0?this.pushCommands(n):this.logger.warn("Failed to generate barcode for content: "+t),this}getBuffer(){if(this.cachedBuffer)return this.cachedBuffer;const t=this.buffer.reduce((t,e)=>t+e.length,0),e=new Uint8Array(t);let n=0;for(const i of this.buffer)e.set(i,n),n+=i.length;return this.cachedBuffer=e,e}getTotalBytes(){return this.buffer.reduce((t,e)=>t+e.length,0)}}class M extends m{constructor(t,e,n){super(),this.printerLogger=a.scope("BluetoothPrinter"),this.state=h.DISCONNECTED,this.connectionManager=this.resolveConnectionManager(t),this.printJobManager=null!=e?e:new I(this.connectionManager),this.commandBuilder=null!=n?n:new L,this.updateState()}resolveConnectionManager(t){return t?"function"==typeof t.getState?t:new b(t):new b}handleError(t,e,n){const i=t instanceof l?t:new l(e,n,d(t));return this.emit("error",i),this.updateState(),i}updateState(){this.printJobManager.isPaused()?this.state=h.PAUSED:this.printJobManager.isInProgress()?this.state=h.PRINTING:this.state=this.connectionManager.getState(),this.emit("state-change",this.state),this.printerLogger.debug("State updated:",this.state)}connect(t){return o(this,null,function*(){this.printerLogger.info("Connecting to device:",t);try{return yield this.connectionManager.connect(t),this.updateState(),this.emit("connected",t),this.printerLogger.info("Connected successfully"),this}catch(e){throw this.handleError(e,u.CONNECTION_FAILED,"Connection failed")}})}disconnect(){return o(this,null,function*(){const t=this.connectionManager.getDeviceId();if(t){this.printerLogger.info("Disconnecting from device:",t);try{yield this.connectionManager.disconnect(),this.printJobManager.cancel(),this.updateState(),this.emit("disconnected",t),this.printerLogger.info("Disconnected successfully")}catch(e){throw this.handleError(e,u.DEVICE_DISCONNECTED,"Disconnect failed")}}else this.printerLogger.warn("Disconnect called but no device connected")})}text(t,e){return this.commandBuilder.text(t,e),this}feed(t=1){return this.commandBuilder.feed(t),this}cut(){return this.commandBuilder.cut(),this}image(t,e,n){return this.commandBuilder.image(t,e,n),this}qr(t,e){return this.commandBuilder.qr(t,e),this}align(t){return this.commandBuilder.align(t),this}setSize(t,e){return this.commandBuilder.setSize(t,e),this}setBold(t){return this.commandBuilder.setBold(t),this}setUnderline(t){return this.commandBuilder.setUnderline(t),this}resetStyle(){return this.commandBuilder.resetStyle(),this}barcode(t,e,n){return this.commandBuilder.barcode(t,r({format:e},n)),this}setOptions(t){return this.printJobManager.setOptions(t),this}writeRaw(t,e){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new l(u.CONNECTION_FAILED,"Printer not connected. Call connect() first.");this.printerLogger.info(`writeRaw: ${t.length} bytes`),e&&this.printJobManager.setOptions(e),this.updateState(),this.printJobManager.setProgressCallback((t,e)=>{this.emit("progress",{sent:t,total:e})});const n=Date.now();try{yield this.printJobManager.start(t),this.printJobManager.isPaused()||(this.emit("print-complete"),this.emit("job-completed",{source:"writeRaw",bytes:t.length,completedAt:Date.now(),durationMs:Date.now()-n}))}catch(i){const e=this.handleError(i,u.PRINT_JOB_FAILED,"writeRaw failed");throw this.emit("job-failed",{source:"writeRaw",bytes:t.length,completedAt:Date.now(),durationMs:Date.now()-n,error:e}),e}finally{this.updateState()}})}pause(){this.printJobManager.pause(),this.updateState(),this.printerLogger.info("Print job paused")}resume(){return o(this,null,function*(){this.printerLogger.info("Resuming print job");try{yield this.printJobManager.resume(),this.updateState(),this.printerLogger.info("Print job resumed")}catch(t){throw this.handleError(t,u.PRINT_JOB_FAILED,"Failed to resume print job")}})}cancel(){this.printJobManager.cancel(),this.commandBuilder.clear(),this.updateState(),this.printerLogger.info("Print job cancelled")}remaining(){return this.printJobManager.remaining()}print(){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new l(u.CONNECTION_FAILED,"Printer not connected. Call connect() first.");const t=this.commandBuilder.getBuffer();this.printerLogger.info(`Starting print job: ${t.length} bytes`),this.commandBuilder.clear(),this.updateState(),this.printJobManager.setProgressCallback((t,e)=>{this.emit("progress",{sent:t,total:e})});const e=Date.now();try{yield this.printJobManager.start(t),this.printJobManager.isPaused()?this.printerLogger.info("Print job paused"):(this.emit("print-complete"),this.emit("job-completed",{source:"print",bytes:t.length,completedAt:Date.now(),durationMs:Date.now()-e}),this.printerLogger.info("Print job completed successfully"))}catch(n){this.printerLogger.error("Print job failed with error:",n);const i=this.handleError(n,u.PRINT_JOB_FAILED,"Print job failed");throw this.emit("job-failed",{source:"print",bytes:t.length,completedAt:Date.now(),durationMs:Date.now()-e,error:i}),i}finally{this.updateState()}})}getConnectionManager(){return this.connectionManager}getCommandBuilder(){return this.commandBuilder}destroy(){this.printerLogger.info("Destroying BluetoothPrinter instance"),this.printJobManager.cancel(),this.commandBuilder.clear(),this.connectionManager.isConnected()&&this.connectionManager.disconnect().catch(t=>{this.printerLogger.warn("Error during disconnect in destroy:",t)}),this.connectionManager.destroy(),this.removeAllListeners(),this.printerLogger.info("BluetoothPrinter instance destroyed")}}export{M as B,b as C,m as E,I as P,y as T,P as a,E as b,D as c,L as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t=Object.defineProperty,e=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,i=Math.pow,s=(e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,o=(t,i)=>{for(var o in i||(i={}))r.call(i,o)&&s(t,o,i[o]);if(e)for(var o of e(i))n.call(i,o)&&s(t,o,i[o]);return t},a=(t,e,r)=>new Promise((n,i)=>{var s=t=>{try{a(r.next(t))}catch(e){i(e)}},o=t=>{try{a(r.throw(t))}catch(e){i(e)}},a=t=>t.done?n(t.value):Promise.resolve(t.value).then(s,o);a((r=r.apply(t,e)).next())});import{i as c,g as h,a as l,u,b as d,c as f,d as g}from"./gbk-data-BhfiCGRq.js";var E=/* @__PURE__ */(t=>(t.DISCONNECTED="disconnected",t.CONNECTING="connecting",t.CONNECTED="connected",t.DISCONNECTING="disconnecting",t.PRINTING="printing",t.PAUSED="paused",t))(E||{});const I={maxLength:1e4,suffix:"... [truncated]",preserveHead:!0,headLength:5e3,tailLength:5e3};function p(t,e={}){const r=o(o({},I),e);if(t.length<=r.maxLength)return t;if(r.preserveHead&&r.headLength+r.tailLength+r.suffix.length<r.maxLength){const e=t.slice(0,r.headLength),n=t.slice(-r.tailLength);return`${e}${r.suffix}${n}`}return t.slice(0,r.maxLength-r.suffix.length)+r.suffix}function A(t,e=2e3){if(null===t)return"null";if(void 0===t)return"undefined";let r;if("string"==typeof t)r=t;else{if("number"==typeof t||"boolean"==typeof t)return t+"";if(t instanceof Error)return r=`${t.name}: ${t.message}`,t.stack&&(r+="\n"+p(t.stack,{maxLength:1e3})),r;if(t instanceof Uint8Array||t instanceof ArrayBuffer){const e=t instanceof ArrayBuffer?new Uint8Array(t):t;return r=`Uint8Array(${e.length}) [${p(Array.from(e.slice(0,100)).map(t=>t.toString(16).padStart(2,"0")).join(" "),{maxLength:300})}]`,e.length>100&&(r+=` ... (${e.length} bytes total)`),r}try{r=JSON.stringify(t)}catch(n){r=Object.prototype.toString.call(t)}}return p(r,{maxLength:e})}function T(t,e,r){return a(this,null,function*(){const n=[],i=Math.ceil(t.length/e);for(let o=0;o<t.length;o+=e){const a=t.slice(o,o+e),c=Math.floor(o/e)+1;try{const t=yield r(a,c);n.push(...t)}catch(s){throw s instanceof Error?s:Error(s+"")}i>c&&(yield new Promise(t=>setTimeout(t,0)))}return n})}function y(t=5e3){return{log:(...e)=>{e.map(e=>A(e,t))},warn:(...e)=>{e.map(e=>A(e,t))},error:(...e)=>{e.map(e=>A(e,t))}}}function N(t){if(null===t)return"null";if(void 0===t)return"undefined";if("string"==typeof t)return`string(${t.length}): "${p(t,{maxLength:100})}"`;if("number"==typeof t)return"number: "+t;if("boolean"==typeof t)return"boolean: "+t;if(Array.isArray(t))return`array[${t.length}]`;if(t instanceof Uint8Array)return`Uint8Array(${t.length} bytes)`;if(t instanceof ArrayBuffer)return`ArrayBuffer(${t.byteLength} bytes)`;if(t instanceof Error)return`Error: ${t.name}: ${p(t.message,{maxLength:100})}`;if("object"==typeof t){const e=Object.keys(t);return`object{${e.length} keys: ${e.slice(0,5).join(", ")}${e.length>5?"...":""}}`}return t+""}var _=/* @__PURE__ */(t=>(t[t.DEBUG=0]="DEBUG",t[t.INFO=1]="INFO",t[t.WARN=2]="WARN",t[t.ERROR=3]="ERROR",t[t.NONE=4]="NONE",t))(_||{});const O=class t{static configure(t){this.config=o(o({},this.config),t)}static setLevel(t){this.config.level=t}static getLevel(){return this.config.level}static formatPrefix(t,e){return`${e?`${this.config.prefix}:${e}`:this.config.prefix} [${{0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"NONE"}[t]}]`}static formatMessage(t,e,r){return`${this.formatPrefix(t,r)} ${e}`}static log(t,e,r,n){if(this.config.level>t)return;this.formatPrefix(t,n);const i=this.formatMessage(t,e,n),s={level:t,message:e,args:this.config.useSummaryMode?r.map(t=>N(t)):r.map(t=>A(t,this.config.maxOutputLength)),timestamp:/* @__PURE__ */new Date,scope:n,formatted:i};this.config.handler&&this.config.handler(s)}static debug(t,...e){this.log(0,t,e)}static info(t,...e){this.log(1,t,e)}static warn(t,...e){this.log(2,t,e)}static error(t,...e){this.log(3,t,e)}static scope(e){return{debug:(r,...n)=>{t.log(0,r,n,e)},info:(r,...n)=>{t.log(1,r,n,e)},warn:(r,...n)=>{t.log(2,r,n,e)},error:(r,...n)=>{t.log(3,r,n,e)}}}};O.config={level:2,prefix:"[TaroBTPrint]",maxOutputLength:5e3,useSummaryMode:!1};let m=O;function D(t){return t instanceof Error?t:Error(null==t?"Unknown error (null or undefined)":t+"")}function R(t,e){const r=D(t);throw e("error",r),r}var w=/* @__PURE__ */(t=>(t.CONNECTION_FAILED="CONNECTION_FAILED",t.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",t.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",t.DEVICE_DISCONNECTED="DEVICE_DISCONNECTED",t.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",t.CHARACTERISTIC_NOT_FOUND="CHARACTERISTIC_NOT_FOUND",t.SERVICE_DISCOVERY_FAILED="SERVICE_DISCOVERY_FAILED",t.WRITE_FAILED="WRITE_FAILED",t.WRITE_TIMEOUT="WRITE_TIMEOUT",t.PRINT_JOB_IN_PROGRESS="PRINT_JOB_IN_PROGRESS",t.PRINT_JOB_CANCELLED="PRINT_JOB_CANCELLED",t.PRINT_JOB_FAILED="PRINT_JOB_FAILED",t.INVALID_CONFIGURATION="INVALID_CONFIGURATION",t.ENCODING_NOT_SUPPORTED="ENCODING_NOT_SUPPORTED",t.INVALID_IMAGE_DATA="INVALID_IMAGE_DATA",t.INVALID_QR_DATA="INVALID_QR_DATA",t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.QUEUE_FULL="QUEUE_FULL",t.QUEUE_JOB_NOT_FOUND="QUEUE_JOB_NOT_FOUND",t.PREVIEW_FAILED="PREVIEW_FAILED",t))(w||{});function C(t){return Object.values(w).includes(t)}class S extends Error{constructor(t,e,r){super(e),this.code=t,this.originalError=r,this.name="BluetoothPrintError",Error.captureStackTrace&&Error.captureStackTrace(this,S)}toString(){let t=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(t+="\nCaused by: "+this.originalError.message,this.originalError.stack&&(t+="\n"+this.originalError.stack)),this.stack&&(t+="\n"+this.stack),t}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}}}function U(t,e,r="Operation timed out"){return a(this,null,function*(){let n;const i=new Promise((t,i)=>{n=setTimeout(()=>{i(Error(`${r} after ${e}ms`))},e)});try{return yield Promise.race([t,i])}finally{void 0!==n&&clearTimeout(n)}})}var x=/* @__PURE__ */(t=>(t.WECHAT="wechat",t.ALIPAY="alipay",t.BAIDU="baidu",t.BYTEDANCE="bytedance",t.QQ="qq",t.WEB="web",t.UNKNOWN="unknown",t))(x||{});function M(t){return"object"==typeof t&&null!==t&&"request"in t}function L(){return"undefined"!=typeof wx&&M(wx)?"wechat":"undefined"!=typeof my&&M(my)?"alipay":"undefined"!=typeof swan&&M(swan)?"baidu":"undefined"!=typeof tt&&M(tt)?"bytedance":"undefined"!=typeof qq&&M(qq)?"qq":"undefined"!=typeof window&&"object"==typeof(t=window)&&null!==t&&"navigator"in t?"web":"unknown";var t}function b(){const t=L();return"unknown"!==t&&"web"!==t}function P(t){return t>=44032&&55215>=t}function F(t){return t>=19968&&40959>=t||t>=63744&&64255>=t||t>=13312&&19903>=t}function v(t){return t>=4352&&4607>=t||t>=12592&&12687>=t||t>=65440&&65503>=t}function B(t){return t>=12352&&12447>=t}function G(t){return t>=12448&&12543>=t}function k(t){return t>=19968&&40959>=t||t>=13312&&19903>=t||t>=63744&&64255>=t}function V(t){if(!P(t))return null;const e=t-44032,r=Math.floor(e/588),n=Math.floor(e%588/28),i=e%28,s=[129,130,132,133,136,138,139,140,141,142,143,144,145,146],o=[0,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155];if(r>=s.length)return null;if(n>=21)return null;const a=s[r];let c=0;if(i>0&&o.length>i){const t=o[i];void 0!==t&&(c=t)}const h=a,l=0!==c?c:0;if(0===c){const t=Math.floor(21*(a-129)+n);return[255&176+Math.floor(t/94),255&161+t%94]}return[h,l]}function $(t){return 12352>t||t>12447?null:[130,255&t-12352+159]}function J(t){return 12448>t||t>12543?null:[131,255&t-12448+64]}const W=new Uint8Array([27,40,66]),z=new Uint8Array([27,36,66]);function j(t){return B(t)||G(t)||k(t)}function H(t){return t>=65377&&65439>=t||t>=12448&&12543>=t}const K={defaultEncoding:"GBK",fallbackChar:"?",showWarnings:!0},Y=class t{constructor(t){this.logger=m.scope("EncodingService"),this.config=o(o({},K),t)}configure(t){this.config=o(o({},this.config),t)}getConfig(){return o({},this.config)}encode(e,r){if(!e||"string"!=typeof e)return new Uint8Array(0);switch(this.normalizeEncoding(r||this.config.defaultEncoding)){case"UTF8":case"UTF-8":return t.utf8Encoder.encode(e);case"GBK":case"GB2312":return this.encodeGbk(e);case"BIG5":return this.encodeBig5(e);case"EUCKR":case"EUC-KR":return this.encodeKorean(e);case"SHIFTJIS":case"SHIFT-JIS":case"SJIS":return this.encodeShiftJis(e);case"ISO2022JP":case"ISO-2022-JP":case"JIS":return this.encodeIso2022Jp(e);default:return this.config.showWarnings&&this.logger.warn(`Unknown encoding "${r}", falling back to UTF-8`),t.utf8Encoder.encode(e)}}encodeWithInfo(e,r){if(!e||"string"!=typeof e)return{bytes:new Uint8Array(0),unsupportedCount:0,unsupportedChars:[]};const n=this.normalizeEncoding(r||this.config.defaultEncoding);if("UTF8"===n||"UTF-8"===n)return{bytes:t.utf8Encoder.encode(e),unsupportedCount:0,unsupportedChars:[]};const i=[],s=[],o=this.config.fallbackChar.charCodeAt(0);for(let t=0;t<e.length;t++){const r=e.charAt(t),a=e.charCodeAt(t);if(a>=55296&&56319>=a&&t+1<e.length){const r=e.charCodeAt(t+1);if(r>=56320&&57343>=r){s.push(e.substring(t,t+2)),i.push(o),t++;continue}}if(c(a)){i.push(a);continue}let l=null;l="BIG5"===n?h(a):g(a),l?i.push(l[0],l[1]):(void 0!==r&&s.push(r),i.push(o),this.config.showWarnings&&1===s.length&&void 0!==r&&this.logger.warn(`Character "${r}" (U+${a.toString(16).toUpperCase()}) not supported in ${n}`))}return{bytes:new Uint8Array(i),unsupportedCount:s.length,unsupportedChars:[...new Set(s)]}}isSupported(t){if(!t||"string"!=typeof t)return!1;const e=this.normalizeEncoding(t);return["GBK","GB2312","BIG5","UTF8","UTF-8","EUCKR","EUC-KR","SHIFTJIS","SHIFT-JIS","SJIS","ISO2022JP","ISO-2022-JP","JIS"].includes(e)}detectEncoding(t){if(!t||"string"!=typeof t)return"UTF-8";let e=!1,r=!1,n=!1,i=0,s=0,o=0;for(let g=0;g<t.length;g++){const a=t.charCodeAt(g);(55296>a||a>57343)&&(c(a)?e=!0:(o++,l(a)?(r=!0,u.has(a)&&i++,d.has(a)&&s++):f(a)&&(n=!0,u.has(a)&&i++)))}if(!r&&!n&&e)return"UTF-8";if(0===o)return"UTF-8";const a=i/o,h=s/o;return h>a&&h>.8?"BIG5":a>.8?"GBK":"UTF-8"}getSupportedEncodings(){return["GBK","GB2312","BIG5","UTF-8","EUC-KR","SHIFT-JIS","ISO-2022-JP"]}encodeGbk(t){return this.encodeWithStrategy(t,t=>g(t))}encodeBig5(t){return this.encodeWithStrategy(t,t=>h(t)||g(t))}encodeKorean(t){try{(new TextEncoder).encode("\uac00")}catch(e){}return this.encodeWithStrategy(t,t=>P(t)?V(t):(v(t)||F(t),null))}encodeShiftJis(t){return this.encodeWithStrategy(t,t=>{const e=$(t);if(e)return e;return J(t)||null})}encodeIso2022Jp(t){return this.encodeWithStrategy(t,t=>{if(j(t)){const e=$(t);if(e)return[...z,...e];const r=J(t);return r?[...z,...r]:null}return null},{init:t=>t.push(...W),onSurrogate:(t,e)=>{t.push(...W,e)},onAscii:(t,e)=>{t.push(...W,e)},finalize:t=>t.push(...W)})}normalizeEncoding(t){return t.toUpperCase().replace(/-/g,"").replace("_","")}encodeWithStrategy(t,e,r){var n,i;const s=[],o=this.config.fallbackChar.charCodeAt(0);null==(n=null==r?void 0:r.init)||n.call(r,s);for(let a=0;a<t.length;a++){const n=t.charCodeAt(a);if(n>=55296&&56319>=n&&a+1<t.length){const e=t.charCodeAt(a+1);if(e>=56320&&57343>=e){(null==r?void 0:r.onSurrogate)?r.onSurrogate(s,o):s.push(o),a++;continue}}if(c(n)){(null==r?void 0:r.onAscii)?r.onAscii(s,n):s.push(n);continue}const i=e(n);i?s.push(...i):s.push(o)}return null==(i=null==r?void 0:r.finalize)||i.call(r,s),new Uint8Array(s)}};Y.utf8Encoder=new TextEncoder;let Q=Y;const q=new Q,X=m.scope("Encoding"),Z=class{static configure(t){this.config=o(o({},this.config),t)}static encode(t,e="GBK"){if(!t||"string"!=typeof t)return new Uint8Array(0);const r=e.toUpperCase().replace("-","");return"UTF8"===r||"UTF-8"===r||this.config.showWarnings&&!this.warningShown&&(X.warn(`Encoding ${e} not yet fully implemented, falling back to UTF-8. This may cause display issues with some printers.`),this.warningShown=!0),this.utf8Encoder.encode(t)}static isSupported(t){if(!t||"string"!=typeof t)return!1;const e=t.toUpperCase().replace("-","");return"UTF8"===e||"UTF-8"===e}};Z.utf8Encoder=new TextEncoder,Z.warningShown=!1,Z.config={showWarnings:!0};let et=Z;const rt=class{static toBitmap(t,e,r,n){if(!(t&&t instanceof Uint8Array&&e>0&&r>0))return new Uint8Array(0);if(t.length!==e*r*4)throw new S(w.INVALID_IMAGE_DATA,`Invalid image data length: expected ${e*r*4}, got ${t.length}`);let i=n||{};if(i.qualityPreset){const t=this.QUALITY_PRESETS[i.qualityPreset];i=o(o({},i),t)}const{targetWidth:s,targetHeight:a,useDithering:c=!0,ditheringAlgorithm:h="floyd-steinberg",scalingAlgorithm:l="nearest",contrast:u=1,brightness:d=0,threshold:f=128,orderedMatrixSize:g=4,halftoneDotType:E="round"}=i;let I=t,p=e,A=r;if(s||a){const n=this.scaleImage(t,e,r,s||e,a||r,{algorithm:l});I=n.newData,p=n.newWidth,A=n.newHeight}const T=Math.ceil(p/8),y=new Uint8Array(T*A),N=this.toGrayscaleAdjusted(I,p,A,u,d);return c?this.applyDithering(N,p,A,y,T,{algorithm:h,threshold:f,orderedMatrixSize:g,halftoneDotType:E}):this.applyThresholdDithering(N,p,A,y,T,()=>f),y}static preprocessImage(t,e,r,n){if(!(t&&t instanceof Uint8Array))return t;let i=t;return(null==n?void 0:n.gamma)&&1!==n.gamma&&(i=this.applyGammaCorrection(i,n.gamma)),(null==n?void 0:n.denoise)&&(i=this.applyMedianFilter(i,e,r)),(null==n?void 0:n.sharpen)&&(i=this.applyUnsharpMask(i,e,r)),(null==n?void 0:n.posterize)&&(i=this.applyPosterization(i,n.posterize)),i}static toGrayscaleAdjusted(t,e,r,n,i){const s=e*r,o=new Float32Array(s),a=1!==n||0!==i,c=255*i;for(let h=0;s>h;h++){const e=h<<2;let r=(299*t[e]+587*t[e+1]+114*t[e+2])/1e3;a?(r=(r-128)*n+128+c,o[h]=0>r?0:r>255?255:r):o[h]=r}return o}static applyDithering(t,e,r,n,i,s){switch(s.algorithm){case"ordered":{const o=2===s.orderedMatrixSize?this.BAYER_MATRIX_2:8===s.orderedMatrixSize?this.BAYER_MATRIX_8:this.BAYER_MATRIX_4,a=4===s.orderedMatrixSize?16:8===s.orderedMatrixSize?64:4,c=s.threshold,h=s.orderedMatrixSize;this.applyThresholdDithering(t,e,r,n,i,(t,e)=>{var r,n;return c+(null!=(n=null==(r=o[e%h])?void 0:r[t%h])?n:0)/a*48});break}case"halftone":{const o=4,a=this.getHalftoneThresholds(o,s.halftoneDotType),c=s.threshold;this.applyThresholdDithering(t,e,r,n,i,(t,e,r)=>{var n,i;return(null!=(i=null==(n=a[e%o])?void 0:n[t%o])?i:128)+(c>r?-30:30)});break}case"floyd-steinberg":case"atkinson":case"sierra":case"stucki":{const o=this.ERROR_KERNELS[s.algorithm];this.applyErrorDiffusionDithering(t,e,r,n,i,s.threshold,o);break}default:this.applyErrorDiffusionDithering(t,e,r,n,i,s.threshold,this.ERROR_KERNELS["floyd-steinberg"])}}static applyErrorDiffusionDithering(t,e,r,n,i,s,o){const a=o.length;for(let c=0;r>c;c++)this.processErrorDiffusionRow(t,e,r,n,i,c,s,o,a)}static processErrorDiffusionRow(t,e,r,n,i,s,o,a,c){const h=s*e,l=s*i;for(let u=0;e>u;u++){const i=t[h+u],d=o>i?0:255;0===d&&this.writeBlackPixel(n,l,u);const f=i-d;0!==f&&this.distributeError(t,e,r,u,s,f,a,c)}}static writeBlackPixel(t,e,r){var n;const i=e+(r>>3),s=128>>(7&r);t[i]=(null!=(n=t[i])?n:0)|s}static distributeError(t,e,r,n,i,s,o,a){for(let c=0;a>c;c++){const a=o[c],h=n+a.dx,l=i+a.dy;if(h>=0&&e>h&&l>=0&&r>l){const r=l*e+h,n=t[r]+s*a.weight;t[r]=0>n?0:n>255?255:n}}}static applyThresholdDithering(t,e,r,n,i,s){var o;for(let a=0;r>a;a++)for(let r=0;e>r;r++){const c=t[a*e+r];if(c<s(r,a,c)){const t=a*i+(r>>3);n[t]=(null!=(o=n[t])?o:0)|128>>(7&r)}}}static getHalftoneThresholds(t,e){const r=`${t}_${e}`;let n=this.halftoneThresholdCache.get(r);return n||(n=this.computeHalftoneThresholds(t,e),this.halftoneThresholdCache.set(r,n)),n}static computeHalftoneThresholds(t,e){const r=[],n=(t-1)/2;for(let s=0;t>s;s++){r[s]=[];for(let o=0;t>o;o++){let t;t="round"===e?Math.sqrt(i(o-n,2)+i(s-n,2))/n:"diamond"===e?(Math.abs(o-n)+Math.abs(s-n))/n:Math.max(Math.abs(o-n),Math.abs(s-n))/n,r[s][o]=Math.min(255,Math.round(224*t+32))}}return r}static scaleImage(t,e,r,n,i,s){const o=e/r;let a=n,c=i;a/c>o?a=Math.round(c*o):c=Math.round(a/o);const h=new Uint8Array(a*c*4);return"bilinear"===(null==s?void 0:s.algorithm)?this.applyBilinearInterpolation(t,e,r,h,a,c):this.applyNearestNeighbor(t,e,r,h,a,c),{newData:h,newWidth:a,newHeight:c}}static applyNearestNeighbor(t,e,r,n,i,s){this.resampleImage(e,r,i,s,(r,i,s,o,a)=>{const c=4*(o*e+s);n[a]=t[c],n[a+1]=t[c+1],n[a+2]=t[c+2],n[a+3]=t[c+3]})}static applyBilinearInterpolation(t,e,r,n,i,s){this.resampleImage(e,r,i,s,(o,a,c,h,l)=>{const u=Math.min(e-1,o*(e/i)),d=Math.min(r-1,a*(r/s)),f=Math.floor(u),g=Math.floor(d),E=Math.min(f+1,e-1),I=Math.min(g+1,r-1),p=u-f,A=d-g,T=(1-p)*(1-A),y=p*(1-A),N=(1-p)*A,_=p*A;for(let r=0;4>r;r++){const i=4*(g*e+E)+r,s=4*(I*e+f)+r,o=4*(I*e+E)+r,a=t[4*(g*e+f)+r]*T+t[i]*y+t[s]*N+t[o]*_;n[l+r]=Math.round(a)}})}static resampleImage(t,e,r,n,i){const s=t/r,o=e/n;for(let a=0;n>a;a++)for(let n=0;r>n;n++)i(n,a,Math.min(t-1,Math.round(n*s)),Math.min(e-1,Math.round(a*o)),4*(a*r+n))}static applyGammaCorrection(t,e){const r=1/e,n=new Uint8Array(256);for(let s=0;256>s;s++)n[s]=Math.round(255*Math.pow(s/255,r));const i=new Uint8Array(t.length);for(let s=0;s<t.length;s+=4){const e=t[s],r=t[s+1],o=t[s+2];i[s]=n[e],i[s+1]=n[r],i[s+2]=n[o],i[s+3]=t[s+3]}return i}static processPixels(t,e,r,n){if(4>t.length||0>=e||0>=r)return new Uint8Array(0);const i=new Uint8Array(t.length);for(let s=0;r>s;s++)for(let t=0;e>t;t++)n(i,t,s,4*(s*e+t));return i}static applyMedianFilter(t,e,r){return this.processPixels(t,e,r,(n,i,s,o)=>{var a;const c=this.collectNeighborhoodWindow(t,e,r,i,s);c.sort((t,e)=>t-e);for(let t=0;4>t;t++)n[o+t]=null!=(a=c[18+9*t])?a:128})}static collectNeighborhoodWindow(t,e,r,n,i){const s=[];for(let o=-1;1>=o;o++)for(let a=-1;1>=a;a++){const c=this.clampCoordinate(n+a,e),h=4*(this.clampCoordinate(i+o,r)*e+c);for(let e=0;4>e;e++)s.push(t[h+e])}return s}static clampCoordinate(t,e){return 0>t?0:e>t?t:e-1}static applyUnsharpMask(t,e,r){const n=this.getSharpeningKernel();return this.processPixels(t,e,r,(i,s,o,a)=>{for(let c=0;4>c;c++){const h=this.convolveChannel(t,e,r,s,o,c,n);i[a+c]=this.clampToByte(h)}})}static getSharpeningKernel(){return[[-.5,-1,-.5],[-1,3,-1],[-.5,-1,-.5]]}static convolveChannel(t,e,r,n,i,s,o){var a,c;let h=0;for(let l=0;3>l;l++)for(let u=0;3>u;u++){const d=this.clampCoordinate(n+u-1,e),f=4*(this.clampCoordinate(i+l-1,r)*e+d)+s,g=null!=(c=null==(a=o[l])?void 0:a[u])?c:0;h+=t[f]*g}return h}static clampToByte(t){return Math.max(0,Math.min(255,Math.round(t)))}static applyPosterization(t,e){if(4>t.length)return new Uint8Array(0);const r=255/(Math.pow(2,Math.max(1,Math.min(8,e)))-1),n=new Uint8Array(t.length);for(let i=0;i<t.length;i+=4)n[i]=Math.round(Math.round(t[i]/r)*r),n[i+1]=Math.round(Math.round(t[i+1]/r)*r),n[i+2]=Math.round(Math.round(t[i+2]/r)*r),n[i+3]=t[i+3];return n}};rt.BAYER_MATRIX_2=[[0,2],[3,1]],rt.BAYER_MATRIX_4=[[0,8,2,10],[12,4,14,6],[3,11,1,9],[15,7,13,5]],rt.BAYER_MATRIX_8=(()=>{var t,e;const r=rt.BAYER_MATRIX_4,n=[];for(let i=0;8>i;i++){n[i]=[];for(let s=0;8>s;s++){const o=(null!=(e=null==(t=r[i>>1])?void 0:t[s>>1])?e:0)+i%2*32+s%2*64;n[i][s]=o}}return n})(),rt.QUALITY_PRESETS={draft:{contrast:.9,brightness:-.05,algorithm:"ordered"},normal:{contrast:1,brightness:0,algorithm:"floyd-steinberg"},high:{contrast:1.15,brightness:.08,algorithm:"halftone"}},rt.ERROR_KERNELS={"floyd-steinberg":[{dx:1,dy:0,weight:7/16},{dx:-1,dy:1,weight:3/16},{dx:0,dy:1,weight:5/16},{dx:1,dy:1,weight:1/16}],atkinson:[{dx:1,dy:0,weight:1/8},{dx:2,dy:0,weight:1/8},{dx:-1,dy:1,weight:1/8},{dx:0,dy:1,weight:1/8},{dx:1,dy:1,weight:1/8},{dx:0,dy:2,weight:1/8}],sierra:[{dx:1,dy:0,weight:5/32},{dx:2,dy:0,weight:2/32},{dx:-2,dy:1,weight:2/32},{dx:-1,dy:1,weight:3/32},{dx:0,dy:1,weight:5/32},{dx:1,dy:1,weight:2/32},{dx:-1,dy:2,weight:2/32},{dx:0,dy:2,weight:3/32},{dx:1,dy:2,weight:2/32},{dx:2,dy:2,weight:1/32}],stucki:[{dx:1,dy:0,weight:8/42},{dx:2,dy:0,weight:4/42},{dx:-2,dy:1,weight:2/42},{dx:-1,dy:1,weight:4/42},{dx:0,dy:1,weight:8/42},{dx:1,dy:1,weight:4/42},{dx:2,dy:1,weight:2/42},{dx:-2,dy:2,weight:1/42},{dx:-1,dy:2,weight:2/42},{dx:0,dy:2,weight:4/42},{dx:1,dy:2,weight:2/42},{dx:2,dy:2,weight:1/42}]},rt.halftoneThresholdCache=/* @__PURE__ */new Map;let nt=rt;function it(t,e){const r=Math.min(t.length,null!=e?e:t.length),n=[];for(let i=0;r>i;i++)n.push(t[i].toString(16).padStart(2,"0").toUpperCase());return n.join("")}class st{constructor(t){if(this.maxEntries=t,this.entries=/* @__PURE__ */new Map,this.orderedIds=[],1>t)throw new RangeError("BoundedOrderedMap: maxEntries must be >= 1")}set(t,e){this.entries.set(t,e);const r=this.findInsertPosition(e.createdAt);this.orderedIds.splice(r,0,{id:t,createdAt:e.createdAt}),this.enforceMaxEntries()}get(t){return this.entries.get(t)}has(t){return this.entries.has(t)}delete(t){const e=this.entries.delete(t);if(e){const e=this.orderedIds.findIndex(e=>e.id===t);-1!==e&&this.orderedIds.splice(e,1)}return e}clear(){this.entries.clear(),this.orderedIds.length=0}get size(){return this.entries.size}get maxSize(){return this.maxEntries}values(){return this.entries.values()}keys(){return this.entries.keys()}entriesIter(){return this.entries.entries()}rebuildIndex(){this.orderedIds.length=0;for(const[t,e]of this.entries)this.orderedIds.push({id:t,createdAt:e.createdAt});this.orderedIds.sort((t,e)=>t.createdAt-e.createdAt)}enforceMaxEntries(){const t=this.entries.size-this.maxEntries;if(t>0){for(let e=0;t>e;e++){const t=this.orderedIds[e];t&&this.entries.delete(t.id)}this.orderedIds.splice(0,t)}}findInsertPosition(t){let e=0,r=this.orderedIds.length;for(;r>e;){const n=e+r>>>1,i=this.orderedIds[n];i&&i.createdAt<=t?e=n+1:r=n}return e}}function ot(t=4,e){let r;switch(t){case 1:r=function(){var t,e;const r=Date.now(),n=4294967295&r,i=r>>32&65535,s=r>>48&4095,o=new Uint8Array(6);crypto.getRandomValues(o),o[0]=1|(null!=(t=o[0])?t:0);const a=Math.floor(16383*Math.random()),c=new Uint8Array(16);return c[0]=n>>24&255,c[1]=n>>16&255,c[2]=n>>8&255,c[3]=255&n,c[4]=i>>8&255,c[5]=255&i,c[6]=15&(null!=(e=c[6])?e:0)|16,c[7]=255&s,c[8]=a>>8&63|128,c[9]=255&a,c.set(o,10),at(c)}();break;case 7:r=function(){var t,e;const r=Date.now(),n=new Uint8Array(10);crypto.getRandomValues(n);const i=new Uint8Array(16),s=0xffffffffffff&r;return i[0]=s>>40&255,i[1]=s>>32&255,i[2]=s>>24&255,i[3]=s>>16&255,i[4]=s>>8&255,i[5]=255&s,n[0]=15&(null!=(t=n[0])?t:0)|112,n[2]=63&(null!=(e=n[2])?e:0)|128,i.set(n.slice(0,6),6),i.set(n.slice(6),12),at(i)}();break;default:r=function(){var t,e;const r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=15&(null!=(t=r[6])?t:0)|64,r[8]=63&(null!=(e=r[8])?e:0)|128,at(r)}()}return r}function at(t){const e=Array.from(t).map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}var ct=/* @__PURE__ */(t=>(t.FAILED="CONNECTION_FAILED",t.TIMEOUT="CONNECTION_TIMEOUT",t.NOT_FOUND="DEVICE_NOT_FOUND",t.DISCONNECTED="DEVICE_DISCONNECTED",t.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",t.CHARACTERISTIC_NOT_FOUND="CHARACTERISTIC_NOT_FOUND",t.DISCOVERY_FAILED="SERVICE_DISCOVERY_FAILED",t.PLATFORM_UNSUPPORTED="PLATFORM_NOT_SUPPORTED",t))(ct||{});class ht extends S{constructor(t,e,r){super(C(t)?t:w.CONNECTION_FAILED,e,r),this.name="ConnectionError",Error.captureStackTrace&&Error.captureStackTrace(this,ht)}static isConnectionError(t){return t instanceof ht}}var lt=/* @__PURE__ */(t=>(t.FAILED="PRINT_JOB_FAILED",t.IN_PROGRESS="PRINT_JOB_IN_PROGRESS",t.CANCELLED="PRINT_JOB_CANCELLED",t.INVALID_DATA="INVALID_IMAGE_DATA",t.WRITE_FAILED="WRITE_FAILED",t.WRITE_TIMEOUT="WRITE_TIMEOUT",t))(lt||{});class ut extends S{constructor(t,e,r){super(C(t)?t:w.PRINT_JOB_FAILED,e,r),this.jobErrorCode=t,this.name="PrintJobError",Error.captureStackTrace&&Error.captureStackTrace(this,ut)}static isPrintJobError(t){return t instanceof ut}}var dt=/* @__PURE__ */(t=>(t.INVALID_CONFIG="INVALID_CONFIGURATION",t.ENCODING_NOT_SUPPORTED="ENCODING_NOT_SUPPORTED",t.INVALID_IMAGE="INVALID_IMAGE_DATA",t.INVALID_QR="INVALID_QR_DATA",t.DRIVER_ERROR="DRIVER_ERROR",t))(dt||{});const ft={INVALID_CONFIGURATION:w.INVALID_CONFIGURATION,ENCODING_NOT_SUPPORTED:w.ENCODING_NOT_SUPPORTED,INVALID_IMAGE_DATA:w.INVALID_IMAGE_DATA,INVALID_QR_DATA:w.INVALID_QR_DATA,DRIVER_ERROR:w.PRINT_JOB_FAILED};class gt extends S{constructor(t,e,r){var n;super(null!=(n=ft[t])?n:w.INVALID_CONFIGURATION,e,r),this.buildErrorCode=t,this.name="CommandBuildError",Error.captureStackTrace&&Error.captureStackTrace(this,gt)}static isCommandBuildError(t){return t instanceof gt}}export{ct as A,S as B,gt as C,ut as D,Q as E,lt as F,T as G,y as H,W as I,N as J,b as K,m as L,A as M,p as N,it as O,E as P,z as a,q as b,k as c,G as d,V as e,H as f,P as g,F as h,B as i,v as j,J as k,et as l,nt as m,w as n,D as o,L as p,x as q,j as r,st as s,R as t,$ as u,ot as v,U as w,_ as x,dt as y,ht as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var t=Object.defineProperty,e=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,i=Math.pow,o=(e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,s=(t,i)=>{for(var s in i||(i={}))r.call(i,s)&&o(t,s,i[s]);if(e)for(var s of e(i))n.call(i,s)&&o(t,s,i[s]);return t},a=(t,e,r)=>new Promise((n,i)=>{var o=t=>{try{a(r.next(t))}catch(e){i(e)}},s=t=>{try{a(r.throw(t))}catch(e){i(e)}},a=t=>t.done?n(t.value):Promise.resolve(t.value).then(o,s);a((r=r.apply(t,e)).next())});const c=require("./gbk-data-Cunq2WDW.js");var h=(t=>(t.DISCONNECTED="disconnected",t.CONNECTING="connecting",t.CONNECTED="connected",t.DISCONNECTING="disconnecting",t.PRINTING="printing",t.PAUSED="paused",t))(h||{});const l={maxLength:1e4,suffix:"... [truncated]",preserveHead:!0,headLength:5e3,tailLength:5e3};function u(t,e={}){const r=s(s({},l),e);if(t.length<=r.maxLength)return t;if(r.preserveHead&&r.headLength+r.tailLength+r.suffix.length<r.maxLength){const e=t.slice(0,r.headLength),n=t.slice(-r.tailLength);return`${e}${r.suffix}${n}`}return t.slice(0,r.maxLength-r.suffix.length)+r.suffix}function d(t,e=2e3){if(null===t)return"null";if(void 0===t)return"undefined";let r;if("string"==typeof t)r=t;else{if("number"==typeof t||"boolean"==typeof t)return t+"";if(t instanceof Error)return r=`${t.name}: ${t.message}`,t.stack&&(r+="\n"+u(t.stack,{maxLength:1e3})),r;if(t instanceof Uint8Array||t instanceof ArrayBuffer){const e=t instanceof ArrayBuffer?new Uint8Array(t):t;return r=`Uint8Array(${e.length}) [${u(Array.from(e.slice(0,100)).map(t=>t.toString(16).padStart(2,"0")).join(" "),{maxLength:300})}]`,e.length>100&&(r+=` ... (${e.length} bytes total)`),r}try{r=JSON.stringify(t)}catch(n){r=Object.prototype.toString.call(t)}}return u(r,{maxLength:e})}function f(t){if(null===t)return"null";if(void 0===t)return"undefined";if("string"==typeof t)return`string(${t.length}): "${u(t,{maxLength:100})}"`;if("number"==typeof t)return"number: "+t;if("boolean"==typeof t)return"boolean: "+t;if(Array.isArray(t))return`array[${t.length}]`;if(t instanceof Uint8Array)return`Uint8Array(${t.length} bytes)`;if(t instanceof ArrayBuffer)return`ArrayBuffer(${t.byteLength} bytes)`;if(t instanceof Error)return`Error: ${t.name}: ${u(t.message,{maxLength:100})}`;if("object"==typeof t){const e=Object.keys(t);return`object{${e.length} keys: ${e.slice(0,5).join(", ")}${e.length>5?"...":""}}`}return t+""}var g=(t=>(t[t.DEBUG=0]="DEBUG",t[t.INFO=1]="INFO",t[t.WARN=2]="WARN",t[t.ERROR=3]="ERROR",t[t.NONE=4]="NONE",t))(g||{});const p=class t{static configure(t){this.config=s(s({},this.config),t)}static setLevel(t){this.config.level=t}static getLevel(){return this.config.level}static formatPrefix(t,e){return`${e?`${this.config.prefix}:${e}`:this.config.prefix} [${{0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"NONE"}[t]}]`}static formatMessage(t,e,r){return`${this.formatPrefix(t,r)} ${e}`}static log(t,e,r,n){if(this.config.level>t)return;this.formatPrefix(t,n);const i=this.formatMessage(t,e,n),o={level:t,message:e,args:this.config.useSummaryMode?r.map(t=>f(t)):r.map(t=>d(t,this.config.maxOutputLength)),timestamp:new Date,scope:n,formatted:i};this.config.handler&&this.config.handler(o)}static debug(t,...e){this.log(0,t,e)}static info(t,...e){this.log(1,t,e)}static warn(t,...e){this.log(2,t,e)}static error(t,...e){this.log(3,t,e)}static scope(e){return{debug:(r,...n)=>{t.log(0,r,n,e)},info:(r,...n)=>{t.log(1,r,n,e)},warn:(r,...n)=>{t.log(2,r,n,e)},error:(r,...n)=>{t.log(3,r,n,e)}}}};p.config={level:2,prefix:"[TaroBTPrint]",maxOutputLength:5e3,useSummaryMode:!1};let E=p;function I(t){return t instanceof Error?t:Error(null==t?"Unknown error (null or undefined)":t+"")}var A=(t=>(t.CONNECTION_FAILED="CONNECTION_FAILED",t.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",t.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",t.DEVICE_DISCONNECTED="DEVICE_DISCONNECTED",t.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",t.CHARACTERISTIC_NOT_FOUND="CHARACTERISTIC_NOT_FOUND",t.SERVICE_DISCOVERY_FAILED="SERVICE_DISCOVERY_FAILED",t.WRITE_FAILED="WRITE_FAILED",t.WRITE_TIMEOUT="WRITE_TIMEOUT",t.PRINT_JOB_IN_PROGRESS="PRINT_JOB_IN_PROGRESS",t.PRINT_JOB_CANCELLED="PRINT_JOB_CANCELLED",t.PRINT_JOB_FAILED="PRINT_JOB_FAILED",t.INVALID_CONFIGURATION="INVALID_CONFIGURATION",t.ENCODING_NOT_SUPPORTED="ENCODING_NOT_SUPPORTED",t.INVALID_IMAGE_DATA="INVALID_IMAGE_DATA",t.INVALID_QR_DATA="INVALID_QR_DATA",t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.QUEUE_FULL="QUEUE_FULL",t.QUEUE_JOB_NOT_FOUND="QUEUE_JOB_NOT_FOUND",t.PREVIEW_FAILED="PREVIEW_FAILED",t))(A||{});function T(t){return Object.values(A).includes(t)}class y extends Error{constructor(t,e,r){super(e),this.code=t,this.originalError=r,this.name="BluetoothPrintError",Error.captureStackTrace&&Error.captureStackTrace(this,y)}toString(){let t=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(t+="\nCaused by: "+this.originalError.message,this.originalError.stack&&(t+="\n"+this.originalError.stack)),this.stack&&(t+="\n"+this.stack),t}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}}}var N=(t=>(t.WECHAT="wechat",t.ALIPAY="alipay",t.BAIDU="baidu",t.BYTEDANCE="bytedance",t.QQ="qq",t.WEB="web",t.UNKNOWN="unknown",t))(N||{});function _(t){return"object"==typeof t&&null!==t&&"request"in t}function O(){return"undefined"!=typeof wx&&_(wx)?"wechat":"undefined"!=typeof my&&_(my)?"alipay":"undefined"!=typeof swan&&_(swan)?"baidu":"undefined"!=typeof tt&&_(tt)?"bytedance":"undefined"!=typeof qq&&_(qq)?"qq":"undefined"!=typeof window&&"object"==typeof(t=window)&&null!==t&&"navigator"in t?"web":"unknown";var t}function m(t){return t>=44032&&55215>=t}function D(t){return t>=19968&&40959>=t||t>=63744&&64255>=t||t>=13312&&19903>=t}function R(t){return t>=4352&&4607>=t||t>=12592&&12687>=t||t>=65440&&65503>=t}function x(t){return t>=12352&&12447>=t}function w(t){return t>=12448&&12543>=t}function C(t){return t>=19968&&40959>=t||t>=13312&&19903>=t||t>=63744&&64255>=t}function S(t){if(!m(t))return null;const e=t-44032,r=Math.floor(e/588),n=Math.floor(e%588/28),i=e%28,o=[129,130,132,133,136,138,139,140,141,142,143,144,145,146],s=[0,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155];if(r>=o.length)return null;if(n>=21)return null;const a=o[r];let c=0;if(i>0&&s.length>i){const t=s[i];void 0!==t&&(c=t)}const h=a,l=0!==c?c:0;if(0===c){const t=Math.floor(21*(a-129)+n);return[255&176+Math.floor(t/94),255&161+t%94]}return[h,l]}function U(t){return 12352>t||t>12447?null:[130,255&t-12352+159]}function M(t){return 12448>t||t>12543?null:[131,255&t-12448+64]}const L=new Uint8Array([27,40,66]),b=new Uint8Array([27,36,66]);function P(t){return x(t)||w(t)||C(t)}const F={defaultEncoding:"GBK",fallbackChar:"?",showWarnings:!0},v=class t{constructor(t){this.logger=E.scope("EncodingService"),this.config=s(s({},F),t)}configure(t){this.config=s(s({},this.config),t)}getConfig(){return s({},this.config)}encode(e,r){if(!e||"string"!=typeof e)return new Uint8Array(0);switch(this.normalizeEncoding(r||this.config.defaultEncoding)){case"UTF8":case"UTF-8":return t.utf8Encoder.encode(e);case"GBK":case"GB2312":return this.encodeGbk(e);case"BIG5":return this.encodeBig5(e);case"EUCKR":case"EUC-KR":return this.encodeKorean(e);case"SHIFTJIS":case"SHIFT-JIS":case"SJIS":return this.encodeShiftJis(e);case"ISO2022JP":case"ISO-2022-JP":case"JIS":return this.encodeIso2022Jp(e);default:return this.config.showWarnings&&this.logger.warn(`Unknown encoding "${r}", falling back to UTF-8`),t.utf8Encoder.encode(e)}}encodeWithInfo(e,r){if(!e||"string"!=typeof e)return{bytes:new Uint8Array(0),unsupportedCount:0,unsupportedChars:[]};const n=this.normalizeEncoding(r||this.config.defaultEncoding);if("UTF8"===n||"UTF-8"===n)return{bytes:t.utf8Encoder.encode(e),unsupportedCount:0,unsupportedChars:[]};const i=[],o=[],s=this.config.fallbackChar.charCodeAt(0);for(let t=0;t<e.length;t++){const r=e.charAt(t),a=e.charCodeAt(t);if(a>=55296&&56319>=a&&t+1<e.length){const r=e.charCodeAt(t+1);if(r>=56320&&57343>=r){o.push(e.substring(t,t+2)),i.push(s),t++;continue}}if(c.i(a)){i.push(a);continue}let h=null;h="BIG5"===n?c.g(a):c.d(a),h?i.push(h[0],h[1]):(void 0!==r&&o.push(r),i.push(s),this.config.showWarnings&&1===o.length&&void 0!==r&&this.logger.warn(`Character "${r}" (U+${a.toString(16).toUpperCase()}) not supported in ${n}`))}return{bytes:new Uint8Array(i),unsupportedCount:o.length,unsupportedChars:[...new Set(o)]}}isSupported(t){if(!t||"string"!=typeof t)return!1;const e=this.normalizeEncoding(t);return["GBK","GB2312","BIG5","UTF8","UTF-8","EUCKR","EUC-KR","SHIFTJIS","SHIFT-JIS","SJIS","ISO2022JP","ISO-2022-JP","JIS"].includes(e)}detectEncoding(t){if(!t||"string"!=typeof t)return"UTF-8";let e=!1,r=!1,n=!1,i=0,o=0,s=0;for(let l=0;l<t.length;l++){const a=t.charCodeAt(l);(55296>a||a>57343)&&(c.i(a)?e=!0:(s++,c.a(a)?(r=!0,c.u.has(a)&&i++,c.b.has(a)&&o++):c.c(a)&&(n=!0,c.u.has(a)&&i++)))}if(!r&&!n&&e)return"UTF-8";if(0===s)return"UTF-8";const a=i/s,h=o/s;return h>a&&h>.8?"BIG5":a>.8?"GBK":"UTF-8"}getSupportedEncodings(){return["GBK","GB2312","BIG5","UTF-8","EUC-KR","SHIFT-JIS","ISO-2022-JP"]}encodeGbk(t){return this.encodeWithStrategy(t,t=>c.d(t))}encodeBig5(t){return this.encodeWithStrategy(t,t=>c.g(t)||c.d(t))}encodeKorean(t){try{(new TextEncoder).encode("\uac00")}catch(e){}return this.encodeWithStrategy(t,t=>m(t)?S(t):(R(t)||D(t),null))}encodeShiftJis(t){return this.encodeWithStrategy(t,t=>{const e=U(t);if(e)return e;return M(t)||null})}encodeIso2022Jp(t){return this.encodeWithStrategy(t,t=>{if(P(t)){const e=U(t);if(e)return[...b,...e];const r=M(t);return r?[...b,...r]:null}return null},{init:t=>t.push(...L),onSurrogate:(t,e)=>{t.push(...L,e)},onAscii:(t,e)=>{t.push(...L,e)},finalize:t=>t.push(...L)})}normalizeEncoding(t){return t.toUpperCase().replace(/-/g,"").replace("_","")}encodeWithStrategy(t,e,r){var n,i;const o=[],s=this.config.fallbackChar.charCodeAt(0);null==(n=null==r?void 0:r.init)||n.call(r,o);for(let a=0;a<t.length;a++){const n=t.charCodeAt(a);if(n>=55296&&56319>=n&&a+1<t.length){const e=t.charCodeAt(a+1);if(e>=56320&&57343>=e){(null==r?void 0:r.onSurrogate)?r.onSurrogate(o,s):o.push(s),a++;continue}}if(c.i(n)){(null==r?void 0:r.onAscii)?r.onAscii(o,n):o.push(n);continue}const i=e(n);i?o.push(...i):o.push(s)}return null==(i=null==r?void 0:r.finalize)||i.call(r,o),new Uint8Array(o)}};v.utf8Encoder=new TextEncoder;let B=v;const G=new B,k=E.scope("Encoding"),V=class{static configure(t){this.config=s(s({},this.config),t)}static encode(t,e="GBK"){if(!t||"string"!=typeof t)return new Uint8Array(0);const r=e.toUpperCase().replace("-","");return"UTF8"===r||"UTF-8"===r||this.config.showWarnings&&!this.warningShown&&(k.warn(`Encoding ${e} not yet fully implemented, falling back to UTF-8. This may cause display issues with some printers.`),this.warningShown=!0),this.utf8Encoder.encode(t)}static isSupported(t){if(!t||"string"!=typeof t)return!1;const e=t.toUpperCase().replace("-","");return"UTF8"===e||"UTF-8"===e}};V.utf8Encoder=new TextEncoder,V.warningShown=!1,V.config={showWarnings:!0};let $=V;const J=class{static toBitmap(t,e,r,n){if(!(t&&t instanceof Uint8Array&&e>0&&r>0))return new Uint8Array(0);if(t.length!==e*r*4)throw new y(A.INVALID_IMAGE_DATA,`Invalid image data length: expected ${e*r*4}, got ${t.length}`);let i=n||{};if(i.qualityPreset){const t=this.QUALITY_PRESETS[i.qualityPreset];i=s(s({},i),t)}const{targetWidth:o,targetHeight:a,useDithering:c=!0,ditheringAlgorithm:h="floyd-steinberg",scalingAlgorithm:l="nearest",contrast:u=1,brightness:d=0,threshold:f=128,orderedMatrixSize:g=4,halftoneDotType:p="round"}=i;let E=t,I=e,T=r;if(o||a){const n=this.scaleImage(t,e,r,o||e,a||r,{algorithm:l});E=n.newData,I=n.newWidth,T=n.newHeight}const N=Math.ceil(I/8),_=new Uint8Array(N*T),O=this.toGrayscaleAdjusted(E,I,T,u,d);return c?this.applyDithering(O,I,T,_,N,{algorithm:h,threshold:f,orderedMatrixSize:g,halftoneDotType:p}):this.applyThresholdDithering(O,I,T,_,N,()=>f),_}static preprocessImage(t,e,r,n){if(!(t&&t instanceof Uint8Array))return t;let i=t;return(null==n?void 0:n.gamma)&&1!==n.gamma&&(i=this.applyGammaCorrection(i,n.gamma)),(null==n?void 0:n.denoise)&&(i=this.applyMedianFilter(i,e,r)),(null==n?void 0:n.sharpen)&&(i=this.applyUnsharpMask(i,e,r)),(null==n?void 0:n.posterize)&&(i=this.applyPosterization(i,n.posterize)),i}static toGrayscaleAdjusted(t,e,r,n,i){const o=e*r,s=new Float32Array(o),a=1!==n||0!==i,c=255*i;for(let h=0;o>h;h++){const e=h<<2;let r=(299*t[e]+587*t[e+1]+114*t[e+2])/1e3;a?(r=(r-128)*n+128+c,s[h]=0>r?0:r>255?255:r):s[h]=r}return s}static applyDithering(t,e,r,n,i,o){switch(o.algorithm){case"ordered":{const s=2===o.orderedMatrixSize?this.BAYER_MATRIX_2:8===o.orderedMatrixSize?this.BAYER_MATRIX_8:this.BAYER_MATRIX_4,a=4===o.orderedMatrixSize?16:8===o.orderedMatrixSize?64:4,c=o.threshold,h=o.orderedMatrixSize;this.applyThresholdDithering(t,e,r,n,i,(t,e)=>{var r,n;return c+(null!=(n=null==(r=s[e%h])?void 0:r[t%h])?n:0)/a*48});break}case"halftone":{const s=4,a=this.getHalftoneThresholds(s,o.halftoneDotType),c=o.threshold;this.applyThresholdDithering(t,e,r,n,i,(t,e,r)=>{var n,i;return(null!=(i=null==(n=a[e%s])?void 0:n[t%s])?i:128)+(c>r?-30:30)});break}case"floyd-steinberg":case"atkinson":case"sierra":case"stucki":{const s=this.ERROR_KERNELS[o.algorithm];this.applyErrorDiffusionDithering(t,e,r,n,i,o.threshold,s);break}default:this.applyErrorDiffusionDithering(t,e,r,n,i,o.threshold,this.ERROR_KERNELS["floyd-steinberg"])}}static applyErrorDiffusionDithering(t,e,r,n,i,o,s){const a=s.length;for(let c=0;r>c;c++)this.processErrorDiffusionRow(t,e,r,n,i,c,o,s,a)}static processErrorDiffusionRow(t,e,r,n,i,o,s,a,c){const h=o*e,l=o*i;for(let u=0;e>u;u++){const i=t[h+u],d=s>i?0:255;0===d&&this.writeBlackPixel(n,l,u);const f=i-d;0!==f&&this.distributeError(t,e,r,u,o,f,a,c)}}static writeBlackPixel(t,e,r){var n;const i=e+(r>>3),o=128>>(7&r);t[i]=(null!=(n=t[i])?n:0)|o}static distributeError(t,e,r,n,i,o,s,a){for(let c=0;a>c;c++){const a=s[c],h=n+a.dx,l=i+a.dy;if(h>=0&&e>h&&l>=0&&r>l){const r=l*e+h,n=t[r]+o*a.weight;t[r]=0>n?0:n>255?255:n}}}static applyThresholdDithering(t,e,r,n,i,o){var s;for(let a=0;r>a;a++)for(let r=0;e>r;r++){const c=t[a*e+r];if(c<o(r,a,c)){const t=a*i+(r>>3);n[t]=(null!=(s=n[t])?s:0)|128>>(7&r)}}}static getHalftoneThresholds(t,e){const r=`${t}_${e}`;let n=this.halftoneThresholdCache.get(r);return n||(n=this.computeHalftoneThresholds(t,e),this.halftoneThresholdCache.set(r,n)),n}static computeHalftoneThresholds(t,e){const r=[],n=(t-1)/2;for(let o=0;t>o;o++){r[o]=[];for(let s=0;t>s;s++){let t;t="round"===e?Math.sqrt(i(s-n,2)+i(o-n,2))/n:"diamond"===e?(Math.abs(s-n)+Math.abs(o-n))/n:Math.max(Math.abs(s-n),Math.abs(o-n))/n,r[o][s]=Math.min(255,Math.round(224*t+32))}}return r}static scaleImage(t,e,r,n,i,o){const s=e/r;let a=n,c=i;a/c>s?a=Math.round(c*s):c=Math.round(a/s);const h=new Uint8Array(a*c*4);return"bilinear"===(null==o?void 0:o.algorithm)?this.applyBilinearInterpolation(t,e,r,h,a,c):this.applyNearestNeighbor(t,e,r,h,a,c),{newData:h,newWidth:a,newHeight:c}}static applyNearestNeighbor(t,e,r,n,i,o){this.resampleImage(e,r,i,o,(r,i,o,s,a)=>{const c=4*(s*e+o);n[a]=t[c],n[a+1]=t[c+1],n[a+2]=t[c+2],n[a+3]=t[c+3]})}static applyBilinearInterpolation(t,e,r,n,i,o){this.resampleImage(e,r,i,o,(s,a,c,h,l)=>{const u=Math.min(e-1,s*(e/i)),d=Math.min(r-1,a*(r/o)),f=Math.floor(u),g=Math.floor(d),p=Math.min(f+1,e-1),E=Math.min(g+1,r-1),I=u-f,A=d-g,T=(1-I)*(1-A),y=I*(1-A),N=(1-I)*A,_=I*A;for(let r=0;4>r;r++){const i=4*(g*e+p)+r,o=4*(E*e+f)+r,s=4*(E*e+p)+r,a=t[4*(g*e+f)+r]*T+t[i]*y+t[o]*N+t[s]*_;n[l+r]=Math.round(a)}})}static resampleImage(t,e,r,n,i){const o=t/r,s=e/n;for(let a=0;n>a;a++)for(let n=0;r>n;n++)i(n,a,Math.min(t-1,Math.round(n*o)),Math.min(e-1,Math.round(a*s)),4*(a*r+n))}static applyGammaCorrection(t,e){const r=1/e,n=new Uint8Array(256);for(let o=0;256>o;o++)n[o]=Math.round(255*Math.pow(o/255,r));const i=new Uint8Array(t.length);for(let o=0;o<t.length;o+=4){const e=t[o],r=t[o+1],s=t[o+2];i[o]=n[e],i[o+1]=n[r],i[o+2]=n[s],i[o+3]=t[o+3]}return i}static processPixels(t,e,r,n){if(4>t.length||0>=e||0>=r)return new Uint8Array(0);const i=new Uint8Array(t.length);for(let o=0;r>o;o++)for(let t=0;e>t;t++)n(i,t,o,4*(o*e+t));return i}static applyMedianFilter(t,e,r){return this.processPixels(t,e,r,(n,i,o,s)=>{var a;const c=this.collectNeighborhoodWindow(t,e,r,i,o);c.sort((t,e)=>t-e);for(let t=0;4>t;t++)n[s+t]=null!=(a=c[18+9*t])?a:128})}static collectNeighborhoodWindow(t,e,r,n,i){const o=[];for(let s=-1;1>=s;s++)for(let a=-1;1>=a;a++){const c=this.clampCoordinate(n+a,e),h=4*(this.clampCoordinate(i+s,r)*e+c);for(let e=0;4>e;e++)o.push(t[h+e])}return o}static clampCoordinate(t,e){return 0>t?0:e>t?t:e-1}static applyUnsharpMask(t,e,r){const n=this.getSharpeningKernel();return this.processPixels(t,e,r,(i,o,s,a)=>{for(let c=0;4>c;c++){const h=this.convolveChannel(t,e,r,o,s,c,n);i[a+c]=this.clampToByte(h)}})}static getSharpeningKernel(){return[[-.5,-1,-.5],[-1,3,-1],[-.5,-1,-.5]]}static convolveChannel(t,e,r,n,i,o,s){var a,c;let h=0;for(let l=0;3>l;l++)for(let u=0;3>u;u++){const d=this.clampCoordinate(n+u-1,e),f=4*(this.clampCoordinate(i+l-1,r)*e+d)+o,g=null!=(c=null==(a=s[l])?void 0:a[u])?c:0;h+=t[f]*g}return h}static clampToByte(t){return Math.max(0,Math.min(255,Math.round(t)))}static applyPosterization(t,e){if(4>t.length)return new Uint8Array(0);const r=255/(Math.pow(2,Math.max(1,Math.min(8,e)))-1),n=new Uint8Array(t.length);for(let i=0;i<t.length;i+=4)n[i]=Math.round(Math.round(t[i]/r)*r),n[i+1]=Math.round(Math.round(t[i+1]/r)*r),n[i+2]=Math.round(Math.round(t[i+2]/r)*r),n[i+3]=t[i+3];return n}};J.BAYER_MATRIX_2=[[0,2],[3,1]],J.BAYER_MATRIX_4=[[0,8,2,10],[12,4,14,6],[3,11,1,9],[15,7,13,5]],J.BAYER_MATRIX_8=(()=>{var t,e;const r=J.BAYER_MATRIX_4,n=[];for(let i=0;8>i;i++){n[i]=[];for(let o=0;8>o;o++){const s=(null!=(e=null==(t=r[i>>1])?void 0:t[o>>1])?e:0)+i%2*32+o%2*64;n[i][o]=s}}return n})(),J.QUALITY_PRESETS={draft:{contrast:.9,brightness:-.05,algorithm:"ordered"},normal:{contrast:1,brightness:0,algorithm:"floyd-steinberg"},high:{contrast:1.15,brightness:.08,algorithm:"halftone"}},J.ERROR_KERNELS={"floyd-steinberg":[{dx:1,dy:0,weight:7/16},{dx:-1,dy:1,weight:3/16},{dx:0,dy:1,weight:5/16},{dx:1,dy:1,weight:1/16}],atkinson:[{dx:1,dy:0,weight:1/8},{dx:2,dy:0,weight:1/8},{dx:-1,dy:1,weight:1/8},{dx:0,dy:1,weight:1/8},{dx:1,dy:1,weight:1/8},{dx:0,dy:2,weight:1/8}],sierra:[{dx:1,dy:0,weight:5/32},{dx:2,dy:0,weight:2/32},{dx:-2,dy:1,weight:2/32},{dx:-1,dy:1,weight:3/32},{dx:0,dy:1,weight:5/32},{dx:1,dy:1,weight:2/32},{dx:-1,dy:2,weight:2/32},{dx:0,dy:2,weight:3/32},{dx:1,dy:2,weight:2/32},{dx:2,dy:2,weight:1/32}],stucki:[{dx:1,dy:0,weight:8/42},{dx:2,dy:0,weight:4/42},{dx:-2,dy:1,weight:2/42},{dx:-1,dy:1,weight:4/42},{dx:0,dy:1,weight:8/42},{dx:1,dy:1,weight:4/42},{dx:2,dy:1,weight:2/42},{dx:-2,dy:2,weight:1/42},{dx:-1,dy:2,weight:2/42},{dx:0,dy:2,weight:4/42},{dx:1,dy:2,weight:2/42},{dx:2,dy:2,weight:1/42}]},J.halftoneThresholdCache=new Map;let W=J;function z(t){const e=Array.from(t).map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}var j=(t=>(t.FAILED="CONNECTION_FAILED",t.TIMEOUT="CONNECTION_TIMEOUT",t.NOT_FOUND="DEVICE_NOT_FOUND",t.DISCONNECTED="DEVICE_DISCONNECTED",t.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",t.CHARACTERISTIC_NOT_FOUND="CHARACTERISTIC_NOT_FOUND",t.DISCOVERY_FAILED="SERVICE_DISCOVERY_FAILED",t.PLATFORM_UNSUPPORTED="PLATFORM_NOT_SUPPORTED",t))(j||{});class H extends y{constructor(t,e,r){super(T(t)?t:A.CONNECTION_FAILED,e,r),this.name="ConnectionError",Error.captureStackTrace&&Error.captureStackTrace(this,H)}static isConnectionError(t){return t instanceof H}}var K=(t=>(t.FAILED="PRINT_JOB_FAILED",t.IN_PROGRESS="PRINT_JOB_IN_PROGRESS",t.CANCELLED="PRINT_JOB_CANCELLED",t.INVALID_DATA="INVALID_IMAGE_DATA",t.WRITE_FAILED="WRITE_FAILED",t.WRITE_TIMEOUT="WRITE_TIMEOUT",t))(K||{});class Y extends y{constructor(t,e,r){super(T(t)?t:A.PRINT_JOB_FAILED,e,r),this.jobErrorCode=t,this.name="PrintJobError",Error.captureStackTrace&&Error.captureStackTrace(this,Y)}static isPrintJobError(t){return t instanceof Y}}var q=(t=>(t.INVALID_CONFIG="INVALID_CONFIGURATION",t.ENCODING_NOT_SUPPORTED="ENCODING_NOT_SUPPORTED",t.INVALID_IMAGE="INVALID_IMAGE_DATA",t.INVALID_QR="INVALID_QR_DATA",t.DRIVER_ERROR="DRIVER_ERROR",t))(q||{});const Q={INVALID_CONFIGURATION:A.INVALID_CONFIGURATION,ENCODING_NOT_SUPPORTED:A.ENCODING_NOT_SUPPORTED,INVALID_IMAGE_DATA:A.INVALID_IMAGE_DATA,INVALID_QR_DATA:A.INVALID_QR_DATA,DRIVER_ERROR:A.PRINT_JOB_FAILED};class X extends y{constructor(t,e,r){var n;super(null!=(n=Q[t])?n:A.INVALID_CONFIGURATION,e,r),this.buildErrorCode=t,this.name="CommandBuildError",Error.captureStackTrace&&Error.captureStackTrace(this,X)}static isCommandBuildError(t){return t instanceof X}}exports.A=j,exports.B=y,exports.C=X,exports.D=Y,exports.E=B,exports.F=K,exports.G=function(t,e,r){return a(this,null,function*(){const n=[],i=Math.ceil(t.length/e);for(let s=0;s<t.length;s+=e){const a=t.slice(s,s+e),c=Math.floor(s/e)+1;try{const t=yield r(a,c);n.push(...t)}catch(o){throw o instanceof Error?o:Error(o+"")}i>c&&(yield new Promise(t=>setTimeout(t,0)))}return n})},exports.H=function(t=5e3){return{log:(...e)=>{e.map(e=>d(e,t))},warn:(...e)=>{e.map(e=>d(e,t))},error:(...e)=>{e.map(e=>d(e,t))}}},exports.I=L,exports.J=f,exports.K=function(){const t=O();return"unknown"!==t&&"web"!==t},exports.L=E,exports.M=d,exports.N=u,exports.O=function(t,e){const r=Math.min(t.length,null!=e?e:t.length),n=[];for(let i=0;r>i;i++)n.push(t[i].toString(16).padStart(2,"0").toUpperCase());return n.join("")},exports.P=h,exports.a=b,exports.b=G,exports.c=C,exports.d=w,exports.e=S,exports.f=function(t){return t>=65377&&65439>=t||t>=12448&&12543>=t},exports.g=m,exports.h=D,exports.i=x,exports.j=R,exports.k=M,exports.l=$,exports.m=W,exports.n=A,exports.o=I,exports.p=O,exports.q=N,exports.r=P,exports.s=class{constructor(t){if(this.maxEntries=t,this.entries=new Map,this.orderedIds=[],1>t)throw new RangeError("BoundedOrderedMap: maxEntries must be >= 1")}set(t,e){this.entries.set(t,e);const r=this.findInsertPosition(e.createdAt);this.orderedIds.splice(r,0,{id:t,createdAt:e.createdAt}),this.enforceMaxEntries()}get(t){return this.entries.get(t)}has(t){return this.entries.has(t)}delete(t){const e=this.entries.delete(t);if(e){const e=this.orderedIds.findIndex(e=>e.id===t);-1!==e&&this.orderedIds.splice(e,1)}return e}clear(){this.entries.clear(),this.orderedIds.length=0}get size(){return this.entries.size}get maxSize(){return this.maxEntries}values(){return this.entries.values()}keys(){return this.entries.keys()}entriesIter(){return this.entries.entries()}rebuildIndex(){this.orderedIds.length=0;for(const[t,e]of this.entries)this.orderedIds.push({id:t,createdAt:e.createdAt});this.orderedIds.sort((t,e)=>t.createdAt-e.createdAt)}enforceMaxEntries(){const t=this.entries.size-this.maxEntries;if(t>0){for(let e=0;t>e;e++){const t=this.orderedIds[e];t&&this.entries.delete(t.id)}this.orderedIds.splice(0,t)}}findInsertPosition(t){let e=0,r=this.orderedIds.length;for(;r>e;){const n=e+r>>>1,i=this.orderedIds[n];i&&i.createdAt<=t?e=n+1:r=n}return e}},exports.t=function(t,e){const r=I(t);throw e("error",r),r},exports.u=U,exports.v=function(t=4,e){let r;switch(t){case 1:r=function(){var t,e;const r=Date.now(),n=4294967295&r,i=r>>32&65535,o=r>>48&4095,s=new Uint8Array(6);crypto.getRandomValues(s),s[0]=1|(null!=(t=s[0])?t:0);const a=Math.floor(16383*Math.random()),c=new Uint8Array(16);return c[0]=n>>24&255,c[1]=n>>16&255,c[2]=n>>8&255,c[3]=255&n,c[4]=i>>8&255,c[5]=255&i,c[6]=15&(null!=(e=c[6])?e:0)|16,c[7]=255&o,c[8]=a>>8&63|128,c[9]=255&a,c.set(s,10),z(c)}();break;case 7:r=function(){var t,e;const r=Date.now(),n=new Uint8Array(10);crypto.getRandomValues(n);const i=new Uint8Array(16),o=0xffffffffffff&r;return i[0]=o>>40&255,i[1]=o>>32&255,i[2]=o>>24&255,i[3]=o>>16&255,i[4]=o>>8&255,i[5]=255&o,n[0]=15&(null!=(t=n[0])?t:0)|112,n[2]=63&(null!=(e=n[2])?e:0)|128,i.set(n.slice(0,6),6),i.set(n.slice(6),12),z(i)}();break;default:r=function(){var t,e;const r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=15&(null!=(t=r[6])?t:0)|64,r[8]=63&(null!=(e=r[8])?e:0)|128,z(r)}()}return r},exports.w=function(t,e,r="Operation timed out"){return a(this,null,function*(){let n;const i=new Promise((t,i)=>{n=setTimeout(()=>{i(Error(`${r} after ${e}ms`))},e)});try{return yield Promise.race([t,i])}finally{void 0!==n&&clearTimeout(n)}})},exports.x=g,exports.y=q,exports.z=H;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../chunks/index-Cee15KIh.js");exports.BluetoothPrinter=e.B,exports.EventEmitter=e.E;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as t,E as e}from"../chunks/index-DIquif_6.js";export{t as BluetoothPrinter,e as EventEmitter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var t=Object.defineProperty,s=Object.getOwnPropertySymbols,e=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,r=Math.pow,i=(s,e,n)=>e in s?t(s,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[e]=n;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("../chunks/EscPosDriver-BEwkA9KT.js"),a=require("../chunks/shared-CvHoYVGG.js");class o extends h.E{printAndFeed(t){return[new Uint8Array([27,100,t])]}}class u extends h.E{init(){return super.init()}getStatus(){return[new Uint8Array([27,105])]}getDetailedStatus(){const t=[];for(let s=1;4>=s;s++)t.push(new Uint8Array([16,4,s]));return t}feedAndCut(t){return[new Uint8Array([27,100,t]),new Uint8Array([29,86,0])]}}class c extends h.E{sleep(){return[new Uint8Array([27,61,1])]}wakeUp(){return[new Uint8Array([0])]}wakeUpDeep(){const t=[];for(let s=0;5>s;s++)t.push(new Uint8Array([0]));return t.push(new Uint8Array([27,64])),t}setAutoSleep(t){return[new Uint8Array([27,61,t?1:0])]}}function m(t,r,h={}){const a=t;return a.code128=function(s,e=0,n=0,i=50){return r.call(t,s,{x:e,y:n,type:"128",height:i})},a.code39=function(a,o=0,u=0,c=50){return r.call(t,a,((t,r)=>{for(var h in r||(r={}))e.call(r,h)&&i(t,h,r[h]);if(s)for(var h of s(r))n.call(r,h)&&i(t,h,r[h]);return t})({x:o,y:u,type:"39",height:c},h))},a}exports.EscPos=h.E,exports.CpclDriver=class{constructor(t=576,s=0){this.commands=[],this.logger=a.L.scope("CpclDriver"),this.pageWidth=576,this.pageHeight=0,this.pageWidth=t,this.pageHeight=s,m(this,this.barcode.bind(this),{wide:2,narrow:1})}setPageSize(t,s=0){return this.pageWidth=t,this.pageHeight=s,this}usePageSize(t){const[s,e]={"4X6":[576,864],"4X4":[576,576],"4X2":[576,288],"2.25X1.25":[324,180],A4:[992,1406],A5:[701,992],LETTER:[1050,1500],CUSTOM:[576,0]}[t]||[576,0];return this.pageWidth=s,this.pageHeight=e,this}pageStart(){return this.commands.push("! U1 SETLP 5 0 30"),this.commands.push("! U1 PAGE WIDTH "+this.pageWidth),this.pageHeight>0&&this.commands.push("! U1 PAGE HEIGHT "+this.pageHeight),this.commands.push("START"),this}pageEnd(){return this.commands.push("END"),this}formFeed(){return this.commands.push("FORM"),this}setLinePrint(t=5,s=0,e=30){return this.commands.push(`! U1 SETLP ${t} ${s} ${e}`),this}setFont(t=3,s=1,e=1,n=0){const r={0:"N",90:"R",180:"B",270:"I"}[n]||"N";return this.commands.push(`! U1 SETLP ${t} ${s} ${e} ${r}`),this}text(t){return this.commands.push("! U1 TEXT "+this.escapeText(t)),this}textAt(t,s){const{x:e=0,y:n=0,font:r=3,xMulti:i=1,yMulti:h=1,rotation:a=0}=s,o={0:"N",90:"R",180:"B",270:"I"}[a]||"N";return this.commands.push(`! U1 SETLP ${r} ${i} ${h} ${o}`),this.commands.push(`! U1 ${e} ${n} TEXT ${this.escapeText(t)}`),this}legacyText(t,s,e,n=3){return this.commands.push(`TEXT ${s} ${e} ${n} "${this.escapeText(t)}"`),this}barcode(t,s){const{x:e=0,y:n=0,type:r="128",height:i=50,wide:h=2,narrow:a=1,readable:o=!0}=s,u=o?"B":"N";switch(r){case"128":default:this.commands.push(`BARCODE 128 ${e} ${n} ${i} ${u} 0 ${a} ${h} "${t}"`);break;case"39":this.commands.push(`BARCODE 39 ${e} ${n} ${i} ${u} ${h} ${a} "${t}"`);break;case"EAN13":this.commands.push(`BARCODE EAN13 ${e} ${n} ${i} ${u} "${t}"`);break;case"EAN8":this.commands.push(`BARCODE EAN8 ${e} ${n} ${i} ${u} "${t}"`);break;case"UPCA":this.commands.push(`BARCODE UPCA ${e} ${n} ${i} ${u} "${t}"`);break;case"UPCE":this.commands.push(`BARCODE UPCE ${e} ${n} ${i} ${u} "${t}"`);break;case"PDF417":this.commands.push(`BARCODE PDF417 ${e} ${n} 6 200 "${t}"`);break;case"DATAMATRIX":this.commands.push(`BARCODE DATAMATRIX ${e} ${n} 200 "${t}"`);break;case"QR":this.qrcode(t,{x:e,y:n})}return this}qrcode(t,s){const{x:e=0,y:n=0,model:r=2,errorCorrection:i="M",cellSize:h=4}=s||{};return this.commands.push(`BARCODE QR ${e} ${n} ${r} ${h} A ${i} "${t}"`),this}twoDBarcode(t,s,e=0,n=0,r=200){return"PDF417"===s?this.commands.push(`BARCODE PDF417 ${e} ${n} 6 ${r} "${t}"`):this.commands.push(`BARCODE DATAMATRIX ${e} ${n} ${r} "${t}"`),this}line(t){const{x1:s,y1:e,x2:n,y2:r,width:i=1}=t;return this.commands.push(`LINE ${s} ${e} ${n} ${r} ${i}`),this}box(t){const{x:s,y:e,width:n,height:r,thickness:i=1}=t;return this.commands.push(`BOX ${s} ${e} ${n} ${r} ${i}`),this}inverse(t,s,e,n){return this.commands.push(`INVERSE ${e} ${n} ${t} ${s}`),this}setDensity(t){const s=Math.min(50,Math.max(-50,t));return this.commands.push("! U1 SETDENSITY "+s),this}setSpeed(t){const s=Math.min(6,Math.max(2,t));return this.commands.push("! U1 SETSPEED "+s),this}cut(){return this.commands.push("CUT"),this}partialCut(){return this.commands.push("PCUT"),this}feedCut(){return this.commands.push("FEED CUT"),this}beep(t=1,s=5){return this.commands.push(`BEEP ${t} ${s}`),this}logo(t,s,e){return this.commands.push(`LOGO ${t} ${s} "${e}"`),this}downloadLogo(t,s,e){var n,r;const i=null!=(n=null==e?void 0:e.width)?n:100,h=Math.ceil(i/8),o=null!=(r=null==e?void 0:e.height)?r:Math.max(1,Math.floor(s.length/h)),u=h*o;s.length<u&&this.logger.warn(`CPCL logo bitmap size mismatch: expected ${u}, got ${s.length}`);const c=a.O(s,u);return this.commands.push("! DF "+t),this.commands.push(`CG ${u} ${h} ${o} ${c}`),this.commands.push("! DF"),this.logger.debug(`CPCL logo downloaded: ${t} (${i}x${o})`),this}printLogo(t,s=0,e=0){return this.commands.push(`LOGO ${s} ${e} "${t}"`),this}getCommands(){return this.commands.join("\r\n")+"\r\n"}getBuffer(){const t=this.getCommands();return this.logger.debug("CPCL commands:\n"+t),a.l.encode(t,"ASCII")}getCommandList(){return[...this.commands]}reset(){return this.commands=[],this}getPageWidth(){return this.pageWidth}escapeText(t){return t.replace(/"/g,'""')}},exports.GPrinterDriver=o,exports.SprtDriver=c,exports.StarPrinter=class{constructor(t){var s,e,n,r;this.logger=a.L.scope("StarPrinter"),this._boldEnabled=!1,this._alignment="left",this.useEncodingService=null==(s=null==t?void 0:t.useEncodingService)||s,this.internationalCharset=null==(e=null==t?void 0:t.internationalCharset)||e,this.encodingService=new a.E({showWarnings:null==(n=null==t?void 0:t.showEncodingWarnings)||n,fallbackChar:null!=(r=null==t?void 0:t.fallbackChar)?r:"?"}),this.logger.info("StarPrinter driver initialized")}init(){const t=[];return t.push(new Uint8Array([27,64])),this.internationalCharset&&t.push(new Uint8Array([27,82,0])),this._boldEnabled=!1,this._alignment="left",t}text(t,s="GBK"){if(!t||"string"!=typeof t)return[];const e=[];if("left"!==this._alignment){const t=this.align(this._alignment);t.length>0&&t[0]&&e.push(t[0])}if(this._boldEnabled&&e.push(new Uint8Array([27,69,1])),this.useEncodingService&&this.encodingService.isSupported(s)){const n=this.encodingService.encode(t,s);e.push(n)}else{const s=(new TextEncoder).encode(t);e.push(s)}return e.push(new Uint8Array([10])),this._boldEnabled&&e.push(new Uint8Array([27,69,0])),"left"!==this._alignment&&e.push(new Uint8Array([27,97,0])),e}feed(t=1){return[new Uint8Array([27,100,Math.max(1,Math.min(255,Math.floor(t)))])]}cut(){const t=[];return t.push(new Uint8Array([27,100,3])),t.push(new Uint8Array([29,86,0])),t}qr(t,s){var e,n,r,i,h;if(!t||"string"!=typeof t)return[];const a=null!=(e=null==s?void 0:s.model)?e:2;let o=4;s&&("cellSize"in s?o=null!=(n=s.cellSize)?n:4:"size"in s&&(o=null!=(r=s.size)?r:4));const u=null!=(i=null==s?void 0:s.errorCorrection)?i:"M",c=[];c.push(new Uint8Array([27,29,87,1,1===a?48:49])),c.push(new Uint8Array([27,29,87,2,Math.min(8,Math.max(1,o))]));const m=null!=(h={L:0,M:1,Q:2,H:3}[u])?h:1;c.push(new Uint8Array([27,29,87,3,m]));const d=this.useEncodingService&&this.encodingService.isSupported("UTF-8")?this.encodingService.encode(t,"UTF-8"):(new TextEncoder).encode(t),l=d.length,p=l%256,$=Math.floor(l/256);return c.push(new Uint8Array([27,29,87,0,p,$])),c.push(d),c.push(new Uint8Array([27,29,87,4])),c}barcode(t,s){var e,n,r,i,h;if(!t||"string"!=typeof t)return[];const a=null!=(e=null==s?void 0:s.type)?e:"CODE128",o=Math.max(1,Math.min(255,null!=(n=null==s?void 0:s.height)?n:40)),u=Math.max(1,Math.min(5,null!=(r=null==s?void 0:s.width)?r:2)),c=[],m=null!=(h={none:0,above:1,below:2,both:3}[null!=(i=null==s?void 0:s.hri)?i:"below"])?h:2;switch(c.push(new Uint8Array([29,104,o])),c.push(new Uint8Array([29,119,u])),c.push(new Uint8Array([29,72,m])),a){case"CODE39":{const s=`*${t.toUpperCase()}*`;c.push(new Uint8Array([29,107,4])),c.push((new TextEncoder).encode(s)),c.push(new Uint8Array([0]));break}case"EAN13":{const s=t.replace(/\D/g,"");12>s.length&&this.logger.warn("EAN13 requires 12 digits, got "+s.length),c.push(new Uint8Array([29,107,2]));const e=s.padStart(12,"0").substring(0,12);c.push((new TextEncoder).encode(e)),c.push(new Uint8Array([0]));break}default:c.push(new Uint8Array([29,107,73])),c.push((new TextEncoder).encode(t)),c.push(new Uint8Array([0]))}return c}image(t,s,e,n){if(!(t&&t instanceof Uint8Array&&s>0&&e>0))return this.logger.warn("Invalid image parameters"),[];const r=s*e*4;if(t.length!==r)return this.logger.warn(`Invalid image data length: expected ${r}, got ${t.length}`),[];const i=[],h=a.m.toBitmap(t,s,e),o=Math.ceil(s/8),u=o%256,c=Math.floor(o/256);i.push(new Uint8Array([27,42,u,c]));for(let a=0;e>a;a++){const t=h.slice(a*o,(a+1)*o);i.push(t)}return i}beep(){return[new Uint8Array([27,66,5])]}bold(t){return this._boldEnabled=t,[new Uint8Array([27,69,t?1:0])]}align(t){var s;this._alignment=t;const e=null!=(s={left:0,center:1,right:2}[t])?s:0;return[new Uint8Array([27,97,e])]}},exports.TsplDriver=class{constructor(){this.commands=[],this.logger=a.L.scope("TsplDriver"),this.dpi=203}setDPI(t){return this.dpi=t,this}mmToDots(t){return Math.round(t*this.dpi/25.4)}dotsToMm(t){return 25.4*t/this.dpi}size(t,s){return this.commands.push(`SIZE ${t} mm, ${s} mm`),this}gap(t,s=0){return this.commands.push(`GAP ${t} mm, ${s} mm`),this}speed(t){return this.commands.push("SPEED "+Math.min(10,Math.max(1,t))),this}density(t){return this.commands.push("DENSITY "+Math.min(15,Math.max(0,t))),this}direction(t){return this.commands.push("DIRECTION "+t),this}clear(){return this.commands.push("CLS"),this}text(t,s){const{x:e,y:n,font:r=2,rotation:i=0,xMultiplier:h=1,yMultiplier:a=1}=s;return this.commands.push(`TEXT ${e},${n},"${r}",${i},${h},${a},"${this.escapeString(t)}"`),this}barcode(t,s){const{x:e,y:n,type:r,height:i=100,narrow:h=2,wide:a=4,showText:o=!0,rotation:u=0}=s,c=o?1:0;return"QRCODE"===r?this.qrcode(t,{x:e,y:n,rotation:u}):(this.commands.push(`BARCODE ${e},${n},"${r}",${i},${c},${u},${h},${a},"${t}"`),this)}qrcode(t,s){const{x:e,y:n,eccLevel:r="M",cellWidth:i=6,mode:h="A",rotation:a=0}=s;return this.commands.push(`QRCODE ${e},${n},${r},${i},${h},${a},"${this.escapeString(t)}"`),this}box(t){const{x:s,y:e,width:n,height:r,thickness:i=2}=t;return this.commands.push(`BOX ${s},${e},${s+n},${e+r},${i}`),this}line(t){const{x1:s,y1:e,x2:n,y2:i,thickness:h=2}=t;if(s===n||e===i){const t=Math.abs(n-s)||h,r=Math.abs(i-e)||h;this.commands.push(`BAR ${Math.min(s,n)},${Math.min(e,i)},${t},${r}`)}else this.commands.push(`DIAGONAL ${s},${e},${h},${Math.sqrt(r(n-s,2)+r(i-e,2))},${180*Math.atan2(i-e,n-s)/Math.PI}`);return this}bar(t,s,e,n){return this.commands.push(`BAR ${t},${s},${e},${n}`),this}reverse(t,s,e,n){return this.commands.push(`REVERSE ${t},${s},${e},${n}`),this}print(t=1,s=1){return this.commands.push(`PRINT ${t},${s}`),this}feed(t=1){this.commands.push("FORMFEED");for(let s=1;t>s;s++)this.commands.push("FORMFEED");return this}cut(){return this.commands.push("CUT"),this}beep(){return this.commands.push("BEEP"),this}home(){return this.commands.push("HOME"),this}escapeString(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}getCommands(){return this.commands.join("\r\n")+"\r\n"}getBuffer(){const t=this.getCommands();return this.logger.debug("TSPL commands:\n"+t),a.l.encode(t,"ASCII")}reset(){return this.commands=[],this}},exports.XprinterDriver=u,exports.ZplDriver=class{constructor(){this.commands=[],this.logger=a.L.scope("ZplDriver"),this.startFormat(),m(this,this.barcode.bind(this),{checkDigit:"Y"})}startFormat(){return this.commands.push("^XA"),this}endFormat(){return this.commands.push("^XZ"),this}labelHome(t,s){return this.commands.push(`^FO${t},${s}`),this}fieldData(t){return this.commands.push("^FD"+this.escapeField(t)),this}fieldOrigin(t,s){return this.commands.push(`^FO${t},${s}`),this}printWidth(t){return this.commands.push("^PW"+t),this}labelLength(t){return this.commands.push("^LL"+t),this}labelGap(t){return this.commands.push("^LS"+t),this}quantity(t){return this.commands.push(`^PQ${t},0,1,Y`),this}text(t,s){if(s){const{x:e=0,y:n=0,font:r="0",rotation:i="N",xMultiplier:h=1,yMultiplier:a=1}=s;this.commands.push(`^FO${e},${n}^A${r}${i},${a},${h}^FD${this.escapeField(t)}^FS`)}else this.commands.push(`^FD${this.escapeField(t)}^FS`);return this}textAt(t,s,e,n="0",r="N"){return this.commands.push(`^FO${s},${e}^A${n}${r}^FD${this.escapeField(t)}^FS`),this}font(t,s,e,n=30,r=20){return this.commands.push(`^FO${s},${e}^A${n},${r}^FD${this.escapeField(t)}^FS`),this}scalableText(t,s,e,n="0",r=30,i=20){return this.commands.push(`^FO${s},${e}^A${n}N,${r},${i}^FD${this.escapeField(t)}^FS`),this}barcode(t,s){const{x:e=0,y:n=0,type:r="128",height:i=50,showText:h="Y",checkDigit:a="N",interpretLine:o="Y",interpretLineAbove:u="N"}=s;return this.commands.push(`^FO${e},${n}^B${r}${h},${i},${o},${u},${a}^FD${this.escapeField(t)}^FS`),this}ean13(t,s=0,e=0,n=50){return this.barcode(t,{x:s,y:e,type:"EAN13",height:n})}qrcode(t,s){const{x:e=0,y:n=0,model:r=2,magnification:i=4,errorCorrection:h="M"}=s||{},a=1===r?"1":"2";return this.commands.push(`^FO${e},${n}^BQN,${a},${i}^FD${h},${this.escapeField(t)}^FS`),this}box(t){const{x:s=0,y:e=0,width:n,height:r,borderThickness:i=2,cornerRounding:h=0}=t;return this.commands.push(`^FO${s},${e}^GB${n},${r},${i},${h}^FS`),this}line(t,s,e,n,r=2){const i=Math.abs(e-t)||r,h=Math.abs(n-s)||r,a=Math.min(t,e),o=Math.min(s,n);return this.commands.push(`^FO${a},${o}^GB${i},${h},${r}^FS`),this}circle(t,s,e,n=2){return this.commands.push(`^FO${t},${s}^GC${e},${n}^FS`),this}diagonal(t,s,e,n,r=2){return this.commands.push(`^FO${t},${s}^GD${e},${n},${r}^FS`),this}ellipse(t,s,e,n,r=2){return this.commands.push(`^FO${t},${s}^GE${e},${n},${r}^FS`),this}image(t,s,e,n,r){const i=Math.ceil(e/8),h=i*n;r.length<h&&this.logger.warn(`ZPL image bitmap size mismatch: expected ${h}, got ${r.length}`);const o=a.O(r,h);return this.commands.push(`^FO${t},${s}`),this.commands.push(`^GFA,${h},${h},${i},${o}`),this.commands.push("^FS"),this.logger.debug(`ZPL image encoded: ${e}x${n} at (${t},${s})`),this}setDarkness(t=15){return this.commands.push("~SD"+Math.min(30,Math.max(0,Math.floor(t)))),this}setSpeed(t){const s=Math.min(14,Math.max(1,Math.floor(t)));return this.commands.push("^PR"+s),this}printConfigLabel(){return this.commands.push("~WC"),this}calibrate(){return this.commands.push("~JC"),this}reset(){return this.commands.push("^JUS"),this}getCommands(){var t,s;return(null==(t=this.commands[0])?void 0:t.startsWith("^XA"))||this.startFormat(),(null==(s=this.commands[this.commands.length-1])?void 0:s.startsWith("^XZ"))||this.endFormat(),this.commands.join("\n")}getBuffer(){const t=this.getCommands();return this.logger.debug("ZPL commands:\n"+t),a.l.encode(t,"UTF-8")}getCommandList(){return[...this.commands]}resetCommands(){return this.commands=[],this.startFormat(),this}print(t=1){return this.quantity(t),this.endFormat(),this}escapeField(t){return t.replace(/\\/g,"\\\\").replace(/\^/g,"\\^").replace(/~/g,"\\~")}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t=Object.defineProperty,s=Object.getOwnPropertySymbols,e=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,i=Math.pow,r=(s,e,n)=>e in s?t(s,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[e]=n;import{E as h}from"../chunks/EscPosDriver-ju4j3bXJ.js";import{L as a,l as o,O as u,E as c,m}from"../chunks/shared-C7eA759x.js";class d extends h{printAndFeed(t){return[new Uint8Array([27,100,t])]}}class l extends h{init(){return super.init()}getStatus(){return[new Uint8Array([27,105])]}getDetailedStatus(){const t=[];for(let s=1;4>=s;s++)t.push(new Uint8Array([16,4,s]));return t}feedAndCut(t){return[new Uint8Array([27,100,t]),new Uint8Array([29,86,0])]}}class $ extends h{sleep(){return[new Uint8Array([27,61,1])]}wakeUp(){return[new Uint8Array([0])]}wakeUpDeep(){const t=[];for(let s=0;5>s;s++)t.push(new Uint8Array([0]));return t.push(new Uint8Array([27,64])),t}setAutoSleep(t){return[new Uint8Array([27,61,t?1:0])]}}class p{constructor(){this.commands=[],this.logger=a.scope("TsplDriver"),this.dpi=203}setDPI(t){return this.dpi=t,this}mmToDots(t){return Math.round(t*this.dpi/25.4)}dotsToMm(t){return 25.4*t/this.dpi}size(t,s){return this.commands.push(`SIZE ${t} mm, ${s} mm`),this}gap(t,s=0){return this.commands.push(`GAP ${t} mm, ${s} mm`),this}speed(t){return this.commands.push("SPEED "+Math.min(10,Math.max(1,t))),this}density(t){return this.commands.push("DENSITY "+Math.min(15,Math.max(0,t))),this}direction(t){return this.commands.push("DIRECTION "+t),this}clear(){return this.commands.push("CLS"),this}text(t,s){const{x:e,y:n,font:i=2,rotation:r=0,xMultiplier:h=1,yMultiplier:a=1}=s;return this.commands.push(`TEXT ${e},${n},"${i}",${r},${h},${a},"${this.escapeString(t)}"`),this}barcode(t,s){const{x:e,y:n,type:i,height:r=100,narrow:h=2,wide:a=4,showText:o=!0,rotation:u=0}=s,c=o?1:0;return"QRCODE"===i?this.qrcode(t,{x:e,y:n,rotation:u}):(this.commands.push(`BARCODE ${e},${n},"${i}",${r},${c},${u},${h},${a},"${t}"`),this)}qrcode(t,s){const{x:e,y:n,eccLevel:i="M",cellWidth:r=6,mode:h="A",rotation:a=0}=s;return this.commands.push(`QRCODE ${e},${n},${i},${r},${h},${a},"${this.escapeString(t)}"`),this}box(t){const{x:s,y:e,width:n,height:i,thickness:r=2}=t;return this.commands.push(`BOX ${s},${e},${s+n},${e+i},${r}`),this}line(t){const{x1:s,y1:e,x2:n,y2:r,thickness:h=2}=t;if(s===n||e===r){const t=Math.abs(n-s)||h,i=Math.abs(r-e)||h;this.commands.push(`BAR ${Math.min(s,n)},${Math.min(e,r)},${t},${i}`)}else this.commands.push(`DIAGONAL ${s},${e},${h},${Math.sqrt(i(n-s,2)+i(r-e,2))},${180*Math.atan2(r-e,n-s)/Math.PI}`);return this}bar(t,s,e,n){return this.commands.push(`BAR ${t},${s},${e},${n}`),this}reverse(t,s,e,n){return this.commands.push(`REVERSE ${t},${s},${e},${n}`),this}print(t=1,s=1){return this.commands.push(`PRINT ${t},${s}`),this}feed(t=1){this.commands.push("FORMFEED");for(let s=1;t>s;s++)this.commands.push("FORMFEED");return this}cut(){return this.commands.push("CUT"),this}beep(){return this.commands.push("BEEP"),this}home(){return this.commands.push("HOME"),this}escapeString(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}getCommands(){return this.commands.join("\r\n")+"\r\n"}getBuffer(){const t=this.getCommands();return this.logger.debug("TSPL commands:\n"+t),o.encode(t,"ASCII")}reset(){return this.commands=[],this}}function g(t,i,h={}){const a=t;return a.code128=function(s,e=0,n=0,r=50){return i.call(t,s,{x:e,y:n,type:"128",height:r})},a.code39=function(a,o=0,u=0,c=50){return i.call(t,a,((t,i)=>{for(var h in i||(i={}))e.call(i,h)&&r(t,h,i[h]);if(s)for(var h of s(i))n.call(i,h)&&r(t,h,i[h]);return t})({x:o,y:u,type:"39",height:c},h))},a}class A{constructor(){this.commands=[],this.logger=a.scope("ZplDriver"),this.startFormat(),g(this,this.barcode.bind(this),{checkDigit:"Y"})}startFormat(){return this.commands.push("^XA"),this}endFormat(){return this.commands.push("^XZ"),this}labelHome(t,s){return this.commands.push(`^FO${t},${s}`),this}fieldData(t){return this.commands.push("^FD"+this.escapeField(t)),this}fieldOrigin(t,s){return this.commands.push(`^FO${t},${s}`),this}printWidth(t){return this.commands.push("^PW"+t),this}labelLength(t){return this.commands.push("^LL"+t),this}labelGap(t){return this.commands.push("^LS"+t),this}quantity(t){return this.commands.push(`^PQ${t},0,1,Y`),this}text(t,s){if(s){const{x:e=0,y:n=0,font:i="0",rotation:r="N",xMultiplier:h=1,yMultiplier:a=1}=s;this.commands.push(`^FO${e},${n}^A${i}${r},${a},${h}^FD${this.escapeField(t)}^FS`)}else this.commands.push(`^FD${this.escapeField(t)}^FS`);return this}textAt(t,s,e,n="0",i="N"){return this.commands.push(`^FO${s},${e}^A${n}${i}^FD${this.escapeField(t)}^FS`),this}font(t,s,e,n=30,i=20){return this.commands.push(`^FO${s},${e}^A${n},${i}^FD${this.escapeField(t)}^FS`),this}scalableText(t,s,e,n="0",i=30,r=20){return this.commands.push(`^FO${s},${e}^A${n}N,${i},${r}^FD${this.escapeField(t)}^FS`),this}barcode(t,s){const{x:e=0,y:n=0,type:i="128",height:r=50,showText:h="Y",checkDigit:a="N",interpretLine:o="Y",interpretLineAbove:u="N"}=s;return this.commands.push(`^FO${e},${n}^B${i}${h},${r},${o},${u},${a}^FD${this.escapeField(t)}^FS`),this}ean13(t,s=0,e=0,n=50){return this.barcode(t,{x:s,y:e,type:"EAN13",height:n})}qrcode(t,s){const{x:e=0,y:n=0,model:i=2,magnification:r=4,errorCorrection:h="M"}=s||{},a=1===i?"1":"2";return this.commands.push(`^FO${e},${n}^BQN,${a},${r}^FD${h},${this.escapeField(t)}^FS`),this}box(t){const{x:s=0,y:e=0,width:n,height:i,borderThickness:r=2,cornerRounding:h=0}=t;return this.commands.push(`^FO${s},${e}^GB${n},${i},${r},${h}^FS`),this}line(t,s,e,n,i=2){const r=Math.abs(e-t)||i,h=Math.abs(n-s)||i,a=Math.min(t,e),o=Math.min(s,n);return this.commands.push(`^FO${a},${o}^GB${r},${h},${i}^FS`),this}circle(t,s,e,n=2){return this.commands.push(`^FO${t},${s}^GC${e},${n}^FS`),this}diagonal(t,s,e,n,i=2){return this.commands.push(`^FO${t},${s}^GD${e},${n},${i}^FS`),this}ellipse(t,s,e,n,i=2){return this.commands.push(`^FO${t},${s}^GE${e},${n},${i}^FS`),this}image(t,s,e,n,i){const r=Math.ceil(e/8),h=r*n;i.length<h&&this.logger.warn(`ZPL image bitmap size mismatch: expected ${h}, got ${i.length}`);const a=u(i,h);return this.commands.push(`^FO${t},${s}`),this.commands.push(`^GFA,${h},${h},${r},${a}`),this.commands.push("^FS"),this.logger.debug(`ZPL image encoded: ${e}x${n} at (${t},${s})`),this}setDarkness(t=15){return this.commands.push("~SD"+Math.min(30,Math.max(0,Math.floor(t)))),this}setSpeed(t){const s=Math.min(14,Math.max(1,Math.floor(t)));return this.commands.push("^PR"+s),this}printConfigLabel(){return this.commands.push("~WC"),this}calibrate(){return this.commands.push("~JC"),this}reset(){return this.commands.push("^JUS"),this}getCommands(){var t,s;return(null==(t=this.commands[0])?void 0:t.startsWith("^XA"))||this.startFormat(),(null==(s=this.commands[this.commands.length-1])?void 0:s.startsWith("^XZ"))||this.endFormat(),this.commands.join("\n")}getBuffer(){const t=this.getCommands();return this.logger.debug("ZPL commands:\n"+t),o.encode(t,"UTF-8")}getCommandList(){return[...this.commands]}resetCommands(){return this.commands=[],this.startFormat(),this}print(t=1){return this.quantity(t),this.endFormat(),this}escapeField(t){return t.replace(/\\/g,"\\\\").replace(/\^/g,"\\^").replace(/~/g,"\\~")}}class E{constructor(t=576,s=0){this.commands=[],this.logger=a.scope("CpclDriver"),this.pageWidth=576,this.pageHeight=0,this.pageWidth=t,this.pageHeight=s,g(this,this.barcode.bind(this),{wide:2,narrow:1})}setPageSize(t,s=0){return this.pageWidth=t,this.pageHeight=s,this}usePageSize(t){const[s,e]={"4X6":[576,864],"4X4":[576,576],"4X2":[576,288],"2.25X1.25":[324,180],A4:[992,1406],A5:[701,992],LETTER:[1050,1500],CUSTOM:[576,0]}[t]||[576,0];return this.pageWidth=s,this.pageHeight=e,this}pageStart(){return this.commands.push("! U1 SETLP 5 0 30"),this.commands.push("! U1 PAGE WIDTH "+this.pageWidth),this.pageHeight>0&&this.commands.push("! U1 PAGE HEIGHT "+this.pageHeight),this.commands.push("START"),this}pageEnd(){return this.commands.push("END"),this}formFeed(){return this.commands.push("FORM"),this}setLinePrint(t=5,s=0,e=30){return this.commands.push(`! U1 SETLP ${t} ${s} ${e}`),this}setFont(t=3,s=1,e=1,n=0){const i={0:"N",90:"R",180:"B",270:"I"}[n]||"N";return this.commands.push(`! U1 SETLP ${t} ${s} ${e} ${i}`),this}text(t){return this.commands.push("! U1 TEXT "+this.escapeText(t)),this}textAt(t,s){const{x:e=0,y:n=0,font:i=3,xMulti:r=1,yMulti:h=1,rotation:a=0}=s,o={0:"N",90:"R",180:"B",270:"I"}[a]||"N";return this.commands.push(`! U1 SETLP ${i} ${r} ${h} ${o}`),this.commands.push(`! U1 ${e} ${n} TEXT ${this.escapeText(t)}`),this}legacyText(t,s,e,n=3){return this.commands.push(`TEXT ${s} ${e} ${n} "${this.escapeText(t)}"`),this}barcode(t,s){const{x:e=0,y:n=0,type:i="128",height:r=50,wide:h=2,narrow:a=1,readable:o=!0}=s,u=o?"B":"N";switch(i){case"128":default:this.commands.push(`BARCODE 128 ${e} ${n} ${r} ${u} 0 ${a} ${h} "${t}"`);break;case"39":this.commands.push(`BARCODE 39 ${e} ${n} ${r} ${u} ${h} ${a} "${t}"`);break;case"EAN13":this.commands.push(`BARCODE EAN13 ${e} ${n} ${r} ${u} "${t}"`);break;case"EAN8":this.commands.push(`BARCODE EAN8 ${e} ${n} ${r} ${u} "${t}"`);break;case"UPCA":this.commands.push(`BARCODE UPCA ${e} ${n} ${r} ${u} "${t}"`);break;case"UPCE":this.commands.push(`BARCODE UPCE ${e} ${n} ${r} ${u} "${t}"`);break;case"PDF417":this.commands.push(`BARCODE PDF417 ${e} ${n} 6 200 "${t}"`);break;case"DATAMATRIX":this.commands.push(`BARCODE DATAMATRIX ${e} ${n} 200 "${t}"`);break;case"QR":this.qrcode(t,{x:e,y:n})}return this}qrcode(t,s){const{x:e=0,y:n=0,model:i=2,errorCorrection:r="M",cellSize:h=4}=s||{};return this.commands.push(`BARCODE QR ${e} ${n} ${i} ${h} A ${r} "${t}"`),this}twoDBarcode(t,s,e=0,n=0,i=200){return"PDF417"===s?this.commands.push(`BARCODE PDF417 ${e} ${n} 6 ${i} "${t}"`):this.commands.push(`BARCODE DATAMATRIX ${e} ${n} ${i} "${t}"`),this}line(t){const{x1:s,y1:e,x2:n,y2:i,width:r=1}=t;return this.commands.push(`LINE ${s} ${e} ${n} ${i} ${r}`),this}box(t){const{x:s,y:e,width:n,height:i,thickness:r=1}=t;return this.commands.push(`BOX ${s} ${e} ${n} ${i} ${r}`),this}inverse(t,s,e,n){return this.commands.push(`INVERSE ${e} ${n} ${t} ${s}`),this}setDensity(t){const s=Math.min(50,Math.max(-50,t));return this.commands.push("! U1 SETDENSITY "+s),this}setSpeed(t){const s=Math.min(6,Math.max(2,t));return this.commands.push("! U1 SETSPEED "+s),this}cut(){return this.commands.push("CUT"),this}partialCut(){return this.commands.push("PCUT"),this}feedCut(){return this.commands.push("FEED CUT"),this}beep(t=1,s=5){return this.commands.push(`BEEP ${t} ${s}`),this}logo(t,s,e){return this.commands.push(`LOGO ${t} ${s} "${e}"`),this}downloadLogo(t,s,e){var n,i;const r=null!=(n=null==e?void 0:e.width)?n:100,h=Math.ceil(r/8),a=null!=(i=null==e?void 0:e.height)?i:Math.max(1,Math.floor(s.length/h)),o=h*a;s.length<o&&this.logger.warn(`CPCL logo bitmap size mismatch: expected ${o}, got ${s.length}`);const c=u(s,o);return this.commands.push("! DF "+t),this.commands.push(`CG ${o} ${h} ${a} ${c}`),this.commands.push("! DF"),this.logger.debug(`CPCL logo downloaded: ${t} (${r}x${a})`),this}printLogo(t,s=0,e=0){return this.commands.push(`LOGO ${s} ${e} "${t}"`),this}getCommands(){return this.commands.join("\r\n")+"\r\n"}getBuffer(){const t=this.getCommands();return this.logger.debug("CPCL commands:\n"+t),o.encode(t,"ASCII")}getCommandList(){return[...this.commands]}reset(){return this.commands=[],this}getPageWidth(){return this.pageWidth}escapeText(t){return t.replace(/"/g,'""')}}class y{constructor(t){var s,e,n,i;this.logger=a.scope("StarPrinter"),this._boldEnabled=!1,this._alignment="left",this.useEncodingService=null==(s=null==t?void 0:t.useEncodingService)||s,this.internationalCharset=null==(e=null==t?void 0:t.internationalCharset)||e,this.encodingService=new c({showWarnings:null==(n=null==t?void 0:t.showEncodingWarnings)||n,fallbackChar:null!=(i=null==t?void 0:t.fallbackChar)?i:"?"}),this.logger.info("StarPrinter driver initialized")}init(){const t=[];return t.push(new Uint8Array([27,64])),this.internationalCharset&&t.push(new Uint8Array([27,82,0])),this._boldEnabled=!1,this._alignment="left",t}text(t,s="GBK"){if(!t||"string"!=typeof t)return[];const e=[];if("left"!==this._alignment){const t=this.align(this._alignment);t.length>0&&t[0]&&e.push(t[0])}if(this._boldEnabled&&e.push(new Uint8Array([27,69,1])),this.useEncodingService&&this.encodingService.isSupported(s)){const n=this.encodingService.encode(t,s);e.push(n)}else{const s=(new TextEncoder).encode(t);e.push(s)}return e.push(new Uint8Array([10])),this._boldEnabled&&e.push(new Uint8Array([27,69,0])),"left"!==this._alignment&&e.push(new Uint8Array([27,97,0])),e}feed(t=1){return[new Uint8Array([27,100,Math.max(1,Math.min(255,Math.floor(t)))])]}cut(){const t=[];return t.push(new Uint8Array([27,100,3])),t.push(new Uint8Array([29,86,0])),t}qr(t,s){var e,n,i,r,h;if(!t||"string"!=typeof t)return[];const a=null!=(e=null==s?void 0:s.model)?e:2;let o=4;s&&("cellSize"in s?o=null!=(n=s.cellSize)?n:4:"size"in s&&(o=null!=(i=s.size)?i:4));const u=null!=(r=null==s?void 0:s.errorCorrection)?r:"M",c=[];c.push(new Uint8Array([27,29,87,1,1===a?48:49])),c.push(new Uint8Array([27,29,87,2,Math.min(8,Math.max(1,o))]));const m=null!=(h={L:0,M:1,Q:2,H:3}[u])?h:1;c.push(new Uint8Array([27,29,87,3,m]));const d=this.useEncodingService&&this.encodingService.isSupported("UTF-8")?this.encodingService.encode(t,"UTF-8"):(new TextEncoder).encode(t),l=d.length,$=l%256,p=Math.floor(l/256);return c.push(new Uint8Array([27,29,87,0,$,p])),c.push(d),c.push(new Uint8Array([27,29,87,4])),c}barcode(t,s){var e,n,i,r,h;if(!t||"string"!=typeof t)return[];const a=null!=(e=null==s?void 0:s.type)?e:"CODE128",o=Math.max(1,Math.min(255,null!=(n=null==s?void 0:s.height)?n:40)),u=Math.max(1,Math.min(5,null!=(i=null==s?void 0:s.width)?i:2)),c=[],m=null!=(h={none:0,above:1,below:2,both:3}[null!=(r=null==s?void 0:s.hri)?r:"below"])?h:2;switch(c.push(new Uint8Array([29,104,o])),c.push(new Uint8Array([29,119,u])),c.push(new Uint8Array([29,72,m])),a){case"CODE39":{const s=`*${t.toUpperCase()}*`;c.push(new Uint8Array([29,107,4])),c.push((new TextEncoder).encode(s)),c.push(new Uint8Array([0]));break}case"EAN13":{const s=t.replace(/\D/g,"");12>s.length&&this.logger.warn("EAN13 requires 12 digits, got "+s.length),c.push(new Uint8Array([29,107,2]));const e=s.padStart(12,"0").substring(0,12);c.push((new TextEncoder).encode(e)),c.push(new Uint8Array([0]));break}default:c.push(new Uint8Array([29,107,73])),c.push((new TextEncoder).encode(t)),c.push(new Uint8Array([0]))}return c}image(t,s,e,n){if(!(t&&t instanceof Uint8Array&&s>0&&e>0))return this.logger.warn("Invalid image parameters"),[];const i=s*e*4;if(t.length!==i)return this.logger.warn(`Invalid image data length: expected ${i}, got ${t.length}`),[];const r=[],h=m.toBitmap(t,s,e),a=Math.ceil(s/8),o=a%256,u=Math.floor(a/256);r.push(new Uint8Array([27,42,o,u]));for(let c=0;e>c;c++){const t=h.slice(c*a,(c+1)*a);r.push(t)}return r}beep(){return[new Uint8Array([27,66,5])]}bold(t){return this._boldEnabled=t,[new Uint8Array([27,69,t?1:0])]}align(t){var s;this._alignment=t;const e=null!=(s={left:0,center:1,right:2}[t])?s:0;return[new Uint8Array([27,97,e])]}}export{E as CpclDriver,h as EscPos,d as GPrinterDriver,$ as SprtDriver,y as StarPrinter,p as TsplDriver,l as XprinterDriver,A as ZplDriver};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../chunks/shared-CvHoYVGG.js"),s=require("../chunks/gbk-data-Cunq2WDW.js");exports.EncodingService=e.E,exports.ISO2022JP_ESC_ASCII=e.I,exports.ISO2022JP_ESC_JIS0208=e.a,exports.encodeHangulSyllable=e.e,exports.encodingService=e.b,exports.isJapaneseHiragana=e.i,exports.isJapaneseKanji=e.c,exports.isJapaneseKatakana=e.d,exports.isJisX0201Katakana=e.f,exports.isKoreanHangul=e.g,exports.isKoreanHanja=e.h,exports.isKoreanJamo=e.j,exports.requiresJisX0208Escape=e.r,exports.unicodeToShiftJisHiragana=e.u,exports.unicodeToShiftJisKatakana=e.k,exports.big5ToUnicode=s.e,exports.gbkToUnicode=s.f,exports.getBig5Bytes=s.g,exports.getGbkBytes=s.d,exports.getUnicodeFromGbk=s.h,exports.isAscii=s.i,exports.isChinesePunctuation=s.c,exports.isCjk=s.a,exports.unicodeToBig5=s.b,exports.unicodeToGbk=s.u;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{E as a,I as s,a as i,e,b as n,i as o,c,d as r,f as t,g,h as d,j as u,r as k,u as J,k as S}from"../chunks/shared-C7eA759x.js";import{e as b,f as h,g as p,d as K,h as m,i as T,c as f,a as j,b as l,u as C}from"../chunks/gbk-data-BhfiCGRq.js";export{a as EncodingService,s as ISO2022JP_ESC_ASCII,i as ISO2022JP_ESC_JIS0208,b as big5ToUnicode,e as encodeHangulSyllable,n as encodingService,h as gbkToUnicode,p as getBig5Bytes,K as getGbkBytes,m as getUnicodeFromGbk,T as isAscii,f as isChinesePunctuation,j as isCjk,o as isJapaneseHiragana,c as isJapaneseKanji,r as isJapaneseKatakana,t as isJisX0201Katakana,g as isKoreanHangul,d as isKoreanHanja,u as isKoreanJamo,k as requiresJisX0208Escape,l as unicodeToBig5,C as unicodeToGbk,J as unicodeToShiftJisHiragana,S as unicodeToShiftJisKatakana};
|