promise-logic 2.8.5 → 2.9.1
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 +21 -0
- package/README.md +253 -224
- package/dist/factory.cjs.js +1 -1
- package/dist/factory.esm.js +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/types/index.d.ts +21 -14
- package/dist/v2/factory.cjs.js +1 -1
- package/dist/v2/factory.esm.js +1 -1
- package/dist/v2/index.cjs.js +1 -1
- package/dist/v2/index.esm.js +1 -1
- package/dist/v2/types/index.d.ts +27 -18
- package/package.json +1 -1
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,153 @@
|
|
|
1
|
-
|
|
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
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
// Order processing flow
|
|
21
|
+
async function createOrder() {
|
|
22
|
+
// Unified error types
|
|
23
|
+
const PAYMENT_OR_INVENTORY_ERROR = 'PAYMENT_OR_INVENTORY_ERROR';
|
|
24
|
+
const ORDER_ERROR = 'ORDER_ERROR';
|
|
25
|
+
const LOGISTICS_ERROR = 'LOGISTICS_ERROR';
|
|
26
|
+
const COUPON_ERROR = 'COUPON_ERROR';
|
|
27
|
+
|
|
28
|
+
// Destructure and, or methods from PromiseLogic for simpler syntax and understand the logical relationship of the current scenario
|
|
29
|
+
const { and, or } = PromiseLogic;
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
// Execute payment and inventory operations (both must succeed)
|
|
33
|
+
|
|
34
|
+
const [
|
|
35
|
+
[paymentResult, inventoryResult], // Payment and inventory operation results
|
|
36
|
+
logistics, // Logistics operation result
|
|
37
|
+
coupon // Coupon operation result
|
|
38
|
+
] = await and([
|
|
39
|
+
and([paymentAPI(), inventoryAPI()],{
|
|
40
|
+
errorType: PAYMENT_OR_INVENTORY_ERROR,// Custom payment or inventory error type
|
|
41
|
+
}),
|
|
42
|
+
or([oneLogisticsAPI(), twoLogisticsAPI()], {
|
|
43
|
+
errorType: LOGISTICS_ERROR,// Custom logistics error type
|
|
44
|
+
}),
|
|
45
|
+
or([couponAPI1(), couponAPI2()], {
|
|
46
|
+
errorType: COUPON_ERROR,// Custom coupon error type
|
|
47
|
+
})
|
|
48
|
+
], {
|
|
49
|
+
errorType: ORDER_ERROR,// Custom order error type
|
|
50
|
+
errorMessage: 'Order creation failed' // Custom order error message
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Order creation successful, return payment result, inventory result, logistics result and coupon result
|
|
54
|
+
return {
|
|
55
|
+
payment: paymentResult,
|
|
56
|
+
inventory: inventoryResult,
|
|
57
|
+
logistics: logistics,
|
|
58
|
+
coupon: coupon,
|
|
59
|
+
status: 'success'
|
|
60
|
+
};
|
|
61
|
+
} catch (error) {
|
|
62
|
+
// Analyze error type
|
|
63
|
+
switch (error.type) {
|
|
64
|
+
case ORDER_ERROR:
|
|
65
|
+
return {
|
|
66
|
+
status: 'error',
|
|
67
|
+
errorType: 'order_error',
|
|
68
|
+
message: 'Order creation failed',
|
|
69
|
+
details: error
|
|
70
|
+
};
|
|
71
|
+
case PAYMENT_OR_INVENTORY_ERROR:
|
|
72
|
+
return {
|
|
73
|
+
status: 'error',
|
|
74
|
+
errorType: 'payment_or_inventory_failed',
|
|
75
|
+
message: 'Payment or inventory operation failed',
|
|
76
|
+
details: error
|
|
77
|
+
};
|
|
78
|
+
case LOGISTICS_ERROR:
|
|
79
|
+
return {
|
|
80
|
+
status: 'error',
|
|
81
|
+
errorType: 'logistics_unavailable',
|
|
82
|
+
message: 'All logistics services are unavailable',
|
|
83
|
+
details: error
|
|
84
|
+
};
|
|
85
|
+
case COUPON_ERROR:
|
|
86
|
+
return {
|
|
87
|
+
status: 'error',
|
|
88
|
+
errorType: 'coupon_error',
|
|
89
|
+
message: 'All coupons are unavailable',
|
|
90
|
+
details: error
|
|
91
|
+
};
|
|
92
|
+
default:
|
|
93
|
+
return {
|
|
94
|
+
status: 'error',
|
|
95
|
+
errorType: 'default_error',
|
|
96
|
+
message: 'Unknown error occurred during order creation',
|
|
97
|
+
details: error
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
As you can see, the code structure is completely consistent with business rules. Code is documentation, and logic is self-explanatory.
|
|
105
|
+
|
|
8
106
|
---
|
|
9
107
|
|
|
10
|
-
|
|
108
|
+
## Features
|
|
109
|
+
|
|
110
|
+
### 1. Logical Semantics
|
|
111
|
+
|
|
112
|
+
- `and`: All tasks must succeed (equivalent to `Promise.all`)
|
|
113
|
+
- `or`: At least one task succeeds (equivalent to `Promise.any`)
|
|
114
|
+
- `xor`: **Exactly one task succeeds**
|
|
115
|
+
- `nand`: Not all tasks succeed (at least one fails)
|
|
116
|
+
- `nor`: All tasks fail (no task succeeds)
|
|
117
|
+
- `xnor`: All tasks succeed or all fail (same state)
|
|
118
|
+
- `not`: Inverts the result of a single Promise
|
|
119
|
+
- `majority`: Most tasks succeed
|
|
120
|
+
|
|
121
|
+
### 2. Zero Dependencies
|
|
122
|
+
|
|
123
|
+
Only depends on native Promise, no additional runtime dependencies.
|
|
124
|
+
|
|
125
|
+
### 3. Full Test Coverage
|
|
11
126
|
|
|
12
|
-
|
|
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
|
|
127
|
+
All logic gates have undergone rigorous unit testing to ensure behavior meets expectations.
|
|
21
128
|
|
|
22
|
-
|
|
23
|
-
Only depends on native Promise, no additional runtime dependencies.
|
|
129
|
+
### 4. Clear Error Classification
|
|
24
130
|
|
|
25
|
-
|
|
26
|
-
|
|
131
|
+
- `PromiseLogicError` unified error type
|
|
132
|
+
- `error.type` distinguishes specific logical errors (e.g., `'XOR_ERROR'`)
|
|
133
|
+
- Supports custom error types and messages
|
|
27
134
|
|
|
28
|
-
|
|
29
|
-
- `PromiseLogicError` unified error type
|
|
30
|
-
- `error.type` distinguishes specific logical errors (e.g., `'XOR_ERROR'`)
|
|
135
|
+
### 5. Timeout Control
|
|
31
136
|
|
|
32
|
-
|
|
33
|
-
|
|
137
|
+
- `maxTimer`: Adds timeout functionality to any Promise operation (unit: milliseconds)
|
|
138
|
+
- Supports custom timeout error messages
|
|
34
139
|
|
|
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.)
|
|
140
|
+
**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.).
|
|
38
141
|
|
|
39
|
-
6.
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
142
|
+
### 6. Extended Operations
|
|
143
|
+
|
|
144
|
+
- `allFulfilled`: Returns all successful results in order, immediately tries to return when there are successful results
|
|
145
|
+
- `allRejected`: Returns all failed results in order, immediately tries to return when there are failed results
|
|
146
|
+
- `allSettled`: Returns all results (both successful and failed)
|
|
43
147
|
|
|
44
148
|
---
|
|
45
149
|
|
|
46
|
-
|
|
150
|
+
## Installation
|
|
47
151
|
|
|
48
152
|
```bash
|
|
49
153
|
npm install promise-logic
|
|
@@ -51,33 +155,58 @@ npm install promise-logic
|
|
|
51
155
|
|
|
52
156
|
---
|
|
53
157
|
|
|
54
|
-
|
|
158
|
+
## Quick Start
|
|
159
|
+
|
|
160
|
+
### Basic Usage Examples
|
|
55
161
|
|
|
56
|
-
####
|
|
162
|
+
#### Destructuring Assignment
|
|
57
163
|
|
|
58
164
|
```javascript
|
|
59
165
|
import { PromiseLogic } from 'promise-logic';
|
|
60
166
|
|
|
61
|
-
//
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
167
|
+
// Destructure methods from PromiseLogic for simpler syntax
|
|
168
|
+
const { and, or, xor, not, race } = PromiseLogic;
|
|
169
|
+
|
|
170
|
+
// Use destructured methods
|
|
171
|
+
and([
|
|
172
|
+
fetch('/api/user').then(r => r.json()),
|
|
173
|
+
fetch('/api/profile').then(r => r.json())
|
|
174
|
+
]).then(results => console.log(results));
|
|
175
|
+
|
|
176
|
+
or([
|
|
177
|
+
fetch('/api/primary').then(r => r.json()).catch(() => { throw new Error('primary failed'); }),
|
|
178
|
+
fetch('/api/backup').then(r => r.json())
|
|
179
|
+
]).then(result => console.log(result));
|
|
180
|
+
|
|
181
|
+
xor([
|
|
182
|
+
fetch('/api/method1').then(r => r.json()),
|
|
183
|
+
fetch('/api/method2').then(r => r.json())
|
|
184
|
+
]).then(result => console.log(result));
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
#### Security Audit (XOR Scenario)
|
|
188
|
+
|
|
189
|
+
```javascript
|
|
190
|
+
import { PromiseLogic } from 'promise-logic';
|
|
65
191
|
|
|
66
192
|
// Execute XOR logic: exactly one success
|
|
67
|
-
PromiseLogic.xor([
|
|
193
|
+
PromiseLogic.xor([
|
|
194
|
+
biometricAuth(), // Biometric authentication
|
|
195
|
+
hardwareKeyAuth() // Hardware key authentication
|
|
196
|
+
])
|
|
68
197
|
.then((result) => {
|
|
69
|
-
console.log('Successfully
|
|
198
|
+
console.log('Successfully authenticated:', result);
|
|
70
199
|
})
|
|
71
200
|
.catch((error) => {
|
|
72
201
|
if (error.type === 'XOR_ERROR') {
|
|
73
|
-
console.error('
|
|
202
|
+
console.error('Conflict between biometric and hardware key authentication');
|
|
74
203
|
} else {
|
|
75
|
-
console.error('
|
|
204
|
+
console.error('Authentication error:', error);
|
|
76
205
|
}
|
|
77
206
|
});
|
|
78
207
|
```
|
|
79
208
|
|
|
80
|
-
####
|
|
209
|
+
#### Majority Decision (Majority Scenario)
|
|
81
210
|
|
|
82
211
|
```javascript
|
|
83
212
|
import { PromiseLogic } from 'promise-logic';
|
|
@@ -88,35 +217,17 @@ const services = [
|
|
|
88
217
|
fetch('https://api.node3.com/vote')
|
|
89
218
|
];
|
|
90
219
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
console.log('Majority of services returned success:', results);
|
|
94
|
-
})
|
|
95
|
-
.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)
|
|
220
|
+
// Custom threshold 0.6 (60%)
|
|
221
|
+
PromiseLogic.majority(services, { max: 0.6 })
|
|
111
222
|
.then((results) => {
|
|
112
|
-
console.log('
|
|
223
|
+
console.log('Custom threshold met, successful results:', results);
|
|
113
224
|
})
|
|
114
225
|
.catch((error) => {
|
|
115
|
-
console.error('
|
|
226
|
+
console.error('Custom threshold not met:', error);
|
|
116
227
|
});
|
|
117
228
|
```
|
|
118
229
|
|
|
119
|
-
####
|
|
230
|
+
#### Timeout Control
|
|
120
231
|
|
|
121
232
|
```javascript
|
|
122
233
|
import { PromiseLogic } from 'promise-logic';
|
|
@@ -127,16 +238,16 @@ PromiseLogic.and([
|
|
|
127
238
|
new Promise((resolve) => setTimeout(resolve, 3000)), // 3 second operation
|
|
128
239
|
Promise.resolve(3)
|
|
129
240
|
])
|
|
130
|
-
.maxTimer(2000, 'Custom timeout error: operation did not complete within 2000ms') // 2 second timeout
|
|
241
|
+
.maxTimer(2000, 'Custom timeout error: operation did not complete within 2000ms') // 2 second timeout
|
|
131
242
|
.then((result) => {
|
|
132
243
|
console.log('Operation completed within timeout:', result);
|
|
133
244
|
})
|
|
134
245
|
.catch((error) => {
|
|
135
|
-
console.error('Operation timed out:', error.message);
|
|
246
|
+
console.error('Operation timed out:', error.message);
|
|
136
247
|
});
|
|
137
248
|
```
|
|
138
249
|
|
|
139
|
-
####
|
|
250
|
+
#### Extended Operations
|
|
140
251
|
|
|
141
252
|
```javascript
|
|
142
253
|
import { PromiseLogic } from 'promise-logic';
|
|
@@ -148,12 +259,12 @@ const operations = [
|
|
|
148
259
|
Promise.reject('error2')
|
|
149
260
|
];
|
|
150
261
|
|
|
151
|
-
// Get all successful results (returns immediately when
|
|
262
|
+
// Get all successful results (returns immediately when there are successes)
|
|
152
263
|
PromiseLogic.allFulfilled(operations).then((results) => {
|
|
153
264
|
console.log('Successful results:', results); // ['success1', 'success2']
|
|
154
265
|
});
|
|
155
266
|
|
|
156
|
-
// Get all failed results (returns immediately when
|
|
267
|
+
// Get all failed results (returns immediately when there are failures)
|
|
157
268
|
PromiseLogic.allRejected(operations).then((errors) => {
|
|
158
269
|
console.log('Failed results:', errors); // ['error1', 'error2']
|
|
159
270
|
});
|
|
@@ -161,138 +272,44 @@ PromiseLogic.allRejected(operations).then((errors) => {
|
|
|
161
272
|
// Get all results (both success and failure)
|
|
162
273
|
PromiseLogic.allSettled(operations).then((results) => {
|
|
163
274
|
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
275
|
});
|
|
172
276
|
```
|
|
173
277
|
|
|
174
|
-
#### Example: allFulfilled - Execution Timing and Results
|
|
175
|
-
|
|
176
|
-
```javascript
|
|
177
|
-
import { PromiseLogic } from 'promise-logic';
|
|
178
278
|
|
|
179
|
-
|
|
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
|
|
279
|
+
### Custom Error Types and Messages
|
|
212
280
|
|
|
213
281
|
```javascript
|
|
214
282
|
import { PromiseLogic } from 'promise-logic';
|
|
215
283
|
|
|
216
|
-
|
|
217
|
-
|
|
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';
|
|
284
|
+
// Custom error type
|
|
285
|
+
const CUSTOM_ERROR_TYPE = 'CUSTOM_ERROR';
|
|
252
286
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
Promise.resolve('service2'),
|
|
256
|
-
Promise.reject('service3'),
|
|
257
|
-
Promise.reject('service4')
|
|
258
|
-
];
|
|
287
|
+
// Custom error message
|
|
288
|
+
const CUSTOM_ERROR_MESSAGE = 'Custom error message';
|
|
259
289
|
|
|
260
|
-
//
|
|
261
|
-
|
|
262
|
-
|
|
290
|
+
// Use custom error type and message
|
|
291
|
+
PromiseLogic.and([Promise.resolve('success1'), Promise.reject('error1')], {
|
|
292
|
+
errorType: CUSTOM_ERROR_TYPE,
|
|
293
|
+
errorMessage: CUSTOM_ERROR_MESSAGE
|
|
294
|
+
})
|
|
263
295
|
.then((results) => {
|
|
264
|
-
console.log(
|
|
296
|
+
console.log(results);
|
|
265
297
|
})
|
|
266
298
|
.catch((error) => {
|
|
267
|
-
|
|
299
|
+
if (error.type === CUSTOM_ERROR_TYPE) {
|
|
300
|
+
console.error(error); // Output: Custom error message
|
|
301
|
+
} else {
|
|
302
|
+
console.error(error);
|
|
303
|
+
}
|
|
268
304
|
});
|
|
269
305
|
```
|
|
270
306
|
|
|
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
307
|
### Using Factory Function
|
|
291
308
|
|
|
292
309
|
The factory function allows you to create PromiseLogic methods with custom names:
|
|
293
310
|
|
|
294
311
|
```javascript
|
|
295
|
-
import { createPromiseLogic } from 'promise-logic
|
|
312
|
+
import { createPromiseLogic } from 'promise-logic';
|
|
296
313
|
|
|
297
314
|
// Create instance with custom naming
|
|
298
315
|
const logic = createPromiseLogic({
|
|
@@ -307,7 +324,6 @@ const logic = createPromiseLogic({
|
|
|
307
324
|
|
|
308
325
|
// Use custom-named methods
|
|
309
326
|
logic.api_all_call([fetch('/api/users'), fetch('/api/posts')]);
|
|
310
|
-
|
|
311
327
|
logic.api_any_call([fetch('/api/cache'), fetch('/api/database')]);
|
|
312
328
|
```
|
|
313
329
|
|
|
@@ -327,9 +343,30 @@ PromiseLogic.and([Promise.resolve(1), Promise.resolve(2)]).then(
|
|
|
327
343
|
PromiseLogic.and<number>([Promise.resolve(1), Promise.resolve(2)]);
|
|
328
344
|
```
|
|
329
345
|
|
|
346
|
+
### Dynamic Logic Nested
|
|
347
|
+
|
|
348
|
+
```javascript
|
|
349
|
+
import { PromiseLogic } from 'promise-logic';
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
// Dynamic nesting example: adjust logistics strategy based on user level
|
|
353
|
+
const orderFlow = async (userLevel) => {
|
|
354
|
+
// VIP users: dual high-availability logistics guarantee (at least one success)
|
|
355
|
+
// Normal users: priority standard logistics, failover to economy logistics (at least one success)
|
|
356
|
+
const logisticsStrategy = userLevel === 'VIP'
|
|
357
|
+
? PromiseLogic.or([premiumLogistics(), backupLogistics()])
|
|
358
|
+
: PromiseLogic.or([standardLogistics(), economyLogistics()]);
|
|
359
|
+
|
|
360
|
+
return await PromiseLogic.and([
|
|
361
|
+
PromiseLogic.and([paymentAPI(), inventoryAPI()]), // Payment + inventory atomic operations
|
|
362
|
+
logisticsStrategy, // Logistics strategy
|
|
363
|
+
couponValidation() // Coupon validation
|
|
364
|
+
]);
|
|
365
|
+
};
|
|
366
|
+
```
|
|
330
367
|
---
|
|
331
368
|
|
|
332
|
-
|
|
369
|
+
## API Reference
|
|
333
370
|
|
|
334
371
|
| API | Description |
|
|
335
372
|
| :------------- | :--------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -347,62 +384,54 @@ PromiseLogic.and<number>([Promise.resolve(1), Promise.resolve(2)]);
|
|
|
347
384
|
| `race` | Returns the first completed Promise result (regardless of success or failure). Equivalent to native `Promise.race`. |
|
|
348
385
|
| `maxTimer` | Adds timeout functionality to any Promise operation (unit: milliseconds). Supports custom timeout error messages. |
|
|
349
386
|
|
|
387
|
+
---
|
|
388
|
+
|
|
389
|
+
## Changelog
|
|
350
390
|
|
|
351
|
-
###
|
|
391
|
+
### v2.9.0
|
|
352
392
|
|
|
353
|
-
|
|
354
|
-
|
|
393
|
+
**Error Mechanism Improvements**
|
|
394
|
+
- Added `errorType` and `errorMessage` parameters to logic gates, supporting custom error types and messages, further fitting business scenarios
|
|
395
|
+
- Optimized the existing error type system to ensure correct TypeScript type definitions
|
|
396
|
+
- Optimized TypeScript type compatibility issues
|
|
397
|
+
- Optimized allSettled gate return type error messages
|
|
398
|
+
- Improved test scripts, covering most promise combination logic boundaries and tricky scenario issues, ensuring more stable operation of logic gates
|
|
399
|
+
- Optimized logic gate execution efficiency, reducing unnecessary Promise wrapping
|
|
355
400
|
|
|
356
|
-
|
|
357
|
-
- Use `majority` to implement majority consensus (e.g., distributed voting).
|
|
401
|
+
### v2.8.0
|
|
358
402
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
403
|
+
- **Performance optimization**: Optimized `allFulfilled` and `allRejected` implementation logic from the bottom layer, existing results return immediately while maintaining consistent input and output order
|
|
404
|
+
- **Added chain timeout control with custom error messages**: Can customize timeout error messages in the `maxTimer` method
|
|
405
|
+
- **Type fixes**: Fixed TypeScript version type declaration issues
|
|
406
|
+
- **Test completion**: Added complete test cases for `allFulfilled`, `allRejected`, and `maxTimer`
|
|
407
|
+
- **Code refactoring**: Improved code structure for better maintainability
|
|
362
408
|
|
|
363
|
-
|
|
364
|
-
- Use `and` to ensure all dependent services succeed (e.g., order creation).
|
|
409
|
+
---
|
|
365
410
|
|
|
366
|
-
|
|
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`.
|
|
411
|
+
## Contribution Guide
|
|
369
412
|
|
|
370
|
-
|
|
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).
|
|
413
|
+
### 1. Development Environment
|
|
373
414
|
|
|
374
|
-
|
|
375
|
-
|
|
415
|
+
```bash
|
|
416
|
+
git clone https://github.com/xier123456/promise-logic.git
|
|
417
|
+
cd promise-logic
|
|
418
|
+
npm install
|
|
419
|
+
```
|
|
376
420
|
|
|
377
|
-
|
|
378
|
-
- Use `race` to return the first completed Promise result (regardless of success or failure).
|
|
421
|
+
### 2. Testing
|
|
379
422
|
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
- Use `xnor` to verify that all Promises succeed or all fail (same state).
|
|
423
|
+
```bash
|
|
424
|
+
npm test
|
|
425
|
+
```
|
|
384
426
|
|
|
385
|
-
|
|
427
|
+
### 3. Commit Guidelines
|
|
386
428
|
|
|
387
|
-
|
|
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.
|
|
429
|
+
- Commit messages must include prefixes like `feat:` (new feature), `fix:` (bug fix), `docs:` (documentation).
|
|
430
|
+
- Pull Requests must include test cases.
|
|
402
431
|
|
|
403
432
|
---
|
|
404
433
|
|
|
405
|
-
|
|
434
|
+
## Resource Links
|
|
406
435
|
|
|
407
436
|
- **GitHub Repository**: [https://github.com/xier123456/promise-logic](https://github.com/xier123456/promise-logic)
|
|
408
437
|
- **npm Package**: [https://www.npmjs.com/package/promise-logic](https://www.npmjs.com/package/promise-logic)
|
package/dist/factory.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,
|
|
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};
|
package/dist/factory.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e extends Error{constructor(e,t,
|
|
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,
|
|
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,
|
|
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};
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
declare class PromiseWithTimer<T> {
|
|
2
|
-
maxTimer(ms: number): Promise<T>;
|
|
2
|
+
maxTimer(ms: number, errorMessage?: string): Promise<T>;
|
|
3
3
|
then<U>(onfulfilled?: ((value: T) => U | PromiseLike<U>) | null, onrejected?: ((reason: Error) => U | PromiseLike<U>) | null): PromiseWithTimer<U>;
|
|
4
4
|
catch<U>(onrejected?: ((reason: Error) => U | PromiseLike<U>) | null): PromiseWithTimer<U>;
|
|
5
5
|
finally(onfinally?: (() => void) | null): PromiseWithTimer<T>;
|
|
@@ -7,11 +7,18 @@ declare class PromiseWithTimer<T> {
|
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
declare class PromiseLogicError extends Error {
|
|
10
|
-
type:
|
|
10
|
+
type: string;
|
|
11
11
|
results: PromiseSettledResult<unknown>[];
|
|
12
12
|
constructor(type: string, message: string, results: PromiseSettledResult<unknown>[]);
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
interface LogicGateOptions {
|
|
16
|
+
errorType?: string;
|
|
17
|
+
errorMessage?: string;
|
|
18
|
+
max?: number;
|
|
19
|
+
[key: string]: string | number | boolean | undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
15
22
|
interface FlipFlop {
|
|
16
23
|
getState(): boolean;
|
|
17
24
|
toggle(): Promise<boolean>;
|
|
@@ -19,20 +26,20 @@ interface FlipFlop {
|
|
|
19
26
|
}
|
|
20
27
|
|
|
21
28
|
declare class PromiseLogic {
|
|
22
|
-
static and<T>(iterable: Iterable<T | PromiseLike<T
|
|
23
|
-
static or<T>(iterable: Iterable<T | PromiseLike<T
|
|
24
|
-
static race<T>(iterable: Iterable<T | PromiseLike<T
|
|
25
|
-
static not<T>(promise: T | PromiseLike<T
|
|
26
|
-
static allSettled<T>(iterable: Iterable<T | PromiseLike<T
|
|
29
|
+
static and<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOption): PromiseWithTimer<T[]>;
|
|
30
|
+
static or<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
|
|
31
|
+
static race<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
|
|
32
|
+
static not<T>(promise: T | PromiseLike<T>, options?: LogicGateOptions): PromiseWithTimer<T>;
|
|
33
|
+
static allSettled<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<PromiseSettledResult<T>[]>;
|
|
27
34
|
|
|
28
|
-
static xor<T>(iterable: Iterable<T | PromiseLike<T
|
|
29
|
-
static nand<T>(iterable: Iterable<T | PromiseLike<T
|
|
30
|
-
static nor<T>(iterable: Iterable<T | PromiseLike<T
|
|
31
|
-
static xnor<T>(iterable: Iterable<T | PromiseLike<T
|
|
32
|
-
static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?:
|
|
35
|
+
static xor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
|
|
36
|
+
static nand<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
|
|
37
|
+
static nor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
|
|
38
|
+
static xnor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
|
|
39
|
+
static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
|
|
33
40
|
|
|
34
41
|
static allFulfilled<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
|
|
35
|
-
static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<
|
|
42
|
+
static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<Error[]>;
|
|
36
43
|
|
|
37
44
|
static createFlipFlop(initialState?: boolean): FlipFlop;
|
|
38
45
|
}
|
|
@@ -50,4 +57,4 @@ declare function createPromiseLogic(options?: CreatePromiseLogicOptions): {
|
|
|
50
57
|
declare function createLogicError(type: string, fulfilledCount: number, total: number, results: PromiseSettledResult<unknown>[]): PromiseLogicError;
|
|
51
58
|
|
|
52
59
|
export { PromiseLogic, PromiseLogicError, PromiseWithTimer, createLogicError, createPromiseLogic };
|
|
53
|
-
export type { CreatePromiseLogicOptions, FlipFlop };
|
|
60
|
+
export type { CreatePromiseLogicOptions, FlipFlop, LogicGateOptions };
|
package/dist/v2/factory.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";class e extends Error{constructor(e,t,
|
|
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};
|
package/dist/v2/factory.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e extends Error{constructor(e,t,
|
|
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};
|
package/dist/v2/index.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";class e extends Error{constructor(e,t,
|
|
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};
|
package/dist/v2/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e extends Error{constructor(e,t,
|
|
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};
|
package/dist/v2/types/index.d.ts
CHANGED
|
@@ -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):
|
|
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:
|
|
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
|
|
60
|
-
static or<T>(iterable: Iterable<T | PromiseLike<T
|
|
61
|
-
static race<T>(iterable: Iterable<T | PromiseLike<T
|
|
62
|
-
static allSettled<T>(iterable: Iterable<T | PromiseLike<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
|
|
66
|
-
static not<T>(promise: T | PromiseLike<T
|
|
67
|
-
static nand<T>(iterable: Iterable<T | PromiseLike<T
|
|
68
|
-
static nor<T>(iterable: Iterable<T | PromiseLike<T
|
|
69
|
-
static xnor<T>(iterable: Iterable<T | PromiseLike<T
|
|
70
|
-
static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?:
|
|
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<
|
|
74
|
-
static allRejected<T>(iterable: Iterable<T | PromiseLike<T
|
|
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,
|
|
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