@munchi_oy/react-native-epson-printer 1.0.2 → 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 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
- - Epson print queueing and hardware-recovery retries
11
- - Receipt printing with generic `PrintJob` commands and embedded payload support
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
- ## Installation
33
+ ## Behavior Support (implemented)
16
34
 
17
- ```bash
18
- npm install @munchi_oy/react-native-epson-printer
19
- # or
20
- pnpm add @munchi_oy/react-native-epson-printer
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. Add the package.
26
- 2. Run CocoaPods install in your iOS project:
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. Ensure Bluetooth/network permissions are configured in `Info.plist` for your transport mode.
94
+ 3. Configure `Info.plist` permissions based on your connection method (Bluetooth/TCP).
33
95
 
34
96
  ## Android Setup
35
97
 
36
- 1. Add the package and sync Gradle.
37
- 2. Ensure runtime permissions are requested in your app before discovery/connection:
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: location permission for Bluetooth discovery (`ACCESS_FINE_LOCATION`)
40
- 3. Rebuild the Android app after installation.
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 (for `connect()` without args) |
71
- | `lang` | `Epos2Lang` | No | Language enum used by native printer object |
72
- | `logger` | `PrinterLogger` | No | SDK logger hook (`error`, optional `info`) |
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({ timeout: 5000, connectionType: 'bluetooth' });
143
+ const printers = await discoverPrinters({
144
+ timeout: 5000,
145
+ connectionType: 'bluetooth',
146
+ });
82
147
  ```
83
148
 
