@munchi_oy/react-native-epson-printer 1.0.3 → 1.0.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/README.md +124 -75
- 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/README.md
CHANGED
|
@@ -1,43 +1,105 @@
|
|
|
1
1
|
# @munchi_oy/react-native-epson-printer
|
|
2
2
|
|
|
3
|
-
Epson printer SDK bridge for React Native.
|
|
3
|
+
Epson printer SDK bridge for React Native (iOS + Android).
|
|
4
|
+
|
|
5
|
+
## Installation (version-pinned recommended)
|
|
6
|
+
|
|
7
|
+
Use an explicit version instead of `latest` to keep production builds predictable.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @munchi_oy/react-native-epson-printer@1.0.3
|
|
11
|
+
# or
|
|
12
|
+
pnpm add @munchi_oy/react-native-epson-printer@1.0.3
|
|
13
|
+
# or
|
|
14
|
+
yarn add @munchi_oy/react-native-epson-printer@1.0.3
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Recommended policy:
|
|
18
|
+
- Pin to an exact version in production.
|
|
19
|
+
- Upgrade intentionally after validating printers on staging.
|
|
4
20
|
|
|
5
21
|
## Overview
|
|
6
22
|
|
|
7
23
|
This package provides:
|
|
8
24
|
- Epson discovery (`discoverPrinters`)
|
|
9
25
|
- Epson connection lifecycle (`connect`, `disconnect`, connection events)
|
|
10
|
-
-
|
|
11
|
-
- Receipt printing
|
|
26
|
+
- Serialized print queue with retry + recovery behavior
|
|
27
|
+
- Receipt printing via generic `PrintJob` commands
|
|
28
|
+
- Embedded payload printing (`printEmbedded`)
|
|
29
|
+
- Cash drawer pulse (`openDrawer`)
|
|
12
30
|
|
|
13
31
|
This package does not include Star or Sunmi drivers.
|
|
14
32
|
|
|
15
|
-
##
|
|
33
|
+
## Behavior Support (implemented)
|
|
16
34
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
35
|
+
| Behavior | Status | Details |
|
|
36
|
+
| :--- | :--- | :--- |
|
|
37
|
+
| Session-isolated instances | Implemented | Each `getPrinter(...)` instance owns a native `sessionId`; events are routed by session. |
|
|
38
|
+
| Target conflict protection | Implemented | Concurrent active usage of the same target returns `TARGET_IN_USE`. |
|
|
39
|
+
| Serialized job queue | Implemented | `connect`, `print`, and `disconnect` are queued to avoid race conditions per instance. |
|
|
40
|
+
| Hardware-error pause/resume | Implemented | Hardware failures pause queue; queue resumes when recovery is detected via status events and polling. |
|
|
41
|
+
| Retry for transient busy/timeout states | Implemented | Native operations retry for retryable states (`BUSY`, `IN_USE`, timeout-family errors). |
|
|
42
|
+
| Print receive timeout guard | Implemented | Native print call fails with `PRINT_TIMEOUT` if printer callback does not return within 30s. |
|
|
43
|
+
| iOS stale-session recovery | Implemented | One-shot session recovery + reconnect + retry for stale/busy/offline connection scenarios. |
|
|
44
|
+
| Post-print auto-disconnect | Implemented | JS driver schedules disconnect after 5s idle after print completion. |
|
|
45
|
+
| Android warm reconnect cache | Implemented | Native Android keeps a short-lived connection cache (up to 120s) for faster reconnect. |
|
|
46
|
+
| Discovery cleanup/filtering | Implemented | Duplicate targets are deduped and Epson sub-devices such as `[local_display]` are filtered out. |
|
|
47
|
+
|
|
48
|
+
## Multi-instance (one tablet -> many printers)
|
|
49
|
+
|
|
50
|
+
Yes, this is supported.
|
|
51
|
+
|
|
52
|
+
- Create one printer instance per physical target.
|
|
53
|
+
- Run them in parallel if needed.
|
|
54
|
+
- Do not connect two active instances to the same target at the same time (`TARGET_IN_USE`).
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { EpsonModel, getPrinter } from '@munchi_oy/react-native-epson-printer';
|
|
58
|
+
|
|
59
|
+
const kitchenPrinter = getPrinter({
|
|
60
|
+
target: 'BT:00:01:90:7B:5A:11',
|
|
61
|
+
model: EpsonModel.TM_M30III,
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const receiptPrinter = getPrinter({
|
|
65
|
+
target: 'TCP:192.168.1.50',
|
|
66
|
+
model: EpsonModel.TM_M30III,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
await Promise.all([
|
|
70
|
+
kitchenPrinter.connect(),
|
|
71
|
+
receiptPrinter.connect(),
|
|
72
|
+
]);
|
|
73
|
+
|
|
74
|
+
await Promise.all([
|
|
75
|
+
kitchenPrinter.print({ commands: [{ type: 'text', text: 'Kitchen ticket\n' }, { type: 'cut' }] }),
|
|
76
|
+
receiptPrinter.print({ commands: [{ type: 'text', text: 'Customer receipt\n' }, { type: 'cut' }] }),
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
await Promise.all([
|
|
80
|
+
kitchenPrinter.disconnect(),
|
|
81
|
+
receiptPrinter.disconnect(),
|
|
82
|
+
]);
|
|
21
83
|
```
|
|
22
84
|
|
|
23
85
|
## iOS Setup
|
|
24
86
|
|
|
25
|
-
1.
|
|
26
|
-
2. Run CocoaPods install
|
|
87
|
+
1. Install the package.
|
|
88
|
+
2. Run CocoaPods install:
|
|
27
89
|
|
|
28
90
|
```bash
|
|
29
91
|
cd ios && pod install
|
|
30
92
|
```
|
|
31
93
|
|
|
32
|
-
3.
|
|
94
|
+
3. Configure `Info.plist` permissions based on your connection method (Bluetooth/TCP).
|
|
33
95
|
|
|
34
96
|
## Android Setup
|
|
35
97
|
|
|
36
|
-
1.
|
|
37
|
-
2.
|
|
98
|
+
1. Install the package and sync Gradle.
|
|
99
|
+
2. Request runtime permissions before discovery/connection:
|
|
38
100
|
- Android 12+ (`API 31+`): `BLUETOOTH_SCAN`, `BLUETOOTH_CONNECT`
|
|
39
|
-
- Android 11 and below:
|
|
40
|
-
3. Rebuild the
|
|
101
|
+
- Android 11 and below: `ACCESS_FINE_LOCATION` (Bluetooth discovery)
|
|
102
|
+
3. Rebuild the app.
|
|
41
103
|
|
|
42
104
|
## Quick Start
|
|
43
105
|
|
|
@@ -67,9 +129,9 @@ await printer.disconnect();
|
|
|
67
129
|
| Field | Type | Required | Description |
|
|
68
130
|
| :--- | :--- | :--- | :--- |
|
|
69
131
|
| `model` | `EpsonModel` | Yes | Epson printer series passed to native init |
|
|
70
|
-
| `target` | `string` | No | Default target
|
|
71
|
-
| `lang` | `Epos2Lang` | No | Language enum
|
|
72
|
-
| `logger` | `PrinterLogger` | No |
|
|
132
|
+
| `target` | `string` | No | Default target used by `connect()` when no target is passed |
|
|
133
|
+
| `lang` | `Epos2Lang` | No | Language enum for native printer object |
|
|
134
|
+
| `logger` | `PrinterLogger` | No | Per-instance logger (`error`, optional `info`) |
|
|
73
135
|
|
|
74
136
|
## Discovery
|
|
75
137
|
|
|
@@ -78,31 +140,38 @@ Use discovery as a standalone API:
|
|
|
78
140
|
```ts
|
|
79
141
|
import { discoverPrinters } from '@munchi_oy/react-native-epson-printer';
|
|
80
142
|
|
|
81
|
-
const printers = await discoverPrinters({
|
|
143
|
+
const printers = await discoverPrinters({
|
|
144
|
+
timeout: 5000,
|
|
145
|
+
connectionType: 'bluetooth',
|
|
146
|
+
});
|
|
82
147
|
```
|
|
83
148
|
|
|
84
|
-
`
|
|
149
|
+
Supported `connectionType` filters:
|
|
150
|
+
- `bluetooth` -> `BT:`
|
|
151
|
+
- `tcp` -> `TCP:`, `TCPS:`
|
|
152
|
+
- `usb` -> `USB:`
|
|
85
153
|
|
|
86
154
|
## Connection Lifecycle
|
|
87
155
|
|
|
88
156
|
- `connect(target?, timeout?)`
|
|
89
157
|
- `disconnect()`
|
|
90
158
|
- `onConnectionChange(callback)`
|
|
159
|
+
- `onStatusChange(callback)`
|
|
91
160
|
|
|
92
|
-
|
|
161
|
+
Example:
|
|
93
162
|
|
|
94
163
|
```ts
|
|
95
164
|
await printer.connect(); // uses config.target
|
|
96
165
|
await printer.connect('TCP:192.168.1.50', 7000); // override target
|
|
97
166
|
|
|
98
|
-
const
|
|
99
|
-
console.log('
|
|
167
|
+
const off = printer.onConnectionChange((status) => {
|
|
168
|
+
console.log('connection', status);
|
|
100
169
|
});
|
|
101
170
|
```
|
|
102
171
|
|
|
103
172
|
## Printing
|
|
104
173
|
|
|
105
|
-
### PrintJob
|
|
174
|
+
### Generic `PrintJob`
|
|
106
175
|
|
|
107
176
|
```ts
|
|
108
177
|
await printer.print({
|
|
@@ -115,7 +184,7 @@ await printer.print({
|
|
|
115
184
|
});
|
|
116
185
|
```
|
|
117
186
|
|
|
118
|
-
### Embedded
|
|
187
|
+
### Embedded payload
|
|
119
188
|
|
|
120
189
|
```ts
|
|
121
190
|
await printer.printEmbedded({
|
|
@@ -125,26 +194,15 @@ await printer.printEmbedded({
|
|
|
125
194
|
});
|
|
126
195
|
```
|
|
127
196
|
|
|
128
|
-
### Cash
|
|
197
|
+
### Cash drawer
|
|
129
198
|
|
|
130
199
|
```ts
|
|
131
200
|
await printer.openDrawer();
|
|
132
201
|
```
|
|
133
202
|
|
|
134
|
-
## Multi-Instance And Session Behavior
|
|
135
|
-
|
|
136
|
-
Each `getPrinter(...)` instance has its own native `sessionId`.
|
|
137
|
-
|
|
138
|
-
This ensures:
|
|
139
|
-
- native calls are isolated per JS instance
|
|
140
|
-
- native events are routed by session
|
|
141
|
-
- instance A does not consume instance B events
|
|
142
|
-
|
|
143
|
-
If two instances connect to the same target at the same time, native returns `TARGET_IN_USE`.
|
|
144
|
-
|
|
145
203
|
## Logging
|
|
146
204
|
|
|
147
|
-
You can
|
|
205
|
+
You can set a global logger:
|
|
148
206
|
|
|
149
207
|
```ts
|
|
150
208
|
import { setGlobalLogger } from '@munchi_oy/react-native-epson-printer';
|
|
@@ -155,9 +213,16 @@ setGlobalLogger({
|
|
|
155
213
|
});
|
|
156
214
|
```
|
|
157
215
|
|
|
158
|
-
##
|
|
216
|
+
## React Helpers
|
|
217
|
+
|
|
218
|
+
The package exports:
|
|
219
|
+
- `PrinterProvider`
|
|
220
|
+
- `usePrinter()`
|
|
221
|
+
- `usePrinterStatus({ enabled?: boolean })`
|
|
222
|
+
|
|
223
|
+
`usePrinterStatus` handles connect/disconnect behavior based on `enabled`, subscribes to connection + hardware status events, and exposes error state.
|
|
159
224
|
|
|
160
|
-
|
|
225
|
+
## Vendor and Platform Support
|
|
161
226
|
|
|
162
227
|
| Vendor | Support |
|
|
163
228
|
| :--- | :--- |
|
|
@@ -165,31 +230,17 @@ setGlobalLogger({
|
|
|
165
230
|
| Star | No |
|
|
166
231
|
| Sunmi | No |
|
|
167
232
|
|
|
168
|
-
### Platform Focus
|
|
169
|
-
|
|
170
233
|
| Platform | Status |
|
|
171
234
|
| :--- | :--- |
|
|
172
235
|
| iOS | Supported |
|
|
173
236
|
| Android | Supported |
|
|
174
237
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
- Bluetooth (`BT:`)
|
|
178
|
-
- TCP (`TCP:`, `TCPS:`)
|
|
179
|
-
- USB (`USB:`)
|
|
238
|
+
## Known Limitations
|
|
180
239
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
-
|
|
184
|
-
-
|
|
185
|
-
- Connecting to the same target from multiple active sessions returns `TARGET_IN_USE`.
|
|
186
|
-
|
|
187
|
-
## Limitations
|
|
188
|
-
|
|
189
|
-
- Epson-only package scope.
|
|
190
|
-
- `model` must be known at instance creation time.
|
|
191
|
-
- No direct API to change model/lang after instance creation; create a new printer instance instead.
|
|
192
|
-
- Bridge behavior depends on Epson ePOS2 SDK constraints.
|
|
240
|
+
- Epson-only scope.
|
|
241
|
+
- `model` must be known at `getPrinter(...)` creation time.
|
|
242
|
+
- Model/language are immutable per instance; create a new instance to change them.
|
|
243
|
+
- Underlying behavior is constrained by Epson ePOS2 SDK.
|
|
193
244
|
|
|
194
245
|
## Troubleshooting
|
|
195
246
|
|
|
@@ -198,26 +249,24 @@ setGlobalLogger({
|
|
|
198
249
|
- Android: clean/sync Gradle and rebuild.
|
|
199
250
|
|
|
200
251
|
2. `Printer target is required`
|
|
201
|
-
- Pass `target` in config or
|
|
252
|
+
- Pass `target` in config or `connect(target)`.
|
|
202
253
|
|
|
203
|
-
3.
|
|
204
|
-
-
|
|
254
|
+
3. `TARGET_IN_USE`
|
|
255
|
+
- Another active session is using the same target. Disconnect old owner first.
|
|
205
256
|
|
|
206
|
-
|
|
257
|
+
4. Busy/timeouts during peak usage
|
|
258
|
+
- Keep one active owner per target and avoid overlapping connect/print flows from different instances.
|
|
207
259
|
|
|
208
|
-
|
|
260
|
+
## Migration Notes (already shipped)
|
|
209
261
|
|
|
210
|
-
|
|
211
|
-
- Removed `PrinterType`, Star/Sunmi drivers, and adapter-style vendor factory.
|
|
262
|
+
If upgrading from older adapter-based versions:
|
|
212
263
|
|
|
213
|
-
|
|
214
|
-
-
|
|
264
|
+
1. Epson-only scope
|
|
265
|
+
- Removed Star/Sunmi and `PrinterType` factory behavior.
|
|
215
266
|
|
|
216
|
-
|
|
217
|
-
-
|
|
218
|
-
- Now: `connect(target?, timeout?)`
|
|
219
|
-
- Model/lang come from instance config.
|
|
267
|
+
2. Config updates
|
|
268
|
+
- `model` is required in `getPrinter({ ... })`.
|
|
220
269
|
|
|
221
|
-
|
|
222
|
-
-
|
|
223
|
-
-
|
|
270
|
+
3. Connect signature
|
|
271
|
+
- Before: `connect(target, timeout, model, lang)`
|
|
272
|
+
- Now: `connect(target?, timeout?)` (model/lang come from instance config).
|
package/dist/index.js
CHANGED
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
`,align:"center",bold:!0})}else i==="B"?e.push({type:"text",text:g+`
|
|
9
9
|
`,bold:!0}):i==="R"?e.push({type:"text",text:g+`
|
|
10
10
|
`,bold:!0}):e.push({type:"text",text:g+`
|
|
11
|
-
`,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var x=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 o=await e();r(o)}catch(o){n(o)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var A=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 L=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!m)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=m.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!m||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await m.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var U=class{constructor(e){this.config=e}statusCallbacks=new Set;latestHardwareStatus=null;statusRefreshPromise=null;statusRefreshTimer=null;subscribe(e){return this.statusCallbacks.add(e),this.latestHardwareStatus?e(this.latestHardwareStatus):this.config.getConnectionStatus()!=="CONNECTED"?e(this.config.defaultStatus):this.refreshNow(),()=>{this.statusCallbacks.delete(e)}}handleStatusEvent(){this.scheduleRefresh()}handleConnected(){this.scheduleRefresh(0)}handleDisconnected(){this.clearRefreshTimer(),this.setHardwareStatus(this.config.defaultStatus)}clear(){this.clearRefreshTimer()}async refreshNow(){if(this.config.getConnectionStatus()!=="CONNECTED"){this.setHardwareStatus(this.config.defaultStatus);return}if(this.statusRefreshPromise){await this.statusRefreshPromise;return}this.statusRefreshPromise=(async()=>{try{let e=await this.config.getStatus();this.setHardwareStatus(e)}catch(e){this.config.logger?.error("[EpsonPrinter] Status refresh failed",e),this.latestHardwareStatus||this.setHardwareStatus(this.config.defaultStatus)}})().finally(()=>{this.statusRefreshPromise=null}),await this.statusRefreshPromise}emitHardwareStatus(e){for(let r of this.statusCallbacks)r(e)}setHardwareStatus(e){this.latestHardwareStatus=e,this.emitHardwareStatus(e)}clearRefreshTimer(){this.statusRefreshTimer&&(clearTimeout(this.statusRefreshTimer),this.statusRefreshTimer=null)}scheduleRefresh(e=150){this.config.getConnectionStatus()==="CONNECTED"&&(this.statusRefreshTimer||(this.statusRefreshTimer=setTimeout(()=>{this.statusRefreshTimer=null,this.refreshNow()},e)))}};var Q={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},Me=5e3,F=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;statusController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new L(this.logger),this.queueController=new x(this.logger),this.recoveryController=new A({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.statusController=new U({logger:this.logger,defaultStatus:Q,getConnectionStatus:()=>this.connectionStatus,getStatus:()=>this.getStatus()}),this.eventRouter=new w({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onEvent:r=>{r.statusEventType!==null&&(this.statusController.handleStatusEvent(),r.isRecoveryEvent&&this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())),r.connectionStatus!==null&&(r.connectionStatus==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r.connectionStatus==="CONNECTED"&&this.statusController.handleConnected(),r.connectionStatus==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected()))}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}isIosConnectionRecoveryCandidate(e){return W.Platform.OS!=="ios"?!1:e.code==="CONNECTION_FAILED"||e.code==="TIMEOUT"&&e.translationCode==="printer.error.connection_timeout"||e.translationCode==="printer.error.offline"}hasTargetInUseToken(e){if(!e||typeof e!="object")return!1;let r=String(e.code??"").toUpperCase(),n=String(e.message??"").toUpperCase();return r.includes("TARGET_IN_USE")||n.includes("TARGET_IN_USE")}isIosConnectBusyRecoveryCandidate(e){return W.Platform.OS!=="ios"||e.translationCode!=="printer.error.busy"?!1:!this.hasTargetInUseToken(e.originalError)}async recoverIosSessionForPrint(){if(!m)throw new Error("Native module not found");let e=this.target??this.defaultTarget;if(!e)throw new Error("Printer target is required");let r=this.sessionManager.getSessionId();if(r)try{await m.disconnect(r)}catch(i){this.logger?.error("[EpsonPrinter] iOS recovery disconnect failed (best-effort)",i)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let n=await this.sessionManager.ensureSession();return await S(()=>m.connect(n,e,Me,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected(),n}async recoverIosSessionForConnect(e,r){if(!m)throw new Error("Native module not found");let n=this.sessionManager.getSessionId();if(n)try{await m.disconnect(n)}catch(o){this.logger?.error("[EpsonPrinter] iOS connect recovery disconnect failed (best-effort)",o)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let i=await this.sessionManager.ensureSession();await S(()=>m.connect(i,e,r,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}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(!m){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");let o=!1;try{await S(()=>m.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(),this.statusController.handleConnected()}catch(l){let g=E(l);if(!o&&this.isIosConnectBusyRecoveryCandidate(g)){o=!0,this.logger?.error("[EpsonPrinter] iOS busy connect suspected stale session. Recovering connection and retrying connect once...",g);try{await this.recoverIosSessionForConnect(n,r),this.logger?.info?.("[EpsonPrinter] iOS connect recovery succeeded."),this.isConnecting=!1;return}catch(c){let N=E(c);throw this.logger?.error("[EpsonPrinter] iOS connect recovery failed",N),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,N}}throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,g),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,g}})}async print(e){if(!m)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0,n=!1;return this.queueController.enqueue(async()=>{let i=await this.sessionManager.ensureSession(),o=se(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await S(()=>m.print(i,o));break}catch(l){let g=ne(l);if(!n&&this.isIosConnectionRecoveryCandidate(g)){n=!0,this.logger?.error("[EpsonPrinter] iOS stale session suspected. Recovering connection and retrying print once...",g);try{i=await this.recoverIosSessionForPrint(),this.logger?.info?.("[EpsonPrinter] iOS session recovery succeeded. Retrying print...");continue}catch(c){let N=E(c);throw this.logger?.error("[EpsonPrinter] iOS session recovery failed",N),N}}if(g.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,g),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await m.print(i,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,g),g}}}).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(m&&this.connectionStatus==="CONNECTED"&&e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),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=oe(e);return await this.print(r)}catch(r){let n=E(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(!m)return;let e=this.sessionManager.getSessionId();if(e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{this.statusController.clear(),await this.sessionManager.disposeSession()}})}async getStatus(){if(!m)return Q;let e=this.sessionManager.getSessionId();if(!e)return Q;try{return await m.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),E(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}onStatusChange(e){return this.statusController.subscribe(e)}};var ue=require("react-native");var ae=ue.NativeModules.MunchiEpsonModule,we={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},be=t=>t.includes("[local_"),xe=(t,e)=>e?we[e].some(n=>t.startsWith(n)):!0,ce=async t=>{if(!ae)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await ae.discover({timeout:t.timeout})).map(ie).filter(r=>!r||be(r.target)?!1:xe(r.target,t.connectionType))}catch(e){let r=E(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};var Ae=[[/^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]],le=t=>{for(let[e,r]of Ae)if(e.test(t))return r;return null};var de=t=>{let e=E(t),r=e.message.toUpperCase(),n=t instanceof p?t.isHardwareError:z(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),o=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),l=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",g=e.code==="DISCOVERY_FAILED",c="UNKNOWN";return n?c="HARDWARE":i?c="BUSY":o?c="TIMEOUT":l?c="CONNECTION":g?c="DISCOVERY":e.code==="PRINT_FAILED"&&(c="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:c,isHardwareError:n,retryable:i||o,shouldPauseQueue:n,raw:t}},Le=t=>de(t);var me=Pe(require("react")),R=require("react");var ge=(0,R.createContext)(void 0),Ue=({config:t,logger:e,children:r})=>{let[n,i]=(0,R.useState)();(0,R.useEffect)(()=>{e&&B(e)},[e]);let o=(0,R.useMemo)(()=>{let g={...t,logger:e??t.logger};return K(g)},[t.lang,t.model,t.target,e]),l=(0,R.useMemo)(()=>({printer:o,config:t,isReady:!0,error:n}),[o,t,n]);return me.default.createElement(ge.Provider,{value:l},r)},k=()=>{let t=(0,R.useContext)(ge);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};var f=require("react");function Fe(t={}){let{enabled:e=!0}=t,{printer:r,config:n}=k(),[i,o]=(0,f.useState)("DISCONNECTED"),[l,g]=(0,f.useState)(null),[c,N]=(0,f.useState)(null),X=(0,f.useRef)("DISCONNECTED"),$=(0,f.useRef)(null),d=c!==null,I=(0,f.useCallback)(C=>{$.current=C,N(C)},[]),_=(0,f.useCallback)(C=>{if(C instanceof Error&&C.message){I(C.message);return}if(typeof C=="string"&&C.length>0){I(C);return}I("Unknown printer error")},[I]),a=(0,f.useCallback)(()=>{$.current!==null&&I(null)},[I]);return(0,f.useEffect)(()=>r.onConnectionChange(O=>{X.current=O,o(O),O==="CONNECTED"&&a()}),[a,r]),(0,f.useEffect)(()=>e?r.onStatusChange(O=>{g(O),a()}):void 0,[a,e,r]),(0,f.useEffect)(()=>{e&&i==="CONNECTED"&&r.getStatus().then(C=>{g(C),a()}).catch(_)},[_,a,i,e,r]),(0,f.useEffect)(()=>{let C=X.current;if(e){C==="DISCONNECTED"&&i==="DISCONNECTED"&&r.connect(n.target,5e3).then(a).catch(_);return}(i==="CONNECTED"||i==="CONNECTING")&&r.disconnect().then(a).catch(_)},[_,a,n.target,i,e,r]),{connectionStatus:i,hardwareStatus:l,isError:d,errorMessage:c}}var Te="1.0.3";function K(t){return new F({...t,logger:t.logger??Y()})}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
|
+
`,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var x=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 o=await e();r(o)}catch(o){n(o)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var A=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 L=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!m)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=m.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!m||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await m.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var U=class{constructor(e){this.config=e}statusCallbacks=new Set;latestHardwareStatus=null;statusRefreshPromise=null;statusRefreshTimer=null;subscribe(e){return this.statusCallbacks.add(e),this.latestHardwareStatus?e(this.latestHardwareStatus):this.config.getConnectionStatus()!=="CONNECTED"?e(this.config.defaultStatus):this.refreshNow(),()=>{this.statusCallbacks.delete(e)}}handleStatusEvent(){this.scheduleRefresh()}handleConnected(){this.scheduleRefresh(0)}handleDisconnected(){this.clearRefreshTimer(),this.setHardwareStatus(this.config.defaultStatus)}clear(){this.clearRefreshTimer()}async refreshNow(){if(this.config.getConnectionStatus()!=="CONNECTED"){this.setHardwareStatus(this.config.defaultStatus);return}if(this.statusRefreshPromise){await this.statusRefreshPromise;return}this.statusRefreshPromise=(async()=>{try{let e=await this.config.getStatus();this.setHardwareStatus(e)}catch(e){this.config.logger?.error("[EpsonPrinter] Status refresh failed",e),this.latestHardwareStatus||this.setHardwareStatus(this.config.defaultStatus)}})().finally(()=>{this.statusRefreshPromise=null}),await this.statusRefreshPromise}emitHardwareStatus(e){for(let r of this.statusCallbacks)r(e)}setHardwareStatus(e){this.latestHardwareStatus=e,this.emitHardwareStatus(e)}clearRefreshTimer(){this.statusRefreshTimer&&(clearTimeout(this.statusRefreshTimer),this.statusRefreshTimer=null)}scheduleRefresh(e=150){this.config.getConnectionStatus()==="CONNECTED"&&(this.statusRefreshTimer||(this.statusRefreshTimer=setTimeout(()=>{this.statusRefreshTimer=null,this.refreshNow()},e)))}};var Q={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},Me=5e3,F=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;statusController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new L(this.logger),this.queueController=new x(this.logger),this.recoveryController=new A({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.statusController=new U({logger:this.logger,defaultStatus:Q,getConnectionStatus:()=>this.connectionStatus,getStatus:()=>this.getStatus()}),this.eventRouter=new w({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onEvent:r=>{r.statusEventType!==null&&(this.statusController.handleStatusEvent(),r.isRecoveryEvent&&this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())),r.connectionStatus!==null&&(r.connectionStatus==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r.connectionStatus==="CONNECTED"&&this.statusController.handleConnected(),r.connectionStatus==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected()))}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}isIosConnectionRecoveryCandidate(e){return W.Platform.OS!=="ios"?!1:e.code==="CONNECTION_FAILED"||e.code==="TIMEOUT"&&e.translationCode==="printer.error.connection_timeout"||e.translationCode==="printer.error.offline"}hasTargetInUseToken(e){if(!e||typeof e!="object")return!1;let r=String(e.code??"").toUpperCase(),n=String(e.message??"").toUpperCase();return r.includes("TARGET_IN_USE")||n.includes("TARGET_IN_USE")}isIosConnectBusyRecoveryCandidate(e){return W.Platform.OS!=="ios"||e.translationCode!=="printer.error.busy"?!1:!this.hasTargetInUseToken(e.originalError)}async recoverIosSessionForPrint(){if(!m)throw new Error("Native module not found");let e=this.target??this.defaultTarget;if(!e)throw new Error("Printer target is required");let r=this.sessionManager.getSessionId();if(r)try{await m.disconnect(r)}catch(i){this.logger?.error("[EpsonPrinter] iOS recovery disconnect failed (best-effort)",i)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let n=await this.sessionManager.ensureSession();return await S(()=>m.connect(n,e,Me,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected(),n}async recoverIosSessionForConnect(e,r){if(!m)throw new Error("Native module not found");let n=this.sessionManager.getSessionId();if(n)try{await m.disconnect(n)}catch(o){this.logger?.error("[EpsonPrinter] iOS connect recovery disconnect failed (best-effort)",o)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let i=await this.sessionManager.ensureSession();await S(()=>m.connect(i,e,r,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}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(!m){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");let o=!1;try{await S(()=>m.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(),this.statusController.handleConnected()}catch(l){let g=E(l);if(!o&&this.isIosConnectBusyRecoveryCandidate(g)){o=!0,this.logger?.error("[EpsonPrinter] iOS busy connect suspected stale session. Recovering connection and retrying connect once...",g);try{await this.recoverIosSessionForConnect(n,r),this.logger?.info?.("[EpsonPrinter] iOS connect recovery succeeded."),this.isConnecting=!1;return}catch(c){let N=E(c);throw this.logger?.error("[EpsonPrinter] iOS connect recovery failed",N),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,N}}throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,g),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,g}})}async print(e){if(!m)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0,n=!1;return this.queueController.enqueue(async()=>{let i=await this.sessionManager.ensureSession(),o=se(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await S(()=>m.print(i,o));break}catch(l){let g=ne(l);if(!n&&this.isIosConnectionRecoveryCandidate(g)){n=!0,this.logger?.error("[EpsonPrinter] iOS stale session suspected. Recovering connection and retrying print once...",g);try{i=await this.recoverIosSessionForPrint(),this.logger?.info?.("[EpsonPrinter] iOS session recovery succeeded. Retrying print...");continue}catch(c){let N=E(c);throw this.logger?.error("[EpsonPrinter] iOS session recovery failed",N),N}}if(g.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,g),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await m.print(i,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,g),g}}}).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(m&&this.connectionStatus==="CONNECTED"&&e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),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=oe(e);return await this.print(r)}catch(r){let n=E(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(!m)return;let e=this.sessionManager.getSessionId();if(e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{this.statusController.clear(),await this.sessionManager.disposeSession()}})}async getStatus(){if(!m)return Q;let e=this.sessionManager.getSessionId();if(!e)return Q;try{return await m.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),E(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}onStatusChange(e){return this.statusController.subscribe(e)}};var ue=require("react-native");var ae=ue.NativeModules.MunchiEpsonModule,we={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},be=t=>t.includes("[local_"),xe=(t,e)=>e?we[e].some(n=>t.startsWith(n)):!0,ce=async t=>{if(!ae)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await ae.discover({timeout:t.timeout})).map(ie).filter(r=>!r||be(r.target)?!1:xe(r.target,t.connectionType))}catch(e){let r=E(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};var Ae=[[/^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]],le=t=>{for(let[e,r]of Ae)if(e.test(t))return r;return null};var de=t=>{let e=E(t),r=e.message.toUpperCase(),n=t instanceof p?t.isHardwareError:z(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),o=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),l=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",g=e.code==="DISCOVERY_FAILED",c="UNKNOWN";return n?c="HARDWARE":i?c="BUSY":o?c="TIMEOUT":l?c="CONNECTION":g?c="DISCOVERY":e.code==="PRINT_FAILED"&&(c="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:c,isHardwareError:n,retryable:i||o,shouldPauseQueue:n,raw:t}},Le=t=>de(t);var me=Pe(require("react")),R=require("react");var ge=(0,R.createContext)(void 0),Ue=({config:t,logger:e,children:r})=>{let[n,i]=(0,R.useState)();(0,R.useEffect)(()=>{e&&B(e)},[e]);let o=(0,R.useMemo)(()=>{let g={...t,logger:e??t.logger};return K(g)},[t.lang,t.model,t.target,e]),l=(0,R.useMemo)(()=>({printer:o,config:t,isReady:!0,error:n}),[o,t,n]);return me.default.createElement(ge.Provider,{value:l},r)},k=()=>{let t=(0,R.useContext)(ge);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};var f=require("react");function Fe(t={}){let{enabled:e=!0}=t,{printer:r,config:n}=k(),[i,o]=(0,f.useState)("DISCONNECTED"),[l,g]=(0,f.useState)(null),[c,N]=(0,f.useState)(null),X=(0,f.useRef)("DISCONNECTED"),$=(0,f.useRef)(null),d=c!==null,I=(0,f.useCallback)(C=>{$.current=C,N(C)},[]),_=(0,f.useCallback)(C=>{if(C instanceof Error&&C.message){I(C.message);return}if(typeof C=="string"&&C.length>0){I(C);return}I("Unknown printer error")},[I]),a=(0,f.useCallback)(()=>{$.current!==null&&I(null)},[I]);return(0,f.useEffect)(()=>r.onConnectionChange(O=>{X.current=O,o(O),O==="CONNECTED"&&a()}),[a,r]),(0,f.useEffect)(()=>e?r.onStatusChange(O=>{g(O),a()}):void 0,[a,e,r]),(0,f.useEffect)(()=>{e&&i==="CONNECTED"&&r.getStatus().then(C=>{g(C),a()}).catch(_)},[_,a,i,e,r]),(0,f.useEffect)(()=>{let C=X.current;if(e){C==="DISCONNECTED"&&i==="DISCONNECTED"&&r.connect(n.target,5e3).then(a).catch(_);return}(i==="CONNECTED"||i==="CONNECTING")&&r.disconnect().then(a).catch(_)},[_,a,n.target,i,e,r]),{connectionStatus:i,hardwareStatus:l,isError:d,errorMessage:c}}var Te="1.0.4";function K(t){return new F({...t,logger:t.logger??Y()})}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 q={},z=t=>{q.logger=t},G=()=>q.logger;import{Platform as j}from"react-native
|
|
|
8
8
|
`,align:"center",bold:!0})}else i==="B"?e.push({type:"text",text:g+`
|
|
9
9
|
`,bold:!0}):i==="R"?e.push({type:"text",text:g+`
|
|
10
10
|
`,bold:!0}):e.push({type:"text",text:g+`
|
|
11
|
-
`,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var v=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 o=await e();r(o)}catch(o){n(o)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var D=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 M=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!m)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=m.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!m||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await m.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var w=class{constructor(e){this.config=e}statusCallbacks=new Set;latestHardwareStatus=null;statusRefreshPromise=null;statusRefreshTimer=null;subscribe(e){return this.statusCallbacks.add(e),this.latestHardwareStatus?e(this.latestHardwareStatus):this.config.getConnectionStatus()!=="CONNECTED"?e(this.config.defaultStatus):this.refreshNow(),()=>{this.statusCallbacks.delete(e)}}handleStatusEvent(){this.scheduleRefresh()}handleConnected(){this.scheduleRefresh(0)}handleDisconnected(){this.clearRefreshTimer(),this.setHardwareStatus(this.config.defaultStatus)}clear(){this.clearRefreshTimer()}async refreshNow(){if(this.config.getConnectionStatus()!=="CONNECTED"){this.setHardwareStatus(this.config.defaultStatus);return}if(this.statusRefreshPromise){await this.statusRefreshPromise;return}this.statusRefreshPromise=(async()=>{try{let e=await this.config.getStatus();this.setHardwareStatus(e)}catch(e){this.config.logger?.error("[EpsonPrinter] Status refresh failed",e),this.latestHardwareStatus||this.setHardwareStatus(this.config.defaultStatus)}})().finally(()=>{this.statusRefreshPromise=null}),await this.statusRefreshPromise}emitHardwareStatus(e){for(let r of this.statusCallbacks)r(e)}setHardwareStatus(e){this.latestHardwareStatus=e,this.emitHardwareStatus(e)}clearRefreshTimer(){this.statusRefreshTimer&&(clearTimeout(this.statusRefreshTimer),this.statusRefreshTimer=null)}scheduleRefresh(e=150){this.config.getConnectionStatus()==="CONNECTED"&&(this.statusRefreshTimer||(this.statusRefreshTimer=setTimeout(()=>{this.statusRefreshTimer=null,this.refreshNow()},e)))}};var F={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},Ee=5e3,b=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;statusController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new M(this.logger),this.queueController=new v(this.logger),this.recoveryController=new D({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.statusController=new w({logger:this.logger,defaultStatus:F,getConnectionStatus:()=>this.connectionStatus,getStatus:()=>this.getStatus()}),this.eventRouter=new y({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onEvent:r=>{r.statusEventType!==null&&(this.statusController.handleStatusEvent(),r.isRecoveryEvent&&this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())),r.connectionStatus!==null&&(r.connectionStatus==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r.connectionStatus==="CONNECTED"&&this.statusController.handleConnected(),r.connectionStatus==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected()))}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}isIosConnectionRecoveryCandidate(e){return j.OS!=="ios"?!1:e.code==="CONNECTION_FAILED"||e.code==="TIMEOUT"&&e.translationCode==="printer.error.connection_timeout"||e.translationCode==="printer.error.offline"}hasTargetInUseToken(e){if(!e||typeof e!="object")return!1;let r=String(e.code??"").toUpperCase(),n=String(e.message??"").toUpperCase();return r.includes("TARGET_IN_USE")||n.includes("TARGET_IN_USE")}isIosConnectBusyRecoveryCandidate(e){return j.OS!=="ios"||e.translationCode!=="printer.error.busy"?!1:!this.hasTargetInUseToken(e.originalError)}async recoverIosSessionForPrint(){if(!m)throw new Error("Native module not found");let e=this.target??this.defaultTarget;if(!e)throw new Error("Printer target is required");let r=this.sessionManager.getSessionId();if(r)try{await m.disconnect(r)}catch(i){this.logger?.error("[EpsonPrinter] iOS recovery disconnect failed (best-effort)",i)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let n=await this.sessionManager.ensureSession();return await N(()=>m.connect(n,e,Ee,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected(),n}async recoverIosSessionForConnect(e,r){if(!m)throw new Error("Native module not found");let n=this.sessionManager.getSessionId();if(n)try{await m.disconnect(n)}catch(o){this.logger?.error("[EpsonPrinter] iOS connect recovery disconnect failed (best-effort)",o)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let i=await this.sessionManager.ensureSession();await N(()=>m.connect(i,e,r,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}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(!m){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");let o=!1;try{await N(()=>m.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(),this.statusController.handleConnected()}catch(l){let g=C(l);if(!o&&this.isIosConnectBusyRecoveryCandidate(g)){o=!0,this.logger?.error("[EpsonPrinter] iOS busy connect suspected stale session. Recovering connection and retrying connect once...",g);try{await this.recoverIosSessionForConnect(n,r),this.logger?.info?.("[EpsonPrinter] iOS connect recovery succeeded."),this.isConnecting=!1;return}catch(c){let p=C(c);throw this.logger?.error("[EpsonPrinter] iOS connect recovery failed",p),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,p}}throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,g),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,g}})}async print(e){if(!m)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0,n=!1;return this.queueController.enqueue(async()=>{let i=await this.sessionManager.ensureSession(),o=$(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await N(()=>m.print(i,o));break}catch(l){let g=K(l);if(!n&&this.isIosConnectionRecoveryCandidate(g)){n=!0,this.logger?.error("[EpsonPrinter] iOS stale session suspected. Recovering connection and retrying print once...",g);try{i=await this.recoverIosSessionForPrint(),this.logger?.info?.("[EpsonPrinter] iOS session recovery succeeded. Retrying print...");continue}catch(c){let p=C(c);throw this.logger?.error("[EpsonPrinter] iOS session recovery failed",p),p}}if(g.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,g),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await m.print(i,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,g),g}}}).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(m&&this.connectionStatus==="CONNECTED"&&e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),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=J(e);return await this.print(r)}catch(r){let n=C(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(!m)return;let e=this.sessionManager.getSessionId();if(e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{this.statusController.clear(),await this.sessionManager.disposeSession()}})}async getStatus(){if(!m)return F;let e=this.sessionManager.getSessionId();if(!e)return F;try{return await m.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),C(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}onStatusChange(e){return this.statusController.subscribe(e)}};import{NativeModules as Re}from"react-native";var Z=Re.MunchiEpsonModule,pe={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},Pe=t=>t.includes("[local_"),Ne=(t,e)=>e?pe[e].some(n=>t.startsWith(n)):!0,Ie=async t=>{if(!Z)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await Z.discover({timeout:t.timeout})).map(X).filter(r=>!r||Pe(r.target)?!1:Ne(r.target,t.connectionType))}catch(e){let r=C(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};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]],_e=t=>{for(let[e,r]of Se)if(e.test(t))return r;return null};var Oe=t=>{let e=C(t),r=e.message.toUpperCase(),n=t instanceof R?t.isHardwareError:A(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),o=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),l=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",g=e.code==="DISCOVERY_FAILED",c="UNKNOWN";return n?c="HARDWARE":i?c="BUSY":o?c="TIMEOUT":l?c="CONNECTION":g?c="DISCOVERY":e.code==="PRINT_FAILED"&&(c="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:c,isHardwareError:n,retryable:i||o,shouldPauseQueue:n,raw:t}},Ot=t=>Oe(t);import ye from"react";import{createContext as ve,useContext as De,useEffect as Me,useMemo as ee,useState as we}from"react";var te=ve(void 0),bt=({config:t,logger:e,children:r})=>{let[n,i]=we();Me(()=>{e&&z(e)},[e]);let o=ee(()=>{let g={...t,logger:e??t.logger};return ne(g)},[t.lang,t.model,t.target,e]),l=ee(()=>({printer:o,config:t,isReady:!0,error:n}),[o,t,n]);return ye.createElement(te.Provider,{value:l},r)},re=()=>{let t=De(te);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};import{useCallback as B,useEffect as x,useRef as ie,useState as Y}from"react";function Ut(t={}){let{enabled:e=!0}=t,{printer:r,config:n}=re(),[i,o]=Y("DISCONNECTED"),[l,g]=Y(null),[c,p]=Y(null),H=ie("DISCONNECTED"),V=ie(null),d=c!==null,P=B(f=>{V.current=f,p(f)},[]),I=B(f=>{if(f instanceof Error&&f.message){P(f.message);return}if(typeof f=="string"&&f.length>0){P(f);return}P("Unknown printer error")},[P]),a=B(()=>{V.current!==null&&P(null)},[P]);return x(()=>r.onConnectionChange(S=>{H.current=S,o(S),S==="CONNECTED"&&a()}),[a,r]),x(()=>e?r.onStatusChange(S=>{g(S),a()}):void 0,[a,e,r]),x(()=>{e&&i==="CONNECTED"&&r.getStatus().then(f=>{g(f),a()}).catch(I)},[I,a,i,e,r]),x(()=>{let f=H.current;if(e){f==="DISCONNECTED"&&i==="DISCONNECTED"&&r.connect(n.target,5e3).then(a).catch(I);return}(i==="CONNECTED"||i==="CONNECTING")&&r.disconnect().then(a).catch(I)},[I,a,n.target,i,e,r]),{connectionStatus:i,hardwareStatus:l,isError:d,errorMessage:c}}var be="1.0.3";function ne(t){return new b({...t,logger:t.logger??G()})}export{ce as Epos2CallbackCode,ae as Epos2ConnectionEvent,ue as Epos2ErrorStatus,le as Epos2Font,W as Epos2Lang,Q as Epos2StatusEvent,k as EpsonModel,U as FontSize,h as MunchiPrinterError,R as PrinterError,_ as PrinterErrorCode,bt as PrinterProvider,O as PrinterTranslationCode,be as VERSION,Ie as discoverPrinters,G as getGlobalLogger,ne as getPrinter,Ot as resolveEpsonError,_e as resolveModelFromBluetoothName,Oe as resolvePrinterError,z as setGlobalLogger,re as usePrinter,Ut as usePrinterStatus};
|
|
11
|
+
`,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var v=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 o=await e();r(o)}catch(o){n(o)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var D=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 M=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!m)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=m.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!m||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await m.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var w=class{constructor(e){this.config=e}statusCallbacks=new Set;latestHardwareStatus=null;statusRefreshPromise=null;statusRefreshTimer=null;subscribe(e){return this.statusCallbacks.add(e),this.latestHardwareStatus?e(this.latestHardwareStatus):this.config.getConnectionStatus()!=="CONNECTED"?e(this.config.defaultStatus):this.refreshNow(),()=>{this.statusCallbacks.delete(e)}}handleStatusEvent(){this.scheduleRefresh()}handleConnected(){this.scheduleRefresh(0)}handleDisconnected(){this.clearRefreshTimer(),this.setHardwareStatus(this.config.defaultStatus)}clear(){this.clearRefreshTimer()}async refreshNow(){if(this.config.getConnectionStatus()!=="CONNECTED"){this.setHardwareStatus(this.config.defaultStatus);return}if(this.statusRefreshPromise){await this.statusRefreshPromise;return}this.statusRefreshPromise=(async()=>{try{let e=await this.config.getStatus();this.setHardwareStatus(e)}catch(e){this.config.logger?.error("[EpsonPrinter] Status refresh failed",e),this.latestHardwareStatus||this.setHardwareStatus(this.config.defaultStatus)}})().finally(()=>{this.statusRefreshPromise=null}),await this.statusRefreshPromise}emitHardwareStatus(e){for(let r of this.statusCallbacks)r(e)}setHardwareStatus(e){this.latestHardwareStatus=e,this.emitHardwareStatus(e)}clearRefreshTimer(){this.statusRefreshTimer&&(clearTimeout(this.statusRefreshTimer),this.statusRefreshTimer=null)}scheduleRefresh(e=150){this.config.getConnectionStatus()==="CONNECTED"&&(this.statusRefreshTimer||(this.statusRefreshTimer=setTimeout(()=>{this.statusRefreshTimer=null,this.refreshNow()},e)))}};var F={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},Ee=5e3,b=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;statusController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new M(this.logger),this.queueController=new v(this.logger),this.recoveryController=new D({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.statusController=new w({logger:this.logger,defaultStatus:F,getConnectionStatus:()=>this.connectionStatus,getStatus:()=>this.getStatus()}),this.eventRouter=new y({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onEvent:r=>{r.statusEventType!==null&&(this.statusController.handleStatusEvent(),r.isRecoveryEvent&&this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())),r.connectionStatus!==null&&(r.connectionStatus==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r.connectionStatus==="CONNECTED"&&this.statusController.handleConnected(),r.connectionStatus==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected()))}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}isIosConnectionRecoveryCandidate(e){return j.OS!=="ios"?!1:e.code==="CONNECTION_FAILED"||e.code==="TIMEOUT"&&e.translationCode==="printer.error.connection_timeout"||e.translationCode==="printer.error.offline"}hasTargetInUseToken(e){if(!e||typeof e!="object")return!1;let r=String(e.code??"").toUpperCase(),n=String(e.message??"").toUpperCase();return r.includes("TARGET_IN_USE")||n.includes("TARGET_IN_USE")}isIosConnectBusyRecoveryCandidate(e){return j.OS!=="ios"||e.translationCode!=="printer.error.busy"?!1:!this.hasTargetInUseToken(e.originalError)}async recoverIosSessionForPrint(){if(!m)throw new Error("Native module not found");let e=this.target??this.defaultTarget;if(!e)throw new Error("Printer target is required");let r=this.sessionManager.getSessionId();if(r)try{await m.disconnect(r)}catch(i){this.logger?.error("[EpsonPrinter] iOS recovery disconnect failed (best-effort)",i)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let n=await this.sessionManager.ensureSession();return await N(()=>m.connect(n,e,Ee,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected(),n}async recoverIosSessionForConnect(e,r){if(!m)throw new Error("Native module not found");let n=this.sessionManager.getSessionId();if(n)try{await m.disconnect(n)}catch(o){this.logger?.error("[EpsonPrinter] iOS connect recovery disconnect failed (best-effort)",o)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let i=await this.sessionManager.ensureSession();await N(()=>m.connect(i,e,r,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}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(!m){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");let o=!1;try{await N(()=>m.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(),this.statusController.handleConnected()}catch(l){let g=C(l);if(!o&&this.isIosConnectBusyRecoveryCandidate(g)){o=!0,this.logger?.error("[EpsonPrinter] iOS busy connect suspected stale session. Recovering connection and retrying connect once...",g);try{await this.recoverIosSessionForConnect(n,r),this.logger?.info?.("[EpsonPrinter] iOS connect recovery succeeded."),this.isConnecting=!1;return}catch(c){let p=C(c);throw this.logger?.error("[EpsonPrinter] iOS connect recovery failed",p),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,p}}throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,g),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,g}})}async print(e){if(!m)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0,n=!1;return this.queueController.enqueue(async()=>{let i=await this.sessionManager.ensureSession(),o=$(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await N(()=>m.print(i,o));break}catch(l){let g=K(l);if(!n&&this.isIosConnectionRecoveryCandidate(g)){n=!0,this.logger?.error("[EpsonPrinter] iOS stale session suspected. Recovering connection and retrying print once...",g);try{i=await this.recoverIosSessionForPrint(),this.logger?.info?.("[EpsonPrinter] iOS session recovery succeeded. Retrying print...");continue}catch(c){let p=C(c);throw this.logger?.error("[EpsonPrinter] iOS session recovery failed",p),p}}if(g.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,g),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await m.print(i,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,g),g}}}).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(m&&this.connectionStatus==="CONNECTED"&&e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),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=J(e);return await this.print(r)}catch(r){let n=C(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(!m)return;let e=this.sessionManager.getSessionId();if(e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{this.statusController.clear(),await this.sessionManager.disposeSession()}})}async getStatus(){if(!m)return F;let e=this.sessionManager.getSessionId();if(!e)return F;try{return await m.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),C(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}onStatusChange(e){return this.statusController.subscribe(e)}};import{NativeModules as Re}from"react-native";var Z=Re.MunchiEpsonModule,pe={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},Pe=t=>t.includes("[local_"),Ne=(t,e)=>e?pe[e].some(n=>t.startsWith(n)):!0,Ie=async t=>{if(!Z)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await Z.discover({timeout:t.timeout})).map(X).filter(r=>!r||Pe(r.target)?!1:Ne(r.target,t.connectionType))}catch(e){let r=C(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};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]],_e=t=>{for(let[e,r]of Se)if(e.test(t))return r;return null};var Oe=t=>{let e=C(t),r=e.message.toUpperCase(),n=t instanceof R?t.isHardwareError:A(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),o=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),l=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",g=e.code==="DISCOVERY_FAILED",c="UNKNOWN";return n?c="HARDWARE":i?c="BUSY":o?c="TIMEOUT":l?c="CONNECTION":g?c="DISCOVERY":e.code==="PRINT_FAILED"&&(c="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:c,isHardwareError:n,retryable:i||o,shouldPauseQueue:n,raw:t}},Ot=t=>Oe(t);import ye from"react";import{createContext as ve,useContext as De,useEffect as Me,useMemo as ee,useState as we}from"react";var te=ve(void 0),bt=({config:t,logger:e,children:r})=>{let[n,i]=we();Me(()=>{e&&z(e)},[e]);let o=ee(()=>{let g={...t,logger:e??t.logger};return ne(g)},[t.lang,t.model,t.target,e]),l=ee(()=>({printer:o,config:t,isReady:!0,error:n}),[o,t,n]);return ye.createElement(te.Provider,{value:l},r)},re=()=>{let t=De(te);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};import{useCallback as B,useEffect as x,useRef as ie,useState as Y}from"react";function Ut(t={}){let{enabled:e=!0}=t,{printer:r,config:n}=re(),[i,o]=Y("DISCONNECTED"),[l,g]=Y(null),[c,p]=Y(null),H=ie("DISCONNECTED"),V=ie(null),d=c!==null,P=B(f=>{V.current=f,p(f)},[]),I=B(f=>{if(f instanceof Error&&f.message){P(f.message);return}if(typeof f=="string"&&f.length>0){P(f);return}P("Unknown printer error")},[P]),a=B(()=>{V.current!==null&&P(null)},[P]);return x(()=>r.onConnectionChange(S=>{H.current=S,o(S),S==="CONNECTED"&&a()}),[a,r]),x(()=>e?r.onStatusChange(S=>{g(S),a()}):void 0,[a,e,r]),x(()=>{e&&i==="CONNECTED"&&r.getStatus().then(f=>{g(f),a()}).catch(I)},[I,a,i,e,r]),x(()=>{let f=H.current;if(e){f==="DISCONNECTED"&&i==="DISCONNECTED"&&r.connect(n.target,5e3).then(a).catch(I);return}(i==="CONNECTED"||i==="CONNECTING")&&r.disconnect().then(a).catch(I)},[I,a,n.target,i,e,r]),{connectionStatus:i,hardwareStatus:l,isError:d,errorMessage:c}}var be="1.0.4";function ne(t){return new b({...t,logger:t.logger??G()})}export{ce as Epos2CallbackCode,ae as Epos2ConnectionEvent,ue as Epos2ErrorStatus,le as Epos2Font,W as Epos2Lang,Q as Epos2StatusEvent,k as EpsonModel,U as FontSize,h as MunchiPrinterError,R as PrinterError,_ as PrinterErrorCode,bt as PrinterProvider,O as PrinterTranslationCode,be as VERSION,Ie as discoverPrinters,G as getGlobalLogger,ne as getPrinter,Ot as resolveEpsonError,_e as resolveModelFromBluetoothName,Oe as resolvePrinterError,z as setGlobalLogger,re as usePrinter,Ut 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.4";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|