@context-action/core 1.2.6 → 1.3.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +18 -1
  3. package/dist/element-BJpk34By.d.cts +35 -0
  4. package/dist/element-BJpk34By.d.cts.map +1 -0
  5. package/dist/element-BJpk34By.d.ts +35 -0
  6. package/dist/element-BJpk34By.d.ts.map +1 -0
  7. package/dist/element-BcfeiQgA.cjs +190 -0
  8. package/dist/element-DSSLaFmw.js +180 -0
  9. package/dist/element-DSSLaFmw.js.map +1 -0
  10. package/dist/element-react.cjs +81 -0
  11. package/dist/element-react.d.cts +11 -0
  12. package/dist/element-react.d.cts.map +1 -0
  13. package/dist/element-react.d.ts +11 -0
  14. package/dist/element-react.d.ts.map +1 -0
  15. package/dist/element-react.js +79 -0
  16. package/dist/element-react.js.map +1 -0
  17. package/dist/element.cjs +5 -0
  18. package/dist/element.d.cts +3 -0
  19. package/dist/element.d.ts +3 -0
  20. package/dist/element.js +3 -0
  21. package/dist/index.cjs +154 -47
  22. package/dist/index.d.cts +2 -1
  23. package/dist/index.d.cts.map +1 -1
  24. package/dist/index.d.ts +2 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +154 -47
  27. package/dist/index.js.map +1 -1
  28. package/dist/public-action-methods-C_ppItRr.d.cts +5 -0
  29. package/dist/public-action-methods-C_ppItRr.d.cts.map +1 -0
  30. package/dist/public-action-methods-C_ppItRr.d.ts +5 -0
  31. package/dist/public-action-methods-C_ppItRr.d.ts.map +1 -0
  32. package/docs/action-contracts.md +78 -0
  33. package/docs/element-host-patterns.en.md +129 -0
  34. package/docs/element-host-patterns.ko.md +116 -0
  35. package/docs/element-interop.md +126 -0
  36. package/docs/interop-review.en.md +55 -0
  37. package/docs/interop-review.ko.md +51 -0
  38. package/package.json +35 -4
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  //#region src/action-guard.ts
2
+ function validateDelay(value, label) {
3
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new RangeError(`${label} must be a non-negative finite number.`);
4
+ }
2
5
  /**
3
6
  * Action Guard system for managing action execution timing
4
7
  *
@@ -97,6 +100,7 @@ var ActionGuard = class {
97
100
  * @internal
98
101
  */