84
- `discoverPrinters` filters out Epson sub-device targets like `[local_display]`.
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
- Examples:
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 unsubscribe = printer.onConnectionChange((status) => {
99
- console.log('status', status);
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 Payload
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 Drawer
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 inject logger per instance or set a global logger.
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
- ## What We Support
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
- ### Vendor Support
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
- ### Connection Types
176
-
177
- - Bluetooth (`BT:`)
178
- - TCP (`TCP:`, `TCPS:`)
179
- - USB (`USB:`)
238
+ ## Known Limitations
180
239
 
181
- ## Known Issues
182
-
183
- - If printer hardware state is bad (cover open/paper out), jobs pause until recovery is detected.
184
- - Discovery quality depends on OS radio/network state and Epson SDK behavior.
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 in `connect(target)`.
252
+ - Pass `target` in config or `connect(target)`.
202
253
 
203
- 3. Frequent busy/connect retries
204
- - Ensure only one active session per target and stable transport.
254
+ 3. `TARGET_IN_USE`
255
+ - Another active session is using the same target. Disconnect old owner first.
205
256
 
206
- ## Migration Guide (Breaking Changes)
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
- If you are upgrading from older versions:
260
+ ## Migration Notes (already shipped)
209
261
 
210
- 1. Epson-only
211
- - Removed `PrinterType`, Star/Sunmi drivers, and adapter-style vendor factory.
262
+ If upgrading from older adapter-based versions:
212
263
 
213
- 2. Config changes
214
- - `model` is now required in `getPrinter({ ... })`.
264
+ 1. Epson-only scope
265
+ - Removed Star/Sunmi and `PrinterType` factory behavior.
215
266
 
216
- 3. Connect signature changes
217
- - Before: `connect(target, timeout, model, lang)`
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
- 4. Paths and exports
222
- - Epson internals moved from `src/vendors/epson/*` to `src/epson/*`.
223
- - Public imports remain from `@munchi_oy/react-native-epson-printer`.
270
+ 3. Connect signature
271
+ - Before: `connect(target, timeout, model, lang)`
272
+ - Now: `connect(target?, timeout?)` (model/lang come from instance config).
@@ -169,6 +169,7 @@ public class MunchiEpsonModule extends ReactContextBaseJavaModule implements Con
169
169
  int safeLang = normalizeLanguage((int) lang);
170
170
 
171
171
  EpsonSession session;
172
+ EpsonSession ownerSessionToReclaim = null;
172
173
  CachedConnection cachedConnection;
173
174
  synchronized (lock) {
174
175
  session = sessions.get(sessionId);
@@ -179,11 +180,22 @@ public class MunchiEpsonModule extends ReactContextBaseJavaModule implements Con
179
180
 
180
181
  String ownerSessionId = targetToSessionId.get(target);
181
182
  if (ownerSessionId != null && !ownerSessionId.equals(sessionId)) {
182
- promise.reject("TARGET_IN_USE", "Target is already connected by another session: " + target);
183
- return;
183
+ EpsonSession ownerSession = sessions.get(ownerSessionId);
184
+ if (ownerSession == null) {
185
+ targetToSessionId.remove(target);
186
+ } else if (ownerSession.printPromise != null) {
187
+ promise.reject("TARGET_IN_USE", "Target is busy with an active print job: " + target);
188
+ return;
189
+ } else {
190
+ ownerSessionToReclaim = ownerSession;
191
+ }
184
192
  }
185
193
  }
186
194
 
195
+ if (ownerSessionToReclaim != null) {
196
+ teardownPrinter(ownerSessionToReclaim, true);
197
+ }
198
+
187
199
  if (!ensureBluetoothOperationReadiness(target, promise)) {
188
200
  return;
189
201
  }
@@ -235,15 +247,10 @@ public class MunchiEpsonModule extends ReactContextBaseJavaModule implements Con
235
247
  printer.setStatusChangeEventListener(this);
236
248
  printer.setReceiveEventListener(this);
237
249
  printer.connect(target, (int) timeout);
250
+ printer.startMonitor();
238
251
  } catch (Exception error) {
239
252
  if (printer != null) {
240
- try {
241
- printer.setReceiveEventListener(null);
242
- printer.setConnectionEventListener(null);
243
- printer.setStatusChangeEventListener(null);
244
- printer.disconnect();
245
- } catch (Exception ignored) {
246
- }
253
+ disconnectPrinterQuietly(printer);
247
254
  }
248
255
  rejectWithEposError(promise, "CONNECT_ERROR", "Failed to connect", error);
249
256
  return;
@@ -252,10 +259,7 @@ public class MunchiEpsonModule extends ReactContextBaseJavaModule implements Con
252
259
  synchronized (lock) {
253
260
  EpsonSession latestSession = sessions.get(sessionId);
254
261
  if (latestSession == null) {
255
- try {
256
- printer.disconnect();
257
- } catch (Exception ignored) {
258
- }
262
+ disconnectPrinterQuietly(printer);
259
263
  promise.reject("SESSION_ERROR", "Session disposed while connecting");
260
264
  return;
261
265
  }
@@ -703,6 +707,7 @@ public class MunchiEpsonModule extends ReactContextBaseJavaModule implements Con
703
707
  printer.setReceiveEventListener(null);
704
708
  printer.setConnectionEventListener(null);
705
709
  printer.setStatusChangeEventListener(null);
710
+ printer.stopMonitor();
706
711
  printer.disconnect();
707
712
  } catch (Exception ignored) {
708
713
  }
@@ -1,4 +1,4 @@
1
- import { MunchiPrinter } from '../types';
1
+ import type { MunchiPrinter } from '../types';
2
2
  export type ConnectionType = 'bluetooth' | 'tcp' | 'usb';
3
3
  export interface DiscoveryParams {
4
4
  timeout?: number;
@@ -1 +1 @@
1
- {"version":3,"file":"discovery.d.ts","sourceRoot":"","sources":["../../src/epson/discovery.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAUzC,MAAM,MAAM,cAAc,GAAG,WAAW,GAAG,KAAK,GAAG,KAAK,CAAC;AAEzD,MAAM,WAAW,eAAe;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,cAAc,CAAC;CACnC;AAiBD;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,GAAU,QAAQ,eAAe,KAAG,OAAO,CAAC,aAAa,EAAE,CAoBvF,CAAC"}
1
+ {"version":3,"file":"discovery.d.ts","sourceRoot":"","sources":["../../src/epson/discovery.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAU9C,MAAM,MAAM,cAAc,GAAG,WAAW,GAAG,KAAK,GAAG,KAAK,CAAC;AAEzD,MAAM,WAAW,eAAe;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,cAAc,CAAC;CACnC;AAiBD;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,GAAU,QAAQ,eAAe,KAAG,OAAO,CAAC,aAAa,EAAE,CAoBvF,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import type { EpsonPrinterConfig, MunchiEmbeddedPayload, PrinterConnectionStatus, PrinterStatus, PrintJob } from '../types';
2
+ import { type StatusChangeCallback } from './statusController';
2
3
  export declare class EpsonPrinter {
3
4
  private disconnectTimer;
4
5
  private connectionStatus;
@@ -11,9 +12,15 @@ export declare class EpsonPrinter {
11
12
  private readonly sessionManager;
12
13
  private readonly queueController;
13
14
  private readonly recoveryController;
15
+ private readonly statusController;
14
16
  private readonly eventRouter;
15
17
  constructor(config: EpsonPrinterConfig);
16
18
  private resumeQueue;
19
+ private isIosConnectionRecoveryCandidate;
20
+ private hasTargetInUseToken;
21
+ private isIosConnectBusyRecoveryCandidate;
22
+ private recoverIosSessionForPrint;
23
+ private recoverIosSessionForConnect;
17
24
  connect(target?: string, timeout?: number): Promise<void>;
18
25
  print(job: PrintJob): Promise<void>;
19
26
  private performDisconnect;
@@ -22,5 +29,6 @@ export declare class EpsonPrinter {
22
29
  getStatus(): Promise<PrinterStatus>;
23
30
  openDrawer(): Promise<void>;
24
31
  onConnectionChange(callback: (status: PrinterConnectionStatus) => void): () => void;
32
+ onStatusChange(callback: StatusChangeCallback): () => void;
25
33
  }
26
34
  //# sourceMappingURL=driver.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"driver.d.ts","sourceRoot":"","sources":["../../src/epson/driver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,uBAAuB,EAAiB,aAAa,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAqB3I,qBAAa,YAAY;IACvB,OAAO,CAAC,eAAe,CAA+B;IACtD,OAAO,CAAC,gBAAgB,CAA2C;IACnE,OAAO,CAAC,YAAY,CAAkB;IACtC,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAgB;IAC9C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAa;IACnC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAY;IACjC,OAAO,CAAC,MAAM,CAAC,CAAgB;IAC/B,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAsB;IACrD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAuB;IACvD,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAA0B;IAC7D,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAmB;gBAEnC,MAAM,EAAE,kBAAkB;IA+BtC,OAAO,CAAC,WAAW;IAQb,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,GAAE,MAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IA+C/D,KAAK,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAiDzC,OAAO,CAAC,iBAAiB;IAoBnB,aAAa,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC;IAa5D,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IA2B3B,SAAS,IAAI,OAAO,CAAC,aAAa,CAAC;IAkBnC,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAKjC,kBAAkB,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,uBAAuB,KAAK,IAAI,GAAG,MAAM,IAAI;CAGpF"}
1
+ {"version":3,"file":"driver.d.ts","sourceRoot":"","sources":["../../src/epson/driver.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,uBAAuB,EAAiB,aAAa,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAW3I,OAAO,EAAyB,KAAK,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAYtF,qBAAa,YAAY;IACvB,OAAO,CAAC,eAAe,CAA+B;IACtD,OAAO,CAAC,gBAAgB,CAA2C;IACnE,OAAO,CAAC,YAAY,CAAkB;IACtC,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAgB;IAC9C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAa;IACnC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAY;IACjC,OAAO,CAAC,MAAM,CAAC,CAAgB;IAC/B,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAsB;IACrD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAuB;IACvD,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAA0B;IAC7D,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAwB;IACzD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAmB;gBAEnC,MAAM,EAAE,kBAAkB;IA+CtC,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,gCAAgC;IASxC,OAAO,CAAC,mBAAmB;IAU3B,OAAO,CAAC,iCAAiC;YAM3B,yBAAyB;YAqCzB,2BAA2B;IA8BnC,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,GAAE,MAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAuE/D,KAAK,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAiEzC,OAAO,CAAC,iBAAiB;IAqBnB,aAAa,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC;IAa5D,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IA6B3B,SAAS,IAAI,OAAO,CAAC,aAAa,CAAC;IAkBnC,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAKjC,kBAAkB,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,uBAAuB,KAAK,IAAI,GAAG,MAAM,IAAI;IAInF,cAAc,CAAC,QAAQ,EAAE,oBAAoB,GAAG,MAAM,IAAI;CAG3D"}
@@ -1,4 +1,4 @@
1
- import { MunchiPrinterError, PrinterErrorCode, PrinterTranslationCode } from '../errors';
1
+ import { MunchiPrinterError, type PrinterErrorCode, type PrinterTranslationCode } from '../errors';
2
2
  export declare class PrinterError extends MunchiPrinterError {
3
3
  readonly isHardwareError: boolean;
4
4
  constructor(isHardwareError: boolean, code: PrinterErrorCode, translationCode: PrinterTranslationCode, message: string, originalError?: unknown);
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/epson/errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AAGzF,qBAAa,YAAa,SAAQ,kBAAkB;aAE5B,eAAe,EAAE,OAAO;gBAAxB,eAAe,EAAE,OAAO,EACxC,IAAI,EAAE,gBAAgB,EACtB,eAAe,EAAE,sBAAsB,EACvC,OAAO,EAAE,MAAM,EACf,aAAa,CAAC,EAAE,OAAO;CAO9B;AAED,eAAO,MAAM,eAAe,GAAI,OAAO,GAAG,KAAG,OAwB5C,CAAC;AAEF,eAAO,MAAM,kBAAkB,GAAI,OAAO,GAAG,KAAG,YAiB/C,CAAC"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/epson/errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,KAAK,gBAAgB,EAAE,KAAK,sBAAsB,EAAE,MAAM,WAAW,CAAC;AAGnG,qBAAa,YAAa,SAAQ,kBAAkB;aAE5B,eAAe,EAAE,OAAO;gBAAxB,eAAe,EAAE,OAAO,EACxC,IAAI,EAAE,gBAAgB,EACtB,eAAe,EAAE,sBAAsB,EACvC,OAAO,EAAE,MAAM,EACf,aAAa,CAAC,EAAE,OAAO;CAO9B;AAED,eAAO,MAAM,eAAe,GAAI,OAAO,GAAG,KAAG,OAwB5C,CAAC;AAEF,eAAO,MAAM,kBAAkB,GAAI,OAAO,GAAG,KAAG,YAiB/C,CAAC"}
@@ -1,11 +1,15 @@
1
1
  import type { PrinterConnectionStatus, PrinterLogger } from '../types';
2
2
  import { Epos2StatusEvent } from './constants';
3
+ export interface EpsonRouterEvent {
4
+ connectionStatus: PrinterConnectionStatus | null;
5
+ statusEventType: Epos2StatusEvent | null;
6
+ isRecoveryEvent: boolean;
7
+ }
3
8
  interface EpsonEventRouterConfig {
4
9
  logger?: PrinterLogger;
5
10
  getSessionId: () => string | null;
6
11
  getConnectionStatus: () => PrinterConnectionStatus;
7
- onRecoveryEvent: (eventType: Epos2StatusEvent) => void;
8
- onConnectionEvent: (status: PrinterConnectionStatus) => void;
12
+ onEvent: (event: EpsonRouterEvent) => void;
9
13
  }
10
14
  export declare class EpsonEventRouter {
11
15
  private config;
@@ -1 +1 @@
1
- {"version":3,"file":"eventRouter.d.ts","sourceRoot":"","sources":["../../src/epson/eventRouter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAU/C,UAAU,sBAAsB;IAC9B,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,YAAY,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IAClC,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;IACnD,eAAe,EAAE,CAAC,SAAS,EAAE,gBAAgB,KAAK,IAAI,CAAC;IACvD,iBAAiB,EAAE,CAAC,MAAM,EAAE,uBAAuB,KAAK,IAAI,CAAC;CAC9D;AAED,qBAAa,gBAAgB;IAKf,OAAO,CAAC,MAAM;IAJ1B,OAAO,CAAC,kBAAkB,CAAuC;IACjE,OAAO,CAAC,sBAAsB,CAAuC;IACrE,OAAO,CAAC,mBAAmB,CAA6D;gBAEpE,MAAM,EAAE,sBAAsB;IAElD,UAAU,CAAC,MAAM,EAAE,uBAAuB,GAAG,IAAI;IAMjD,oBAAoB,IAAI,IAAI;IAoB5B,wBAAwB,IAAI,IAAI;IAyBhC,oBAAoB,IAAI,IAAI;IAM5B,kBAAkB,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,uBAAuB,KAAK,IAAI,GAAG,MAAM,IAAI;CAcpF"}
1
+ {"version":3,"file":"eventRouter.d.ts","sourceRoot":"","sources":["../../src/epson/eventRouter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAU/C,MAAM,WAAW,gBAAgB;IAC/B,gBAAgB,EAAE,uBAAuB,GAAG,IAAI,CAAC;IACjD,eAAe,EAAE,gBAAgB,GAAG,IAAI,CAAC;IACzC,eAAe,EAAE,OAAO,CAAC;CAC1B;AAED,UAAU,sBAAsB;IAC9B,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,YAAY,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IAClC,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;IACnD,OAAO,EAAE,CAAC,KAAK,EAAE,gBAAgB,KAAK,IAAI,CAAC;CAC5C;AAED,qBAAa,gBAAgB;IAKf,OAAO,CAAC,MAAM;IAJ1B,OAAO,CAAC,kBAAkB,CAAuC;IACjE,OAAO,CAAC,sBAAsB,CAAuC;IACrE,OAAO,CAAC,mBAAmB,CAA6D;gBAEpE,MAAM,EAAE,sBAAsB;IAElD,UAAU,CAAC,MAAM,EAAE,uBAAuB,GAAG,IAAI;IAMjD,oBAAoB,IAAI,IAAI;IAqB5B,wBAAwB,IAAI,IAAI;IA6BhC,oBAAoB,IAAI,IAAI;IAM5B,kBAAkB,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,uBAAuB,KAAK,IAAI,GAAG,MAAM,IAAI;CAcpF"}
@@ -1,4 +1,4 @@
1
- import { PrintJob } from '../types';
1
+ import { type PrintJob } from "../types";
2
2
  export declare enum EpsonNativeCommandEnum {
3
3
  ADD_TEXT = "addText",
4
4
  ADD_TEXT_ALIGN = "addTextAlign",
@@ -1 +1 @@
1
- {"version":3,"file":"mapper.d.ts","sourceRoot":"","sources":["../../src/epson/mapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAY,MAAM,UAAU,CAAC;AAE9C,oBAAY,sBAAsB;IAChC,QAAQ,YAAY;IACpB,cAAc,iBAAiB;IAC/B,cAAc,iBAAiB;IAC/B,aAAa,gBAAgB;IAC7B,aAAa,gBAAgB;IAC7B,SAAS,aAAa;IACtB,OAAO,WAAW;IAClB,SAAS,aAAa;IACtB,WAAW,eAAe;IAC1B,UAAU,cAAc;IACxB,aAAa,gBAAgB;IAC7B,aAAa,gBAAgB;CAC9B;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,sBAAsB,CAAC;IAC5B,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAsBD,eAAO,MAAM,uBAAuB,GAAI,QAAQ,OAAO,KAAG,GAiBzD,CAAC;AAEF,eAAO,MAAM,eAAe,GAAI,KAAK,QAAQ,KAAG,kBAAkB,EAoFjE,CAAC"}
1
+ {"version":3,"file":"mapper.d.ts","sourceRoot":"","sources":["../../src/epson/mapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEnD,oBAAY,sBAAsB;IAChC,QAAQ,YAAY;IACpB,cAAc,iBAAiB;IAC/B,cAAc,iBAAiB;IAC/B,aAAa,gBAAgB;IAC7B,aAAa,gBAAgB;IAC7B,SAAS,aAAa;IACtB,OAAO,WAAW;IAClB,SAAS,aAAa;IACtB,WAAW,eAAe;IAC1B,UAAU,cAAc;IACxB,aAAa,gBAAgB;IAC7B,aAAa,gBAAgB;CAC9B;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,sBAAsB,CAAC;IAC5B,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAsBD,eAAO,MAAM,uBAAuB,GAAI,QAAQ,OAAO,KAAG,GAiBzD,CAAC;AAEF,eAAO,MAAM,eAAe,GAAI,KAAK,QAAQ,KAAG,kBAAkB,EAoFjE,CAAC"}
@@ -1,4 +1,4 @@
1
- import { MunchiEmbeddedPayload, PrintJob } from '../types';
1
+ import { type MunchiEmbeddedPayload, type PrintJob } from '../types';
2
2
  /**
3
3
  * Expands a compact embedded payload into a PrintJob optimized for Epson printers.
4
4
  * Handles header generation (ID, Time, Table) and line formatting.
@@ -1 +1 @@
1
- {"version":3,"file":"payloadMapper.d.ts","sourceRoot":"","sources":["../../src/epson/payloadMapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,QAAQ,EAA0B,MAAM,UAAU,CAAC;AAEnF;;;GAGG;AACH,eAAO,MAAM,qBAAqB,GAAI,SAAS,qBAAqB,KAAG,QAmEtE,CAAC"}
1
+ {"version":3,"file":"payloadMapper.d.ts","sourceRoot":"","sources":["../../src/epson/payloadMapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,qBAAqB,EAAqB,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAC;AAElG;;;GAGG;AACH,eAAO,MAAM,qBAAqB,GAAI,SAAS,qBAAqB,KAAG,QAmEtE,CAAC"}
@@ -0,0 +1,28 @@
1
+ import type { PrinterConnectionStatus, PrinterLogger, PrinterStatus } from '../types';
2
+ export type StatusChangeCallback = (status: PrinterStatus) => void;
3
+ interface EpsonStatusControllerConfig {
4
+ logger?: PrinterLogger;
5
+ defaultStatus: PrinterStatus;
6
+ getConnectionStatus: () => PrinterConnectionStatus;
7
+ getStatus: () => Promise<PrinterStatus>;
8
+ }
9
+ export declare class EpsonStatusController {
10
+ private config;
11
+ private readonly statusCallbacks;
12
+ private latestHardwareStatus;
13
+ private statusRefreshPromise;
14
+ private statusRefreshTimer;
15
+ constructor(config: EpsonStatusControllerConfig);
16
+ subscribe(callback: StatusChangeCallback): () => void;
17
+ handleStatusEvent(): void;
18
+ handleConnected(): void;
19
+ handleDisconnected(): void;
20
+ clear(): void;
21
+ refreshNow(): Promise<void>;
22
+ private emitHardwareStatus;
23
+ private setHardwareStatus;
24
+ private clearRefreshTimer;
25
+ private scheduleRefresh;
26
+ }
27
+ export {};
28
+ //# sourceMappingURL=statusController.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statusController.d.ts","sourceRoot":"","sources":["../../src/epson/statusController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEtF,MAAM,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,aAAa,KAAK,IAAI,CAAC;AAEnE,UAAU,2BAA2B;IACnC,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,aAAa,EAAE,aAAa,CAAC;IAC7B,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;IACnD,SAAS,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,CAAC;CACzC;AAID,qBAAa,qBAAqB;IAMpB,OAAO,CAAC,MAAM;IAL1B,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAwC;IACxE,OAAO,CAAC,oBAAoB,CAA8B;IAC1D,OAAO,CAAC,oBAAoB,CAA8B;IAC1D,OAAO,CAAC,kBAAkB,CAA+B;gBAErC,MAAM,EAAE,2BAA2B;IAEvD,SAAS,CAAC,QAAQ,EAAE,oBAAoB,GAAG,MAAM,IAAI;IAgBrD,iBAAiB,IAAI,IAAI;IAIzB,eAAe,IAAI,IAAI;IAIvB,kBAAkB,IAAI,IAAI;IAK1B,KAAK,IAAI,IAAI;IAIP,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IA4BjC,OAAO,CAAC,kBAAkB;IAM1B,OAAO,CAAC,iBAAiB;IAKzB,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,eAAe;CASxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"errorResolver.d.ts","sourceRoot":"","sources":["../src/errorResolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAIxF,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG,MAAM,GAAG,SAAS,GAAG,YAAY,GAAG,WAAW,GAAG,OAAO,GAAG,SAAS,CAAC;AAEtH,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,gBAAgB,CAAC;IACvB,eAAe,EAAE,sBAAsB,CAAC;IACxC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,eAAe,EAAE,OAAO,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;IACnB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,GAAG,EAAE,OAAO,CAAC;CACd;AAED,eAAO,MAAM,mBAAmB,GAAI,OAAO,OAAO,KAAG,oBA4CpD,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAAI,OAAO,OAAO,KAAG,oBACvB,CAAC"}
1
+ {"version":3,"file":"errorResolver.d.ts","sourceRoot":"","sources":["../src/errorResolver.ts"],"names":[],"mappings":"AACA,OAAO,EAA2B,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAG7F,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG,MAAM,GAAG,SAAS,GAAG,YAAY,GAAG,WAAW,GAAG,OAAO,GAAG,SAAS,CAAC;AAEtH,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,gBAAgB,CAAC;IACvB,eAAe,EAAE,sBAAsB,CAAC;IACxC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,eAAe,EAAE,OAAO,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;IACnB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,GAAG,EAAE,OAAO,CAAC;CACd;AAED,eAAO,MAAM,mBAAmB,GAAI,OAAO,OAAO,KAAG,oBA4CpD,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAAI,OAAO,OAAO,KAAG,oBACvB,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,15 +1,15 @@
1
- import { EpsonPrinterConfig } from './types';
2
1
  import { EpsonPrinter } from './epson/driver';
3
- export { VERSION } from './version';
4
- export * from './types';
5
- export * from './errors';
2
+ import type { EpsonPrinterConfig } from './types';
6
3
  export * from './config';
4
+ export * from './epson/constants';
5
+ export { type ConnectionType, type DiscoveryParams, discoverPrinters } from './epson/discovery';
6
+ export { PrinterError } from './epson/errors';
7
+ export { resolveModelFromBluetoothName } from './epson/modelUtils';
7
8
  export * from './errorResolver';
9
+ export * from './errors';
8
10
  export * from './react/PrinterProvider';
9
11
  export * from './react/usePrinterStatus';
10
- export * from './epson/constants';
11
- export { resolveModelFromBluetoothName } from './epson/modelUtils';
12
- export { discoverPrinters, type ConnectionType, type DiscoveryParams } from './epson/discovery';
13
- export { PrinterError } from './epson/errors';
12
+ export * from './types';
13
+ export { VERSION } from './version';
14
14
  export declare function getPrinter(config: EpsonPrinterConfig): EpsonPrinter;
15
15
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC;AAChC,cAAc,yBAAyB,CAAC;AACxC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,6BAA6B,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAChG,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,wBAAgB,UAAU,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAKnE"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAElD,cAAc,UAAU,CAAC;AACzB,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAChG,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,6BAA6B,EAAE,MAAM,oBAAoB,CAAC;AACnE,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,yBAAyB,CAAC;AACxC,cAAc,0BAA0B,CAAC;AACzC,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,wBAAgB,UAAU,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAKnE"}
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var ue=Object.create;var C=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,le=Object.prototype.hasOwnProperty;var Te=(t,e)=>{for(var r in e)C(t,r,{get:e[r],enumerable:!0})},G=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of me(e))!le.call(t,i)&&i!==r&&C(t,i,{get:()=>e[i],enumerable:!(n=ce(e,i))||n.enumerable});return t};var ge=(t,e,r)=>(r=t!=null?ue(de(t)):{},G(e||!t||!t.__esModule?C(r,"default",{value:t,enumerable:!0}):r,t)),Re=t=>G(C({},"__esModule",{value:!0}),t);var xe={};Te(xe,{Epos2CallbackCode:()=>k,Epos2ConnectionEvent:()=>J,Epos2ErrorStatus:()=>j,Epos2Font:()=>Z,Epos2Lang:()=>Y,Epos2StatusEvent:()=>B,EpsonModel:()=>V,FontSize:()=>O,MunchiPrinterError:()=>g,PrinterError:()=>E,PrinterErrorCode:()=>I,PrinterProvider:()=>_e,PrinterTranslationCode:()=>_,VERSION:()=>te,discoverPrinters:()=>ae,getGlobalLogger:()=>U,getPrinter:()=>H,resolveEpsonError:()=>Ie,resolveModelFromBluetoothName:()=>ie,resolvePrinterError:()=>re,setGlobalLogger:()=>L,usePrinter:()=>q,usePrinterStatus:()=>ye});module.exports=Re(xe);var Q={},L=t=>{Q.logger=t},U=()=>Q.logger;var I=(u=>(u.CONNECTION_FAILED="CONNECTION_FAILED",u.PRINT_FAILED="PRINT_FAILED",u.DISCOVERY_FAILED="DISCOVERY_FAILED",u.TIMEOUT="TIMEOUT",u.NATIVE_MODULE_MISSING="NATIVE_MODULE_MISSING",u.UNKNOWN="UNKNOWN",u))(I||{}),_=(u=>(u.ERR_PRINTER_OFFLINE="printer.error.offline",u.ERR_PRINTER_BUSY="printer.error.busy",u.ERR_PRINTER_COVER_OPEN="printer.error.cover_open",u.ERR_PRINTER_PAPER_EMPTY="printer.error.paper_empty",u.ERR_CONNECTION_TIMEOUT="printer.error.connection_timeout",u.ERR_UNKNOWN="printer.error.unknown",u))(_||{}),g=class t extends Error{constructor(r,n,i,s){super(i);this.code=r;this.translationCode=n;this.originalError=s;this.name="MunchiPrinterError",Object.setPrototypeOf(this,t.prototype)}};var Pe=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e:""},fe=t=>{if(t instanceof Error)return t.message;if(t&&typeof t=="object"){let e=t.message;if(typeof e=="string")return e}return String(t)},l=(t,e,r)=>t.includes(r)||e===r||e.includes(r),f=t=>{if(t instanceof g)return t;let e=fe(t),r=Pe(t),n=e.toUpperCase(),i=r.toUpperCase();return n.includes("ERROR CODE: 4")?new g("PRINT_FAILED","printer.error.cover_open","Printer cover is open",t):n.includes("ERROR CODE: 3")?new g("PRINT_FAILED","printer.error.busy","Printer is performing auto-recovery",t):n.includes("ERROR CODE: 7")?new g("PRINT_FAILED","printer.error.paper_empty","Printer paper is empty",t):l(n,i,"TARGET_IN_USE")||l(n,i,"BUSY")||l(n,i,"IN_USE")||l(n,i,"PRINT_BUSY")||l(n,i,"DISCOVERY_BUSY")?new g("TIMEOUT","printer.error.busy","Printer is busy",t):l(n,i,"TIMEOUT")||l(n,i,"ERR_TIMEOUT")||l(n,i,"PRINT_TIMEOUT")?new g("TIMEOUT","printer.error.connection_timeout","Operation timed out",t):l(n,i,"PERMISSION_DENIED")||l(n,i,"LOCATION_DISABLED")||l(n,i,"BLUETOOTH_DISABLED")?new g("CONNECTION_FAILED","printer.error.offline",e,t):l(n,i,"DISCOVERY_ERROR")||n.includes("DISCOVERY")?new g("DISCOVERY_FAILED","printer.error.unknown",e,t):l(n,i,"PRINTER_OFFLINE")||l(n,i,"SESSION_ERROR")||l(n,i,"STATUS_ERROR")||l(n,i,"INIT_ERROR")||l(n,i,"PRINT_CANCELED")||l(n,i,"DISCONNECT")||l(n,i,"ERR_DISCONNECT")||n.includes("PRINTER NOT CONNECTED")||n.includes("OFFLINE")?new g("CONNECTION_FAILED","printer.error.offline",n.includes("OFFLINE")?e:"Printer disconnected",t):l(n,i,"CONNECT_ERROR")||n.includes("FAILED TO CONNECT")||l(n,i,"ERR_CONNECT")?new g("CONNECTION_FAILED","printer.error.offline","Failed to connect to printer",t):l(n,i,"PRINT_ERROR")||l(n,i,"PRINT_FAILURE")?new g("PRINT_FAILED","printer.error.unknown",e,t):new g("UNKNOWN","printer.error.unknown",e,t)};var O=(n=>(n.Small="Small",n.Medium="Medium",n.Large="Large",n))(O||{});var W=t=>{let e=[];if(t.settings?.fontSize){let r="Medium";t.settings.fontSize==="Small"&&(r="Small"),t.settings.fontSize==="Large"&&(r="Large"),e.push({type:"fontSize",size:r})}t.settings?.fontStyle==="Bold"&&e.push({type:"bold",value:!0}),e.push({type:"align",align:"center"}),t.tbl&&e.push({type:"text",text:`Table: ${t.tbl}
1
+ "use strict";var he=Object.create;var D=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var pe=(t,e)=>{for(var r in e)D(t,r,{get:e[r],enumerable:!0})},J=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ce(e))!Re.call(t,i)&&i!==r&&D(t,i,{get:()=>e[i],enumerable:!(n=fe(e,i))||n.enumerable});return t};var Pe=(t,e,r)=>(r=t!=null?he(Ee(t)):{},J(e||!t||!t.__esModule?D(r,"default",{value:t,enumerable:!0}):r,t)),Ne=t=>J(D({},"__esModule",{value:!0}),t);var Be={};pe(Be,{Epos2CallbackCode:()=>te,Epos2ConnectionEvent:()=>Z,Epos2ErrorStatus:()=>ee,Epos2Font:()=>re,Epos2Lang:()=>V,Epos2StatusEvent:()=>H,EpsonModel:()=>q,FontSize:()=>b,MunchiPrinterError:()=>h,PrinterError:()=>p,PrinterErrorCode:()=>y,PrinterProvider:()=>Ue,PrinterTranslationCode:()=>v,VERSION:()=>Te,discoverPrinters:()=>ce,getGlobalLogger:()=>Y,getPrinter:()=>K,resolveEpsonError:()=>Le,resolveModelFromBluetoothName:()=>le,resolvePrinterError:()=>de,setGlobalLogger:()=>B,usePrinter:()=>k,usePrinterStatus:()=>Fe});module.exports=Ne(Be);var j={},B=t=>{j.logger=t},Y=()=>j.logger;var W=require("react-native");var y=(l=>(l.CONNECTION_FAILED="CONNECTION_FAILED",l.PRINT_FAILED="PRINT_FAILED",l.DISCOVERY_FAILED="DISCOVERY_FAILED",l.TIMEOUT="TIMEOUT",l.NATIVE_MODULE_MISSING="NATIVE_MODULE_MISSING",l.UNKNOWN="UNKNOWN",l))(y||{}),v=(l=>(l.ERR_PRINTER_OFFLINE="printer.error.offline",l.ERR_PRINTER_BUSY="printer.error.busy",l.ERR_PRINTER_COVER_OPEN="printer.error.cover_open",l.ERR_PRINTER_PAPER_EMPTY="printer.error.paper_empty",l.ERR_CONNECTION_TIMEOUT="printer.error.connection_timeout",l.ERR_UNKNOWN="printer.error.unknown",l))(v||{}),h=class t extends Error{constructor(r,n,i,o){super(i);this.code=r;this.translationCode=n;this.originalError=o;this.name="MunchiPrinterError",Object.setPrototypeOf(this,t.prototype)}};var Ie=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e:""},Se=t=>{if(t instanceof Error)return t.message;if(t&&typeof t=="object"){let e=t.message;if(typeof e=="string")return e}return String(t)},T=(t,e,r)=>t.includes(r)||e===r||e.includes(r),E=t=>{if(t instanceof h)return t;let e=Se(t),r=Ie(t),n=e.toUpperCase(),i=r.toUpperCase();return n.includes("ERROR CODE: 4")?new h("PRINT_FAILED","printer.error.cover_open","Printer cover is open",t):n.includes("ERROR CODE: 3")?new h("PRINT_FAILED","printer.error.busy","Printer is performing auto-recovery",t):n.includes("ERROR CODE: 7")?new h("PRINT_FAILED","printer.error.paper_empty","Printer paper is empty",t):T(n,i,"TARGET_IN_USE")||T(n,i,"BUSY")||T(n,i,"IN_USE")||T(n,i,"PRINT_BUSY")||T(n,i,"DISCOVERY_BUSY")?new h("TIMEOUT","printer.error.busy","Printer is busy",t):T(n,i,"TIMEOUT")||T(n,i,"ERR_TIMEOUT")||T(n,i,"PRINT_TIMEOUT")?new h("TIMEOUT","printer.error.connection_timeout","Operation timed out",t):T(n,i,"PERMISSION_DENIED")||T(n,i,"LOCATION_DISABLED")||T(n,i,"BLUETOOTH_DISABLED")?new h("CONNECTION_FAILED","printer.error.offline",e,t):T(n,i,"DISCOVERY_ERROR")||n.includes("DISCOVERY")?new h("DISCOVERY_FAILED","printer.error.unknown",e,t):T(n,i,"PRINTER_OFFLINE")||T(n,i,"SESSION_ERROR")||T(n,i,"STATUS_ERROR")||T(n,i,"INIT_ERROR")||T(n,i,"PRINT_CANCELED")||T(n,i,"DISCONNECT")||T(n,i,"ERR_DISCONNECT")||n.includes("PRINTER NOT CONNECTED")||n.includes("OFFLINE")?new h("CONNECTION_FAILED","printer.error.offline",n.includes("OFFLINE")?e:"Printer disconnected",t):T(n,i,"CONNECT_ERROR")||n.includes("FAILED TO CONNECT")||T(n,i,"ERR_CONNECT")?new h("CONNECTION_FAILED","printer.error.offline","Failed to connect to printer",t):T(n,i,"PRINT_ERROR")||T(n,i,"PRINT_FAILURE")?new h("PRINT_FAILED","printer.error.unknown",e,t):new h("UNKNOWN","printer.error.unknown",e,t)};var H=(a=>(a[a.ONLINE=0]="ONLINE",a[a.OFFLINE=1]="OFFLINE",a[a.POWER_OFF=2]="POWER_OFF",a[a.COVER_CLOSE=3]="COVER_CLOSE",a[a.COVER_OPEN=4]="COVER_OPEN",a[a.PAPER_OK=5]="PAPER_OK",a[a.PAPER_NEAR_END=6]="PAPER_NEAR_END",a[a.PAPER_EMPTY=7]="PAPER_EMPTY",a[a.DRAWER_HIGH=8]="DRAWER_HIGH",a[a.DRAWER_LOW=9]="DRAWER_LOW",a[a.BATTERY_ENOUGH=10]="BATTERY_ENOUGH",a[a.BATTERY_EMPTY=11]="BATTERY_EMPTY",a[a.AUTO_RECOVER_ERROR=20]="AUTO_RECOVER_ERROR",a[a.AUTO_RECOVER_OK=21]="AUTO_RECOVER_OK",a[a.UNRECOVERABLE_ERROR=22]="UNRECOVERABLE_ERROR",a))(H||{}),Z=(n=>(n[n.RECONNECTING=0]="RECONNECTING",n[n.RECONNECT=1]="RECONNECT",n[n.DISCONNECT=2]="DISCONNECT",n))(Z||{}),ee=(u=>(u[u.SUCCESS=0]="SUCCESS",u[u.ERR_PARAM=1]="ERR_PARAM",u[u.ERR_CONNECT=2]="ERR_CONNECT",u[u.ERR_TIMEOUT=3]="ERR_TIMEOUT",u[u.ERR_MEMORY=4]="ERR_MEMORY",u[u.ERR_ILLEGAL=5]="ERR_ILLEGAL",u[u.ERR_PROCESSING=6]="ERR_PROCESSING",u[u.ERR_NOT_FOUND=7]="ERR_NOT_FOUND",u[u.ERR_IN_USE=8]="ERR_IN_USE",u[u.ERR_TYPE_INVALID=9]="ERR_TYPE_INVALID",u[u.ERR_DISCONNECT=10]="ERR_DISCONNECT",u[u.ERR_ALREADY_OPENED=11]="ERR_ALREADY_OPENED",u[u.ERR_ALREADY_USED=12]="ERR_ALREADY_USED",u[u.ERR_BOX_COUNT_OVER=13]="ERR_BOX_COUNT_OVER",u[u.ERR_BOX_CLIENT_OVER=14]="ERR_BOX_CLIENT_OVER",u[u.ERR_UNSUPPORTED=15]="ERR_UNSUPPORTED",u[u.ERR_DEVICE_BUSY=16]="ERR_DEVICE_BUSY",u[u.ERR_RECOVERY_FAILURE=17]="ERR_RECOVERY_FAILURE",u[u.ERR_FAILURE=255]="ERR_FAILURE",u))(ee||{}),te=(d=>(d[d.SUCCESS=0]="SUCCESS",d[d.ERR_TIMEOUT=1]="ERR_TIMEOUT",d[d.ERR_NOT_FOUND=2]="ERR_NOT_FOUND",d[d.ERR_AUTORECOVER=3]="ERR_AUTORECOVER",d[d.ERR_COVER_OPEN=4]="ERR_COVER_OPEN",d[d.ERR_CUTTER=5]="ERR_CUTTER",d[d.ERR_MECHANICAL=6]="ERR_MECHANICAL",d[d.ERR_EMPTY=7]="ERR_EMPTY",d[d.ERR_UNRECOVERABLE=8]="ERR_UNRECOVERABLE",d[d.ERR_SYSTEM=9]="ERR_SYSTEM",d[d.ERR_PORT=10]="ERR_PORT",d[d.ERR_FAILURE=255]="ERR_FAILURE",d))(te||{}),V=(c=>(c[c.EN=0]="EN",c[c.JA=1]="JA",c[c.ZH_CN=2]="ZH_CN",c[c.ZH_TW=3]="ZH_TW",c[c.KO=4]="KO",c[c.TH=5]="TH",c[c.VI=6]="VI",c[c.MULTI=7]="MULTI",c))(V||{}),re=(o=>(o[o.FONT_A=0]="FONT_A",o[o.FONT_B=1]="FONT_B",o[o.FONT_C=2]="FONT_C",o[o.FONT_D=3]="FONT_D",o[o.FONT_E=4]="FONT_E",o))(re||{}),q=(s=>(s[s.TM_M10=0]="TM_M10",s[s.TM_M30=1]="TM_M30",s[s.TM_P20=2]="TM_P20",s[s.TM_P60=3]="TM_P60",s[s.TM_P60II=4]="TM_P60II",s[s.TM_P80=5]="TM_P80",s[s.TM_T20=6]="TM_T20",s[s.TM_T60=7]="TM_T60",s[s.TM_T70=8]="TM_T70",s[s.TM_T81=9]="TM_T81",s[s.TM_T82=10]="TM_T82",s[s.TM_T83=11]="TM_T83",s[s.TM_T88=12]="TM_T88",s[s.TM_T90=13]="TM_T90",s[s.TM_T90KP=14]="TM_T90KP",s[s.TM_U220=15]="TM_U220",s[s.TM_U330=16]="TM_U330",s[s.TM_L90=17]="TM_L90",s[s.TM_H6000=18]="TM_H6000",s[s.TM_T83III=19]="TM_T83III",s[s.TM_T100=20]="TM_T100",s[s.TM_M30II=21]="TM_M30II",s[s.TM_M50=23]="TM_M50",s[s.TM_T88VII=24]="TM_T88VII",s[s.TM_L90LFC=25]="TM_L90LFC",s[s.TM_L100=26]="TM_L100",s[s.TM_P20II=27]="TM_P20II",s[s.TM_P80II=28]="TM_P80II",s[s.TM_M30III=29]="TM_M30III",s[s.TM_M50II=30]="TM_M50II",s[s.TM_M55=31]="TM_M55",s[s.TM_U220II=32]="TM_U220II",s))(q||{});var p=class t extends h{constructor(r,n,i,o,l){super(n,i,o,l);this.isHardwareError=r;this.name="PrinterError",Object.setPrototypeOf(this,t.prototype)}},z=t=>{if(t instanceof p)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")},ne=t=>{if(t instanceof p)return t;let e=E(t),r=z(t);return new p(r,e.code,e.translationCode,e.message,e.originalError)};var M=require("react-native"),m=M.NativeModules.MunchiEpsonModule,G=()=>m?new M.NativeEventEmitter(m):null,_e=t=>new Promise(e=>setTimeout(e,t)),Oe=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e.toUpperCase():""},ye=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=ye(n),o=Oe(n);if(P(i,o,"TARGET_IN_USE"))throw n;if(P(i,o,"BUSY")||P(i,o,"IN_USE")||P(i,o,"ERR_IN_USE")||P(i,o,"PRINT_BUSY")||P(i,o,"ERR_CONNECT")||P(i,o,"CONNECT_ERROR")||P(i,o,"ERR_TIMEOUT")||P(i,o,"PRINT_TIMEOUT"))return await _e(r),S(t,e-1,r);throw n}};var ve=new Set([0,3,5,21]),w=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=G();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),this.config.onEvent({connectionStatus:null,statusEventType:r.eventType,isRecoveryEvent:ve.has(r.eventType)})}))}ensureConnectionListener(){if(this.connectionSubscription)return;let e=G();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.onEvent({connectionStatus:n,statusEventType:null,isRecoveryEvent:!1}),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 b=(n=>(n.Small="Small",n.Medium="Medium",n.Large="Large",n))(b||{});var De=(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},ie=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"}},se=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=De(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:`------------------
2
+ `};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 oe=t=>{let e=[];if(t.settings?.fontSize){let r="Medium";t.settings.fontSize==="Small"&&(r="Small"),t.settings.fontSize==="Large"&&(r="Large"),e.push({type:"fontSize",size:r})}t.settings?.fontStyle==="Bold"&&e.push({type:"bold",value:!0}),e.push({type:"align",align:"center"}),t.tbl&&e.push({type:"text",text:`Table: ${t.tbl}
2
3
  `,bold:!0,size:"double-height"}),e.push({type:"text",text:`Order: ${t.id}
3
4
  `,bold:!0}),e.push({type:"text",text:`${t.ts}
4
5
  `}),e.push({type:"text",text:`--------------------------------
5
- `}),e.push({type:"align",align:"left"});for(let r of t.lines){let n=r.t,i=r.s,s=r.i||0,P=`${" ".repeat(s)}${n}`;if(i==="C"){if(n.includes("---")){e.push({type:"text",text:`--------------------------------
6
- `,align:"center"});continue}e.push({type:"text",text:P+`
7
- `,align:"center",bold:!0})}else i==="B"?e.push({type:"text",text:P+`
8
- `,bold:!0}):i==="R"?e.push({type:"text",text:P+`
9
- `,bold:!0}):e.push({type:"text",text:P+`
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.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});
6
+ `}),e.push({type:"align",align:"left"});for(let r of t.lines){let n=r.t,i=r.s,o=r.i||0,g=`${" ".repeat(o)}${n}`;if(i==="C"){if(n.includes("---")){e.push({type:"text",text:`--------------------------------
7
+ `,align:"center"});continue}e.push({type:"text",text:g+`
8
+ `,align:"center",bold:!0})}else i==="B"?e.push({type:"text",text:g+`
9
+ `,bold:!0}):i==="R"?e.push({type:"text",text:g+`
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.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
@@ -1,11 +1,11 @@
1
- var w={},L=t=>{w.logger=t},U=()=>w.logger;var D=(u=>(u.CONNECTION_FAILED="CONNECTION_FAILED",u.PRINT_FAILED="PRINT_FAILED",u.DISCOVERY_FAILED="DISCOVERY_FAILED",u.TIMEOUT="TIMEOUT",u.NATIVE_MODULE_MISSING="NATIVE_MODULE_MISSING",u.UNKNOWN="UNKNOWN",u))(D||{}),M=(u=>(u.ERR_PRINTER_OFFLINE="printer.error.offline",u.ERR_PRINTER_BUSY="printer.error.busy",u.ERR_PRINTER_COVER_OPEN="printer.error.cover_open",u.ERR_PRINTER_PAPER_EMPTY="printer.error.paper_empty",u.ERR_CONNECTION_TIMEOUT="printer.error.connection_timeout",u.ERR_UNKNOWN="printer.error.unknown",u))(M||{}),g=class t extends Error{constructor(n,r,o,s){super(o);this.code=n;this.translationCode=r;this.originalError=s;this.name="MunchiPrinterError",Object.setPrototypeOf(this,t.prototype)}};var j=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e:""},k=t=>{if(t instanceof Error)return t.message;if(t&&typeof t=="object"){let e=t.message;if(typeof e=="string")return e}return String(t)},l=(t,e,n)=>t.includes(n)||e===n||e.includes(n),P=t=>{if(t instanceof g)return t;let e=k(t),n=j(t),r=e.toUpperCase(),o=n.toUpperCase();return r.includes("ERROR CODE: 4")?new g("PRINT_FAILED","printer.error.cover_open","Printer cover is open",t):r.includes("ERROR CODE: 3")?new g("PRINT_FAILED","printer.error.busy","Printer is performing auto-recovery",t):r.includes("ERROR CODE: 7")?new g("PRINT_FAILED","printer.error.paper_empty","Printer paper is empty",t):l(r,o,"TARGET_IN_USE")||l(r,o,"BUSY")||l(r,o,"IN_USE")||l(r,o,"PRINT_BUSY")||l(r,o,"DISCOVERY_BUSY")?new g("TIMEOUT","printer.error.busy","Printer is busy",t):l(r,o,"TIMEOUT")||l(r,o,"ERR_TIMEOUT")||l(r,o,"PRINT_TIMEOUT")?new g("TIMEOUT","printer.error.connection_timeout","Operation timed out",t):l(r,o,"PERMISSION_DENIED")||l(r,o,"LOCATION_DISABLED")||l(r,o,"BLUETOOTH_DISABLED")?new g("CONNECTION_FAILED","printer.error.offline",e,t):l(r,o,"DISCOVERY_ERROR")||r.includes("DISCOVERY")?new g("DISCOVERY_FAILED","printer.error.unknown",e,t):l(r,o,"PRINTER_OFFLINE")||l(r,o,"SESSION_ERROR")||l(r,o,"STATUS_ERROR")||l(r,o,"INIT_ERROR")||l(r,o,"PRINT_CANCELED")||l(r,o,"DISCONNECT")||l(r,o,"ERR_DISCONNECT")||r.includes("PRINTER NOT CONNECTED")||r.includes("OFFLINE")?new g("CONNECTION_FAILED","printer.error.offline",r.includes("OFFLINE")?e:"Printer disconnected",t):l(r,o,"CONNECT_ERROR")||r.includes("FAILED TO CONNECT")||l(r,o,"ERR_CONNECT")?new g("CONNECTION_FAILED","printer.error.offline","Failed to connect to printer",t):l(r,o,"PRINT_ERROR")||l(r,o,"PRINT_FAILURE")?new g("PRINT_FAILED","printer.error.unknown",e,t):new g("UNKNOWN","printer.error.unknown",e,t)};var v=(r=>(r.Small="Small",r.Medium="Medium",r.Large="Large",r))(v||{});var F=t=>{let e=[];if(t.settings?.fontSize){let n="Medium";t.settings.fontSize==="Small"&&(n="Small"),t.settings.fontSize==="Large"&&(n="Large"),e.push({type:"fontSize",size:n})}t.settings?.fontStyle==="Bold"&&e.push({type:"bold",value:!0}),e.push({type:"align",align:"center"}),t.tbl&&e.push({type:"text",text:`Table: ${t.tbl}
1
+ var q={},z=t=>{q.logger=t},G=()=>q.logger;import{Platform as j}from"react-native";var _=(l=>(l.CONNECTION_FAILED="CONNECTION_FAILED",l.PRINT_FAILED="PRINT_FAILED",l.DISCOVERY_FAILED="DISCOVERY_FAILED",l.TIMEOUT="TIMEOUT",l.NATIVE_MODULE_MISSING="NATIVE_MODULE_MISSING",l.UNKNOWN="UNKNOWN",l))(_||{}),O=(l=>(l.ERR_PRINTER_OFFLINE="printer.error.offline",l.ERR_PRINTER_BUSY="printer.error.busy",l.ERR_PRINTER_COVER_OPEN="printer.error.cover_open",l.ERR_PRINTER_PAPER_EMPTY="printer.error.paper_empty",l.ERR_CONNECTION_TIMEOUT="printer.error.connection_timeout",l.ERR_UNKNOWN="printer.error.unknown",l))(O||{}),h=class t extends Error{constructor(r,n,i,o){super(i);this.code=r;this.translationCode=n;this.originalError=o;this.name="MunchiPrinterError",Object.setPrototypeOf(this,t.prototype)}};var se=t=>{if(!t||typeof t!="object")return"";let e=t.code;return typeof e=="string"?e:""},oe=t=>{if(t instanceof Error)return t.message;if(t&&typeof t=="object"){let e=t.message;if(typeof e=="string")return e}return String(t)},T=(t,e,r)=>t.includes(r)||e===r||e.includes(r),C=t=>{if(t instanceof h)return t;let e=oe(t),r=se(t),n=e.toUpperCase(),i=r.toUpperCase();return n.includes("ERROR CODE: 4")?new h("PRINT_FAILED","printer.error.cover_open","Printer cover is open",t):n.includes("ERROR CODE: 3")?new h("PRINT_FAILED","printer.error.busy","Printer is performing auto-recovery",t):n.includes("ERROR CODE: 7")?new h("PRINT_FAILED","printer.error.paper_empty","Printer paper is empty",t):T(n,i,"TARGET_IN_USE")||T(n,i,"BUSY")||T(n,i,"IN_USE")||T(n,i,"PRINT_BUSY")||T(n,i,"DISCOVERY_BUSY")?new h("TIMEOUT","printer.error.busy","Printer is busy",t):T(n,i,"TIMEOUT")||T(n,i,"ERR_TIMEOUT")||T(n,i,"PRINT_TIMEOUT")?new h("TIMEOUT","printer.error.connection_timeout","Operation timed out",t):T(n,i,"PERMISSION_DENIED")||T(n,i,"LOCATION_DISABLED")||T(n,i,"BLUETOOTH_DISABLED")?new h("CONNECTION_FAILED","printer.error.offline",e,t):T(n,i,"DISCOVERY_ERROR")||n.includes("DISCOVERY")?new h("DISCOVERY_FAILED","printer.error.unknown",e,t):T(n,i,"PRINTER_OFFLINE")||T(n,i,"SESSION_ERROR")||T(n,i,"STATUS_ERROR")||T(n,i,"INIT_ERROR")||T(n,i,"PRINT_CANCELED")||T(n,i,"DISCONNECT")||T(n,i,"ERR_DISCONNECT")||n.includes("PRINTER NOT CONNECTED")||n.includes("OFFLINE")?new h("CONNECTION_FAILED","printer.error.offline",n.includes("OFFLINE")?e:"Printer disconnected",t):T(n,i,"CONNECT_ERROR")||n.includes("FAILED TO CONNECT")||T(n,i,"ERR_CONNECT")?new h("CONNECTION_FAILED","printer.error.offline","Failed to connect to printer",t):T(n,i,"PRINT_ERROR")||T(n,i,"PRINT_FAILURE")?new h("PRINT_FAILED","printer.error.unknown",e,t):new h("UNKNOWN","printer.error.unknown",e,t)};var Q=(a=>(a[a.ONLINE=0]="ONLINE",a[a.OFFLINE=1]="OFFLINE",a[a.POWER_OFF=2]="POWER_OFF",a[a.COVER_CLOSE=3]="COVER_CLOSE",a[a.COVER_OPEN=4]="COVER_OPEN",a[a.PAPER_OK=5]="PAPER_OK",a[a.PAPER_NEAR_END=6]="PAPER_NEAR_END",a[a.PAPER_EMPTY=7]="PAPER_EMPTY",a[a.DRAWER_HIGH=8]="DRAWER_HIGH",a[a.DRAWER_LOW=9]="DRAWER_LOW",a[a.BATTERY_ENOUGH=10]="BATTERY_ENOUGH",a[a.BATTERY_EMPTY=11]="BATTERY_EMPTY",a[a.AUTO_RECOVER_ERROR=20]="AUTO_RECOVER_ERROR",a[a.AUTO_RECOVER_OK=21]="AUTO_RECOVER_OK",a[a.UNRECOVERABLE_ERROR=22]="UNRECOVERABLE_ERROR",a))(Q||{}),ae=(n=>(n[n.RECONNECTING=0]="RECONNECTING",n[n.RECONNECT=1]="RECONNECT",n[n.DISCONNECT=2]="DISCONNECT",n))(ae||{}),ue=(u=>(u[u.SUCCESS=0]="SUCCESS",u[u.ERR_PARAM=1]="ERR_PARAM",u[u.ERR_CONNECT=2]="ERR_CONNECT",u[u.ERR_TIMEOUT=3]="ERR_TIMEOUT",u[u.ERR_MEMORY=4]="ERR_MEMORY",u[u.ERR_ILLEGAL=5]="ERR_ILLEGAL",u[u.ERR_PROCESSING=6]="ERR_PROCESSING",u[u.ERR_NOT_FOUND=7]="ERR_NOT_FOUND",u[u.ERR_IN_USE=8]="ERR_IN_USE",u[u.ERR_TYPE_INVALID=9]="ERR_TYPE_INVALID",u[u.ERR_DISCONNECT=10]="ERR_DISCONNECT",u[u.ERR_ALREADY_OPENED=11]="ERR_ALREADY_OPENED",u[u.ERR_ALREADY_USED=12]="ERR_ALREADY_USED",u[u.ERR_BOX_COUNT_OVER=13]="ERR_BOX_COUNT_OVER",u[u.ERR_BOX_CLIENT_OVER=14]="ERR_BOX_CLIENT_OVER",u[u.ERR_UNSUPPORTED=15]="ERR_UNSUPPORTED",u[u.ERR_DEVICE_BUSY=16]="ERR_DEVICE_BUSY",u[u.ERR_RECOVERY_FAILURE=17]="ERR_RECOVERY_FAILURE",u[u.ERR_FAILURE=255]="ERR_FAILURE",u))(ue||{}),ce=(d=>(d[d.SUCCESS=0]="SUCCESS",d[d.ERR_TIMEOUT=1]="ERR_TIMEOUT",d[d.ERR_NOT_FOUND=2]="ERR_NOT_FOUND",d[d.ERR_AUTORECOVER=3]="ERR_AUTORECOVER",d[d.ERR_COVER_OPEN=4]="ERR_COVER_OPEN",d[d.ERR_CUTTER=5]="ERR_CUTTER",d[d.ERR_MECHANICAL=6]="ERR_MECHANICAL",d[d.ERR_EMPTY=7]="ERR_EMPTY",d[d.ERR_UNRECOVERABLE=8]="ERR_UNRECOVERABLE",d[d.ERR_SYSTEM=9]="ERR_SYSTEM",d[d.ERR_PORT=10]="ERR_PORT",d[d.ERR_FAILURE=255]="ERR_FAILURE",d))(ce||{}),W=(c=>(c[c.EN=0]="EN",c[c.JA=1]="JA",c[c.ZH_CN=2]="ZH_CN",c[c.ZH_TW=3]="ZH_TW",c[c.KO=4]="KO",c[c.TH=5]="TH",c[c.VI=6]="VI",c[c.MULTI=7]="MULTI",c))(W||{}),le=(o=>(o[o.FONT_A=0]="FONT_A",o[o.FONT_B=1]="FONT_B",o[o.FONT_C=2]="FONT_C",o[o.FONT_D=3]="FONT_D",o[o.FONT_E=4]="FONT_E",o))(le||{}),k=(s=>(s[s.TM_M10=0]="TM_M10",s[s.TM_M30=1]="TM_M30",s[s.TM_P20=2]="TM_P20",s[s.TM_P60=3]="TM_P60",s[s.TM_P60II=4]="TM_P60II",s[s.TM_P80=5]="TM_P80",s[s.TM_T20=6]="TM_T20",s[s.TM_T60=7]="TM_T60",s[s.TM_T70=8]="TM_T70",s[s.TM_T81=9]="TM_T81",s[s.TM_T82=10]="TM_T82",s[s.TM_T83=11]="TM_T83",s[s.TM_T88=12]="TM_T88",s[s.TM_T90=13]="TM_T90",s[s.TM_T90KP=14]="TM_T90KP",s[s.TM_U220=15]="TM_U220",s[s.TM_U330=16]="TM_U330",s[s.TM_L90=17]="TM_L90",s[s.TM_H6000=18]="TM_H6000",s[s.TM_T83III=19]="TM_T83III",s[s.TM_T100=20]="TM_T100",s[s.TM_M30II=21]="TM_M30II",s[s.TM_M50=23]="TM_M50",s[s.TM_T88VII=24]="TM_T88VII",s[s.TM_L90LFC=25]="TM_L90LFC",s[s.TM_L100=26]="TM_L100",s[s.TM_P20II=27]="TM_P20II",s[s.TM_P80II=28]="TM_P80II",s[s.TM_M30III=29]="TM_M30III",s[s.TM_M50II=30]="TM_M50II",s[s.TM_M55=31]="TM_M55",s[s.TM_U220II=32]="TM_U220II",s))(k||{});var R=class t extends h{constructor(r,n,i,o,l){super(n,i,o,l);this.isHardwareError=r;this.name="PrinterError",Object.setPrototypeOf(this,t.prototype)}},A=t=>{if(t instanceof R)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 R)return t;let e=C(t),r=A(t);return new R(r,e.code,e.translationCode,e.message,e.originalError)};import{NativeEventEmitter as de,NativeModules as me}from"react-native";var m=me.MunchiEpsonModule,L=()=>m?new de(m):null,ge=t=>new Promise(e=>setTimeout(e,t)),Te=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()},E=(t,e,r)=>t.includes(r)||e===r||e.includes(r),N=async(t,e=3,r=500)=>{try{return await t()}catch(n){if(e<=1)throw n;let i=he(n),o=Te(n);if(E(i,o,"TARGET_IN_USE"))throw n;if(E(i,o,"BUSY")||E(i,o,"IN_USE")||E(i,o,"ERR_IN_USE")||E(i,o,"PRINT_BUSY")||E(i,o,"ERR_CONNECT")||E(i,o,"CONNECT_ERROR")||E(i,o,"ERR_TIMEOUT")||E(i,o,"PRINT_TIMEOUT"))return await ge(r),N(t,e-1,r);throw n}};var fe=new Set([0,3,5,21]),y=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=L();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),this.config.onEvent({connectionStatus:null,statusEventType:r.eventType,isRecoveryEvent:fe.has(r.eventType)})}))}ensureConnectionListener(){if(this.connectionSubscription)return;let e=L();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.onEvent({connectionStatus:n,statusEventType:null,isRecoveryEvent:!1}),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 U=(n=>(n.Small="Small",n.Medium="Medium",n.Large="Large",n))(U||{});var Ce=(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=Ce(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:`------------------
2
+ `};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 J=t=>{let e=[];if(t.settings?.fontSize){let r="Medium";t.settings.fontSize==="Small"&&(r="Small"),t.settings.fontSize==="Large"&&(r="Large"),e.push({type:"fontSize",size:r})}t.settings?.fontStyle==="Bold"&&e.push({type:"bold",value:!0}),e.push({type:"align",align:"center"}),t.tbl&&e.push({type:"text",text:`Table: ${t.tbl}
2
3
  `,bold:!0,size:"double-height"}),e.push({type:"text",text:`Order: ${t.id}
3
4
  `,bold:!0}),e.push({type:"text",text:`${t.ts}
4
5
  `}),e.push({type:"text",text:`--------------------------------
5
- `}),e.push({type:"align",align:"left"});for(let n of t.lines){let r=n.t,o=n.s,s=n.i||0,R=`${" ".repeat(s)}${r}`;if(o==="C"){if(r.includes("---")){e.push({type:"text",text:`--------------------------------
6
- `,align:"center"});continue}e.push({type:"text",text:R+`
7
- `,align:"center",bold:!0})}else o==="B"?e.push({type:"text",text:R+`
8
- `,bold:!0}):o==="R"?e.push({type:"text",text:R+`
9
- `,bold:!0}):e.push({type:"text",text:R+`
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.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};
6
+ `}),e.push({type:"align",align:"left"});for(let r of t.lines){let n=r.t,i=r.s,o=r.i||0,g=`${" ".repeat(o)}${n}`;if(i==="C"){if(n.includes("---")){e.push({type:"text",text:`--------------------------------
7
+ `,align:"center"});continue}e.push({type:"text",text:g+`
8
+ `,align:"center",bold:!0})}else i==="B"?e.push({type:"text",text:g+`
9
+ `,bold:!0}):i==="R"?e.push({type:"text",text:g+`
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.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};
@@ -1,7 +1,7 @@
1
- import React from 'react';
2
- import { EpsonPrinterConfig, PrinterLogger } from '../types';
3
- import { MunchiPrinterError } from '../errors';
4
- import { EpsonPrinter } from '../epson/driver';
1
+ import React from "react";
2
+ import type { EpsonPrinter } from "../epson/driver";
3
+ import type { MunchiPrinterError } from "../errors";
4
+ import type { EpsonPrinterConfig, PrinterLogger } from "../types";
5
5
  interface PrinterContextValue {
6
6
  printer: EpsonPrinter;
7
7
  config: EpsonPrinterConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"PrinterProvider.d.ts","sourceRoot":"","sources":["../../src/react/PrinterProvider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAkE,MAAM,OAAO,CAAC;AACvF,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,UAAU,mBAAmB;IAC3B,OAAO,EAAE,YAAY,CAAC;IACtB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,kBAAkB,GAAG,SAAS,CAAC;CACvC;AAID,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,kBAAkB,CAAC;IAC3B,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;CAC3B;AAED,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,EAAE,CAAC,oBAAoB,CA8B1D,CAAC;AAEF,eAAO,MAAM,UAAU,2BAMtB,CAAC"}
1
+ {"version":3,"file":"PrinterProvider.d.ts","sourceRoot":"","sources":["../../src/react/PrinterProvider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAEpD,OAAO,KAAK,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAElE,UAAU,mBAAmB;IAC5B,OAAO,EAAE,YAAY,CAAC;IACtB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,kBAAkB,GAAG,SAAS,CAAC;CACtC;AAMD,MAAM,WAAW,oBAAoB;IACpC,MAAM,EAAE,kBAAkB,CAAC;IAC3B,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;CAC1B;AAED,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,EAAE,CAAC,oBAAoB,CA+B1D,CAAC;AAEF,eAAO,MAAM,UAAU,2BAMtB,CAAC"}
@@ -2,10 +2,10 @@ import type { PrinterConnectionStatus, PrinterStatus } from '../types';
2
2
  export interface PrinterStatusState {
3
3
  connectionStatus: PrinterConnectionStatus;
4
4
  hardwareStatus: PrinterStatus | null;
5
- isPolling: boolean;
5
+ isError: boolean;
6
+ errorMessage: string | null;
6
7
  }
7
8
  export interface UsePrinterStatusOptions {
8
- pollIntervalMs?: number;
9
9
  enabled?: boolean;
10
10
  }
11
11
  export declare function usePrinterStatus(options?: UsePrinterStatusOptions): PrinterStatusState;
@@ -1 +1 @@
1
- {"version":3,"file":"usePrinterStatus.d.ts","sourceRoot":"","sources":["../../src/react/usePrinterStatus.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGvE,MAAM,WAAW,kBAAkB;IACjC,gBAAgB,EAAE,uBAAuB,CAAC;IAC1C,cAAc,EAAE,aAAa,GAAG,IAAI,CAAC;IACrC,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,uBAAuB;IACtC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAWD,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,uBAA4B,GAAG,kBAAkB,CAiD1F"}
1
+ {"version":3,"file":"usePrinterStatus.d.ts","sourceRoot":"","sources":["../../src/react/usePrinterStatus.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGvE,MAAM,WAAW,kBAAkB;IACjC,gBAAgB,EAAE,uBAAuB,CAAC;IAC1C,cAAc,EAAE,aAAa,GAAG,IAAI,CAAC;IACrC,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,uBAA4B,GAAG,kBAAkB,CAuF1F"}
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "1.0.2";
1
+ export declare const VERSION = "1.0.4";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -132,8 +132,15 @@ class MunchiEpsonModule: RCTEventEmitter, Epos2ConnectionDelegate, Epos2PtrStatu
132
132
  }
133
133
 
134
134
  if let ownerSessionId = self.targetToSessionId[target], ownerSessionId != sessionId {
135
- reject("TARGET_IN_USE", "Target is already connected by another session: \(target)", nil)
136
- return
135
+ if let ownerSession = self.sessions[ownerSessionId] {
136
+ if ownerSession.printResolve != nil {
137
+ reject("TARGET_IN_USE", "Target is busy with an active print job: \(target)", nil)
138
+ return
139
+ }
140
+ _ = self.teardownPrinter(ownerSession, disconnect: true)
141
+ } else {
142
+ self.targetToSessionId.removeValue(forKey: target)
143
+ }
137
144
  }
138
145
 
139
146
  let safeLang = self.normalizedLanguage(lang)
@@ -156,6 +163,7 @@ class MunchiEpsonModule: RCTEventEmitter, Epos2ConnectionDelegate, Epos2PtrStatu
156
163
  let result = p.connect(target, timeout: connectTimeout)
157
164
 
158
165
  if result == EPOS2_SUCCESS.rawValue {
166
+ _ = p.startMonitor()
159
167
  self.targetToSessionId[target] = sessionId
160
168
  resolve("Connected to \(target)")
161
169
  } else {
@@ -442,6 +450,7 @@ class MunchiEpsonModule: RCTEventEmitter, Epos2ConnectionDelegate, Epos2PtrStatu
442
450
  printer.setReceiveEventDelegate(nil)
443
451
  printer.setConnectionEventDelegate(nil)
444
452
  printer.setStatusChangeEventDelegate(nil)
453
+ _ = printer.stopMonitor()
445
454
 
446
455
  var result: Int32? = nil
447
456
  if disconnect {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@munchi_oy/react-native-epson-printer",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Munchi Printer SDK Bridge",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -54,6 +54,7 @@
54
54
  "react-native": "0.76.9",
55
55
  "react-test-renderer": "18.1.0",
56
56
  "tsup": "^8.5.1",
57
- "typescript": "^5.0.0"
57
+ "typescript": "^5.0.0",
58
+ "yalc": "1.0.0-pre.53"
58
59
  }
59
60
  }