promise-logic 2.8.5 → 2.9.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xier123456
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,49 +1,140 @@
1
- ### **1. Core Philosophy**
1
+ ## Core Philosophy
2
+
3
+ **Replace API Memory with Logical Concepts**
4
+
5
+ The design philosophy of `promise-logic` is: **Developers should focus on business logic, not on details of Promise APIs**.
6
+
7
+ Traditional Promise combinations (such as `Promise.all`, `Promise.race`) have naming and semantics that are not intuitive enough, especially in complex asynchronous scenarios where code readability rapidly declines.
2
8
 
3
- **Replace API Memory with Logical Concepts**
4
- The design philosophy of `promise-logic` is: **Developers should focus on business logic, not on details of Promise APIs**.
5
- Traditional Promise combinations (such as `Promise.all`, `Promise.race`) have naming and semantics that are not intuitive enough, especially in complex asynchronous scenarios where code readability rapidly declines.
6
9
  `promise-logic` abstracts asynchronous combinations into logical operations like `and`, `or`, `xor` through the concept of **Logic Gates**, making code semantically clear and self-explanatory.
7
10
 
11
+ ### Example Scenario: E-commerce Order Processing
12
+
13
+ ```javascript
14
+ import { PromiseLogic } from 'promise-logic';
15
+
16
+ // Order processing flow
17
+ async function createOrder() {
18
+ try {
19
+ // Execute payment and inventory operations (both must succeed)
20
+ const [
21
+ [paymentResult, inventoryResult], // Payment and inventory operation results
22
+ logistics, // Logistics operation result
23
+ coupon // Coupon operation result
24
+ ] = await PromiseLogic.and([
25
+ // Payment and inventory operations must both succeed
26
+ PromiseLogic.and([paymentAPI(), inventoryAPI()]),
27
+ // At least one logistics operation must succeed
28
+ PromiseLogic.or([oneLogisticsAPI(), twoLogisticsAPI()], {
29
+ errorType: 'LOGISTICS_ERROR', // Custom logistics error type
30
+ }),
31
+ // At least one coupon must be available
32
+ PromiseLogic.or([couponAPI1(), couponAPI2()], {
33
+ errorType: 'COUPON_ERROR', // Custom coupon error type
34
+ })
35
+ ], {
36
+ errorType: 'ORDER_ERROR', // Custom order error type
37
+ errorMessage: 'Order creation failed' // Custom order error message
38
+ });
39
+
40
+ // Order creation successful, return payment result, inventory result, logistics result and coupon result
41
+ return {
42
+ payment: paymentResult,
43
+ inventory: inventoryResult,
44
+ logistics: logistics,
45
+ coupon: coupon,
46
+ status: 'success'
47
+ };
48
+ } catch (error) {
49
+ // Analyze error type
50
+ switch (error.type) {
51
+ case 'ORDER_ERROR':
52
+ return {
53
+ status: 'error',
54
+ errorType: 'order_error',
55
+ message: 'Order creation failed',
56
+ details: error
57
+ };
58
+ case 'AND_ERROR':
59
+ return {
60
+ status: 'error',
61
+ errorType: 'payment_or_inventory_failed',
62
+ message: 'Payment or inventory operation failed',
63
+ details: error
64
+ };
65
+ case 'LOGISTICS_ERROR':
66
+ return {
67
+ status: 'error',
68
+ errorType: 'logistics_unavailable',
69
+ message: 'All logistics services are unavailable',
70
+ details: error
71
+ };
72
+ case 'COUPON_ERROR':
73
+ return {
74
+ status: 'error',
75
+ errorType: 'coupon_error',
76
+ message: 'All coupons are unavailable',
77
+ details: error
78
+ };
79
+ default:
80
+ return {
81
+ status: 'error',
82
+ errorType: 'default_error',
83
+ message: 'Unknown error occurred during order creation',
84
+ details: error
85
+ };
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ As you can see, the code structure is completely consistent with business rules. Code is documentation, and logic is self-explanatory.
92
+
8
93
  ---
9
94
 
10
- ### **2. Features**
95
+ ## Features
11
96
 
12
- 1. **Logical Semantics**
13
- - `and`: All tasks must succeed (equivalent to native `Promise.all`)
14
- - `or`: At least one task succeeds (equivalent to native `Promise.any`)
15
- - `xor`: **Exactly one task succeeds**
16
- - `nand`: Not all tasks succeed (at least one fails)
17
- - `nor`: All tasks fail (no task succeeds)
18
- - `xnor`: All tasks succeed or all fail (same state)
19
- - `not`: Inverts the result of a single Promise
20
- - `majority`: Most tasks succeed
97
+ ### 1. Logical Semantics
21
98
 
22
- 2. **Zero Dependencies**
23
- Only depends on native Promise, no additional runtime dependencies.
99
+ - `and`: All tasks must succeed (equivalent to `Promise.all`)
100
+ - `or`: At least one task succeeds (equivalent to `Promise.any`)
101
+ - `xor`: **Exactly one task succeeds**
102
+ - `nand`: Not all tasks succeed (at least one fails)
103
+ - `nor`: All tasks fail (no task succeeds)
104
+ - `xnor`: All tasks succeed or all fail (same state)
105
+ - `not`: Inverts the result of a single Promise
106
+ - `majority`: Most tasks succeed
24
107
 
25
- 3. **Full Test Coverage**
26
- All logic gates have undergone rigorous unit testing to ensure behavior meets expectations.
108
+ ### 2. Zero Dependencies
27
109
 
28
- 4. **Clear Error Classification**
29
- - `PromiseLogicError` unified error type
30
- - `error.type` distinguishes specific logical errors (e.g., `'XOR_ERROR'`)
110
+ Only depends on native Promise, no additional runtime dependencies.
31
111
 
32
- 5. **Timeout Control**
33
- - `maxTimer`: Adds timeout functionality to any Promise operation (unit: milliseconds).
112
+ ### 3. Full Test Coverage
34
113
 
35
- **Note**:
36
- - After timeout, it immediately interrupts the execution of the current Promise chain and jumps to error handling
37
- - However, please note that this does not cancel underlying asynchronous operations that have already started (such as network requests, file read/write, etc.)
114
+ All logic gates have undergone rigorous unit testing to ensure behavior meets expectations.
38
115
 
39
- 6. **Extended Operations**
40
- - `allFulfilled`: Returns all successful results in order. Returns immediately when a result exists.
41
- - `allRejected`: Returns all failed results in order. Returns immediately when a result exists.
42
- - `allSettled`: Returns all results (both successful and failed)
116
+ ### 4. Clear Error Classification
117
+
118
+ - `PromiseLogicError` unified error type
119
+ - `error.type` distinguishes specific logical errors (e.g., `'XOR_ERROR'`)
120
+ - Supports custom error types and messages
121
+
122
+ ### 5. Timeout Control
123
+
124
+ - `maxTimer`: Adds timeout functionality to any Promise operation (unit: milliseconds)
125
+ - Supports custom timeout error messages
126
+
127
+ **Note**: After timeout, it immediately interrupts the execution of the current Promise chain and jumps to error handling, but does not cancel underlying asynchronous operations that have already started (such as network requests, file read/write, etc.).
128
+
129
+ ### 6. Extended Operations
130
+
131
+ - `allFulfilled`: Returns all successful results in order, immediately tries to return when there are successful results
132
+ - `allRejected`: Returns all failed results in order, immediately tries to return when there are failed results
133
+ - `allSettled`: Returns all results (both successful and failed)
43
134
 
44
135
  ---
45
136
 
46
- ### **3. Installation**
137
+ ## Installation
47
138
 
48
139
  ```bash
49
140
  npm install promise-logic
@@ -51,33 +142,33 @@ npm install promise-logic
51
142
 
52
143
  ---
53
144
 
54
- ### **4. Quick Start**
145
+ ## Quick Start
55
146
 
56
- #### Example: Primary/Backup Service Call (XOR Scenario)
147
+ ### Basic Usage Examples
148
+
149
+ #### Security Audit (XOR Scenario)
57
150
 
58
151
  ```javascript
59
152
  import { PromiseLogic } from 'promise-logic';
60
153
 
61
- // Primary service call
62
- const primary = fetch('https://api.main.com/data');
63
- // Backup service call
64
- const backup = fetch('https://api.backup.com/data');
65
-
66
154
  // Execute XOR logic: exactly one success
67
- PromiseLogic.xor([primary, backup])
155
+ PromiseLogic.xor([
156
+ biometricAuth(), // Biometric authentication
157
+ hardwareKeyAuth() // Hardware key authentication
158
+ ])
68
159
  .then((result) => {
69
- console.log('Successfully fetched data:', result);
160
+ console.log('Successfully authenticated:', result);
70
161
  })
71
162
  .catch((error) => {
72
163
  if (error.type === 'XOR_ERROR') {
73
- console.error('Both primary and backup services succeeded or failed, which does not meet XOR semantics');
164
+ console.error('Conflict between biometric and hardware key authentication');
74
165
  } else {
75
- console.error('Network error:', error);
166
+ console.error('Authentication error:', error);
76
167
  }
77
168
  });
78
169
  ```
79
170
 
80
- #### Example: Majority Decision (Majority Scenario)
171
+ #### Majority Decision (Majority Scenario)
81
172
 