99
102
  async debounce(actionKey, debounceMs, signal) {
103
+ validateDelay(debounceMs, "debounce");
100
104
  this.ensureAutoCleanup();
101
105
  if (signal?.aborted) return false;
102
106
  /** Get or create guard state for this action */
@@ -176,6 +180,7 @@ var ActionGuard = class {
176
180
  * @internal
177
181
  */
178
182
  throttle(actionKey, throttleMs, signal) {
183
+ validateDelay(throttleMs, "throttle");
179
184
  this.ensureAutoCleanup();
180
185
  if (signal?.aborted) return false;
181
186
  /** Get or create guard state for this action */
@@ -698,6 +703,26 @@ function createSkippedOutcome(registration) {
698
703
  metadata: registration.config.metadata ? { ...registration.config.metadata } : void 0
699
704
  };
700
705
  }
706
+ /** Concurrent-mode conditions are preconditions for the entire attempt.
707
+ * Do not consume once registrations until every condition has been evaluated
708
+ * without throwing. A false condition skips only its own registration. */
709
+ function selectConcurrentHandlers(context) {
710
+ const eligibleHandlers = [];
711
+ for (const registration of context.handlers) {
712
+ if (registration.config.condition && !registration.config.condition(context.payload)) {
713
+ (context.handlerOutcomes ?? (context.handlerOutcomes = [])).push(createSkippedOutcome(registration));
714
+ continue;
715
+ }
716
+ eligibleHandlers.push(registration);
717
+ }
718
+ return eligibleHandlers.filter((registration) => {
719
+ if (context.claimOnce && !context.claimOnce(registration)) {
720
+ (context.handlerOutcomes ?? (context.handlerOutcomes = [])).push(createSkippedOutcome(registration));
721
+ return false;
722
+ }
723
+ return true;
724
+ });
725
+ }
701
726
  function finishOutcome(outcome, startedAt, status, result, error) {
702
727
  outcome.status = status;
703
728
  outcome.duration = Date.now() - startedAt;
@@ -863,18 +888,7 @@ async function executeParallel(context, createController) {
863
888
  * before any handler starts so a predicate error rejects the dispatch rather
864
889
  * than being mistaken for a non-blocking handler failure.
865
890
  */
866
- const runnableHandlers = [];
867
- for (const registration of context.handlers) {
868
- if (registration.config.condition && !registration.config.condition(context.payload)) {
869
- (context.handlerOutcomes ?? (context.handlerOutcomes = [])).push(createSkippedOutcome(registration));
870
- continue;
871
- }
872
- if (context.claimOnce && !context.claimOnce(registration)) {
873
- (context.handlerOutcomes ?? (context.handlerOutcomes = [])).push(createSkippedOutcome(registration));
874
- continue;
875
- }
876
- runnableHandlers.push(registration);
877
- }
891
+ const runnableHandlers = selectConcurrentHandlers(context);
878
892
  const terminationSlots = runnableHandlers.map(() => ({
879
893
  requested: false,
880
894
  result: void 0
@@ -973,18 +987,7 @@ async function executeParallel(context, createController) {
973
987
  */
974
988
  async function executeRace(context, createController) {
975
989
  /** See executeParallel: condition errors are dispatch errors in concurrent modes. */
976
- const runnableHandlers = [];
977
- for (const registration of context.handlers) {
978
- if (registration.config.condition && !registration.config.condition(context.payload)) {
979
- (context.handlerOutcomes ?? (context.handlerOutcomes = [])).push(createSkippedOutcome(registration));
980
- continue;
981
- }
982
- if (context.claimOnce && !context.claimOnce(registration)) {
983
- (context.handlerOutcomes ?? (context.handlerOutcomes = [])).push(createSkippedOutcome(registration));
984
- continue;
985
- }
986
- runnableHandlers.push(registration);
987
- }
990
+ const runnableHandlers = selectConcurrentHandlers(context);
988
991
  if (runnableHandlers.length === 0) return;
989
992
  /** Create promises for all handlers */
990
993
  const handlerPromises = runnableHandlers.map(async (registration, _index) => {
@@ -1108,6 +1111,29 @@ function normalizePositiveLimit(value, fallback, label) {
1108
1111
  if (!Number.isSafeInteger(limit) || limit <= 0) throw new RangeError(`${label} must be a positive safe integer or Infinity.`);
1109
1112
  return limit;
1110
1113
  }
1114
+ function validateNonNegativeFiniteNumber(value, label) {
1115
+ if (value === void 0) return;
1116
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new RangeError(`${label} must be a non-negative finite number.`);
1117
+ }
1118
+ function validateTimingConfig(config) {
1119
+ validateNonNegativeFiniteNumber(config?.debounce, "debounce");
1120
+ validateNonNegativeFiniteNumber(config?.throttle, "throttle");
1121
+ }
1122
+ function validateRetryOptions(options) {
1123
+ const retry = options?.retryOnError;
1124
+ if (!retry) return;
1125
+ if (retry.maxAttempts !== void 0 && (!Number.isSafeInteger(retry.maxAttempts) || retry.maxAttempts < 1)) throw new RangeError("retryOnError.maxAttempts must be a positive safe integer.");
1126
+ validateNonNegativeFiniteNumber(retry.delay, "retryOnError.delay");
1127
+ if (retry.attemptBarrier !== void 0 && retry.attemptBarrier !== "abort-and-drain" && retry.attemptBarrier !== "abort-and-overlap") throw new TypeError("retryOnError.attemptBarrier must be \"abort-and-drain\" or \"abort-and-overlap\".");
1128
+ }
1129
+ function validateDispatchTimingOptions(options) {
1130
+ validateNonNegativeFiniteNumber(options?.debounce, "debounce");
1131
+ validateNonNegativeFiniteNumber(options?.throttle, "throttle");
1132
+ validateRetryOptions(options);
1133
+ }
1134
+ function getAbortReason(signal) {
1135
+ return typeof signal?.reason === "string" ? signal.reason : "Action dispatch aborted by signal";
1136
+ }
1111
1137
  /**
1112
1138
  * Action Register for managing action handlers with priority-based execution
1113
1139
  *
@@ -1436,6 +1462,7 @@ var ActionRegister = class {
1436
1462
  * 🆕 Perform synchronous handler registration
1437
1463
  */
1438
1464
  _performRegistrationSync(action, handler, config, handlerId, role = "legacy") {
1465
+ validateTimingConfig(config);
1439
1466
  const registration = {
1440
1467
  handler,
1441
1468
  config: resolveHandlerConfig(config, handlerId),
@@ -1450,24 +1477,29 @@ var ActionRegister = class {
1450
1477
  if (existingIndex !== -1) {
1451
1478
  const existing = pipeline[existingIndex];
1452
1479
  const existingUnregister = actionUnregisterFunctions.get(handlerId);
1453
- if (existing && (existing.role ?? "legacy") !== role) throw new Error(`Action handler role conflict for "${String(action)}" and id "${handlerId}": cannot replace ${existing.role ?? "legacy"} with ${role}.`);
1480
+ if (!existing) throw new Error("Internal error: existing handler should be defined in duplicate handler block");
1481
+ if ((existing.role ?? "legacy") !== role) throw new Error(`Action handler role conflict for "${String(action)}" and id "${handlerId}": cannot replace ${existing.role ?? "legacy"} with ${role}.`);
1454
1482
  if (registration.config.replaceExisting) {
1483
+ this.removeRegistration(action, existing, false);
1484
+ let currentPipeline = this.pipelines.get(action);
1485
+ if (!currentPipeline) {
1486
+ currentPipeline = [];
1487
+ this.pipelines.set(action, currentPipeline);
1488
+ }
1489
+ currentPipeline.push(registration);
1490
+ currentPipeline.sort((a, b) => b.config.priority - a.config.priority);
1491
+ this.lastRegisteredTimestamps.set(action, /* @__PURE__ */ new Date());
1492
+ const newUnregister = this.createUnregisterFunction(action, handlerId, registration);
1493
+ this.getUnregisterFunctions(action).set(handlerId, newUnregister);
1455
1494
  if (existing?.config.cleanup && typeof existing.config.cleanup === "function") try {
1456
1495
  existing.config.cleanup();
1457
1496
  } catch (cleanupError) {
1458
1497
  this.log(`Cleanup error for replaced handler: ${String(action)}`, cleanupError, "warn");
1459
1498
  }
1460
- if (existing) this.observerHandlers.delete(existing);
1461
- if (existingUnregister) actionUnregisterFunctions.delete(handlerId);
1462
- pipeline[existingIndex] = registration;
1463
- pipeline.sort((a, b) => b.config.priority - a.config.priority);
1464
- this.lastRegisteredTimestamps.set(action, /* @__PURE__ */ new Date());
1465
- const newUnregister = this.createUnregisterFunction(action, handlerId, registration);
1466
- actionUnregisterFunctions.set(handlerId, newUnregister);
1467
1499
  this.log(`Handler replaced: ${String(action)}`, {
1468
1500
  handlerId,
1469
1501
  priority: config.priority,
1470
- totalHandlers: pipeline.length,
1502
+ totalHandlers: this.pipelines.get(action)?.length ?? 0,
1471
1503
  hadExistingUnregister: Boolean(existingUnregister)
1472
1504
  });
1473
1505
  return newUnregister;
@@ -1499,12 +1531,21 @@ var ActionRegister = class {
1499
1531
  dispatch(action, ...args) {
1500
1532
  this.assertStringActionKey(action);
1501
1533
  const [payload, options] = args;
1534
+ validateDispatchTimingOptions(options);
1502
1535
  const trace = this.beginDispatchTrace(String(action), options);
1503
1536
  if (this.lifecycleState !== "active") return this.withDispatchTrace(this.rejectedLifecyclePromise(), trace, () => "failed");
1504
1537
  const timeoutScope = this.createTimeoutScope(action, options);
1505
1538
  const dispatchHandlerPromises = /* @__PURE__ */ new Set();
1506
1539
  const attemptState = { count: 0 };
1507
- const plan = this.resolveDispatchPlan(action, options);
1540
+ let plan;
1541
+ try {
1542
+ plan = this.resolveDispatchPlan(action, options);
1543
+ } catch (error) {
1544
+ timeoutScope.cleanup();
1545
+ timeoutScope.cleanupSignals();
1546
+ trace.settle("failed");
1547
+ throw error;
1548
+ }
1508
1549
  const hasTimingGuard = plan.debounceMs !== void 0 || plan.throttleMs !== void 0;
1509
1550
  const notifiedObservers = /* @__PURE__ */ new Set();
1510
1551
  const notifiedObserverOutcomes = /* @__PURE__ */ new Set();
@@ -1639,7 +1680,37 @@ var ActionRegister = class {
1639
1680
  if (timeoutScope.options?.immediate || !this.dispatchQueue) return pipelineOperation();
1640
1681
  const queued = this.dispatchQueue.enqueueWithHandle(pipelineOperation, timeoutScope.options?.queuePriority ?? 0);
1641
1682
  timeoutScope.onTimeout((error) => queued.cancel(error));
1642
- return queued.promise;
1683
+ const callerSignal = options?.signal;
1684
+ let removeCallerAbortListener;
1685
+ const cleanupCallerAbortListener = () => {
1686
+ removeCallerAbortListener?.();
1687
+ removeCallerAbortListener = void 0;
1688
+ };
1689
+ if (callerSignal) {
1690
+ const cancelQueued = () => {
1691
+ queued.cancel(callerSignal.reason);
1692
+ };
1693
+ callerSignal.addEventListener("abort", cancelQueued, { once: true });
1694
+ removeCallerAbortListener = () => callerSignal.removeEventListener("abort", cancelQueued);
1695
+ if (callerSignal.aborted) cancelQueued();
1696
+ }
1697
+ return queued.promise.then((value) => {
1698
+ cleanupCallerAbortListener();
1699
+ return value;
1700
+ }, (error) => {
1701
+ cleanupCallerAbortListener();
1702
+ throw error;
1703
+ }).catch(async (error) => {
1704
+ if (!(this.lifecycleState === "active" && callerSignal?.aborted === true && !(timeoutScope.options?.signal?.reason instanceof ActionTimeoutError))) throw error;
1705
+ await notifyObservers({
1706
+ action: String(action),
1707
+ payload,
1708
+ outcome: "cancelled",
1709
+ result: void 0,
1710
+ errors: [],
1711
+ signal: timeoutScope.options?.signal
1712
+ });
1713
+ });
1643
1714
  };
1644
1715
  let dispatchPromise;
1645
1716
  let observedDispatchPromise;
@@ -1692,9 +1763,8 @@ var ActionRegister = class {
1692
1763
  }
1693
1764
  /** Execute a dispatch operation with an optional whole-action retry policy. */
1694
1765
  async executeWithRetry(operation, options, attemptState, shouldRetryResult, canRetry = () => true, telemetry, beforeRetry) {
1695
- const configuredAttempts = options?.retryOnError?.maxAttempts ?? 1;
1696
- const maxAttempts = Number.isFinite(configuredAttempts) ? Math.max(1, Math.floor(configuredAttempts)) : 1;
1697
- const retryDelay = Math.max(0, options?.retryOnError?.delay ?? 0);
1766
+ const maxAttempts = options?.retryOnError?.maxAttempts ?? 1;
1767
+ const retryDelay = options?.retryOnError?.delay ?? 0;
1698
1768
  while (attemptState.count < maxAttempts) {
1699
1769
  attemptState.count += 1;
1700
1770
  const attemptStartedAt = Date.now();
@@ -1946,7 +2016,7 @@ var ActionRegister = class {
1946
2016
  errors: result.error.issues.map((issue) => issue.message)
1947
2017
  };
1948
2018
  }
1949
- createAbortedExecutionResult(startTime, skippedRegistrations = [], validation) {
2019
+ createAbortedExecutionResult(startTime, skippedRegistrations = [], validation, abortReason = "Action dispatch aborted by signal") {
1950
2020
  const endTime = Date.now();
1951
2021
  const handlers = skippedRegistrations.map((registration) => ({
1952
2022
  id: registration.id,
@@ -1960,7 +2030,7 @@ var ActionRegister = class {
1960
2030
  return {
1961
2031
  success: false,
1962
2032
  aborted: true,
1963
- abortReason: "Action dispatch aborted by signal",
2033
+ abortReason,
1964
2034
  terminated: false,
1965
2035
  outcome: "cancelled",
1966
2036
  validation,
@@ -2055,6 +2125,7 @@ var ActionRegister = class {
2055
2125
  }
2056
2126
  if (!shouldRun) continue;
2057
2127
  const detachedOnce = registration.config.once && this.removeRegistration(action, registration, false);
2128
+ if (registration.config.once && !detachedOnce) continue;
2058
2129
  const cleanupOnce = () => {
2059
2130
  if (detachedOnce) this.runRegistrationCleanup(action, registration);
2060
2131
  };
@@ -2272,6 +2343,7 @@ var ActionRegister = class {
2272
2343
  dispatchWithResult(action, ...args) {
2273
2344
  this.assertStringActionKey(action);
2274
2345
  const [payload, options] = args;
2346
+ validateDispatchTimingOptions(options);
2275
2347
  const trace = this.beginDispatchTrace(String(action), options);
2276
2348
  if (this.lifecycleState !== "active") return this.withDispatchTrace(this.rejectedLifecyclePromise(), trace, () => "failed");
2277
2349
  const timeoutScope = this.createTimeoutScope(action, options);
@@ -2287,7 +2359,15 @@ var ActionRegister = class {
2287
2359
  retryDelayDuration: 0,
2288
2360
  attempts: []
2289
2361
  };
2290
- const plan = this.resolveDispatchPlan(action, options);
2362
+ let plan;
2363
+ try {
2364
+ plan = this.resolveDispatchPlan(action, options);
2365
+ } catch (error) {
2366
+ timeoutScope.cleanup();
2367
+ timeoutScope.cleanupSignals();
2368
+ trace.settle("failed");
2369
+ throw error;
2370
+ }
2291
2371
  const hasTimingGuard = plan.debounceMs !== void 0 || plan.throttleMs !== void 0;
2292
2372
  const pipelineOperation = async () => {
2293
2373
  pipelineStartedAt = Date.now();
@@ -2354,19 +2434,19 @@ var ActionRegister = class {
2354
2434
  const operation = async () => {
2355
2435
  if (timeoutScope.options?.signal?.aborted) {
2356
2436
  admissionEndedAt = Date.now();
2357
- return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results]);
2437
+ return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results], void 0, getAbortReason(timeoutScope.options?.signal));
2358
2438
  }
2359
2439
  validation = this.validatePayload(action, payload);
2360
2440
  if (timeoutScope.options?.signal?.aborted) {
2361
2441
  admissionEndedAt = Date.now();
2362
- return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results], validation);
2442
+ return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results], validation, getAbortReason(timeoutScope.options?.signal));
2363
2443
  }
2364
2444
  this.validateResultOptions(options?.result);
2365
2445
  if (hasTimingGuard) {
2366
2446
  const admission = await this.evaluateTimingGuards(String(action), plan, timeoutScope.options?.signal);
2367
2447
  if (admission.aborted || timeoutScope.options?.signal?.aborted) {
2368
2448
  admissionEndedAt = Date.now();
2369
- return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results], validation);
2449
+ return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results], validation, getAbortReason(timeoutScope.options?.signal));
2370
2450
  }
2371
2451
  if (admission.reason) {
2372
2452
  admissionEndedAt = Date.now();
@@ -2375,13 +2455,36 @@ var ActionRegister = class {
2375
2455
  }
2376
2456
  if (timeoutScope.options?.signal?.aborted) {
2377
2457
  admissionEndedAt = Date.now();
2378
- return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results], validation);
2458
+ return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results], validation, getAbortReason(timeoutScope.options?.signal));
2379
2459
  }
2380
2460
  admissionEndedAt = Date.now();
2381
2461
  if (timeoutScope.options?.immediate || !this.dispatchQueue) return pipelineOperation();
2382
2462
  const queued = this.dispatchQueue.enqueueWithHandle(pipelineOperation, timeoutScope.options?.queuePriority ?? 0);
2383
2463
  timeoutScope.onTimeout((error) => queued.cancel(error));
2384
- return queued.promise;
2464
+ const callerSignal = options?.signal;
2465
+ let removeCallerAbortListener;
2466
+ const cleanupCallerAbortListener = () => {
2467
+ removeCallerAbortListener?.();
2468
+ removeCallerAbortListener = void 0;
2469
+ };
2470
+ if (callerSignal) {
2471
+ const cancelQueued = () => {
2472
+ queued.cancel(callerSignal.reason);
2473
+ };
2474
+ callerSignal.addEventListener("abort", cancelQueued, { once: true });
2475
+ removeCallerAbortListener = () => callerSignal.removeEventListener("abort", cancelQueued);
2476
+ if (callerSignal.aborted) cancelQueued();
2477
+ }
2478
+ return queued.promise.then((value) => {
2479
+ cleanupCallerAbortListener();
2480
+ return value;
2481
+ }, (error) => {
2482
+ cleanupCallerAbortListener();
2483
+ throw error;
2484
+ }).catch((error) => {
2485
+ if (!(this.lifecycleState === "active" && callerSignal?.aborted === true && !(timeoutScope.options?.signal?.reason instanceof ActionTimeoutError))) throw error;
2486
+ return this.createAbortedExecutionResult(dispatchStartTime, [...plan.guards, ...plan.results], validation, getAbortReason(timeoutScope.options?.signal));
2487
+ });
2385
2488
  };
2386
2489
  const notifiedObservers = /* @__PURE__ */ new Set();
2387
2490
  const notifiedObserverOutcomes = /* @__PURE__ */ new Set();
@@ -2488,7 +2591,7 @@ var ActionRegister = class {
2488
2591
  if (options?.autoAbort?.onControllerCreated && autoAbortController) options.autoAbort.onControllerCreated(autoAbortController);
2489
2592
  if (effectiveSignal?.aborted) {
2490
2593
  cleanup();
2491
- return this.createAbortedExecutionResult(_startTime, plan.results, validation);
2594
+ return this.createAbortedExecutionResult(_startTime, plan.results, validation, getAbortReason(effectiveSignal));
2492
2595
  }
2493
2596
  const pipeline = plan.pipelineSnapshot;
2494
2597
  if (!pipeline || pipeline.length === 0) {
@@ -2876,6 +2979,8 @@ var ActionRegister = class {
2876
2979
  this.pipelines.delete(action);
2877
2980
  this.lastRegisteredTimestamps.delete(action);
2878
2981
  this.actionGuard.clearGuards(String(action));
2982
+ this.actionDispatchers.delete(String(action));
2983
+ this.actionResultDispatchers.delete(String(action));
2879
2984
  }
2880
2985
  /**
2881
2986
  * Remove all handlers for all actions
@@ -2894,6 +2999,8 @@ var ActionRegister = class {
2894
2999
  this.unregisterFunctions.clear();
2895
3000
  this.actionGuard.clearAll();
2896
3001
  this.observerHandlers.clear();
3002
+ this.actionDispatchers.clear();
3003
+ this.actionResultDispatchers.clear();
2897
3004
  }
2898
3005
  /**
2899
3006
  * Get the name of this action register