@munchi_oy/react-native-epson-printer 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
`,bold:!0}):i==="R"?e.push({type:"text",text:P+`
|
|
9
9
|
`,bold:!0}):e.push({type:"text",text:P+`
|
|
10
10
|
`,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var E=class t extends g{constructor(r,n,i,s,u){super(n,i,s,u);this.isHardwareError=r;this.name="PrinterError",Object.setPrototypeOf(this,t.prototype)}},F=t=>{if(t instanceof E)return t.isHardwareError;let e=String(t.message||t).toUpperCase();return e.includes("ERR_OFF_LINE")||e.includes("ERR_COVER_OPEN")||e.includes("ERR_PAPER_OUT")||e.includes("ERR_FAILURE")||e.includes("DISCONNECT")||e.includes("PRINT_TIMEOUT")||e.includes("ERROR CODE: 4")||e.includes("ERROR CODE: 7")||e.includes("ERROR CODE: 3")},K=t=>{if(t instanceof E)return t;let e=f(t),r=F(t);return new E(r,e.code,e.translationCode,e.message,e.originalError)};var Ee=(t,e=!1)=>{let r={Small:{normal:{width:1,height:1},item:{width:1,height:1}},Medium:{normal:{width:2,height:2},item:{width:2,height:2}},Large:{normal:{width:2,height:2},item:{width:3,height:3}}},n=e?"item":"normal";return r[t]?.[n]??r.Small.normal},X=t=>{if(typeof t!="object"||t===null)return null;let e=t;return{target:String(e.target||""),name:String(e.name||""),macAddress:e.macAddress?String(e.macAddress):void 0,ipAddress:e.ipAddress?String(e.ipAddress):void 0,bdAddress:e.bdAddress?String(e.bdAddress):void 0,type:"EPSON"}},$=t=>t.commands.map(e=>{switch(e.type){case"text":return{cmd:"addText",data:e.text,align:e.align,bold:e.bold,underline:e.underline,size:e.size};case"align":return{cmd:"addTextAlign",align:e.align};case"bold":return{cmd:"addTextStyle",bold:e.value};case"fontSize":{let r=Ee(e.size,e.isItemName);return{cmd:"addTextSize",width:r.width,height:r.height}}case"newline":return{cmd:"addFeedLine",line:e.lines||1};case"separator":return{cmd:"addText",data:`------------------
|
|
11
|
-
`};case"textLang":return{cmd:"addTextLang",lang:e.lang};case"textFont":return{cmd:"addTextFont",font:e.font};case"image":return{cmd:"addImage",data:e.base64,width:e.width};case"cut":return{cmd:"addCut"};case"drawer":return{cmd:"addPulse"};case"barcode":return{cmd:"addBarcode",data:e.data,type:e.system,width:e.width,height:e.height};case"qr":return{cmd:"addSymbol",data:e.data,type:"QRCODE_MODEL_2",level:e.errorCorrection||"M",width:e.size||3};case"feed":return{cmd:"addFeedLine",line:e.lines};default:return null}}).filter(e=>e!==null);var B=(c=>(c[c.ONLINE=0]="ONLINE",c[c.OFFLINE=1]="OFFLINE",c[c.POWER_OFF=2]="POWER_OFF",c[c.COVER_CLOSE=3]="COVER_CLOSE",c[c.COVER_OPEN=4]="COVER_OPEN",c[c.PAPER_OK=5]="PAPER_OK",c[c.PAPER_NEAR_END=6]="PAPER_NEAR_END",c[c.PAPER_EMPTY=7]="PAPER_EMPTY",c[c.DRAWER_HIGH=8]="DRAWER_HIGH",c[c.DRAWER_LOW=9]="DRAWER_LOW",c[c.BATTERY_ENOUGH=10]="BATTERY_ENOUGH",c[c.BATTERY_EMPTY=11]="BATTERY_EMPTY",c[c.AUTO_RECOVER_ERROR=20]="AUTO_RECOVER_ERROR",c[c.AUTO_RECOVER_OK=21]="AUTO_RECOVER_OK",c[c.UNRECOVERABLE_ERROR=22]="UNRECOVERABLE_ERROR",c))(B||{}),J=(n=>(n[n.RECONNECTING=0]="RECONNECTING",n[n.RECONNECT=1]="RECONNECT",n[n.DISCONNECT=2]="DISCONNECT",n))(J||{}),j=(a=>(a[a.SUCCESS=0]="SUCCESS",a[a.ERR_PARAM=1]="ERR_PARAM",a[a.ERR_CONNECT=2]="ERR_CONNECT",a[a.ERR_TIMEOUT=3]="ERR_TIMEOUT",a[a.ERR_MEMORY=4]="ERR_MEMORY",a[a.ERR_ILLEGAL=5]="ERR_ILLEGAL",a[a.ERR_PROCESSING=6]="ERR_PROCESSING",a[a.ERR_NOT_FOUND=7]="ERR_NOT_FOUND",a[a.ERR_IN_USE=8]="ERR_IN_USE",a[a.ERR_TYPE_INVALID=9]="ERR_TYPE_INVALID",a[a.ERR_DISCONNECT=10]="ERR_DISCONNECT",a[a.ERR_ALREADY_OPENED=11]="ERR_ALREADY_OPENED",a[a.ERR_ALREADY_USED=12]="ERR_ALREADY_USED",a[a.ERR_BOX_COUNT_OVER=13]="ERR_BOX_COUNT_OVER",a[a.ERR_BOX_CLIENT_OVER=14]="ERR_BOX_CLIENT_OVER",a[a.ERR_UNSUPPORTED=15]="ERR_UNSUPPORTED",a[a.ERR_DEVICE_BUSY=16]="ERR_DEVICE_BUSY",a[a.ERR_RECOVERY_FAILURE=17]="ERR_RECOVERY_FAILURE",a[a.ERR_FAILURE=255]="ERR_FAILURE",a))(j||{}),k=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.ERR_TIMEOUT=1]="ERR_TIMEOUT",m[m.ERR_NOT_FOUND=2]="ERR_NOT_FOUND",m[m.ERR_AUTORECOVER=3]="ERR_AUTORECOVER",m[m.ERR_COVER_OPEN=4]="ERR_COVER_OPEN",m[m.ERR_CUTTER=5]="ERR_CUTTER",m[m.ERR_MECHANICAL=6]="ERR_MECHANICAL",m[m.ERR_EMPTY=7]="ERR_EMPTY",m[m.ERR_UNRECOVERABLE=8]="ERR_UNRECOVERABLE",m[m.ERR_SYSTEM=9]="ERR_SYSTEM",m[m.ERR_PORT=10]="ERR_PORT",m[m.ERR_FAILURE=255]="ERR_FAILURE",m))(k||{}),Y=(d=>(d[d.EN=0]="EN",d[d.JA=1]="JA",d[d.ZH_CN=2]="ZH_CN",d[d.ZH_TW=3]="ZH_TW",d[d.KO=4]="KO",d[d.TH=5]="TH",d[d.VI=6]="VI",d[d.MULTI=7]="MULTI",d))(Y||{}),Z=(s=>(s[s.FONT_A=0]="FONT_A",s[s.FONT_B=1]="FONT_B",s[s.FONT_C=2]="FONT_C",s[s.FONT_D=3]="FONT_D",s[s.FONT_E=4]="FONT_E",s))(Z||{}),V=(o=>(o[o.TM_M10=0]="TM_M10",o[o.TM_M30=1]="TM_M30",o[o.TM_P20=2]="TM_P20",o[o.TM_P60=3]="TM_P60",o[o.TM_P60II=4]="TM_P60II",o[o.TM_P80=5]="TM_P80",o[o.TM_T20=6]="TM_T20",o[o.TM_T60=7]="TM_T60",o[o.TM_T70=8]="TM_T70",o[o.TM_T81=9]="TM_T81",o[o.TM_T82=10]="TM_T82",o[o.TM_T83=11]="TM_T83",o[o.TM_T88=12]="TM_T88",o[o.TM_T90=13]="TM_T90",o[o.TM_T90KP=14]="TM_T90KP",o[o.TM_U220=15]="TM_U220",o[o.TM_U330=16]="TM_U330",o[o.TM_L90=17]="TM_L90",o[o.TM_H6000=18]="TM_H6000",o[o.TM_T83III=19]="TM_T83III",o[o.TM_T100=20]="TM_T100",o[o.TM_M30II=21]="TM_M30II",o[o.TM_M50=23]="TM_M50",o[o.TM_T88VII=24]="TM_T88VII",o[o.TM_L90LFC=25]="TM_L90LFC",o[o.TM_L100=26]="TM_L100",o[o.TM_P20II=27]="TM_P20II",o[o.TM_P80II=28]="TM_P80II",o[o.TM_M30III=29]="TM_M30III",o[o.TM_M50II=30]="TM_M50II",o[o.TM_M55=31]="TM_M55",o[o.TM_U220II=32]="TM_U220II",o))(V||{});var y=require("react-native"),T=y.NativeModules.MunchiEpsonModule,z=()=>T?new y.NativeEventEmitter(T):null,pe=t=>new Promise(e=>setTimeout(e,t)),Ne=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e.toUpperCase():""},he=t=>{if(t instanceof Error)return t.message.toUpperCase();if(t&&typeof t=="object"){let e=t.message;if(typeof e=="string")return e.toUpperCase()}return String(t).toUpperCase()},p=(t,e,r)=>t.includes(r)||e===r||e.includes(r),S=async(t,e=3,r=500)=>{try{return await t()}catch(n){if(e<=1)throw n;let i=he(n),s=Ne(n);if(p(i,s,"TARGET_IN_USE"))throw n;if(p(i,s,"BUSY")||p(i,s,"IN_USE")||p(i,s,"ERR_IN_USE")||p(i,s,"PRINT_BUSY")||p(i,s,"ERR_CONNECT")||p(i,s,"CONNECT_ERROR")||p(i,s,"ERR_TIMEOUT")||p(i,s,"PRINT_TIMEOUT"))return await pe(r),S(t,e-1,r);throw n}};var D=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!T)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=T.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!T||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await T.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var M=class{constructor(e){this.logger=e}queue=Promise.resolve();isQueuePaused=!1;resumeQueueResolver=null;isPaused(){return this.isQueuePaused}pause(){this.isQueuePaused=!0}resume(){this.isQueuePaused&&(this.isQueuePaused=!1,this.resumeQueueResolver&&(this.resumeQueueResolver(),this.resumeQueueResolver=null))}async waitUntilResumed(){if(this.isQueuePaused)return new Promise(e=>{let r=this.resumeQueueResolver;this.resumeQueueResolver=()=>{r&&r(),e()}})}enqueue(e){return new Promise((r,n)=>{let i=async()=>{this.isQueuePaused&&(this.logger?.info?.("[EpsonPrinter] Queue is PAUSED. Waiting for resume..."),await this.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Queue RESUMED."));try{let s=await e();r(s)}catch(s){n(s)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var v=class{constructor(e){this.config=e}recoveryTimer=null;start(){this.recoveryTimer||(this.config.logger?.info?.("[EpsonPrinter] Starting recovery polling..."),this.recoveryTimer=setInterval(async()=>{try{let e=await this.config.getStatus();if(e.online&&!e.coverOpen&&e.errorStatus==="NONE")this.config.logger?.info?.("[EpsonPrinter] Poller detected healthy status. Requesting queue resume."),this.config.onRecovered();else{let n=`[EpsonPrinter] Polling... Status: Online=${e.online}, Cover=${e.coverOpen}, Err=${e.errorStatus}`;this.config.logger?.info?.(n)}}catch(e){this.config.logger?.error("[EpsonPrinter] Recovery poll failed",e)}},2e3))}stop(){this.recoveryTimer&&(this.config.logger?.info?.("[EpsonPrinter] Stopping recovery polling."),clearInterval(this.recoveryTimer),this.recoveryTimer=null)}};var Ce=new Set([0,3,5,21]),x=class{constructor(e){this.config=e}statusSubscription=null;connectionSubscription=null;connectionCallbacks=new Set;emitStatus(e){for(let r of this.connectionCallbacks)r(e)}ensureStatusListener(){if(this.statusSubscription)return;let e=z();e&&(this.config.logger?.info?.("[EpsonPrinter] Starting status listener for queue management"),this.statusSubscription=e.addListener("onPrinterStatusChange",r=>{if(!this.config.getSessionId()||r.sessionId!==this.config.getSessionId())return;let n=`[EpsonPrinter] Received Status Event: ${r.eventType}`;this.config.logger?.info?.(n),Ce.has(r.eventType)&&this.config.onRecoveryEvent(r.eventType)}))}ensureConnectionListener(){if(this.connectionSubscription)return;let e=z();e&&(this.connectionSubscription=e.addListener("onPrinterConnectionChange",r=>{if(!this.config.getSessionId()||r.sessionId!==this.config.getSessionId())return;let n="UNKNOWN";switch(r.status){case"RECONNECTING":n="RECONNECTING";break;case"RECONNECTED":n="CONNECTED";break;case"DISCONNECTED":n="DISCONNECTED";break;default:n="UNKNOWN"}this.config.onConnectionEvent(n),this.emitStatus(n)}))}removeStatusListener(){this.statusSubscription&&(this.statusSubscription.remove(),this.statusSubscription=null)}onConnectionChange(e){return this.connectionCallbacks.add(e),e(this.config.getConnectionStatus()),this.ensureConnectionListener(),()=>{this.connectionCallbacks.delete(e),this.connectionCallbacks.size===0&&this.connectionSubscription&&(this.connectionSubscription.remove(),this.connectionSubscription=null)}}};var ee={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},A=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new D(this.logger),this.queueController=new M(this.logger),this.recoveryController=new v({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.eventRouter=new x({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onRecoveryEvent:()=>{this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())},onConnectionEvent:r=>{r==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED")}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}async connect(e,r=5e3){let n=e??this.defaultTarget;if(!n){let i=new Error("Printer target is required");throw this.logger?.error("[EpsonPrinter] Connect failed: missing target",i),i}return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!T){this.logger?.error("[EpsonPrinter] Native module not found");return}if(this.connectionStatus==="CONNECTED"&&this.target===n)return;let i=await this.sessionManager.ensureSession();this.isConnecting=!0,this.connectionStatus="CONNECTING",this.eventRouter.emitStatus("CONNECTING");try{await S(()=>T.connect(i,n,r,this.model,this.lang)),this.target=n,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.isConnecting=!1,this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener()}catch(s){let u=f(s);throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,u),this.connectionStatus="DISCONNECTED",this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,u}})}async print(e){if(!T)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0;return this.queueController.enqueue(async()=>{let n=await this.sessionManager.ensureSession(),i=$(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await S(()=>T.print(n,i));break}catch(s){let u=K(s);if(u.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,u),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await T.print(n,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,u),u}}}).finally(()=>{this.disconnectTimer&&clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{this.performDisconnect()},5e3)})}performDisconnect(){this.queueController.enqueueBackground(async()=>{if(!this.disconnectTimer)return;let e=this.sessionManager.getSessionId();if(T&&this.connectionStatus==="CONNECTED"&&e)try{await T.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.eventRouter.emitStatus("DISCONNECTED"),await this.sessionManager.disposeSession()}catch(r){this.logger?.error("[EpsonPrinter] Auto-Disconnect failed",r)}this.disconnectTimer=null})}async printEmbedded(e){try{let r=W(e);return await this.print(r)}catch(r){let n=f(r);throw String(r).includes("MunchiPrinterError")||this.logger?.error("[EpsonPrinter] Embedded print failed",n),n}}async disconnect(){return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!T)return;let e=this.sessionManager.getSessionId();if(e)try{await T.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{await this.sessionManager.disposeSession()}})}async getStatus(){if(!T)return ee;let e=this.sessionManager.getSessionId();if(!e)return ee;try{return await T.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),f(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}};var te="1.0.1";var re=t=>{let e=f(t),r=e.message.toUpperCase(),n=t instanceof E?t.isHardwareError:F(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),s=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),u=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",P=e.code==="DISCOVERY_FAILED",d="UNKNOWN";return n?d="HARDWARE":i?d="BUSY":s?d="TIMEOUT":u?d="CONNECTION":P?d="DISCOVERY":e.code==="PRINT_FAILED"&&(d="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:d,isHardwareError:n,retryable:i||s,shouldPauseQueue:n,raw:t}},Ie=t=>re(t);var R=ge(require("react"));var ne=(0,R.createContext)(void 0),_e=({config:t,logger:e,children:r})=>{let[n,i]=(0,R.useState)();(0,R.useEffect)(()=>{e&&L(e)},[e]);let s=(0,R.useMemo)(()=>{let P={...t,logger:e??t.logger};return H(P)},[t.lang,t.model,t.target,e]),u=(0,R.useMemo)(()=>({printer:s,config:t,isReady:!0,error:n}),[s,t,n]);return R.default.createElement(ne.Provider,{value:u},r)},q=()=>{let t=(0,R.useContext)(ne);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};var N=require("react");var Oe={online:!1,coverOpen:!1,paper:"EMPTY",paperEmpty:!0,drawerOpen:!1,errorStatus:"NONE"};function ye(t={}){let{pollIntervalMs:e=5e3,enabled:r=!0}=t,{printer:n}=q(),[i,s]=(0,N.useState)("DISCONNECTED"),[u,P]=(0,N.useState)(null),[d,b]=(0,N.useState)(!1),h=(0,N.useRef)(null);return(0,N.useEffect)(()=>n.onConnectionChange(m=>{s(m)}),[n]),(0,N.useEffect)(()=>{if(!r||i!=="CONNECTED"){h.current&&(clearInterval(h.current),h.current=null,b(!1));return}let w=async()=>{try{let m=await n.getStatus();P(m)}catch{P(Oe)}};return w(),b(!0),h.current=setInterval(w,e),()=>{h.current&&(clearInterval(h.current),h.current=null,b(!1))}},[n,i,r,e]),{connectionStatus:i,hardwareStatus:u,isPolling:d}}var Se=[[/^TM-m10/i,0],[/^TM-m30III/i,29],[/^TM-m30II/i,21],[/^TM-m30/i,1],[/^TM-m50II/i,30],[/^TM-m50/i,23],[/^TM-m55/i,31],[/^TM-P20II/i,27],[/^TM-P20/i,2],[/^TM-P60II/i,4],[/^TM-P60/i,3],[/^TM-P80II/i,28],[/^TM-P80/i,5],[/^TM-T20/i,6],[/^TM-T60/i,7],[/^TM-T70/i,8],[/^TM-T81/i,9],[/^TM-T82/i,10],[/^TM-T83III/i,19],[/^TM-T83/i,11],[/^TM-T88VII/i,24],[/^TM-T88/i,12],[/^TM-T90KP/i,14],[/^TM-T90/i,13],[/^TM-T100/i,20],[/^TM-U220II/i,32],[/^TM-U220/i,15],[/^TM-U330/i,16],[/^TM-L90LFC/i,25],[/^TM-L90/i,17],[/^TM-L100/i,26],[/^TM-H6000/i,18]],ie=t=>{for(let[e,r]of Se)if(e.test(t))return r;return null};var se=require("react-native");var oe=se.NativeModules.MunchiEpsonModule,De={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},Me=t=>t.includes("[local_"),ve=(t,e)=>e?De[e].some(n=>t.startsWith(n)):!0,ae=async t=>{if(!oe)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await oe.discover({timeout:t.timeout})).map(X).filter(r=>!r||Me(r.target)?!1:ve(r.target,t.connectionType))}catch(e){let r=f(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};function H(t){return new A({...t,logger:t.logger??U()})}0&&(module.exports={Epos2CallbackCode,Epos2ConnectionEvent,Epos2ErrorStatus,Epos2Font,Epos2Lang,Epos2StatusEvent,EpsonModel,FontSize,MunchiPrinterError,PrinterError,PrinterErrorCode,PrinterProvider,PrinterTranslationCode,VERSION,discoverPrinters,getGlobalLogger,getPrinter,resolveEpsonError,resolveModelFromBluetoothName,resolvePrinterError,setGlobalLogger,usePrinter,usePrinterStatus});
|
|
11
|
+
`};case"textLang":return{cmd:"addTextLang",lang:e.lang};case"textFont":return{cmd:"addTextFont",font:e.font};case"image":return{cmd:"addImage",data:e.base64,width:e.width};case"cut":return{cmd:"addCut"};case"drawer":return{cmd:"addPulse"};case"barcode":return{cmd:"addBarcode",data:e.data,type:e.system,width:e.width,height:e.height};case"qr":return{cmd:"addSymbol",data:e.data,type:"QRCODE_MODEL_2",level:e.errorCorrection||"M",width:e.size||3};case"feed":return{cmd:"addFeedLine",line:e.lines};default:return null}}).filter(e=>e!==null);var B=(c=>(c[c.ONLINE=0]="ONLINE",c[c.OFFLINE=1]="OFFLINE",c[c.POWER_OFF=2]="POWER_OFF",c[c.COVER_CLOSE=3]="COVER_CLOSE",c[c.COVER_OPEN=4]="COVER_OPEN",c[c.PAPER_OK=5]="PAPER_OK",c[c.PAPER_NEAR_END=6]="PAPER_NEAR_END",c[c.PAPER_EMPTY=7]="PAPER_EMPTY",c[c.DRAWER_HIGH=8]="DRAWER_HIGH",c[c.DRAWER_LOW=9]="DRAWER_LOW",c[c.BATTERY_ENOUGH=10]="BATTERY_ENOUGH",c[c.BATTERY_EMPTY=11]="BATTERY_EMPTY",c[c.AUTO_RECOVER_ERROR=20]="AUTO_RECOVER_ERROR",c[c.AUTO_RECOVER_OK=21]="AUTO_RECOVER_OK",c[c.UNRECOVERABLE_ERROR=22]="UNRECOVERABLE_ERROR",c))(B||{}),J=(n=>(n[n.RECONNECTING=0]="RECONNECTING",n[n.RECONNECT=1]="RECONNECT",n[n.DISCONNECT=2]="DISCONNECT",n))(J||{}),j=(a=>(a[a.SUCCESS=0]="SUCCESS",a[a.ERR_PARAM=1]="ERR_PARAM",a[a.ERR_CONNECT=2]="ERR_CONNECT",a[a.ERR_TIMEOUT=3]="ERR_TIMEOUT",a[a.ERR_MEMORY=4]="ERR_MEMORY",a[a.ERR_ILLEGAL=5]="ERR_ILLEGAL",a[a.ERR_PROCESSING=6]="ERR_PROCESSING",a[a.ERR_NOT_FOUND=7]="ERR_NOT_FOUND",a[a.ERR_IN_USE=8]="ERR_IN_USE",a[a.ERR_TYPE_INVALID=9]="ERR_TYPE_INVALID",a[a.ERR_DISCONNECT=10]="ERR_DISCONNECT",a[a.ERR_ALREADY_OPENED=11]="ERR_ALREADY_OPENED",a[a.ERR_ALREADY_USED=12]="ERR_ALREADY_USED",a[a.ERR_BOX_COUNT_OVER=13]="ERR_BOX_COUNT_OVER",a[a.ERR_BOX_CLIENT_OVER=14]="ERR_BOX_CLIENT_OVER",a[a.ERR_UNSUPPORTED=15]="ERR_UNSUPPORTED",a[a.ERR_DEVICE_BUSY=16]="ERR_DEVICE_BUSY",a[a.ERR_RECOVERY_FAILURE=17]="ERR_RECOVERY_FAILURE",a[a.ERR_FAILURE=255]="ERR_FAILURE",a))(j||{}),k=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.ERR_TIMEOUT=1]="ERR_TIMEOUT",m[m.ERR_NOT_FOUND=2]="ERR_NOT_FOUND",m[m.ERR_AUTORECOVER=3]="ERR_AUTORECOVER",m[m.ERR_COVER_OPEN=4]="ERR_COVER_OPEN",m[m.ERR_CUTTER=5]="ERR_CUTTER",m[m.ERR_MECHANICAL=6]="ERR_MECHANICAL",m[m.ERR_EMPTY=7]="ERR_EMPTY",m[m.ERR_UNRECOVERABLE=8]="ERR_UNRECOVERABLE",m[m.ERR_SYSTEM=9]="ERR_SYSTEM",m[m.ERR_PORT=10]="ERR_PORT",m[m.ERR_FAILURE=255]="ERR_FAILURE",m))(k||{}),Y=(d=>(d[d.EN=0]="EN",d[d.JA=1]="JA",d[d.ZH_CN=2]="ZH_CN",d[d.ZH_TW=3]="ZH_TW",d[d.KO=4]="KO",d[d.TH=5]="TH",d[d.VI=6]="VI",d[d.MULTI=7]="MULTI",d))(Y||{}),Z=(s=>(s[s.FONT_A=0]="FONT_A",s[s.FONT_B=1]="FONT_B",s[s.FONT_C=2]="FONT_C",s[s.FONT_D=3]="FONT_D",s[s.FONT_E=4]="FONT_E",s))(Z||{}),V=(o=>(o[o.TM_M10=0]="TM_M10",o[o.TM_M30=1]="TM_M30",o[o.TM_P20=2]="TM_P20",o[o.TM_P60=3]="TM_P60",o[o.TM_P60II=4]="TM_P60II",o[o.TM_P80=5]="TM_P80",o[o.TM_T20=6]="TM_T20",o[o.TM_T60=7]="TM_T60",o[o.TM_T70=8]="TM_T70",o[o.TM_T81=9]="TM_T81",o[o.TM_T82=10]="TM_T82",o[o.TM_T83=11]="TM_T83",o[o.TM_T88=12]="TM_T88",o[o.TM_T90=13]="TM_T90",o[o.TM_T90KP=14]="TM_T90KP",o[o.TM_U220=15]="TM_U220",o[o.TM_U330=16]="TM_U330",o[o.TM_L90=17]="TM_L90",o[o.TM_H6000=18]="TM_H6000",o[o.TM_T83III=19]="TM_T83III",o[o.TM_T100=20]="TM_T100",o[o.TM_M30II=21]="TM_M30II",o[o.TM_M50=23]="TM_M50",o[o.TM_T88VII=24]="TM_T88VII",o[o.TM_L90LFC=25]="TM_L90LFC",o[o.TM_L100=26]="TM_L100",o[o.TM_P20II=27]="TM_P20II",o[o.TM_P80II=28]="TM_P80II",o[o.TM_M30III=29]="TM_M30III",o[o.TM_M50II=30]="TM_M50II",o[o.TM_M55=31]="TM_M55",o[o.TM_U220II=32]="TM_U220II",o))(V||{});var y=require("react-native"),T=y.NativeModules.MunchiEpsonModule,z=()=>T?new y.NativeEventEmitter(T):null,pe=t=>new Promise(e=>setTimeout(e,t)),Ne=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e.toUpperCase():""},he=t=>{if(t instanceof Error)return t.message.toUpperCase();if(t&&typeof t=="object"){let e=t.message;if(typeof e=="string")return e.toUpperCase()}return String(t).toUpperCase()},p=(t,e,r)=>t.includes(r)||e===r||e.includes(r),S=async(t,e=3,r=500)=>{try{return await t()}catch(n){if(e<=1)throw n;let i=he(n),s=Ne(n);if(p(i,s,"TARGET_IN_USE"))throw n;if(p(i,s,"BUSY")||p(i,s,"IN_USE")||p(i,s,"ERR_IN_USE")||p(i,s,"PRINT_BUSY")||p(i,s,"ERR_CONNECT")||p(i,s,"CONNECT_ERROR")||p(i,s,"ERR_TIMEOUT")||p(i,s,"PRINT_TIMEOUT"))return await pe(r),S(t,e-1,r);throw n}};var D=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!T)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=T.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!T||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await T.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var M=class{constructor(e){this.logger=e}queue=Promise.resolve();isQueuePaused=!1;resumeQueueResolver=null;isPaused(){return this.isQueuePaused}pause(){this.isQueuePaused=!0}resume(){this.isQueuePaused&&(this.isQueuePaused=!1,this.resumeQueueResolver&&(this.resumeQueueResolver(),this.resumeQueueResolver=null))}async waitUntilResumed(){if(this.isQueuePaused)return new Promise(e=>{let r=this.resumeQueueResolver;this.resumeQueueResolver=()=>{r&&r(),e()}})}enqueue(e){return new Promise((r,n)=>{let i=async()=>{this.isQueuePaused&&(this.logger?.info?.("[EpsonPrinter] Queue is PAUSED. Waiting for resume..."),await this.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Queue RESUMED."));try{let s=await e();r(s)}catch(s){n(s)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var v=class{constructor(e){this.config=e}recoveryTimer=null;start(){this.recoveryTimer||(this.config.logger?.info?.("[EpsonPrinter] Starting recovery polling..."),this.recoveryTimer=setInterval(async()=>{try{let e=await this.config.getStatus();if(e.online&&!e.coverOpen&&e.errorStatus==="NONE")this.config.logger?.info?.("[EpsonPrinter] Poller detected healthy status. Requesting queue resume."),this.config.onRecovered();else{let n=`[EpsonPrinter] Polling... Status: Online=${e.online}, Cover=${e.coverOpen}, Err=${e.errorStatus}`;this.config.logger?.info?.(n)}}catch(e){this.config.logger?.error("[EpsonPrinter] Recovery poll failed",e)}},2e3))}stop(){this.recoveryTimer&&(this.config.logger?.info?.("[EpsonPrinter] Stopping recovery polling."),clearInterval(this.recoveryTimer),this.recoveryTimer=null)}};var Ce=new Set([0,3,5,21]),x=class{constructor(e){this.config=e}statusSubscription=null;connectionSubscription=null;connectionCallbacks=new Set;emitStatus(e){for(let r of this.connectionCallbacks)r(e)}ensureStatusListener(){if(this.statusSubscription)return;let e=z();e&&(this.config.logger?.info?.("[EpsonPrinter] Starting status listener for queue management"),this.statusSubscription=e.addListener("onPrinterStatusChange",r=>{if(!this.config.getSessionId()||r.sessionId!==this.config.getSessionId())return;let n=`[EpsonPrinter] Received Status Event: ${r.eventType}`;this.config.logger?.info?.(n),Ce.has(r.eventType)&&this.config.onRecoveryEvent(r.eventType)}))}ensureConnectionListener(){if(this.connectionSubscription)return;let e=z();e&&(this.connectionSubscription=e.addListener("onPrinterConnectionChange",r=>{if(!this.config.getSessionId()||r.sessionId!==this.config.getSessionId())return;let n="UNKNOWN";switch(r.status){case"RECONNECTING":n="RECONNECTING";break;case"RECONNECTED":n="CONNECTED";break;case"DISCONNECTED":n="DISCONNECTED";break;default:n="UNKNOWN"}this.config.onConnectionEvent(n),this.emitStatus(n)}))}removeStatusListener(){this.statusSubscription&&(this.statusSubscription.remove(),this.statusSubscription=null)}onConnectionChange(e){return this.connectionCallbacks.add(e),e(this.config.getConnectionStatus()),this.ensureConnectionListener(),()=>{this.connectionCallbacks.delete(e),this.connectionCallbacks.size===0&&this.connectionSubscription&&(this.connectionSubscription.remove(),this.connectionSubscription=null)}}};var ee={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},A=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new D(this.logger),this.queueController=new M(this.logger),this.recoveryController=new v({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.eventRouter=new x({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onRecoveryEvent:()=>{this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())},onConnectionEvent:r=>{r==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED")}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}async connect(e,r=5e3){let n=e??this.defaultTarget;if(!n){let i=new Error("Printer target is required");throw this.logger?.error("[EpsonPrinter] Connect failed: missing target",i),i}return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!T){this.logger?.error("[EpsonPrinter] Native module not found");return}if(this.connectionStatus==="CONNECTED"&&this.target===n)return;let i=await this.sessionManager.ensureSession();this.isConnecting=!0,this.connectionStatus="CONNECTING",this.eventRouter.emitStatus("CONNECTING");try{await S(()=>T.connect(i,n,r,this.model,this.lang)),this.target=n,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.isConnecting=!1,this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener()}catch(s){let u=f(s);throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,u),this.connectionStatus="DISCONNECTED",this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,u}})}async print(e){if(!T)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0;return this.queueController.enqueue(async()=>{let n=await this.sessionManager.ensureSession(),i=$(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await S(()=>T.print(n,i));break}catch(s){let u=K(s);if(u.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,u),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await T.print(n,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,u),u}}}).finally(()=>{this.disconnectTimer&&clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{this.performDisconnect()},5e3)})}performDisconnect(){this.queueController.enqueueBackground(async()=>{if(!this.disconnectTimer)return;let e=this.sessionManager.getSessionId();if(T&&this.connectionStatus==="CONNECTED"&&e)try{await T.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.eventRouter.emitStatus("DISCONNECTED"),await this.sessionManager.disposeSession()}catch(r){this.logger?.error("[EpsonPrinter] Auto-Disconnect failed",r)}this.disconnectTimer=null})}async printEmbedded(e){try{let r=W(e);return await this.print(r)}catch(r){let n=f(r);throw String(r).includes("MunchiPrinterError")||this.logger?.error("[EpsonPrinter] Embedded print failed",n),n}}async disconnect(){return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!T)return;let e=this.sessionManager.getSessionId();if(e)try{await T.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{await this.sessionManager.disposeSession()}})}async getStatus(){if(!T)return ee;let e=this.sessionManager.getSessionId();if(!e)return ee;try{return await T.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),f(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}};var te="1.0.2";var re=t=>{let e=f(t),r=e.message.toUpperCase(),n=t instanceof E?t.isHardwareError:F(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),s=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),u=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",P=e.code==="DISCOVERY_FAILED",d="UNKNOWN";return n?d="HARDWARE":i?d="BUSY":s?d="TIMEOUT":u?d="CONNECTION":P?d="DISCOVERY":e.code==="PRINT_FAILED"&&(d="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:d,isHardwareError:n,retryable:i||s,shouldPauseQueue:n,raw:t}},Ie=t=>re(t);var R=ge(require("react"));var ne=(0,R.createContext)(void 0),_e=({config:t,logger:e,children:r})=>{let[n,i]=(0,R.useState)();(0,R.useEffect)(()=>{e&&L(e)},[e]);let s=(0,R.useMemo)(()=>{let P={...t,logger:e??t.logger};return H(P)},[t.lang,t.model,t.target,e]),u=(0,R.useMemo)(()=>({printer:s,config:t,isReady:!0,error:n}),[s,t,n]);return R.default.createElement(ne.Provider,{value:u},r)},q=()=>{let t=(0,R.useContext)(ne);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};var N=require("react");var Oe={online:!1,coverOpen:!1,paper:"EMPTY",paperEmpty:!0,drawerOpen:!1,errorStatus:"NONE"};function ye(t={}){let{pollIntervalMs:e=5e3,enabled:r=!0}=t,{printer:n}=q(),[i,s]=(0,N.useState)("DISCONNECTED"),[u,P]=(0,N.useState)(null),[d,b]=(0,N.useState)(!1),h=(0,N.useRef)(null);return(0,N.useEffect)(()=>n.onConnectionChange(m=>{s(m)}),[n]),(0,N.useEffect)(()=>{if(!r||i!=="CONNECTED"){h.current&&(clearInterval(h.current),h.current=null,b(!1));return}let w=async()=>{try{let m=await n.getStatus();P(m)}catch{P(Oe)}};return w(),b(!0),h.current=setInterval(w,e),()=>{h.current&&(clearInterval(h.current),h.current=null,b(!1))}},[n,i,r,e]),{connectionStatus:i,hardwareStatus:u,isPolling:d}}var Se=[[/^TM-m10/i,0],[/^TM-m30III/i,29],[/^TM-m30II/i,21],[/^TM-m30/i,1],[/^TM-m50II/i,30],[/^TM-m50/i,23],[/^TM-m55/i,31],[/^TM-P20II/i,27],[/^TM-P20/i,2],[/^TM-P60II/i,4],[/^TM-P60/i,3],[/^TM-P80II/i,28],[/^TM-P80/i,5],[/^TM-T20/i,6],[/^TM-T60/i,7],[/^TM-T70/i,8],[/^TM-T81/i,9],[/^TM-T82/i,10],[/^TM-T83III/i,19],[/^TM-T83/i,11],[/^TM-T88VII/i,24],[/^TM-T88/i,12],[/^TM-T90KP/i,14],[/^TM-T90/i,13],[/^TM-T100/i,20],[/^TM-U220II/i,32],[/^TM-U220/i,15],[/^TM-U330/i,16],[/^TM-L90LFC/i,25],[/^TM-L90/i,17],[/^TM-L100/i,26],[/^TM-H6000/i,18]],ie=t=>{for(let[e,r]of Se)if(e.test(t))return r;return null};var se=require("react-native");var oe=se.NativeModules.MunchiEpsonModule,De={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},Me=t=>t.includes("[local_"),ve=(t,e)=>e?De[e].some(n=>t.startsWith(n)):!0,ae=async t=>{if(!oe)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await oe.discover({timeout:t.timeout})).map(X).filter(r=>!r||Me(r.target)?!1:ve(r.target,t.connectionType))}catch(e){let r=f(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};function H(t){return new A({...t,logger:t.logger??U()})}0&&(module.exports={Epos2CallbackCode,Epos2ConnectionEvent,Epos2ErrorStatus,Epos2Font,Epos2Lang,Epos2StatusEvent,EpsonModel,FontSize,MunchiPrinterError,PrinterError,PrinterErrorCode,PrinterProvider,PrinterTranslationCode,VERSION,discoverPrinters,getGlobalLogger,getPrinter,resolveEpsonError,resolveModelFromBluetoothName,resolvePrinterError,setGlobalLogger,usePrinter,usePrinterStatus});
|
package/dist/index.mjs
CHANGED
|
@@ -8,4 +8,4 @@ var w={},L=t=>{w.logger=t},U=()=>w.logger;var D=(u=>(u.CONNECTION_FAILED="CONNEC
|
|
|
8
8
|
`,bold:!0}):o==="R"?e.push({type:"text",text:R+`
|
|
9
9
|
`,bold:!0}):e.push({type:"text",text:R+`
|
|
10
10
|
`,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var E=class t extends g{constructor(n,r,o,s,u){super(r,o,s,u);this.isHardwareError=n;this.name="PrinterError",Object.setPrototypeOf(this,t.prototype)}},x=t=>{if(t instanceof E)return t.isHardwareError;let e=String(t.message||t).toUpperCase();return e.includes("ERR_OFF_LINE")||e.includes("ERR_COVER_OPEN")||e.includes("ERR_PAPER_OUT")||e.includes("ERR_FAILURE")||e.includes("DISCONNECT")||e.includes("PRINT_TIMEOUT")||e.includes("ERROR CODE: 4")||e.includes("ERROR CODE: 7")||e.includes("ERROR CODE: 3")},B=t=>{if(t instanceof E)return t;let e=P(t),n=x(t);return new E(n,e.code,e.translationCode,e.message,e.originalError)};var Z=(t,e=!1)=>{let n={Small:{normal:{width:1,height:1},item:{width:1,height:1}},Medium:{normal:{width:2,height:2},item:{width:2,height:2}},Large:{normal:{width:2,height:2},item:{width:3,height:3}}},r=e?"item":"normal";return n[t]?.[r]??n.Small.normal},Y=t=>{if(typeof t!="object"||t===null)return null;let e=t;return{target:String(e.target||""),name:String(e.name||""),macAddress:e.macAddress?String(e.macAddress):void 0,ipAddress:e.ipAddress?String(e.ipAddress):void 0,bdAddress:e.bdAddress?String(e.bdAddress):void 0,type:"EPSON"}},V=t=>t.commands.map(e=>{switch(e.type){case"text":return{cmd:"addText",data:e.text,align:e.align,bold:e.bold,underline:e.underline,size:e.size};case"align":return{cmd:"addTextAlign",align:e.align};case"bold":return{cmd:"addTextStyle",bold:e.value};case"fontSize":{let n=Z(e.size,e.isItemName);return{cmd:"addTextSize",width:n.width,height:n.height}}case"newline":return{cmd:"addFeedLine",line:e.lines||1};case"separator":return{cmd:"addText",data:`------------------
|
|
11
|
-
`};case"textLang":return{cmd:"addTextLang",lang:e.lang};case"textFont":return{cmd:"addTextFont",font:e.font};case"image":return{cmd:"addImage",data:e.base64,width:e.width};case"cut":return{cmd:"addCut"};case"drawer":return{cmd:"addPulse"};case"barcode":return{cmd:"addBarcode",data:e.data,type:e.system,width:e.width,height:e.height};case"qr":return{cmd:"addSymbol",data:e.data,type:"QRCODE_MODEL_2",level:e.errorCorrection||"M",width:e.size||3};case"feed":return{cmd:"addFeedLine",line:e.lines};default:return null}}).filter(e=>e!==null);var z=(c=>(c[c.ONLINE=0]="ONLINE",c[c.OFFLINE=1]="OFFLINE",c[c.POWER_OFF=2]="POWER_OFF",c[c.COVER_CLOSE=3]="COVER_CLOSE",c[c.COVER_OPEN=4]="COVER_OPEN",c[c.PAPER_OK=5]="PAPER_OK",c[c.PAPER_NEAR_END=6]="PAPER_NEAR_END",c[c.PAPER_EMPTY=7]="PAPER_EMPTY",c[c.DRAWER_HIGH=8]="DRAWER_HIGH",c[c.DRAWER_LOW=9]="DRAWER_LOW",c[c.BATTERY_ENOUGH=10]="BATTERY_ENOUGH",c[c.BATTERY_EMPTY=11]="BATTERY_EMPTY",c[c.AUTO_RECOVER_ERROR=20]="AUTO_RECOVER_ERROR",c[c.AUTO_RECOVER_OK=21]="AUTO_RECOVER_OK",c[c.UNRECOVERABLE_ERROR=22]="UNRECOVERABLE_ERROR",c))(z||{}),ee=(r=>(r[r.RECONNECTING=0]="RECONNECTING",r[r.RECONNECT=1]="RECONNECT",r[r.DISCONNECT=2]="DISCONNECT",r))(ee||{}),te=(a=>(a[a.SUCCESS=0]="SUCCESS",a[a.ERR_PARAM=1]="ERR_PARAM",a[a.ERR_CONNECT=2]="ERR_CONNECT",a[a.ERR_TIMEOUT=3]="ERR_TIMEOUT",a[a.ERR_MEMORY=4]="ERR_MEMORY",a[a.ERR_ILLEGAL=5]="ERR_ILLEGAL",a[a.ERR_PROCESSING=6]="ERR_PROCESSING",a[a.ERR_NOT_FOUND=7]="ERR_NOT_FOUND",a[a.ERR_IN_USE=8]="ERR_IN_USE",a[a.ERR_TYPE_INVALID=9]="ERR_TYPE_INVALID",a[a.ERR_DISCONNECT=10]="ERR_DISCONNECT",a[a.ERR_ALREADY_OPENED=11]="ERR_ALREADY_OPENED",a[a.ERR_ALREADY_USED=12]="ERR_ALREADY_USED",a[a.ERR_BOX_COUNT_OVER=13]="ERR_BOX_COUNT_OVER",a[a.ERR_BOX_CLIENT_OVER=14]="ERR_BOX_CLIENT_OVER",a[a.ERR_UNSUPPORTED=15]="ERR_UNSUPPORTED",a[a.ERR_DEVICE_BUSY=16]="ERR_DEVICE_BUSY",a[a.ERR_RECOVERY_FAILURE=17]="ERR_RECOVERY_FAILURE",a[a.ERR_FAILURE=255]="ERR_FAILURE",a))(te||{}),re=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.ERR_TIMEOUT=1]="ERR_TIMEOUT",m[m.ERR_NOT_FOUND=2]="ERR_NOT_FOUND",m[m.ERR_AUTORECOVER=3]="ERR_AUTORECOVER",m[m.ERR_COVER_OPEN=4]="ERR_COVER_OPEN",m[m.ERR_CUTTER=5]="ERR_CUTTER",m[m.ERR_MECHANICAL=6]="ERR_MECHANICAL",m[m.ERR_EMPTY=7]="ERR_EMPTY",m[m.ERR_UNRECOVERABLE=8]="ERR_UNRECOVERABLE",m[m.ERR_SYSTEM=9]="ERR_SYSTEM",m[m.ERR_PORT=10]="ERR_PORT",m[m.ERR_FAILURE=255]="ERR_FAILURE",m))(re||{}),q=(d=>(d[d.EN=0]="EN",d[d.JA=1]="JA",d[d.ZH_CN=2]="ZH_CN",d[d.ZH_TW=3]="ZH_TW",d[d.KO=4]="KO",d[d.TH=5]="TH",d[d.VI=6]="VI",d[d.MULTI=7]="MULTI",d))(q||{}),ne=(s=>(s[s.FONT_A=0]="FONT_A",s[s.FONT_B=1]="FONT_B",s[s.FONT_C=2]="FONT_C",s[s.FONT_D=3]="FONT_D",s[s.FONT_E=4]="FONT_E",s))(ne||{}),H=(i=>(i[i.TM_M10=0]="TM_M10",i[i.TM_M30=1]="TM_M30",i[i.TM_P20=2]="TM_P20",i[i.TM_P60=3]="TM_P60",i[i.TM_P60II=4]="TM_P60II",i[i.TM_P80=5]="TM_P80",i[i.TM_T20=6]="TM_T20",i[i.TM_T60=7]="TM_T60",i[i.TM_T70=8]="TM_T70",i[i.TM_T81=9]="TM_T81",i[i.TM_T82=10]="TM_T82",i[i.TM_T83=11]="TM_T83",i[i.TM_T88=12]="TM_T88",i[i.TM_T90=13]="TM_T90",i[i.TM_T90KP=14]="TM_T90KP",i[i.TM_U220=15]="TM_U220",i[i.TM_U330=16]="TM_U330",i[i.TM_L90=17]="TM_L90",i[i.TM_H6000=18]="TM_H6000",i[i.TM_T83III=19]="TM_T83III",i[i.TM_T100=20]="TM_T100",i[i.TM_M30II=21]="TM_M30II",i[i.TM_M50=23]="TM_M50",i[i.TM_T88VII=24]="TM_T88VII",i[i.TM_L90LFC=25]="TM_L90LFC",i[i.TM_L100=26]="TM_L100",i[i.TM_P20II=27]="TM_P20II",i[i.TM_P80II=28]="TM_P80II",i[i.TM_M30III=29]="TM_M30III",i[i.TM_M50II=30]="TM_M50II",i[i.TM_M55=31]="TM_M55",i[i.TM_U220II=32]="TM_U220II",i))(H||{});import{NativeEventEmitter as ie,NativeModules as oe}from"react-native";var T=oe.MunchiEpsonModule,A=()=>T?new ie(T):null,se=t=>new Promise(e=>setTimeout(e,t)),ae=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e.toUpperCase():""},ue=t=>{if(t instanceof Error)return t.message.toUpperCase();if(t&&typeof t=="object"){let e=t.message;if(typeof e=="string")return e.toUpperCase()}return String(t).toUpperCase()},f=(t,e,n)=>t.includes(n)||e===n||e.includes(n),N=async(t,e=3,n=500)=>{try{return await t()}catch(r){if(e<=1)throw r;let o=ue(r),s=ae(r);if(f(o,s,"TARGET_IN_USE"))throw r;if(f(o,s,"BUSY")||f(o,s,"IN_USE")||f(o,s,"ERR_IN_USE")||f(o,s,"PRINT_BUSY")||f(o,s,"ERR_CONNECT")||f(o,s,"CONNECT_ERROR")||f(o,s,"ERR_TIMEOUT")||f(o,s,"PRINT_TIMEOUT"))return await se(n),N(t,e-1,n);throw r}};var h=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!T)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=T.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!T||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await T.disposeSession(e)}catch(n){this.logger?.error("[EpsonPrinter] Dispose session failed",n)}}};var C=class{constructor(e){this.logger=e}queue=Promise.resolve();isQueuePaused=!1;resumeQueueResolver=null;isPaused(){return this.isQueuePaused}pause(){this.isQueuePaused=!0}resume(){this.isQueuePaused&&(this.isQueuePaused=!1,this.resumeQueueResolver&&(this.resumeQueueResolver(),this.resumeQueueResolver=null))}async waitUntilResumed(){if(this.isQueuePaused)return new Promise(e=>{let n=this.resumeQueueResolver;this.resumeQueueResolver=()=>{n&&n(),e()}})}enqueue(e){return new Promise((n,r)=>{let o=async()=>{this.isQueuePaused&&(this.logger?.info?.("[EpsonPrinter] Queue is PAUSED. Waiting for resume..."),await this.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Queue RESUMED."));try{let s=await e();n(s)}catch(s){r(s)}};this.queue=this.queue.then(o,o)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var I=class{constructor(e){this.config=e}recoveryTimer=null;start(){this.recoveryTimer||(this.config.logger?.info?.("[EpsonPrinter] Starting recovery polling..."),this.recoveryTimer=setInterval(async()=>{try{let e=await this.config.getStatus();if(e.online&&!e.coverOpen&&e.errorStatus==="NONE")this.config.logger?.info?.("[EpsonPrinter] Poller detected healthy status. Requesting queue resume."),this.config.onRecovered();else{let r=`[EpsonPrinter] Polling... Status: Online=${e.online}, Cover=${e.coverOpen}, Err=${e.errorStatus}`;this.config.logger?.info?.(r)}}catch(e){this.config.logger?.error("[EpsonPrinter] Recovery poll failed",e)}},2e3))}stop(){this.recoveryTimer&&(this.config.logger?.info?.("[EpsonPrinter] Stopping recovery polling."),clearInterval(this.recoveryTimer),this.recoveryTimer=null)}};var ce=new Set([0,3,5,21]),_=class{constructor(e){this.config=e}statusSubscription=null;connectionSubscription=null;connectionCallbacks=new Set;emitStatus(e){for(let n of this.connectionCallbacks)n(e)}ensureStatusListener(){if(this.statusSubscription)return;let e=A();e&&(this.config.logger?.info?.("[EpsonPrinter] Starting status listener for queue management"),this.statusSubscription=e.addListener("onPrinterStatusChange",n=>{if(!this.config.getSessionId()||n.sessionId!==this.config.getSessionId())return;let r=`[EpsonPrinter] Received Status Event: ${n.eventType}`;this.config.logger?.info?.(r),ce.has(n.eventType)&&this.config.onRecoveryEvent(n.eventType)}))}ensureConnectionListener(){if(this.connectionSubscription)return;let e=A();e&&(this.connectionSubscription=e.addListener("onPrinterConnectionChange",n=>{if(!this.config.getSessionId()||n.sessionId!==this.config.getSessionId())return;let r="UNKNOWN";switch(n.status){case"RECONNECTING":r="RECONNECTING";break;case"RECONNECTED":r="CONNECTED";break;case"DISCONNECTED":r="DISCONNECTED";break;default:r="UNKNOWN"}this.config.onConnectionEvent(r),this.emitStatus(r)}))}removeStatusListener(){this.statusSubscription&&(this.statusSubscription.remove(),this.statusSubscription=null)}onConnectionChange(e){return this.connectionCallbacks.add(e),e(this.config.getConnectionStatus()),this.ensureConnectionListener(),()=>{this.connectionCallbacks.delete(e),this.connectionCallbacks.size===0&&this.connectionSubscription&&(this.connectionSubscription.remove(),this.connectionSubscription=null)}}};var G={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},O=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new h(this.logger),this.queueController=new C(this.logger),this.recoveryController=new I({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.eventRouter=new _({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onRecoveryEvent:()=>{this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())},onConnectionEvent:n=>{n==="CONNECTED"&&(this.connectionStatus="CONNECTED"),n==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED")}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}async connect(e,n=5e3){let r=e??this.defaultTarget;if(!r){let o=new Error("Printer target is required");throw this.logger?.error("[EpsonPrinter] Connect failed: missing target",o),o}return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!T){this.logger?.error("[EpsonPrinter] Native module not found");return}if(this.connectionStatus==="CONNECTED"&&this.target===r)return;let o=await this.sessionManager.ensureSession();this.isConnecting=!0,this.connectionStatus="CONNECTING",this.eventRouter.emitStatus("CONNECTING");try{await N(()=>T.connect(o,r,n,this.model,this.lang)),this.target=r,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.isConnecting=!1,this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener()}catch(s){let u=P(s);throw this.logger?.error(`[EpsonPrinter] Connect failed for ${r}`,u),this.connectionStatus="DISCONNECTED",this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,u}})}async print(e){if(!T)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let n=0;return this.queueController.enqueue(async()=>{let r=await this.sessionManager.ensureSession(),o=V(e);for(;;){n++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${n}`);try{await N(()=>T.print(r,o));break}catch(s){let u=B(s);if(u.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${n}. Waiting for recovery before retry...`,u),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await T.print(r,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${n}`,u),u}}}).finally(()=>{this.disconnectTimer&&clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{this.performDisconnect()},5e3)})}performDisconnect(){this.queueController.enqueueBackground(async()=>{if(!this.disconnectTimer)return;let e=this.sessionManager.getSessionId();if(T&&this.connectionStatus==="CONNECTED"&&e)try{await T.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.eventRouter.emitStatus("DISCONNECTED"),await this.sessionManager.disposeSession()}catch(n){this.logger?.error("[EpsonPrinter] Auto-Disconnect failed",n)}this.disconnectTimer=null})}async printEmbedded(e){try{let n=F(e);return await this.print(n)}catch(n){let r=P(n);throw String(n).includes("MunchiPrinterError")||this.logger?.error("[EpsonPrinter] Embedded print failed",r),r}}async disconnect(){return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!T)return;let e=this.sessionManager.getSessionId();if(e)try{await T.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(n){this.logger?.error("[EpsonPrinter] Disconnect failed",n)}finally{await this.sessionManager.disposeSession()}})}async getStatus(){if(!T)return G;let e=this.sessionManager.getSessionId();if(!e)return G;try{return await T.getStatus(e)}catch(n){throw this.logger?.error("[EpsonPrinter] GetStatus failed",n),P(n)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}};var me="1.0.1";var de=t=>{let e=P(t),n=e.message.toUpperCase(),r=t instanceof E?t.isHardwareError:x(t),o=e.translationCode==="printer.error.busy"||n.includes("BUSY")||n.includes("IN_USE")||n.includes("PRINT_BUSY"),s=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||n.includes("TIMEOUT"),u=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",R=e.code==="DISCOVERY_FAILED",d="UNKNOWN";return r?d="HARDWARE":o?d="BUSY":s?d="TIMEOUT":u?d="CONNECTION":R?d="DISCOVERY":e.code==="PRINT_FAILED"&&(d="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:d,isHardwareError:r,retryable:o||s,shouldPauseQueue:r,raw:t}},Et=t=>de(t);import le,{createContext as Te,useContext as ge,useEffect as Re,useMemo as Q,useState as Pe}from"react";var W=Te(void 0),It=({config:t,logger:e,children:n})=>{let[r,o]=Pe();Re(()=>{e&&L(e)},[e]);let s=Q(()=>{let R={...t,logger:e??t.logger};return X(R)},[t.lang,t.model,t.target,e]),u=Q(()=>({printer:s,config:t,isReady:!0,error:r}),[s,t,r]);return le.createElement(W.Provider,{value:u},n)},K=()=>{let t=ge(W);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};import{useEffect as $,useRef as fe,useState as b}from"react";var Ee={online:!1,coverOpen:!1,paper:"EMPTY",paperEmpty:!0,drawerOpen:!1,errorStatus:"NONE"};function St(t={}){let{pollIntervalMs:e=5e3,enabled:n=!0}=t,{printer:r}=K(),[o,s]=b("DISCONNECTED"),[u,R]=b(null),[d,y]=b(!1),p=fe(null);return $(()=>r.onConnectionChange(m=>{s(m)}),[r]),$(()=>{if(!n||o!=="CONNECTED"){p.current&&(clearInterval(p.current),p.current=null,y(!1));return}let S=async()=>{try{let m=await r.getStatus();R(m)}catch{R(Ee)}};return S(),y(!0),p.current=setInterval(S,e),()=>{p.current&&(clearInterval(p.current),p.current=null,y(!1))}},[r,o,n,e]),{connectionStatus:o,hardwareStatus:u,isPolling:d}}var pe=[[/^TM-m10/i,0],[/^TM-m30III/i,29],[/^TM-m30II/i,21],[/^TM-m30/i,1],[/^TM-m50II/i,30],[/^TM-m50/i,23],[/^TM-m55/i,31],[/^TM-P20II/i,27],[/^TM-P20/i,2],[/^TM-P60II/i,4],[/^TM-P60/i,3],[/^TM-P80II/i,28],[/^TM-P80/i,5],[/^TM-T20/i,6],[/^TM-T60/i,7],[/^TM-T70/i,8],[/^TM-T81/i,9],[/^TM-T82/i,10],[/^TM-T83III/i,19],[/^TM-T83/i,11],[/^TM-T88VII/i,24],[/^TM-T88/i,12],[/^TM-T90KP/i,14],[/^TM-T90/i,13],[/^TM-T100/i,20],[/^TM-U220II/i,32],[/^TM-U220/i,15],[/^TM-U330/i,16],[/^TM-L90LFC/i,25],[/^TM-L90/i,17],[/^TM-L100/i,26],[/^TM-H6000/i,18]],Ne=t=>{for(let[e,n]of pe)if(e.test(t))return n;return null};import{NativeModules as he}from"react-native";var J=he.MunchiEpsonModule,Ce={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},Ie=t=>t.includes("[local_"),_e=(t,e)=>e?Ce[e].some(r=>t.startsWith(r)):!0,Oe=async t=>{if(!J)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await J.discover({timeout:t.timeout})).map(Y).filter(n=>!n||Ie(n.target)?!1:_e(n.target,t.connectionType))}catch(e){let n=P(e);throw console.error("[EpsonDiscovery] Discovery failed",n),n}};function X(t){return new O({...t,logger:t.logger??U()})}export{re as Epos2CallbackCode,ee as Epos2ConnectionEvent,te as Epos2ErrorStatus,ne as Epos2Font,q as Epos2Lang,z as Epos2StatusEvent,H as EpsonModel,v as FontSize,g as MunchiPrinterError,E as PrinterError,D as PrinterErrorCode,It as PrinterProvider,M as PrinterTranslationCode,me as VERSION,Oe as discoverPrinters,U as getGlobalLogger,X as getPrinter,Et as resolveEpsonError,Ne as resolveModelFromBluetoothName,de as resolvePrinterError,L as setGlobalLogger,K as usePrinter,St as usePrinterStatus};
|
|
11
|
+
`};case"textLang":return{cmd:"addTextLang",lang:e.lang};case"textFont":return{cmd:"addTextFont",font:e.font};case"image":return{cmd:"addImage",data:e.base64,width:e.width};case"cut":return{cmd:"addCut"};case"drawer":return{cmd:"addPulse"};case"barcode":return{cmd:"addBarcode",data:e.data,type:e.system,width:e.width,height:e.height};case"qr":return{cmd:"addSymbol",data:e.data,type:"QRCODE_MODEL_2",level:e.errorCorrection||"M",width:e.size||3};case"feed":return{cmd:"addFeedLine",line:e.lines};default:return null}}).filter(e=>e!==null);var z=(c=>(c[c.ONLINE=0]="ONLINE",c[c.OFFLINE=1]="OFFLINE",c[c.POWER_OFF=2]="POWER_OFF",c[c.COVER_CLOSE=3]="COVER_CLOSE",c[c.COVER_OPEN=4]="COVER_OPEN",c[c.PAPER_OK=5]="PAPER_OK",c[c.PAPER_NEAR_END=6]="PAPER_NEAR_END",c[c.PAPER_EMPTY=7]="PAPER_EMPTY",c[c.DRAWER_HIGH=8]="DRAWER_HIGH",c[c.DRAWER_LOW=9]="DRAWER_LOW",c[c.BATTERY_ENOUGH=10]="BATTERY_ENOUGH",c[c.BATTERY_EMPTY=11]="BATTERY_EMPTY",c[c.AUTO_RECOVER_ERROR=20]="AUTO_RECOVER_ERROR",c[c.AUTO_RECOVER_OK=21]="AUTO_RECOVER_OK",c[c.UNRECOVERABLE_ERROR=22]="UNRECOVERABLE_ERROR",c))(z||{}),ee=(r=>(r[r.RECONNECTING=0]="RECONNECTING",r[r.RECONNECT=1]="RECONNECT",r[r.DISCONNECT=2]="DISCONNECT",r))(ee||{}),te=(a=>(a[a.SUCCESS=0]="SUCCESS",a[a.ERR_PARAM=1]="ERR_PARAM",a[a.ERR_CONNECT=2]="ERR_CONNECT",a[a.ERR_TIMEOUT=3]="ERR_TIMEOUT",a[a.ERR_MEMORY=4]="ERR_MEMORY",a[a.ERR_ILLEGAL=5]="ERR_ILLEGAL",a[a.ERR_PROCESSING=6]="ERR_PROCESSING",a[a.ERR_NOT_FOUND=7]="ERR_NOT_FOUND",a[a.ERR_IN_USE=8]="ERR_IN_USE",a[a.ERR_TYPE_INVALID=9]="ERR_TYPE_INVALID",a[a.ERR_DISCONNECT=10]="ERR_DISCONNECT",a[a.ERR_ALREADY_OPENED=11]="ERR_ALREADY_OPENED",a[a.ERR_ALREADY_USED=12]="ERR_ALREADY_USED",a[a.ERR_BOX_COUNT_OVER=13]="ERR_BOX_COUNT_OVER",a[a.ERR_BOX_CLIENT_OVER=14]="ERR_BOX_CLIENT_OVER",a[a.ERR_UNSUPPORTED=15]="ERR_UNSUPPORTED",a[a.ERR_DEVICE_BUSY=16]="ERR_DEVICE_BUSY",a[a.ERR_RECOVERY_FAILURE=17]="ERR_RECOVERY_FAILURE",a[a.ERR_FAILURE=255]="ERR_FAILURE",a))(te||{}),re=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.ERR_TIMEOUT=1]="ERR_TIMEOUT",m[m.ERR_NOT_FOUND=2]="ERR_NOT_FOUND",m[m.ERR_AUTORECOVER=3]="ERR_AUTORECOVER",m[m.ERR_COVER_OPEN=4]="ERR_COVER_OPEN",m[m.ERR_CUTTER=5]="ERR_CUTTER",m[m.ERR_MECHANICAL=6]="ERR_MECHANICAL",m[m.ERR_EMPTY=7]="ERR_EMPTY",m[m.ERR_UNRECOVERABLE=8]="ERR_UNRECOVERABLE",m[m.ERR_SYSTEM=9]="ERR_SYSTEM",m[m.ERR_PORT=10]="ERR_PORT",m[m.ERR_FAILURE=255]="ERR_FAILURE",m))(re||{}),q=(d=>(d[d.EN=0]="EN",d[d.JA=1]="JA",d[d.ZH_CN=2]="ZH_CN",d[d.ZH_TW=3]="ZH_TW",d[d.KO=4]="KO",d[d.TH=5]="TH",d[d.VI=6]="VI",d[d.MULTI=7]="MULTI",d))(q||{}),ne=(s=>(s[s.FONT_A=0]="FONT_A",s[s.FONT_B=1]="FONT_B",s[s.FONT_C=2]="FONT_C",s[s.FONT_D=3]="FONT_D",s[s.FONT_E=4]="FONT_E",s))(ne||{}),H=(i=>(i[i.TM_M10=0]="TM_M10",i[i.TM_M30=1]="TM_M30",i[i.TM_P20=2]="TM_P20",i[i.TM_P60=3]="TM_P60",i[i.TM_P60II=4]="TM_P60II",i[i.TM_P80=5]="TM_P80",i[i.TM_T20=6]="TM_T20",i[i.TM_T60=7]="TM_T60",i[i.TM_T70=8]="TM_T70",i[i.TM_T81=9]="TM_T81",i[i.TM_T82=10]="TM_T82",i[i.TM_T83=11]="TM_T83",i[i.TM_T88=12]="TM_T88",i[i.TM_T90=13]="TM_T90",i[i.TM_T90KP=14]="TM_T90KP",i[i.TM_U220=15]="TM_U220",i[i.TM_U330=16]="TM_U330",i[i.TM_L90=17]="TM_L90",i[i.TM_H6000=18]="TM_H6000",i[i.TM_T83III=19]="TM_T83III",i[i.TM_T100=20]="TM_T100",i[i.TM_M30II=21]="TM_M30II",i[i.TM_M50=23]="TM_M50",i[i.TM_T88VII=24]="TM_T88VII",i[i.TM_L90LFC=25]="TM_L90LFC",i[i.TM_L100=26]="TM_L100",i[i.TM_P20II=27]="TM_P20II",i[i.TM_P80II=28]="TM_P80II",i[i.TM_M30III=29]="TM_M30III",i[i.TM_M50II=30]="TM_M50II",i[i.TM_M55=31]="TM_M55",i[i.TM_U220II=32]="TM_U220II",i))(H||{});import{NativeEventEmitter as ie,NativeModules as oe}from"react-native";var T=oe.MunchiEpsonModule,A=()=>T?new ie(T):null,se=t=>new Promise(e=>setTimeout(e,t)),ae=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e.toUpperCase():""},ue=t=>{if(t instanceof Error)return t.message.toUpperCase();if(t&&typeof t=="object"){let e=t.message;if(typeof e=="string")return e.toUpperCase()}return String(t).toUpperCase()},f=(t,e,n)=>t.includes(n)||e===n||e.includes(n),N=async(t,e=3,n=500)=>{try{return await t()}catch(r){if(e<=1)throw r;let o=ue(r),s=ae(r);if(f(o,s,"TARGET_IN_USE"))throw r;if(f(o,s,"BUSY")||f(o,s,"IN_USE")||f(o,s,"ERR_IN_USE")||f(o,s,"PRINT_BUSY")||f(o,s,"ERR_CONNECT")||f(o,s,"CONNECT_ERROR")||f(o,s,"ERR_TIMEOUT")||f(o,s,"PRINT_TIMEOUT"))return await se(n),N(t,e-1,n);throw r}};var h=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!T)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=T.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!T||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await T.disposeSession(e)}catch(n){this.logger?.error("[EpsonPrinter] Dispose session failed",n)}}};var C=class{constructor(e){this.logger=e}queue=Promise.resolve();isQueuePaused=!1;resumeQueueResolver=null;isPaused(){return this.isQueuePaused}pause(){this.isQueuePaused=!0}resume(){this.isQueuePaused&&(this.isQueuePaused=!1,this.resumeQueueResolver&&(this.resumeQueueResolver(),this.resumeQueueResolver=null))}async waitUntilResumed(){if(this.isQueuePaused)return new Promise(e=>{let n=this.resumeQueueResolver;this.resumeQueueResolver=()=>{n&&n(),e()}})}enqueue(e){return new Promise((n,r)=>{let o=async()=>{this.isQueuePaused&&(this.logger?.info?.("[EpsonPrinter] Queue is PAUSED. Waiting for resume..."),await this.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Queue RESUMED."));try{let s=await e();n(s)}catch(s){r(s)}};this.queue=this.queue.then(o,o)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var I=class{constructor(e){this.config=e}recoveryTimer=null;start(){this.recoveryTimer||(this.config.logger?.info?.("[EpsonPrinter] Starting recovery polling..."),this.recoveryTimer=setInterval(async()=>{try{let e=await this.config.getStatus();if(e.online&&!e.coverOpen&&e.errorStatus==="NONE")this.config.logger?.info?.("[EpsonPrinter] Poller detected healthy status. Requesting queue resume."),this.config.onRecovered();else{let r=`[EpsonPrinter] Polling... Status: Online=${e.online}, Cover=${e.coverOpen}, Err=${e.errorStatus}`;this.config.logger?.info?.(r)}}catch(e){this.config.logger?.error("[EpsonPrinter] Recovery poll failed",e)}},2e3))}stop(){this.recoveryTimer&&(this.config.logger?.info?.("[EpsonPrinter] Stopping recovery polling."),clearInterval(this.recoveryTimer),this.recoveryTimer=null)}};var ce=new Set([0,3,5,21]),_=class{constructor(e){this.config=e}statusSubscription=null;connectionSubscription=null;connectionCallbacks=new Set;emitStatus(e){for(let n of this.connectionCallbacks)n(e)}ensureStatusListener(){if(this.statusSubscription)return;let e=A();e&&(this.config.logger?.info?.("[EpsonPrinter] Starting status listener for queue management"),this.statusSubscription=e.addListener("onPrinterStatusChange",n=>{if(!this.config.getSessionId()||n.sessionId!==this.config.getSessionId())return;let r=`[EpsonPrinter] Received Status Event: ${n.eventType}`;this.config.logger?.info?.(r),ce.has(n.eventType)&&this.config.onRecoveryEvent(n.eventType)}))}ensureConnectionListener(){if(this.connectionSubscription)return;let e=A();e&&(this.connectionSubscription=e.addListener("onPrinterConnectionChange",n=>{if(!this.config.getSessionId()||n.sessionId!==this.config.getSessionId())return;let r="UNKNOWN";switch(n.status){case"RECONNECTING":r="RECONNECTING";break;case"RECONNECTED":r="CONNECTED";break;case"DISCONNECTED":r="DISCONNECTED";break;default:r="UNKNOWN"}this.config.onConnectionEvent(r),this.emitStatus(r)}))}removeStatusListener(){this.statusSubscription&&(this.statusSubscription.remove(),this.statusSubscription=null)}onConnectionChange(e){return this.connectionCallbacks.add(e),e(this.config.getConnectionStatus()),this.ensureConnectionListener(),()=>{this.connectionCallbacks.delete(e),this.connectionCallbacks.size===0&&this.connectionSubscription&&(this.connectionSubscription.remove(),this.connectionSubscription=null)}}};var G={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},O=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new h(this.logger),this.queueController=new C(this.logger),this.recoveryController=new I({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.eventRouter=new _({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onRecoveryEvent:()=>{this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())},onConnectionEvent:n=>{n==="CONNECTED"&&(this.connectionStatus="CONNECTED"),n==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED")}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}async connect(e,n=5e3){let r=e??this.defaultTarget;if(!r){let o=new Error("Printer target is required");throw this.logger?.error("[EpsonPrinter] Connect failed: missing target",o),o}return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!T){this.logger?.error("[EpsonPrinter] Native module not found");return}if(this.connectionStatus==="CONNECTED"&&this.target===r)return;let o=await this.sessionManager.ensureSession();this.isConnecting=!0,this.connectionStatus="CONNECTING",this.eventRouter.emitStatus("CONNECTING");try{await N(()=>T.connect(o,r,n,this.model,this.lang)),this.target=r,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.isConnecting=!1,this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener()}catch(s){let u=P(s);throw this.logger?.error(`[EpsonPrinter] Connect failed for ${r}`,u),this.connectionStatus="DISCONNECTED",this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,u}})}async print(e){if(!T)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let n=0;return this.queueController.enqueue(async()=>{let r=await this.sessionManager.ensureSession(),o=V(e);for(;;){n++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${n}`);try{await N(()=>T.print(r,o));break}catch(s){let u=B(s);if(u.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${n}. Waiting for recovery before retry...`,u),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await T.print(r,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${n}`,u),u}}}).finally(()=>{this.disconnectTimer&&clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{this.performDisconnect()},5e3)})}performDisconnect(){this.queueController.enqueueBackground(async()=>{if(!this.disconnectTimer)return;let e=this.sessionManager.getSessionId();if(T&&this.connectionStatus==="CONNECTED"&&e)try{await T.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.eventRouter.emitStatus("DISCONNECTED"),await this.sessionManager.disposeSession()}catch(n){this.logger?.error("[EpsonPrinter] Auto-Disconnect failed",n)}this.disconnectTimer=null})}async printEmbedded(e){try{let n=F(e);return await this.print(n)}catch(n){let r=P(n);throw String(n).includes("MunchiPrinterError")||this.logger?.error("[EpsonPrinter] Embedded print failed",r),r}}async disconnect(){return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!T)return;let e=this.sessionManager.getSessionId();if(e)try{await T.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(n){this.logger?.error("[EpsonPrinter] Disconnect failed",n)}finally{await this.sessionManager.disposeSession()}})}async getStatus(){if(!T)return G;let e=this.sessionManager.getSessionId();if(!e)return G;try{return await T.getStatus(e)}catch(n){throw this.logger?.error("[EpsonPrinter] GetStatus failed",n),P(n)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}};var me="1.0.2";var de=t=>{let e=P(t),n=e.message.toUpperCase(),r=t instanceof E?t.isHardwareError:x(t),o=e.translationCode==="printer.error.busy"||n.includes("BUSY")||n.includes("IN_USE")||n.includes("PRINT_BUSY"),s=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||n.includes("TIMEOUT"),u=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",R=e.code==="DISCOVERY_FAILED",d="UNKNOWN";return r?d="HARDWARE":o?d="BUSY":s?d="TIMEOUT":u?d="CONNECTION":R?d="DISCOVERY":e.code==="PRINT_FAILED"&&(d="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:d,isHardwareError:r,retryable:o||s,shouldPauseQueue:r,raw:t}},Et=t=>de(t);import le,{createContext as Te,useContext as ge,useEffect as Re,useMemo as Q,useState as Pe}from"react";var W=Te(void 0),It=({config:t,logger:e,children:n})=>{let[r,o]=Pe();Re(()=>{e&&L(e)},[e]);let s=Q(()=>{let R={...t,logger:e??t.logger};return X(R)},[t.lang,t.model,t.target,e]),u=Q(()=>({printer:s,config:t,isReady:!0,error:r}),[s,t,r]);return le.createElement(W.Provider,{value:u},n)},K=()=>{let t=ge(W);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};import{useEffect as $,useRef as fe,useState as b}from"react";var Ee={online:!1,coverOpen:!1,paper:"EMPTY",paperEmpty:!0,drawerOpen:!1,errorStatus:"NONE"};function St(t={}){let{pollIntervalMs:e=5e3,enabled:n=!0}=t,{printer:r}=K(),[o,s]=b("DISCONNECTED"),[u,R]=b(null),[d,y]=b(!1),p=fe(null);return $(()=>r.onConnectionChange(m=>{s(m)}),[r]),$(()=>{if(!n||o!=="CONNECTED"){p.current&&(clearInterval(p.current),p.current=null,y(!1));return}let S=async()=>{try{let m=await r.getStatus();R(m)}catch{R(Ee)}};return S(),y(!0),p.current=setInterval(S,e),()=>{p.current&&(clearInterval(p.current),p.current=null,y(!1))}},[r,o,n,e]),{connectionStatus:o,hardwareStatus:u,isPolling:d}}var pe=[[/^TM-m10/i,0],[/^TM-m30III/i,29],[/^TM-m30II/i,21],[/^TM-m30/i,1],[/^TM-m50II/i,30],[/^TM-m50/i,23],[/^TM-m55/i,31],[/^TM-P20II/i,27],[/^TM-P20/i,2],[/^TM-P60II/i,4],[/^TM-P60/i,3],[/^TM-P80II/i,28],[/^TM-P80/i,5],[/^TM-T20/i,6],[/^TM-T60/i,7],[/^TM-T70/i,8],[/^TM-T81/i,9],[/^TM-T82/i,10],[/^TM-T83III/i,19],[/^TM-T83/i,11],[/^TM-T88VII/i,24],[/^TM-T88/i,12],[/^TM-T90KP/i,14],[/^TM-T90/i,13],[/^TM-T100/i,20],[/^TM-U220II/i,32],[/^TM-U220/i,15],[/^TM-U330/i,16],[/^TM-L90LFC/i,25],[/^TM-L90/i,17],[/^TM-L100/i,26],[/^TM-H6000/i,18]],Ne=t=>{for(let[e,n]of pe)if(e.test(t))return n;return null};import{NativeModules as he}from"react-native";var J=he.MunchiEpsonModule,Ce={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},Ie=t=>t.includes("[local_"),_e=(t,e)=>e?Ce[e].some(r=>t.startsWith(r)):!0,Oe=async t=>{if(!J)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await J.discover({timeout:t.timeout})).map(Y).filter(n=>!n||Ie(n.target)?!1:_e(n.target,t.connectionType))}catch(e){let n=P(e);throw console.error("[EpsonDiscovery] Discovery failed",n),n}};function X(t){return new O({...t,logger:t.logger??U()})}export{re as Epos2CallbackCode,ee as Epos2ConnectionEvent,te as Epos2ErrorStatus,ne as Epos2Font,q as Epos2Lang,z as Epos2StatusEvent,H as EpsonModel,v as FontSize,g as MunchiPrinterError,E as PrinterError,D as PrinterErrorCode,It as PrinterProvider,M as PrinterTranslationCode,me as VERSION,Oe as discoverPrinters,U as getGlobalLogger,X as getPrinter,Et as resolveEpsonError,Ne as resolveModelFromBluetoothName,de as resolvePrinterError,L as setGlobalLogger,K as usePrinter,St as usePrinterStatus};
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const VERSION = "1.0.
|
|
1
|
+
export declare const VERSION = "1.0.2";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|