82
173
  ```javascript
83
174
  import { PromiseLogic } from 'promise-logic';
@@ -88,35 +179,17 @@ const services = [
88
179
  fetch('https://api.node3.com/vote')
89
180
  ];
90
181
 
91
- PromiseLogic.majority(services)
182
+ // Custom threshold 0.6 (60%)
183
+ PromiseLogic.majority(services, { max: 0.6 })
92
184
  .then((results) => {
93
- console.log('Majority of services returned success:', results);
185
+ console.log('Custom threshold met, successful results:', results);
94
186
  })
95
187
  .catch((error) => {
96
- console.error('Majority of services failed:', error);
97
- });
98
- ```
99
-
100
- ```typescript
101
- import { PromiseLogic } from 'promise-logic/typescript';
102
-
103
- const services = [
104
- fetch('https://api.node1.com/vote'),
105
- fetch('https://api.node2.com/vote'),
106
- fetch('https://api.node3.com/vote')
107
- ];
108
-
109
- // Type assertion can be done, or let PromiseLogic infer types automatically
110
- PromiseLogic.majority<Response>(services)
111
- .then((results) => {
112
- console.log('Majority of services returned success:', results);
113
- })
114
- .catch((error) => {
115
- console.error('Majority of services failed:', error);
188
+ console.error('Custom threshold not met:', error);
116
189
  });
117
190
  ```
118
191
 
119
- #### Example: Timeout Control
192
+ #### Timeout Control
120
193
 
121
194
  ```javascript
122
195
  import { PromiseLogic } from 'promise-logic';
@@ -127,16 +200,16 @@ PromiseLogic.and([
127
200
  new Promise((resolve) => setTimeout(resolve, 3000)), // 3 second operation
128
201
  Promise.resolve(3)
129
202
  ])
130
- .maxTimer(2000, 'Custom timeout error: operation did not complete within 2000ms') // 2 second timeout, custom error message
203
+ .maxTimer(2000, 'Custom timeout error: operation did not complete within 2000ms') // 2 second timeout
131
204
  .then((result) => {
132
205
  console.log('Operation completed within timeout:', result);
133
206
  })
134
207
  .catch((error) => {
135
- console.error('Operation timed out:', error.message); // Output: Custom timeout error: operation did not complete within 2000ms
208
+ console.error('Operation timed out:', error.message);
136
209
  });
137
210
  ```
138
211
 
139
- #### Example: Extended Operations
212
+ #### Extended Operations
140
213
 
141
214
  ```javascript
142
215
  import { PromiseLogic } from 'promise-logic';
@@ -148,12 +221,12 @@ const operations = [
148
221
  Promise.reject('error2')
149
222
  ];
150
223
 
151
- // Get all successful results (returns immediately when a result exists)
224
+ // Get all successful results (returns immediately when there are successes)
152
225
  PromiseLogic.allFulfilled(operations).then((results) => {
153
226
  console.log('Successful results:', results); // ['success1', 'success2']
154
227
  });
155
228
 
156
- // Get all failed results (returns immediately when a result exists)
229
+ // Get all failed results (returns immediately when there are failures)
157
230
  PromiseLogic.allRejected(operations).then((errors) => {
158
231
  console.log('Failed results:', errors); // ['error1', 'error2']
159
232
  });
@@ -161,138 +234,44 @@ PromiseLogic.allRejected(operations).then((errors) => {
161
234
  // Get all results (both success and failure)
162
235
  PromiseLogic.allSettled(operations).then((results) => {
163
236
  console.log('All results:', results);
164
- // Output:
165
- // [
166
- // { status: 'fulfilled', value: 'success1' },
167
- // { status: 'rejected', reason: 'error1' },
168
- // { status: 'fulfilled', value: 'success2' },
169
- // { status: 'rejected', reason: 'error2' }
170
- // ]
171
237
  });
172
238
  ```
173
239
 
174
- #### Example: allFulfilled - Execution Timing and Results
175
-
176
- ```javascript
177
- import { PromiseLogic } from 'promise-logic';
178
240
 
179
- const startTime = Date.now();
180
- console.log('Start executing allFulfilled, time:', startTime);
181
-
182
- const allFulfilledResult = await PromiseLogic.allFulfilled([
183
- new Promise(resolve => {
184
- console.log('First Promise started (slow)');
185
- setTimeout(() => {
186
- console.log('First Promise completed:', 'success1');
187
- resolve('success1');
188
- }, 100);
189
- }),
190
- Promise.reject('error'),
191
- new Promise(resolve => {
192
- console.log('Third Promise started (fast)');
193
- setTimeout(() => {
194
- console.log('Third Promise completed:', 'success2');
195
- resolve('success2');
196
- }, 10);
197
- })
198
- ]);
199
-
200
- const endTime = Date.now();
201
- const elapsedTime = endTime - startTime;
202
- console.log('allFulfilled complete results:', allFulfilledResult); // ['success1', 'success2']
203
- ```
204
-
205
- **Explanation:**
206
- - **First return info**: Third Promise completes at 10ms, immediately returns `['success2']`
207
- - **Complete return info**: First Promise completes at 100ms, final complete result is `['success1', 'success2']`
208
- - **Execution timing**: Returns immediately when a result exists, does not wait for all Promises to complete
209
- - **Order preservation**: Complete results are returned in input order, not completion order
210
-
211
- #### Example: allRejected - Execution Timing and Results
241
+ ### Custom Error Types and Messages
212
242
 
213
243
  ```javascript
214
244
  import { PromiseLogic } from 'promise-logic';
215
245
 
216
- const startTime = Date.now();
217
- console.log('Start executing allRejected, time:', startTime);
218
-
219
- const allRejectedResult = await PromiseLogic.allRejected([
220
- Promise.resolve('success1'),
221
- new Promise((_, reject) => {
222
- console.log('Second Promise started (fast)');
223
- setTimeout(() => {
224
- console.log('Second Promise completed:', 'error1');
225
- reject('error1');
226
- }, 10);
227
- }),
228
- new Promise((_, reject) => {
229
- console.log('Third Promise started (slow)');
230
- setTimeout(() => {
231
- console.log('Third Promise completed:', 'error2');
232
- reject('error2');
233
- }, 100);
234
- })
235
- ]);
236
-
237
- const endTime = Date.now();
238
- const elapsedTime = endTime - startTime;
239
- console.log('allRejected complete results:', allRejectedResult); // ['error1', 'error2']
240
- ```
241
-
242
- **Explanation:**
243
- - **First return info**: Second Promise completes at 10ms, immediately returns `['error1']`
244
- - **Complete return info**: Third Promise completes at 100ms, final complete result is `['error1', 'error2']`
245
- - **Execution timing**: Returns immediately when a result exists, does not wait for all Promises to complete
246
- - **Order preservation**: Complete results are returned in input order, not completion order
247
-
248
- #### Example: Custom majority threshold
249
-
250
- ```javascript
251
- import { PromiseLogic } from 'promise-logic';
246
+ // Custom error type
247
+ const CUSTOM_ERROR_TYPE = 'CUSTOM_ERROR';
252
248
 
253
- const services = [
254
- Promise.resolve('service1'),
255
- Promise.resolve('service2'),
256
- Promise.reject('service3'),
257
- Promise.reject('service4')
258
- ];
249
+ // Custom error message
250
+ const CUSTOM_ERROR_MESSAGE = 'Custom error message';
259
251
 
260
- // Default threshold (0.5): requires at least 3 successes
261
- // Custom threshold (0.4): requires at least 2 successes
262
- PromiseLogic.majority(services, { max: 0.4 })
252
+ // Use custom error type and message
253
+ PromiseLogic.and([Promise.resolve('success1'), Promise.reject('error1')], {
254
+ errorType: CUSTOM_ERROR_TYPE,
255
+ errorMessage: CUSTOM_ERROR_MESSAGE
256
+ })
263
257
  .then((results) => {
264
- console.log('Custom threshold met, successful results:', results); // ['service1', 'service2']
258
+ console.log(results);
265
259
  })
266
260
  .catch((error) => {
267
- console.error('Custom threshold not met:', error);
261
+ if (error.type === CUSTOM_ERROR_TYPE) {
262
+ console.error(error); // Output: Custom error message
263
+ } else {
264
+ console.error(error);
265
+ }
268
266
  });
269
267
  ```
270
268
 
271
- ## Recent Updates
272
-
273
- ### v2.8.0
274
-
275
- - **Performance optimization**: Optimized `allFulfilled` and `allRejected` implementation logic from the bottom layer, existing results return immediately while maintaining consistent input and output order
276
- - **Added chain timeout control with custom error messages**: Can customize timeout error messages in the `maxTimer` method
277
- - **Type fixes**: Fixed TypeScript version type declaration issues
278
- - **Test completion**: Added complete test cases for `allFulfilled`, `allRejected`, and `maxTimer`
279
- - **Code refactoring**: Improved code structure for better maintainability
280
-
281
- ### v2.7.0
282
-
283
- - **Added modular architecture**: Separated logic gate implementations into independent modules for better code maintainability
284
- - **Fixed NOT Logic Gate**: Fixed potential risks in NOT logic gate in production environments
285
- - **Improved Error Messages**: Enhanced error message format for clearer error details
286
- - **Enhanced Test Coverage**: Added complete factory function tests for v1 and v2 versions
287
- - **Updated Documentation**: Added custom factory function usage guide
288
-
289
-
290
269
  ### Using Factory Function
291
270
 
292
271
  The factory function allows you to create PromiseLogic methods with custom names:
293
272
 
294
273
  ```javascript
295
- import { createPromiseLogic } from 'promise-logic/factory';
274
+ import { createPromiseLogic } from 'promise-logic';
296
275
 
297
276
  // Create instance with custom naming
298
277
  const logic = createPromiseLogic({
@@ -307,7 +286,6 @@ const logic = createPromiseLogic({
307
286
 
308
287
  // Use custom-named methods
309
288
  logic.api_all_call([fetch('/api/users'), fetch('/api/posts')]);
310
-
311
289
  logic.api_any_call([fetch('/api/cache'), fetch('/api/database')]);
312
290
  ```
313
291
 
@@ -327,9 +305,30 @@ PromiseLogic.and([Promise.resolve(1), Promise.resolve(2)]).then(
327
305
  PromiseLogic.and<number>([Promise.resolve(1), Promise.resolve(2)]);
328
306
  ```
329
307
 
308
+ ### Dynamic Logic Nested
309
+
310
+ ```javascript
311
+ import { PromiseLogic } from 'promise-logic';
312
+
313
+
314
+ // Dynamic nesting example: adjust logistics strategy based on user level
315
+ const orderFlow = async (userLevel) => {
316
+ // VIP users: dual high-availability logistics guarantee (at least one success)
317
+ // Normal users: priority standard logistics, failover to economy logistics (at least one success)
318
+ const logisticsStrategy = userLevel === 'VIP'
319
+ ? PromiseLogic.or([premiumLogistics(), backupLogistics()])
320
+ : PromiseLogic.or([standardLogistics(), economyLogistics()]);
321
+
322
+ return await PromiseLogic.and([
323
+ PromiseLogic.and([paymentAPI(), inventoryAPI()]), // Payment + inventory atomic operations
324
+ logisticsStrategy, // Logistics strategy
325
+ couponValidation() // Coupon validation
326
+ ]);
327
+ };
328
+ ```
330
329
  ---
331
330
 
332
- ### **5. API Reference**
331
+ ## API Reference
333
332
 
334
333
  | API | Description |
335
334
  | :------------- | :--------------------------------------------------------------------------------------------------------------------------- |
@@ -347,62 +346,54 @@ PromiseLogic.and<number>([Promise.resolve(1), Promise.resolve(2)]);
347
346
  | `race` | Returns the first completed Promise result (regardless of success or failure). Equivalent to native `Promise.race`. |
348
347
  | `maxTimer` | Adds timeout functionality to any Promise operation (unit: milliseconds). Supports custom timeout error messages. |
349
348
 
349
+ ---
350
350
 
351
- ### **6. Real-world Application Scenarios**
351
+ ## Changelog
352
352
 
353
- 1. **Primary/Backup Service Calls**
354
- - Use `xor` to ensure **exactly one service responds**, avoiding duplicate processing.
353
+ ### v2.9.0
355
354
 
356
- 2. **Distributed Decision Making**
357
- - Use `majority` to implement majority consensus (e.g., distributed voting).
355
+ **Error Mechanism Improvements**
356
+ - Added `errorType` and `errorMessage` parameters to logic gates, supporting custom error types and messages, further fitting business scenarios
357
+ - Optimized the existing error type system to ensure correct TypeScript type definitions
358
+ - Optimized TypeScript type compatibility issues
359
+ - Optimized allSettled gate return type error messages
360
+ - Improved test scripts, covering most promise combination logic boundaries and tricky scenario issues, ensuring more stable operation of logic gates
361
+ - Optimized logic gate execution efficiency, reducing unnecessary Promise wrapping
358
362
 
359
- 3. **Resource Competition**
360
- - Use `or` to get the first available resource (e.g., CDN node selection).
361
- - Use `not` to check if a resource is available.
363
+ ### v2.8.0
362
364
 
363
- 4. **Full-link Validation**
364
- - Use `and` to ensure all dependent services succeed (e.g., order creation).
365
+ - **Performance optimization**: Optimized `allFulfilled` and `allRejected` implementation logic from the bottom layer, existing results return immediately while maintaining consistent input and output order
366
+ - **Added chain timeout control with custom error messages**: Can customize timeout error messages in the `maxTimer` method
367
+ - **Type fixes**: Fixed TypeScript version type declaration issues
368
+ - **Test completion**: Added complete test cases for `allFulfilled`, `allRejected`, and `maxTimer`
369
+ - **Code refactoring**: Improved code structure for better maintainability
365
370
 
366
- 5. **Timeout Control**
367
- - Use `maxTimer` to add timeout functionality to any Promise operation (unit: milliseconds).
368
- - Returns custom error message after timeout, default: `Promise timed out after ${ms} ms`.
371
+ ---
369
372
 
370
- 6. **Partial Success Handling**
371
- - Use `allFulfilled` to execute all Promises concurrently and return successful result array (e.g., batch API calls, suitable for high concurrency and partial failure acceptance scenarios).
372
- - Use `allRejected` to execute all Promises concurrently and return failed result array (e.g., error log collection, suitable for batch failure processing scenarios).
373
+ ## Contribution Guide
373
374
 
374
- 7. **Full Result Retrieval**
375
- - Use `allSettled` to get results from all Promises (regardless of success or failure).
375
+ ### 1. Development Environment
376
376
 
377
- 8. **Fast Response**
378
- - Use `race` to return the first completed Promise result (regardless of success or failure).
377
+ ```bash
378
+ git clone https://github.com/xier123456/promise-logic.git
379
+ cd promise-logic
380
+ npm install
381
+ ```
379
382
 
380
- 9. **State Validation**
381
- - Use `nand` to verify that not all Promises succeed (at least one fails).
382
- - Use `nor` to verify that all Promises fail (no task succeeds).
383
- - Use `xnor` to verify that all Promises succeed or all fail (same state).
383
+ ### 2. Testing
384
384
 
385
- ---
385
+ ```bash
386
+ npm test
387
+ ```
388
+
389
+ ### 3. Commit Guidelines
386
390
 
387
- ### **7. Contribution Guide**
388
-
389
- 1. **Development Environment**
390
- ```bash
391
- git clone https://github.com/xier123456/promise-logic.git
392
- cd promise-logic
393
- npm install
394
- ```
395
- 2. **Testing**
396
- ```bash
397
- npm test
398
- ```
399
- 3. **Commit Guidelines**
400
- - Commit messages must include prefixes like `feat:` (new feature), `fix:` (bug fix), `docs:` (documentation).
401
- - Pull Requests must include test cases.
391
+ - Commit messages must include prefixes like `feat:` (new feature), `fix:` (bug fix), `docs:` (documentation).
392
+ - Pull Requests must include test cases.
402
393
 
403
394
  ---
404
395
 
405
- ### **8. Resource Links**
396
+ ## Resource Links
406
397
 
407
398
  - **GitHub Repository**: [https://github.com/xier123456/promise-logic](https://github.com/xier123456/promise-logic)
408
399
  - **npm Package**: [https://www.npmjs.com/package/promise-logic](https://www.npmjs.com/package/promise-logic)
@@ -1 +1 @@
1
- "use strict";class e extends Error{constructor(e,t,r){super(t),this.name="PromiseLogicError",this.type=e,this.results=r}}function t(t,r,l,n,s){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${r} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${l} promises fulfilled (expected at least one rejection).`,NOT_ERROR:"NOT condition failed: promise resolved (expected rejection).",NOR_ERROR:`NOR condition failed: ${r} promises fulfilled (expected all rejected).`,MAJORITY_ERROR:`Majority condition failed: ${r}/${l} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${r}/${l} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${l-r}/${l} promises rejected (expected all to fail).`}[t],a=s.length>0?`\n失败原因:${s.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class l extends r{async execute(e,r={}){try{return await Promise.all(e)}catch(r){throw t("AND_ERROR",0,e.length,[...e],r)}}}class n extends r{async execute(e,r={}){try{return await Promise.any(e)}catch(r){throw t("OR_ERROR",0,e.length,[],r)}}}class s extends r{async execute(e,r={}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=this.filterRejectedResults(l),i=n.length,a=l.length;if(1===i)return n[0];throw t("XOR_ERROR",i,a,l,s)}}class i extends r{async execute(e,r={}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(s===i)throw t("NAND_ERROR",s,i,l,n);return n}}class a extends r{async execute(e,r={}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(0===s)return[];throw t("NOR_ERROR",s,i,l,n)}}class o extends r{async execute(e,r={}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(0===s||s===i)return n;throw t("XNOR_ERROR",s,i,l,n)}}class c extends r{async execute(e,r={max:.5}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(s>Math.floor(i*r.max))return n;throw t("MAJORITY_ERROR",s,i,l)}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(e=>{n++,r[s]=e}).catch(()=>{r[s]=void 0}).finally(()=>{l++,n>0?t(r.filter(e=>void 0!==e)):l===i&&t([])})}):t(r)})}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(()=>{r[s]=void 0}).catch(e=>{n++,r[s]=e}).finally(()=>{l++,n>0?t(r.filter(e=>void 0!==e)):l===i&&t([])})}):t(r)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((l,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class h{static get gates(){return{and:new l,or:new n,xor:new s,nand:new i,nor:new a,xnor:new o,majority:new c,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e).then(e=>Promise.resolve(e)))}static allSettled(e){return new f(Promise.allSettled(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,l=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),l=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(l=new Promise(e=>{r=e})),l),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const l=()=>{t===e?r(t):this.waitForChange().then(l)};l()})}}}}exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:l={}}=e,n={and:h.and.bind(h),or:h.or.bind(h),race:h.race.bind(h),allSettled:h.allSettled.bind(h),xor:h.xor.bind(h),not:h.not.bind(h),nand:h.nand.bind(h),nor:h.nor.bind(h),xnor:h.xnor.bind(h),majority:h.majority.bind(h),allFulfilled:h.allFulfilled.bind(h),allRejected:h.allRejected.bind(h)},s={};return Object.entries(n).forEach(([e,n])=>{const i=l[e]||e;s[`${t}${i}${r}`]=n}),s};
1
+ "use strict";class e extends Error{constructor(e,t,r,s){super(t),this.name="PromiseLogicError",this.type=e,this.results=r,this.errors=s}}function t(t,r,s,n){return new e(t,r,s,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"AND condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class n extends r{async execute(e,r){try{return await Promise.any(e)}catch(e){const s=r.errorMessage||"OR condition failed: all promises rejected.";throw t(r.errorType,s,[],[e])}}}class l extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=this.filterRejectedResults(s),a=n.length,i=s.length;if(1===a)return n[0];{const e=r.errorMessage||(a>1?`XOR condition failed: ${a} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType,e,s,l)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l===a){const e=r.errorMessage||`NAND condition failed: ${l}/${a} fulfilled (need not majority)`;throw t(r.errorType,e,s,n)}return n}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length;if(0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType,e,s,n)}}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===l||l===a)return n;{const e=r.errorMessage||`XNOR condition failed: ${l}/${a} promises fulfilled (expected all or none)`;throw t(r.errorType,e,s,n)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l>Math.floor(a*r.max))return n;{const e=r.errorMessage||`MAJORITY condition failed: ${l}/${a} fulfilled (need majority)`;throw t(r.errorType,e,s,n)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).catch(()=>{}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class h extends r{async execute(e,r){try{return await Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e))}catch(e){throw t(r.errorType,r.errorMessage||"NOT condition failed",[],e)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class m extends r{async execute(e,r){if(0!==e.length)try{return await Promise.race(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType,l,n,s)}}}class w{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((s,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new w(this.promise.then(e,t))}catch(e){return new w(this.promise.catch(e))}finally(e){return new w(this.promise.finally(e))}toPromise(){return this.promise}}class x{static get gates(){return{and:new s,or:new n,xor:new l,nand:new a,nor:new i,xnor:new o,not:new h,race:new m,allSettled:new f,majority:new c,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new w(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new w(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new w(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new w(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new w(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new w(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new w(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new w(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new w(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new w(this.gates.majority.execute(e,t))}static allFulfilled(e){return new w(this.gates.allFulfilled.execute(e))}static allRejected(e){return new w(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,n={and:x.and.bind(x),or:x.or.bind(x),race:x.race.bind(x),allSettled:x.allSettled.bind(x),xor:x.xor.bind(x),not:x.not.bind(x),nand:x.nand.bind(x),nor:x.nor.bind(x),xnor:x.xnor.bind(x),majority:x.majority.bind(x),allFulfilled:x.allFulfilled.bind(x),allRejected:x.allRejected.bind(x)},l={};return Object.entries(n).forEach(([e,n])=>{const a=s[e]||e;l[`${t}${a}${r}`]=n}),l};
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,l){super(t),this.name="PromiseLogicError",this.type=e,this.results=l}}function t(t,l,r,n,s){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOT_ERROR:"NOT condition failed: promise resolved (expected rejection).",NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-l}/${r} promises rejected (expected all to fail).`}[t],a=s.length>0?`\n失败原因:${s.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,n)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class r extends l{async execute(e,l={}){try{return await Promise.all(e)}catch(l){throw t("AND_ERROR",0,e.length,[...e],l)}}}class n extends l{async execute(e,l={}){try{return await Promise.any(e)}catch(l){throw t("OR_ERROR",0,e.length,[],l)}}}class s extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=this.filterRejectedResults(r),i=n.length,a=r.length;if(1===i)return n[0];throw t("XOR_ERROR",i,a,r,s)}}class i extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(s===i)throw t("NAND_ERROR",s,i,r,n);return n}}class a extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(0===s)return[];throw t("NOR_ERROR",s,i,r,n)}}class o extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(0===s||s===i)return n;throw t("XNOR_ERROR",s,i,r,n)}}class c extends l{async execute(e,l={max:.5}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(s>Math.floor(i*l.max))return n;throw t("MAJORITY_ERROR",s,i,r)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(e=>{n++,l[s]=e}).catch(()=>{l[s]=void 0}).finally(()=>{r++,n>0?t(l.filter(e=>void 0!==e)):r===i&&t([])})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(()=>{l[s]=void 0}).catch(e=>{n++,l[s]=e}).finally(()=>{r++,n>0?t(l.filter(e=>void 0!==e)):r===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((r,n)=>{l=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class h{static get gates(){return{and:new r,or:new n,xor:new s,nand:new i,nor:new a,xnor:new o,majority:new c,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e).then(e=>Promise.resolve(e)))}static allSettled(e){return new f(Promise.allSettled(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,l=null,r=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,l&&(l(t),l=null),r=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(l||(r=new Promise(e=>{l=e})),r),waitFor(e){return t===e?Promise.resolve(t):new Promise(l=>{const r=()=>{t===e?l(t):this.waitForChange().then(r)};r()})}}}}function R(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,n={and:h.and.bind(h),or:h.or.bind(h),race:h.race.bind(h),allSettled:h.allSettled.bind(h),xor:h.xor.bind(h),not:h.not.bind(h),nand:h.nand.bind(h),nor:h.nor.bind(h),xnor:h.xnor.bind(h),majority:h.majority.bind(h),allFulfilled:h.allFulfilled.bind(h),allRejected:h.allRejected.bind(h)},s={};return Object.entries(n).forEach(([e,n])=>{const i=r[e]||e;s[`${t}${i}${l}`]=n}),s}export{R as createPromiseLogic};
1
+ class e extends Error{constructor(e,t,r,s){super(t),this.name="PromiseLogicError",this.type=e,this.results=r,this.errors=s}}function t(t,r,s,n){return new e(t,r,s,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"AND condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class n extends r{async execute(e,r){try{return await Promise.any(e)}catch(e){const s=r.errorMessage||"OR condition failed: all promises rejected.";throw t(r.errorType,s,[],[e])}}}class l extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=this.filterRejectedResults(s),a=n.length,o=s.length;if(1===a)return n[0];{const e=r.errorMessage||(a>1?`XOR condition failed: ${a} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${o} promises rejected (expected exactly 1)`);throw t(r.errorType,e,s,l)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l===a){const e=r.errorMessage||`NAND condition failed: ${l}/${a} fulfilled (need not majority)`;throw t(r.errorType,e,s,n)}return n}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length;if(0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType,e,s,n)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===l||l===a)return n;{const e=r.errorMessage||`XNOR condition failed: ${l}/${a} promises fulfilled (expected all or none)`;throw t(r.errorType,e,s,n)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l>Math.floor(a*r.max))return n;{const e=r.errorMessage||`MAJORITY condition failed: ${l}/${a} fulfilled (need majority)`;throw t(r.errorType,e,s,n)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).catch(()=>{}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class h extends r{async execute(e,r){try{return await Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e))}catch(e){throw t(r.errorType,r.errorMessage||"NOT condition failed",[],e)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class m extends r{async execute(e,r){if(0!==e.length)try{return await Promise.race(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType,l,n,s)}}}class w{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((s,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new w(this.promise.then(e,t))}catch(e){return new w(this.promise.catch(e))}finally(e){return new w(this.promise.finally(e))}toPromise(){return this.promise}}class x{static get gates(){return{and:new s,or:new n,xor:new l,nand:new a,nor:new o,xnor:new i,not:new h,race:new m,allSettled:new f,majority:new c,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new w(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new w(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new w(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new w(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new w(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new w(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new w(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new w(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new w(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new w(this.gates.majority.execute(e,t))}static allFulfilled(e){return new w(this.gates.allFulfilled.execute(e))}static allRejected(e){return new w(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}function R(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,n={and:x.and.bind(x),or:x.or.bind(x),race:x.race.bind(x),allSettled:x.allSettled.bind(x),xor:x.xor.bind(x),not:x.not.bind(x),nand:x.nand.bind(x),nor:x.nor.bind(x),xnor:x.xnor.bind(x),majority:x.majority.bind(x),allFulfilled:x.allFulfilled.bind(x),allRejected:x.allRejected.bind(x)},l={};return Object.entries(n).forEach(([e,n])=>{const a=s[e]||e;l[`${t}${a}${r}`]=n}),l}export{R as createPromiseLogic};
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";class e extends Error{constructor(e,t,r){super(t),this.name="PromiseLogicError",this.type=e,this.results=r}}function t(t,r,l,s,n){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${r} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${l} promises fulfilled (expected at least one rejection).`,NOT_ERROR:"NOT condition failed: promise resolved (expected rejection).",NOR_ERROR:`NOR condition failed: ${r} promises fulfilled (expected all rejected).`,MAJORITY_ERROR:`Majority condition failed: ${r}/${l} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${r}/${l} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${l-r}/${l} promises rejected (expected all to fail).`}[t],o=n.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+o,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class l extends r{async execute(e,r={}){try{return await Promise.all(e)}catch(r){throw t("AND_ERROR",0,e.length,[...e],r)}}}class s extends r{async execute(e,r={}){try{return await Promise.any(e)}catch(r){throw t("OR_ERROR",0,e.length,[],r)}}}class n extends r{async execute(e,r={}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=this.filterRejectedResults(l),i=s.length,o=l.length;if(1===i)return s[0];throw t("XOR_ERROR",i,o,l,n)}}class i extends r{async execute(e,r={}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=s.length,i=l.length;if(n===i)throw t("NAND_ERROR",n,i,l,s);return s}}class o extends r{async execute(e,r={}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=s.length,i=l.length;if(0===n)return[];throw t("NOR_ERROR",n,i,l,s)}}class a extends r{async execute(e,r={}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=s.length,i=l.length;if(0===n||n===i)return s;throw t("XNOR_ERROR",n,i,l,s)}}class c extends r{async execute(e,r={max:.5}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=s.length,i=l.length;if(n>Math.floor(i*r.max))return s;throw t("MAJORITY_ERROR",n,i,l)}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0,s=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{s++,r[n]=e}).catch(()=>{r[n]=void 0}).finally(()=>{l++,s>0?t(r.filter(e=>void 0!==e)):l===i&&t([])})}):t(r)})}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0,s=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{r[n]=void 0}).catch(e=>{s++,r[n]=e}).finally(()=>{l++,s>0?t(r.filter(e=>void 0!==e)):l===i&&t([])})}):t(r)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((l,s)=>{r=setTimeout(()=>{s(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class h{static get gates(){return{and:new l,or:new s,xor:new n,nand:new i,nor:new o,xnor:new a,majority:new c,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e).then(e=>Promise.resolve(e)))}static allSettled(e){return new f(Promise.allSettled(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,l=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),l=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(l=new Promise(e=>{r=e})),l),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const l=()=>{t===e?r(t):this.waitForChange().then(l)};l()})}}}}exports.PromiseLogic=h,exports.PromiseLogicError=e,exports.PromiseWithTimer=f,exports.createLogicError=t,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:l={}}=e,s={and:h.and.bind(h),or:h.or.bind(h),race:h.race.bind(h),allSettled:h.allSettled.bind(h),xor:h.xor.bind(h),not:h.not.bind(h),nand:h.nand.bind(h),nor:h.nor.bind(h),xnor:h.xnor.bind(h),majority:h.majority.bind(h),allFulfilled:h.allFulfilled.bind(h),allRejected:h.allRejected.bind(h)},n={};return Object.entries(s).forEach(([e,s])=>{const i=l[e]||e;n[`${t}${i}${r}`]=s}),n};
1
+ "use strict";class e extends Error{constructor(e,t,r,s){super(t),this.name="PromiseLogicError",this.type=e,this.results=r,this.errors=s}}function t(t,r,s,n){return new e(t,r,s,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"AND condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class n extends r{async execute(e,r){try{return await Promise.any(e)}catch(e){const s=r.errorMessage||"OR condition failed: all promises rejected.";throw t(r.errorType,s,[],[e])}}}class l extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=this.filterRejectedResults(s),o=n.length,i=s.length;if(1===o)return n[0];{const e=r.errorMessage||(o>1?`XOR condition failed: ${o} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType,e,s,l)}}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,o=s.length;if(0===o)return[];if(l===o){const e=r.errorMessage||`NAND condition failed: ${l}/${o} fulfilled (need not majority)`;throw t(r.errorType,e,s,n)}return n}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length;if(0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType,e,s,n)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,o=s.length;if(0===l||l===o)return n;{const e=r.errorMessage||`XNOR condition failed: ${l}/${o} promises fulfilled (expected all or none)`;throw t(r.errorType,e,s,n)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,o=s.length;if(0===o)return[];if(l>Math.floor(o*r.max))return n;{const e=r.errorMessage||`MAJORITY condition failed: ${l}/${o} fulfilled (need majority)`;throw t(r.errorType,e,s,n)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let o=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,o=!0,t(r.filter(Boolean))}).catch(()=>{}).finally(()=>{s++,s!==l||o||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let o=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,o=!0,t(r.filter(Boolean))}).finally(()=>{s++,s!==l||o||t([])})}):t([])})}}class h extends r{async execute(e,r){try{return await Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e))}catch(e){throw t(r.errorType,r.errorMessage||"NOT condition failed",[],e)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class m extends r{async execute(e,r){if(0!==e.length)try{return await Promise.race(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType,l,n,s)}}}class x{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((s,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new x(this.promise.then(e,t))}catch(e){return new x(this.promise.catch(e))}finally(e){return new x(this.promise.finally(e))}toPromise(){return this.promise}}class w{static get gates(){return{and:new s,or:new n,xor:new l,nand:new o,nor:new i,xnor:new a,not:new h,race:new m,allSettled:new f,majority:new c,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new x(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new x(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new x(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new x(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new x(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new x(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new x(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new x(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new x(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new x(this.gates.majority.execute(e,t))}static allFulfilled(e){return new x(this.gates.allFulfilled.execute(e))}static allRejected(e){return new x(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}exports.PromiseLogic=w,exports.PromiseLogicError=e,exports.PromiseWithTimer=x,exports.createLogicError=t,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,n={and:w.and.bind(w),or:w.or.bind(w),race:w.race.bind(w),allSettled:w.allSettled.bind(w),xor:w.xor.bind(w),not:w.not.bind(w),nand:w.nand.bind(w),nor:w.nor.bind(w),xnor:w.xnor.bind(w),majority:w.majority.bind(w),allFulfilled:w.allFulfilled.bind(w),allRejected:w.allRejected.bind(w)},l={};return Object.entries(n).forEach(([e,n])=>{const o=s[e]||e;l[`${t}${o}${r}`]=n}),l};
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,l){super(t),this.name="PromiseLogicError",this.type=e,this.results=l}}function t(t,l,r,n,s){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOT_ERROR:"NOT condition failed: promise resolved (expected rejection).",NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-l}/${r} promises rejected (expected all to fail).`}[t],a=s.length>0?`\n失败原因:${s.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,n)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class r extends l{async execute(e,l={}){try{return await Promise.all(e)}catch(l){throw t("AND_ERROR",0,e.length,[...e],l)}}}class n extends l{async execute(e,l={}){try{return await Promise.any(e)}catch(l){throw t("OR_ERROR",0,e.length,[],l)}}}class s extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=this.filterRejectedResults(r),i=n.length,a=r.length;if(1===i)return n[0];throw t("XOR_ERROR",i,a,r,s)}}class i extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(s===i)throw t("NAND_ERROR",s,i,r,n);return n}}class a extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(0===s)return[];throw t("NOR_ERROR",s,i,r,n)}}class o extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(0===s||s===i)return n;throw t("XNOR_ERROR",s,i,r,n)}}class c extends l{async execute(e,l={max:.5}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(s>Math.floor(i*l.max))return n;throw t("MAJORITY_ERROR",s,i,r)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(e=>{n++,l[s]=e}).catch(()=>{l[s]=void 0}).finally(()=>{r++,n>0?t(l.filter(e=>void 0!==e)):r===i&&t([])})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(()=>{l[s]=void 0}).catch(e=>{n++,l[s]=e}).finally(()=>{r++,n>0?t(l.filter(e=>void 0!==e)):r===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((r,n)=>{l=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class h{static get gates(){return{and:new r,or:new n,xor:new s,nand:new i,nor:new a,xnor:new o,majority:new c,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e).then(e=>Promise.resolve(e)))}static allSettled(e){return new f(Promise.allSettled(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,l=null,r=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,l&&(l(t),l=null),r=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(l||(r=new Promise(e=>{l=e})),r),waitFor(e){return t===e?Promise.resolve(t):new Promise(l=>{const r=()=>{t===e?l(t):this.waitForChange().then(r)};r()})}}}}function R(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,n={and:h.and.bind(h),or:h.or.bind(h),race:h.race.bind(h),allSettled:h.allSettled.bind(h),xor:h.xor.bind(h),not:h.not.bind(h),nand:h.nand.bind(h),nor:h.nor.bind(h),xnor:h.xnor.bind(h),majority:h.majority.bind(h),allFulfilled:h.allFulfilled.bind(h),allRejected:h.allRejected.bind(h)},s={};return Object.entries(n).forEach(([e,n])=>{const i=r[e]||e;s[`${t}${i}${l}`]=n}),s}export{h as PromiseLogic,e as PromiseLogicError,f as PromiseWithTimer,t as createLogicError,R as createPromiseLogic};
1
+ class e extends Error{constructor(e,t,r,s){super(t),this.name="PromiseLogicError",this.type=e,this.results=r,this.errors=s}}function t(t,r,s,n){return new e(t,r,s,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"AND condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class n extends r{async execute(e,r){try{return await Promise.any(e)}catch(e){const s=r.errorMessage||"OR condition failed: all promises rejected.";throw t(r.errorType,s,[],[e])}}}class l extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=this.filterRejectedResults(s),a=n.length,o=s.length;if(1===a)return n[0];{const e=r.errorMessage||(a>1?`XOR condition failed: ${a} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${o} promises rejected (expected exactly 1)`);throw t(r.errorType,e,s,l)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l===a){const e=r.errorMessage||`NAND condition failed: ${l}/${a} fulfilled (need not majority)`;throw t(r.errorType,e,s,n)}return n}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length;if(0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType,e,s,n)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===l||l===a)return n;{const e=r.errorMessage||`XNOR condition failed: ${l}/${a} promises fulfilled (expected all or none)`;throw t(r.errorType,e,s,n)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l>Math.floor(a*r.max))return n;{const e=r.errorMessage||`MAJORITY condition failed: ${l}/${a} fulfilled (need majority)`;throw t(r.errorType,e,s,n)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).catch(()=>{}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class h extends r{async execute(e,r){try{return await Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e))}catch(e){throw t(r.errorType,r.errorMessage||"NOT condition failed",[],e)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class m extends r{async execute(e,r){if(0!==e.length)try{return await Promise.race(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType,l,n,s)}}}class w{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((s,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new w(this.promise.then(e,t))}catch(e){return new w(this.promise.catch(e))}finally(e){return new w(this.promise.finally(e))}toPromise(){return this.promise}}class x{static get gates(){return{and:new s,or:new n,xor:new l,nand:new a,nor:new o,xnor:new i,not:new h,race:new m,allSettled:new f,majority:new c,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new w(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new w(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new w(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new w(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new w(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new w(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new w(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new w(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new w(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new w(this.gates.majority.execute(e,t))}static allFulfilled(e){return new w(this.gates.allFulfilled.execute(e))}static allRejected(e){return new w(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}function R(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,n={and:x.and.bind(x),or:x.or.bind(x),race:x.race.bind(x),allSettled:x.allSettled.bind(x),xor:x.xor.bind(x),not:x.not.bind(x),nand:x.nand.bind(x),nor:x.nor.bind(x),xnor:x.xnor.bind(x),majority:x.majority.bind(x),allFulfilled:x.allFulfilled.bind(x),allRejected:x.allRejected.bind(x)},l={};return Object.entries(n).forEach(([e,n])=>{const a=s[e]||e;l[`${t}${a}${r}`]=n}),l}export{x as PromiseLogic,e as PromiseLogicError,w as PromiseWithTimer,t as createLogicError,R as createPromiseLogic};
@@ -22,7 +22,7 @@ declare class PromiseLogic {
22
22
  static and<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
23
23
  static or<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
24
24
  static race<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
25
- static not<T>(promise: T | PromiseLike<T>): PromiseWithTimer<unknown>;
25
+ static not<T>(promise: T | PromiseLike<T>): PromiseWithTimer<T>;
26
26
  static allSettled<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<PromiseSettledResult<T>[]>;
27
27
 
28
28
  static xor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
@@ -32,7 +32,7 @@ declare class PromiseLogic {
32
32
  static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?: { max: number }): PromiseWithTimer<T[]>;
33
33
 
34
34
  static allFulfilled<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
35
- static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<unknown[]>;
35
+ static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<Error[]>;
36
36
 
37
37
  static createFlipFlop(initialState?: boolean): FlipFlop;
38
38
  }
@@ -1 +1 @@
1
- "use strict";class e extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function t(t,l,s,r,n){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${s} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${l}/${s} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${s} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${s} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${s-l}/${s} promises rejected (expected all to fail).`}[t]||"Logic condition failed",a=n&&n?.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,r)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends l{async execute(e){try{return Promise.any(e)}catch(e){throw t("OR_ERROR",0,0,[],[e])}}}class r extends l{async execute(e){try{return Promise.all(e)}catch(e){throw t("AND_ERROR",0,0,[],[e])}}}class n extends l{async execute(e,l){const s=await Promise.allSettled(e),r=this.filterFulfilledResults(s),n=r.length,i=s.length,a=this.filterRejectedResults(s);if(n>Math.floor(i*l.max))return r;throw t("MAJORITY_ERROR",n,i,s,a)}}class i extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(r===n)throw t("NAND_ERROR",r,n,l,i);return s}}class a extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l).length,r=l.length,n=this.filterRejectedResults(l);if(0===s)return[];throw t("NOR_ERROR",s,r,l,n)}}class o extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(0===r||r===n)return s;throw t("XNOR_ERROR",r,n,l,i)}}class c extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(1===r)return s[0];throw t("XOR_ERROR",r,n,l,i)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class d extends l{async execute(e){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((s,r)=>{l=setTimeout(()=>{r(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class R{static get gates(){return{and:new r,or:new s,xor:new c,nand:new i,nor:new a,xnor:new o,majority:new n,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e))}static allSettled(e){return new f(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,s=Promise.resolve(t);const r=()=>(l||(s=new Promise(e=>{l=e})),s);return{getState:()=>t,set:async e=>(t=e,l&&(l(t),l=null),s=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:r,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const s=()=>{t===e?l(t):r().then(s)};s()})}}}exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:l="",rename:s={}}=e,r={and:R.and.bind(R),or:R.or.bind(R),not:R.not.bind(R),race:R.race.bind(R),allSettled:R.allSettled.bind(R),xor:R.xor.bind(R),nand:R.nand.bind(R),nor:R.nor.bind(R),xnor:R.xnor.bind(R),majority:R.majority.bind(R),allFulfilled:R.allFulfilled.bind(R),allRejected:R.allRejected.bind(R)},n={};return Object.entries(r).forEach(([e,r])=>{const i=s[e]||e;n[`${t}${i}${l}`]=r}),n};
1
+ "use strict";class e extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function t(t,r,s,l){return new e(t,r,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.any(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"OR condition failed";throw t(r.errorType||"OR_ERROR",n,l)}}}class l extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"AND condition failed";throw t(r.errorType||"AND_ERROR",n,l)}}}class n extends r{async execute(e,r){const s=r.max||.5,l=await Promise.allSettled(e),n=l.length;if(0===n)return[];const i=this.filterFulfilledResults(l),o=i.length;if(this.filterRejectedResults(l),o>Math.floor(n*s))return i;{const e=r.errorMessage||`Majority condition failed: ${o}/${n} fulfilled (need majority)`;throw t(r.errorType||"MAJORITY_ERROR",e,l)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),n===i){const e=r.errorMessage||`NAND condition failed: all ${i} promises fulfilled (expected at least one rejection)`;throw t(r.errorType||"NAND_ERROR",e,s)}return l}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s).length;if(s.length,this.filterRejectedResults(s),0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType||"NOR_ERROR",e,s)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),0===n||n===i)return l;{const e=r.errorMessage||`XNOR condition failed: ${n}/${i} promises fulfilled (expected all or none)`;throw t(r.errorType||"XNOR_ERROR",e,s)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),1===n)return l[0];{const e=r.errorMessage||(n>1?`XOR condition failed: ${n} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType||"XOR_ERROR",e,s)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).catch(()=>{}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class R extends r{async execute(e,r={}){let s;if("function"==typeof e[Symbol.iterator]){const l=[...e];if(0===l.length)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate requires exactly one promise",[]);if(l.length>1)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate only accepts one promise",[]);s=l[0]}else s=e;return Promise.resolve(s).then(e=>{throw t(r.errorType||"NOT_ERROR",r.errorMessage||`NOT condition failed: ${e}`,[])},e=>e)}}class f extends r{async execute(e,r){if(0===Array.from(e).length)return{};try{return await Promise.race(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType||"RACE_ERROR",n,l)}}}class h extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType||"ALL_SETTLED_ERROR",n,l)}}}class m{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;const s=Promise.race([this.promise,new Promise((s,l)=>{r=setTimeout(()=>{l(new Error(t))},e)})]).finally(()=>clearTimeout(r));return new m(s)}then(e,t){return new m(this.promise.then(e,t))}catch(e){return new m(this.promise.catch(e))}finally(e){return new m(this.promise.finally(e))}toPromise(){return this.promise}}class w{static get gates(){return{and:new l,or:new s,xor:new c,nand:new i,nor:new o,xnor:new a,not:new R,race:new f,allSettled:new h,majority:new n,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new m(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new m(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new m(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new m(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new m(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new m(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new m(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new m(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new m(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new m(this.gates.majority.execute(e,t))}static allFulfilled(e){return new m(this.gates.allFulfilled.execute(e))}static allRejected(e){return new m(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,l={and:w.and.bind(w),or:w.or.bind(w),not:w.not.bind(w),race:w.race.bind(w),allSettled:w.allSettled.bind(w),xor:w.xor.bind(w),nand:w.nand.bind(w),nor:w.nor.bind(w),xnor:w.xnor.bind(w),majority:w.majority.bind(w),allFulfilled:w.allFulfilled.bind(w),allRejected:w.allRejected.bind(w)},n={};return Object.entries(l).forEach(([e,l])=>{const i=s[e]||e;n[`${t}${i}${r}`]=l}),n};
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function t(t,l,s,r,n){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${s} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${l}/${s} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${s} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${s} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${s-l}/${s} promises rejected (expected all to fail).`}[t]||"Logic condition failed",a=n&&n?.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,r)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends l{async execute(e){try{return Promise.any(e)}catch(e){throw t("OR_ERROR",0,0,[],[e])}}}class r extends l{async execute(e){try{return Promise.all(e)}catch(e){throw t("AND_ERROR",0,0,[],[e])}}}class n extends l{async execute(e,l){const s=await Promise.allSettled(e),r=this.filterFulfilledResults(s),n=r.length,i=s.length,a=this.filterRejectedResults(s);if(n>Math.floor(i*l.max))return r;throw t("MAJORITY_ERROR",n,i,s,a)}}class i extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(r===n)throw t("NAND_ERROR",r,n,l,i);return s}}class a extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l).length,r=l.length,n=this.filterRejectedResults(l);if(0===s)return[];throw t("NOR_ERROR",s,r,l,n)}}class o extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(0===r||r===n)return s;throw t("XNOR_ERROR",r,n,l,i)}}class c extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(1===r)return s[0];throw t("XOR_ERROR",r,n,l,i)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class d extends l{async execute(e){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((s,r)=>{l=setTimeout(()=>{r(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class R{static get gates(){return{and:new r,or:new s,xor:new c,nand:new i,nor:new a,xnor:new o,majority:new n,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e))}static allSettled(e){return new f(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,s=Promise.resolve(t);const r=()=>(l||(s=new Promise(e=>{l=e})),s);return{getState:()=>t,set:async e=>(t=e,l&&(l(t),l=null),s=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:r,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const s=()=>{t===e?l(t):r().then(s)};s()})}}}function h(e={}){const{prefix:t="",suffix:l="",rename:s={}}=e,r={and:R.and.bind(R),or:R.or.bind(R),not:R.not.bind(R),race:R.race.bind(R),allSettled:R.allSettled.bind(R),xor:R.xor.bind(R),nand:R.nand.bind(R),nor:R.nor.bind(R),xnor:R.xnor.bind(R),majority:R.majority.bind(R),allFulfilled:R.allFulfilled.bind(R),allRejected:R.allRejected.bind(R)},n={};return Object.entries(r).forEach(([e,r])=>{const i=s[e]||e;n[`${t}${i}${l}`]=r}),n}export{h as createPromiseLogic};
1
+ class e extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function t(t,r,s,l){return new e(t,r,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.any(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"OR condition failed";throw t(r.errorType||"OR_ERROR",n,l)}}}class l extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"AND condition failed";throw t(r.errorType||"AND_ERROR",n,l)}}}class n extends r{async execute(e,r){const s=r.max||.5,l=await Promise.allSettled(e),n=l.length;if(0===n)return[];const i=this.filterFulfilledResults(l),o=i.length;if(this.filterRejectedResults(l),o>Math.floor(n*s))return i;{const e=r.errorMessage||`Majority condition failed: ${o}/${n} fulfilled (need majority)`;throw t(r.errorType||"MAJORITY_ERROR",e,l)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),n===i){const e=r.errorMessage||`NAND condition failed: all ${i} promises fulfilled (expected at least one rejection)`;throw t(r.errorType||"NAND_ERROR",e,s)}return l}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s).length;if(s.length,this.filterRejectedResults(s),0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType||"NOR_ERROR",e,s)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),0===n||n===i)return l;{const e=r.errorMessage||`XNOR condition failed: ${n}/${i} promises fulfilled (expected all or none)`;throw t(r.errorType||"XNOR_ERROR",e,s)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),1===n)return l[0];{const e=r.errorMessage||(n>1?`XOR condition failed: ${n} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType||"XOR_ERROR",e,s)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).catch(()=>{}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class R extends r{async execute(e,r={}){let s;if("function"==typeof e[Symbol.iterator]){const l=[...e];if(0===l.length)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate requires exactly one promise",[]);if(l.length>1)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate only accepts one promise",[]);s=l[0]}else s=e;return Promise.resolve(s).then(e=>{throw t(r.errorType||"NOT_ERROR",r.errorMessage||`NOT condition failed: ${e}`,[])},e=>e)}}class f extends r{async execute(e,r){if(0===Array.from(e).length)return{};try{return await Promise.race(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType||"RACE_ERROR",n,l)}}}class h extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType||"ALL_SETTLED_ERROR",n,l)}}}class m{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;const s=Promise.race([this.promise,new Promise((s,l)=>{r=setTimeout(()=>{l(new Error(t))},e)})]).finally(()=>clearTimeout(r));return new m(s)}then(e,t){return new m(this.promise.then(e,t))}catch(e){return new m(this.promise.catch(e))}finally(e){return new m(this.promise.finally(e))}toPromise(){return this.promise}}class w{static get gates(){return{and:new l,or:new s,xor:new c,nand:new i,nor:new o,xnor:new a,not:new R,race:new f,allSettled:new h,majority:new n,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new m(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new m(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new m(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new m(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new m(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new m(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new m(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new m(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new m(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new m(this.gates.majority.execute(e,t))}static allFulfilled(e){return new m(this.gates.allFulfilled.execute(e))}static allRejected(e){return new m(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}function x(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,l={and:w.and.bind(w),or:w.or.bind(w),not:w.not.bind(w),race:w.race.bind(w),allSettled:w.allSettled.bind(w),xor:w.xor.bind(w),nand:w.nand.bind(w),nor:w.nor.bind(w),xnor:w.xnor.bind(w),majority:w.majority.bind(w),allFulfilled:w.allFulfilled.bind(w),allRejected:w.allRejected.bind(w)},n={};return Object.entries(l).forEach(([e,l])=>{const i=s[e]||e;n[`${t}${i}${r}`]=l}),n}export{x as createPromiseLogic};
@@ -1 +1 @@
1
- "use strict";class e extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function t(t,l,r,s,i){const n={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${l}/${r} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-l}/${r} promises rejected (expected all to fail).`}[t]||"Logic condition failed",o=i&&i?.length>0?`\n失败原因:${i.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,n+o,s)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class r extends l{async execute(e){try{return Promise.any(e)}catch(e){throw t("OR_ERROR",0,0,[],[e])}}}class s extends l{async execute(e){try{return Promise.all(e)}catch(e){throw t("AND_ERROR",0,0,[],[e])}}}class i extends l{async execute(e,l){const r=await Promise.allSettled(e),s=this.filterFulfilledResults(r),i=s.length,n=r.length,o=this.filterRejectedResults(r);if(i>Math.floor(n*l.max))return s;throw t("MAJORITY_ERROR",i,n,r,o)}}class n extends l{async execute(e){const l=await Promise.allSettled(e),r=this.filterFulfilledResults(l),s=r.length,i=l.length,n=this.filterRejectedResults(l);if(s===i)throw t("NAND_ERROR",s,i,l,n);return r}}class o extends l{async execute(e){const l=await Promise.allSettled(e),r=this.filterFulfilledResults(l).length,s=l.length,i=this.filterRejectedResults(l);if(0===r)return[];throw t("NOR_ERROR",r,s,l,i)}}class a extends l{async execute(e){const l=await Promise.allSettled(e),r=this.filterFulfilledResults(l),s=r.length,i=l.length,n=this.filterRejectedResults(l);if(0===s||s===i)return r;throw t("XNOR_ERROR",s,i,l,n)}}class c extends l{async execute(e){const l=await Promise.allSettled(e),r=this.filterFulfilledResults(l),s=r.length,i=l.length,n=this.filterRejectedResults(l);if(1===s)return r[0];throw t("XOR_ERROR",s,i,l,n)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,s=0;const i=[...e],n=i?.length??0;0!==n?i.forEach((e,i)=>{Promise.resolve(e).then(e=>{s++,l[i]=e}).catch(()=>{l[i]=void 0}).finally(()=>{r++,s>0?t(l.filter(e=>void 0!==e)):r===n&&t([])})}):t(l)})}}class d extends l{async execute(e){return new Promise(t=>{const l=[];let r=0,s=0;const i=[...e],n=i?.length??0;0!==n?i.forEach((e,i)=>{Promise.resolve(e).then(()=>{l[i]=void 0}).catch(e=>{s++,l[i]=e}).finally(()=>{r++,s>0?t(l.filter(e=>void 0!==e)):r===n&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((r,s)=>{l=setTimeout(()=>{s(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class R{static get gates(){return{and:new s,or:new r,xor:new c,nand:new n,nor:new o,xnor:new a,majority:new i,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e))}static allSettled(e){return new f(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,r=Promise.resolve(t);const s=()=>(l||(r=new Promise(e=>{l=e})),r);return{getState:()=>t,set:async e=>(t=e,l&&(l(t),l=null),r=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:s,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const r=()=>{t===e?l(t):s().then(r)};r()})}}}exports.PromiseLogic=R,exports.PromiseLogicError=e,exports.PromiseWithTimer=f,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,s={and:R.and.bind(R),or:R.or.bind(R),not:R.not.bind(R),race:R.race.bind(R),allSettled:R.allSettled.bind(R),xor:R.xor.bind(R),nand:R.nand.bind(R),nor:R.nor.bind(R),xnor:R.xnor.bind(R),majority:R.majority.bind(R),allFulfilled:R.allFulfilled.bind(R),allRejected:R.allRejected.bind(R)},i={};return Object.entries(s).forEach(([e,s])=>{const n=r[e]||e;i[`${t}${n}${l}`]=s}),i};
1
+ "use strict";class e extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function t(t,r,s,l){return new e(t,r,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.any(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"OR condition failed";throw t(r.errorType||"OR_ERROR",n,l)}}}class l extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"AND condition failed";throw t(r.errorType||"AND_ERROR",n,l)}}}class n extends r{async execute(e,r){const s=r.max||.5,l=await Promise.allSettled(e),n=l.length;if(0===n)return[];const i=this.filterFulfilledResults(l),o=i.length;if(this.filterRejectedResults(l),o>Math.floor(n*s))return i;{const e=r.errorMessage||`Majority condition failed: ${o}/${n} fulfilled (need majority)`;throw t(r.errorType||"MAJORITY_ERROR",e,l)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),n===i){const e=r.errorMessage||`NAND condition failed: all ${i} promises fulfilled (expected at least one rejection)`;throw t(r.errorType||"NAND_ERROR",e,s)}return l}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s).length;if(s.length,this.filterRejectedResults(s),0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType||"NOR_ERROR",e,s)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),0===n||n===i)return l;{const e=r.errorMessage||`XNOR condition failed: ${n}/${i} promises fulfilled (expected all or none)`;throw t(r.errorType||"XNOR_ERROR",e,s)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),1===n)return l[0];{const e=r.errorMessage||(n>1?`XOR condition failed: ${n} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType||"XOR_ERROR",e,s)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).catch(()=>{}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class R extends r{async execute(e,r={}){let s;if("function"==typeof e[Symbol.iterator]){const l=[...e];if(0===l.length)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate requires exactly one promise",[]);if(l.length>1)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate only accepts one promise",[]);s=l[0]}else s=e;return Promise.resolve(s).then(e=>{throw t(r.errorType||"NOT_ERROR",r.errorMessage||`NOT condition failed: ${e}`,[])},e=>e)}}class h extends r{async execute(e,r){if(0===Array.from(e).length)return{};try{return await Promise.race(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType||"RACE_ERROR",n,l)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType||"ALL_SETTLED_ERROR",n,l)}}}class m{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;const s=Promise.race([this.promise,new Promise((s,l)=>{r=setTimeout(()=>{l(new Error(t))},e)})]).finally(()=>clearTimeout(r));return new m(s)}then(e,t){return new m(this.promise.then(e,t))}catch(e){return new m(this.promise.catch(e))}finally(e){return new m(this.promise.finally(e))}toPromise(){return this.promise}}class x{static get gates(){return{and:new l,or:new s,xor:new c,nand:new i,nor:new o,xnor:new a,not:new R,race:new h,allSettled:new f,majority:new n,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new m(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new m(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new m(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new m(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new m(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new m(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new m(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new m(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new m(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new m(this.gates.majority.execute(e,t))}static allFulfilled(e){return new m(this.gates.allFulfilled.execute(e))}static allRejected(e){return new m(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}exports.PromiseLogic=x,exports.PromiseLogicError=e,exports.PromiseWithTimer=m,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,l={and:x.and.bind(x),or:x.or.bind(x),not:x.not.bind(x),race:x.race.bind(x),allSettled:x.allSettled.bind(x),xor:x.xor.bind(x),nand:x.nand.bind(x),nor:x.nor.bind(x),xnor:x.xnor.bind(x),majority:x.majority.bind(x),allFulfilled:x.allFulfilled.bind(x),allRejected:x.allRejected.bind(x)},n={};return Object.entries(l).forEach(([e,l])=>{const i=s[e]||e;n[`${t}${i}${r}`]=l}),n};
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function t(t,l,s,r,n){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${s} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${l}/${s} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${s} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${s} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${s-l}/${s} promises rejected (expected all to fail).`}[t]||"Logic condition failed",a=n&&n?.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,r)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends l{async execute(e){try{return Promise.any(e)}catch(e){throw t("OR_ERROR",0,0,[],[e])}}}class r extends l{async execute(e){try{return Promise.all(e)}catch(e){throw t("AND_ERROR",0,0,[],[e])}}}class n extends l{async execute(e,l){const s=await Promise.allSettled(e),r=this.filterFulfilledResults(s),n=r.length,i=s.length,a=this.filterRejectedResults(s);if(n>Math.floor(i*l.max))return r;throw t("MAJORITY_ERROR",n,i,s,a)}}class i extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(r===n)throw t("NAND_ERROR",r,n,l,i);return s}}class a extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l).length,r=l.length,n=this.filterRejectedResults(l);if(0===s)return[];throw t("NOR_ERROR",s,r,l,n)}}class o extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(0===r||r===n)return s;throw t("XNOR_ERROR",r,n,l,i)}}class c extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(1===r)return s[0];throw t("XOR_ERROR",r,n,l,i)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class d extends l{async execute(e){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((s,r)=>{l=setTimeout(()=>{r(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class R{static get gates(){return{and:new r,or:new s,xor:new c,nand:new i,nor:new a,xnor:new o,majority:new n,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e))}static allSettled(e){return new f(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,s=Promise.resolve(t);const r=()=>(l||(s=new Promise(e=>{l=e})),s);return{getState:()=>t,set:async e=>(t=e,l&&(l(t),l=null),s=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:r,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const s=()=>{t===e?l(t):r().then(s)};s()})}}}function h(e={}){const{prefix:t="",suffix:l="",rename:s={}}=e,r={and:R.and.bind(R),or:R.or.bind(R),not:R.not.bind(R),race:R.race.bind(R),allSettled:R.allSettled.bind(R),xor:R.xor.bind(R),nand:R.nand.bind(R),nor:R.nor.bind(R),xnor:R.xnor.bind(R),majority:R.majority.bind(R),allFulfilled:R.allFulfilled.bind(R),allRejected:R.allRejected.bind(R)},n={};return Object.entries(r).forEach(([e,r])=>{const i=s[e]||e;n[`${t}${i}${l}`]=r}),n}export{R as PromiseLogic,e as PromiseLogicError,f as PromiseWithTimer,h as createPromiseLogic};
1
+ class e extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function t(t,r,s,l){return new e(t,r,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.any(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"OR condition failed";throw t(r.errorType||"OR_ERROR",n,l)}}}class l extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"AND condition failed";throw t(r.errorType||"AND_ERROR",n,l)}}}class n extends r{async execute(e,r){const s=r.max||.5,l=await Promise.allSettled(e),n=l.length;if(0===n)return[];const i=this.filterFulfilledResults(l),o=i.length;if(this.filterRejectedResults(l),o>Math.floor(n*s))return i;{const e=r.errorMessage||`Majority condition failed: ${o}/${n} fulfilled (need majority)`;throw t(r.errorType||"MAJORITY_ERROR",e,l)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),n===i){const e=r.errorMessage||`NAND condition failed: all ${i} promises fulfilled (expected at least one rejection)`;throw t(r.errorType||"NAND_ERROR",e,s)}return l}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s).length;if(s.length,this.filterRejectedResults(s),0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType||"NOR_ERROR",e,s)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),0===n||n===i)return l;{const e=r.errorMessage||`XNOR condition failed: ${n}/${i} promises fulfilled (expected all or none)`;throw t(r.errorType||"XNOR_ERROR",e,s)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),1===n)return l[0];{const e=r.errorMessage||(n>1?`XOR condition failed: ${n} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType||"XOR_ERROR",e,s)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).catch(()=>{}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class R extends r{async execute(e,r={}){let s;if("function"==typeof e[Symbol.iterator]){const l=[...e];if(0===l.length)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate requires exactly one promise",[]);if(l.length>1)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate only accepts one promise",[]);s=l[0]}else s=e;return Promise.resolve(s).then(e=>{throw t(r.errorType||"NOT_ERROR",r.errorMessage||`NOT condition failed: ${e}`,[])},e=>e)}}class f extends r{async execute(e,r){if(0===Array.from(e).length)return{};try{return await Promise.race(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType||"RACE_ERROR",n,l)}}}class h extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType||"ALL_SETTLED_ERROR",n,l)}}}class m{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;const s=Promise.race([this.promise,new Promise((s,l)=>{r=setTimeout(()=>{l(new Error(t))},e)})]).finally(()=>clearTimeout(r));return new m(s)}then(e,t){return new m(this.promise.then(e,t))}catch(e){return new m(this.promise.catch(e))}finally(e){return new m(this.promise.finally(e))}toPromise(){return this.promise}}class w{static get gates(){return{and:new l,or:new s,xor:new c,nand:new i,nor:new o,xnor:new a,not:new R,race:new f,allSettled:new h,majority:new n,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new m(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new m(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new m(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new m(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new m(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new m(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new m(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new m(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new m(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new m(this.gates.majority.execute(e,t))}static allFulfilled(e){return new m(this.gates.allFulfilled.execute(e))}static allRejected(e){return new m(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}function x(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,l={and:w.and.bind(w),or:w.or.bind(w),not:w.not.bind(w),race:w.race.bind(w),allSettled:w.allSettled.bind(w),xor:w.xor.bind(w),nand:w.nand.bind(w),nor:w.nor.bind(w),xnor:w.xnor.bind(w),majority:w.majority.bind(w),allFulfilled:w.allFulfilled.bind(w),allRejected:w.allRejected.bind(w)},n={};return Object.entries(l).forEach(([e,l])=>{const i=s[e]||e;n[`${t}${i}${r}`]=l}),n}export{w as PromiseLogic,e as PromiseLogicError,m as PromiseWithTimer,x as createPromiseLogic};
@@ -1,11 +1,22 @@
1
1
  // v2版本类型定义 (TypeScript版本 - 现代化设计)
2
2
 
3
+ /**
4
+ * 选项参数接口
5
+ */
6
+ interface LogicGateOptions {
7
+ errorType?: string | undefined;
8
+ errorMessage?: string | undefined;
9
+ max?: number | undefined;
10
+ [key: string]: string | number | boolean | undefined;
11
+
12
+ }
13
+
3
14
  /**
4
15
  * PromiseWithTimer 包装类 - 提供超时控制功能
5
16
  */
6
17
  declare class PromiseWithTimer<T> {
7
18
  /** 添加超时控制 */
8
- maxTimer(ms: number): Promise<T>;
19
+ maxTimer(ms: number, errorMessage?: string): PromiseWithTimer<T>;
9
20
 
10
21
  /** Promise 链式调用 */
11
22
  then<U>(onfulfilled?: ((value: T) => U | PromiseLike<U>) | null, onrejected?: ((reason: Error) => U | PromiseLike<U>) | null): PromiseWithTimer<U>;
@@ -22,10 +33,9 @@ declare class PromiseWithTimer<T> {
22
33
 
23
34
  /**
24
35
  * Promise逻辑错误类
25
- * @deprecated 在v2版本中建议使用更具体的错误类型
26
36
  */
27
37
  declare class PromiseLogicError extends Error {
28
- readonly type: 'XOR_ERROR' | 'NAND_ERROR' | 'NOR_ERROR' | 'XNOR_ERROR' | 'MAJORITY_ERROR' | 'ALL_SUCCESSFUL_ERROR' | 'ALL_FAILED_ERROR';
38
+ readonly type: string;
29
39
  readonly results: PromiseSettledResult<unknown>[];
30
40
 
31
41
  constructor(type: string, message: string, results: PromiseSettledResult<unknown>[]);
@@ -56,22 +66,22 @@ interface FlipFlop {
56
66
  */
57
67
  declare class PromiseLogic {
58
68
  // 基础逻辑门
59
- static and<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
60
- static or<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
61
- static race<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
62
- static allSettled<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<PromiseSettledResult<T>[]>;
69
+ static and<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
70
+ static or<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
71
+ static race<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T | undefined>;
72
+ static allSettled<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<PromiseSettledResult<T>[]>;
63
73
 
64
74
  // 扩展逻辑门
65
- static xor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
66
- static not<T>(promise: T | PromiseLike<T>): PromiseWithTimer<unknown>;
67
- static nand<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
68
- static nor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
69
- static xnor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
70
- static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?: { max: number }): PromiseWithTimer<T[]>;
75
+ static xor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
76
+ static not<T>(promise: T | PromiseLike<T>, options?: LogicGateOptions): PromiseWithTimer<T>;
77
+ static nand<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
78
+ static nor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
79
+ static xnor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
80
+ static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
71
81
 
72
82
  // 实用方法
73
- static allFulfilled(iterable: Iterable<PromiseLike<unknown>>): PromiseWithTimer<unknown[]>;
74
- static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<unknown[]>;
83
+ static allFulfilled<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
84
+ static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<Error[]>;
75
85
 
76
86
  // 状态管理
77
87
  static createFlipFlop(initialState?: boolean): FlipFlop;
@@ -98,9 +108,8 @@ declare function createPromiseLogic(options?: CreatePromiseLogicOptions): Record
98
108
 
99
109
  /**
100
110
  * 创建逻辑错误
101
- * @deprecated 在v2版本中建议使用更具体的错误构造器
102
111
  */
103
- declare function createLogicError(type: string, fulfilledCount: number, total: number, results: PromiseSettledResult<unknown>[]): PromiseLogicError;
112
+ declare function createLogicError(type: string, message: string, results: PromiseSettledResult<unknown>[], error?: unknown): PromiseLogicError;
104
113
 
105
114
  export { PromiseLogic, PromiseLogicError, PromiseWithTimer, createLogicError, createPromiseLogic };
106
- export type { CreatePromiseLogicOptions, FlipFlop };
115
+ export type { CreatePromiseLogicOptions, FlipFlop, LogicGateOptions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promise-logic",
3
- "version": "2.8.5",
3
+ "version": "2.9.0",
4
4
  "description": "Compose promises with logic gate semantics (AND, OR, XOR, NAND, NOR, XNOR, Majority). Forget APIs, remember logic.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",