@nice-code/action 0.0.21 → 0.1.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 (48) hide show
  1. package/build/index.js +1128 -749
  2. package/build/react-query/index.js +170 -45
  3. package/build/types/ActionDomain/NiceActionDomain.d.ts +18 -46
  4. package/build/types/ActionDomain/NiceActionDomain.types.d.ts +9 -45
  5. package/build/types/ActionDomain/NiceActionDomainBase.d.ts +14 -0
  6. package/build/types/ActionDomain/RootDomain/NiceActionRootDomain.d.ts +22 -0
  7. package/build/types/ActionDomain/helpers/createRootActionDomain.d.ts +5 -0
  8. package/build/types/ActionRuntimeEnvironment/ActionConnect/ActionConnect.d.ts +24 -0
  9. package/build/types/ActionRuntimeEnvironment/ActionConnect/ActionConnect.types.d.ts +15 -0
  10. package/build/types/ActionRuntimeEnvironment/ActionConnect/ConnectionConfig/ConnectionConfig.d.ts +12 -0
  11. package/build/types/ActionRuntimeEnvironment/ActionConnect/ConnectionConfig/ConnectionConfig.types.d.ts +6 -0
  12. package/build/types/ActionRuntimeEnvironment/ActionConnect/Transport/Transport.d.ts +16 -0
  13. package/build/types/ActionRuntimeEnvironment/ActionConnect/Transport/Transport.types.d.ts +50 -0
  14. package/build/types/ActionRuntimeEnvironment/ActionConnect/Transport/TransportHttp.d.ts +9 -0
  15. package/build/types/ActionRuntimeEnvironment/ActionConnect/Transport/TransportWebSocket.d.ts +15 -0
  16. package/build/types/ActionRuntimeEnvironment/ActionConnect/Transport/err_nice_transport.d.ts +34 -0
  17. package/build/types/ActionRuntimeEnvironment/ActionConnect/Transport/err_nice_transport_ws.d.ts +18 -0
  18. package/build/types/ActionRuntimeEnvironment/ActionConnect/err_nice_connect.d.ts +5 -0
  19. package/build/types/ActionRuntimeEnvironment/ActionHandler/ActionHandler.d.ts +80 -0
  20. package/build/types/ActionRuntimeEnvironment/ActionHandler/ActionHandler.types.d.ts +68 -0
  21. package/build/types/ActionRuntimeEnvironment/ActionRuntimeEnvironment.d.ts +32 -0
  22. package/build/types/ActionRuntimeEnvironment/ActionRuntimeEnvironment.types.d.ts +15 -0
  23. package/build/types/ActionRuntimeEnvironment/utils/getAssumedRuntimeEnvironment.d.ts +2 -0
  24. package/build/types/ActionSchema/NiceActionSchema.d.ts +11 -7
  25. package/build/types/ActionSchema/NiceActionSchema.types.d.ts +1 -1
  26. package/build/types/NiceAction/MatchAction/MatchAction.d.ts +26 -0
  27. package/build/types/NiceAction/NiceAction.d.ts +18 -20
  28. package/build/types/NiceAction/NiceAction.enums.d.ts +5 -0
  29. package/build/types/NiceAction/NiceAction.types.d.ts +7 -10
  30. package/build/types/NiceAction/NiceActionCombined.types.d.ts +10 -0
  31. package/build/types/NiceAction/NiceActionPrimed.d.ts +19 -36
  32. package/build/types/NiceAction/NiceActionResponse.d.ts +15 -6
  33. package/build/types/NiceAction/utils/isNiceActionInstance.d.ts +3 -0
  34. package/build/types/errors/err_nice_action.d.ts +34 -12
  35. package/build/types/index.d.ts +16 -8
  36. package/build/types/react-query/index.d.ts +6 -8
  37. package/package.json +8 -6
  38. package/build/types/ActionDomain/createActionDomain.d.ts +0 -5
  39. package/build/types/ActionRequestResponse/ActionRequester/NiceActionRequester.d.ts +0 -31
  40. package/build/types/ActionRequestResponse/ActionResponder/NiceActionResponder.d.ts +0 -49
  41. package/build/types/ActionRequestResponse/ActionResponder/NiceActionResponder.types.d.ts +0 -7
  42. package/build/types/ActionRequestResponse/ActionResponder/NiceActionResponderEnvironment.d.ts +0 -42
  43. package/build/types/NiceAction/ActionSchema/NiceActionSchema.d.ts +0 -99
  44. package/build/types/NiceAction/ActionSchema/NiceActionSchema.types.d.ts +0 -31
  45. package/build/types/NiceAction/ActionSchema/NiceActionSchemaBuilder.d.ts +0 -1
  46. package/build/types/NiceAction/ActionSchema/action.d.ts +0 -2
  47. package/build/types/NiceAction/NiceActionPrimed.schema.d.ts +0 -8
  48. package/build/types/test/nice_action_test_schema.d.ts +0 -30
package/build/index.js CHANGED
@@ -30,47 +30,76 @@ var __toESM = (mod, isNodeMode, target) => {
30
30
  };
31
31
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
32
32
 
33
- // src/ActionRequestResponse/ActionRequester/NiceActionRequester.ts
34
- class NiceActionRequester {
35
- cases = [];
36
- _defaultRequester;
37
- async handleAction(action) {
38
- for (const actionCase of this.cases) {
39
- if (!actionCase._matcher(action))
40
- continue;
41
- return await actionCase._requester(action);
42
- }
43
- if (this._defaultRequester) {
44
- return await this._defaultRequester(action);
45
- }
46
- throw new Error(`No handler found for action "${action.coreAction.id}" in domain "${action.coreAction.domain}"`);
47
- }
48
- forDomain(domain, handler) {
49
- this.cases.push({
50
- _matcher: (action) => domain.isExactActionDomain(action),
51
- _requester: handler
52
- });
53
- return this;
54
- }
55
- forActionId(domain, id, handler) {
56
- this.cases.push({
57
- _matcher: (action) => domain.isExactActionDomain(action) && action.coreAction.id === id,
58
- _requester: handler
59
- });
60
- return this;
61
- }
62
- forActionIds(domain, ids, handler) {
63
- this.cases.push({
64
- _matcher: (action) => domain.isExactActionDomain(action) && ids.includes(action.coreAction.id),
65
- _requester: handler
66
- });
67
- return this;
68
- }
69
- setDefaultHandler(handler) {
70
- this._defaultRequester = handler;
71
- return this;
72
- }
33
+ // ../../node_modules/.bun/std-env@4.1.0/node_modules/std-env/dist/index.mjs
34
+ var e = globalThis.process?.env || Object.create(null);
35
+ var t = globalThis.process || { env: e };
36
+ var n = t !== undefined && t.env && t.env.NODE_ENV || undefined;
37
+ var r = [[`claude`, [`CLAUDECODE`, `CLAUDE_CODE`]], [`replit`, [`REPL_ID`]], [`gemini`, [`GEMINI_CLI`]], [`codex`, [`CODEX_SANDBOX`, `CODEX_THREAD_ID`]], [`opencode`, [`OPENCODE`]], [`pi`, [i(`PATH`, /\.pi[\\/]agent/)]], [`auggie`, [`AUGMENT_AGENT`]], [`goose`, [`GOOSE_PROVIDER`]], [`devin`, [i(`EDITOR`, /devin/)]], [`cursor`, [`CURSOR_AGENT`]], [`kiro`, [i(`TERM_PROGRAM`, /kiro/)]]];
38
+ function i(t2, n2) {
39
+ return () => {
40
+ let r2 = e[t2];
41
+ return r2 ? n2.test(r2) : false;
42
+ };
73
43
  }
44
+ function a() {
45
+ let t2 = e.AI_AGENT;
46
+ if (t2)
47
+ return { name: t2.toLowerCase() };
48
+ for (let [t3, n2] of r)
49
+ for (let r2 of n2)
50
+ if (typeof r2 == `string` ? e[r2] : r2())
51
+ return { name: t3 };
52
+ return {};
53
+ }
54
+ var o = a();
55
+ var s = o.name;
56
+ var c = !!o.name;
57
+ var l = [[`APPVEYOR`], [`AWS_AMPLIFY`, `AWS_APP_ID`, { ci: true }], [`AZURE_PIPELINES`, `SYSTEM_TEAMFOUNDATIONCOLLECTIONURI`], [`AZURE_STATIC`, `INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN`], [`APPCIRCLE`, `AC_APPCIRCLE`], [`BAMBOO`, `bamboo_planKey`], [`BITBUCKET`, `BITBUCKET_COMMIT`], [`BITRISE`, `BITRISE_IO`], [`BUDDY`, `BUDDY_WORKSPACE_ID`], [`BUILDKITE`], [`CIRCLE`, `CIRCLECI`], [`CIRRUS`, `CIRRUS_CI`], [`CLOUDFLARE_PAGES`, `CF_PAGES`, { ci: true }], [`CLOUDFLARE_WORKERS`, `WORKERS_CI`, { ci: true }], [`GOOGLE_CLOUDRUN`, `K_SERVICE`], [`GOOGLE_CLOUDRUN_JOB`, `CLOUD_RUN_JOB`], [`CODEBUILD`, `CODEBUILD_BUILD_ARN`], [`CODEFRESH`, `CF_BUILD_ID`], [`DRONE`], [`DRONE`, `DRONE_BUILD_EVENT`], [`DSARI`], [`GITHUB_ACTIONS`], [`GITLAB`, `GITLAB_CI`], [`GITLAB`, `CI_MERGE_REQUEST_ID`], [`GOCD`, `GO_PIPELINE_LABEL`], [`LAYERCI`], [`JENKINS`, `JENKINS_URL`], [`HUDSON`, `HUDSON_URL`], [`MAGNUM`], [`NETLIFY`], [`NETLIFY`, `NETLIFY_LOCAL`, { ci: false }], [`NEVERCODE`], [`RENDER`], [`SAIL`, `SAILCI`], [`SEMAPHORE`], [`SCREWDRIVER`], [`SHIPPABLE`], [`SOLANO`, `TDDIUM`], [`STRIDER`], [`TEAMCITY`, `TEAMCITY_VERSION`], [`TRAVIS`], [`VERCEL`, `NOW_BUILDER`], [`VERCEL`, `VERCEL`, { ci: false }], [`VERCEL`, `VERCEL_ENV`, { ci: false }], [`APPCENTER`, `APPCENTER_BUILD_ID`], [`CODESANDBOX`, `CODESANDBOX_SSE`, { ci: false }], [`CODESANDBOX`, `CODESANDBOX_HOST`, { ci: false }], [`STACKBLITZ`], [`STORMKIT`], [`CLEAVR`], [`ZEABUR`], [`CODESPHERE`, `CODESPHERE_APP_ID`, { ci: true }], [`RAILWAY`, `RAILWAY_PROJECT_ID`], [`RAILWAY`, `RAILWAY_SERVICE_ID`], [`DENO-DEPLOY`, `DENO_DEPLOY`], [`DENO-DEPLOY`, `DENO_DEPLOYMENT_ID`], [`FIREBASE_APP_HOSTING`, `FIREBASE_APP_HOSTING`, { ci: true }], [`EDGEONE_PAGES`, `EO_PAGES_CI`, { ci: true }]];
58
+ function u() {
59
+ for (let t2 of l)
60
+ if (e[t2[1] || t2[0]])
61
+ return { name: t2[0].toLowerCase(), ...t2[2] };
62
+ return e.SHELL === `/bin/jsh` && t.versions?.webcontainer ? { name: `stackblitz`, ci: false } : { name: ``, ci: false };
63
+ }
64
+ var d = u();
65
+ var f = d.name;
66
+ var p = t.platform || ``;
67
+ var m = !!e.CI || d.ci !== false;
68
+ var h = !!t.stdout?.isTTY;
69
+ var _ = !!e.DEBUG;
70
+ var v = n === `test` || !!e.TEST;
71
+ var y = n === `production` || e.MODE === `production`;
72
+ var b = n === `dev` || n === `development` || e.MODE === `development`;
73
+ var x = !!e.MINIMAL || m || v || !h;
74
+ var S = /^win/i.test(p);
75
+ var C = /^linux/i.test(p);
76
+ var w = /^darwin/i.test(p);
77
+ var T = !e.NO_COLOR && (!!e.FORCE_COLOR || (h || S) && e.TERM !== `dumb` || m);
78
+ var E = (t.versions?.node || ``).replace(/^v/, ``) || null;
79
+ var D = Number(E?.split(`.`)[0]) || null;
80
+ var O = !!t?.versions?.node;
81
+ var k = `Bun` in globalThis;
82
+ var A = `Deno` in globalThis;
83
+ var j = `fastly` in globalThis;
84
+ var M = `Netlify` in globalThis;
85
+ var N = `EdgeRuntime` in globalThis;
86
+ var P = globalThis.navigator?.userAgent === `Cloudflare-Workers`;
87
+ var F = [[M, `netlify`], [N, `edge-light`], [P, `workerd`], [j, `fastly`], [A, `deno`], [k, `bun`], [O, `node`]];
88
+ function I() {
89
+ let e2 = F.find((e3) => e3[0]);
90
+ if (e2)
91
+ return { name: e2[1] };
92
+ }
93
+ var L = I();
94
+ var R = L?.name || ``;
95
+
96
+ // src/ActionRuntimeEnvironment/utils/getAssumedRuntimeEnvironment.ts
97
+ var getAssumedRuntimeInfo = () => {
98
+ return {
99
+ assumed: true,
100
+ runtimeName: R
101
+ };
102
+ };
74
103
 
75
104
  // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/legacy.js
76
105
  var ACCEPTED = 202;
@@ -385,14 +414,14 @@ var StatusCodes;
385
414
  })(StatusCodes || (StatusCodes = {}));
386
415
  // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/index.js
387
416
  var __assign = function() {
388
- __assign = Object.assign || function(t) {
389
- for (var s, i = 1, n = arguments.length;i < n; i++) {
390
- s = arguments[i];
391
- for (var p in s)
392
- if (Object.prototype.hasOwnProperty.call(s, p))
393
- t[p] = s[p];
394
- }
395
- return t;
417
+ __assign = Object.assign || function(t2) {
418
+ for (var s2, i2 = 1, n2 = arguments.length;i2 < n2; i2++) {
419
+ s2 = arguments[i2];
420
+ for (var p2 in s2)
421
+ if (Object.prototype.hasOwnProperty.call(s2, p2))
422
+ t2[p2] = s2[p2];
423
+ }
424
+ return t2;
396
425
  };
397
426
  return __assign.apply(this, arguments);
398
427
  };
@@ -512,7 +541,7 @@ class NiceError extends Error {
512
541
  const otherIds = other.getIds().map(String).sort();
513
542
  if (myIds.length !== otherIds.length)
514
543
  return false;
515
- return myIds.every((id, i) => id === otherIds[i]);
544
+ return myIds.every((id, i2) => id === otherIds[i2]);
516
545
  }
517
546
  toJsonObject() {
518
547
  const originError = this.originError ? {
@@ -971,17 +1000,17 @@ var err_nice_handler = err_nice.createChildDomain({
971
1000
  function isNiceErrorObject(obj) {
972
1001
  if (typeof obj !== "object" || obj == null)
973
1002
  return false;
974
- const o = obj;
975
- if (o["name"] !== "NiceError" || typeof o["message"] !== "string" || typeof o["wasntNice"] !== "boolean" || typeof o["httpStatusCode"] !== "number") {
1003
+ const o2 = obj;
1004
+ if (o2["name"] !== "NiceError" || typeof o2["message"] !== "string" || typeof o2["wasntNice"] !== "boolean" || typeof o2["httpStatusCode"] !== "number") {
976
1005
  return false;
977
1006
  }
978
- const def = o["def"];
1007
+ const def = o2["def"];
979
1008
  if (typeof def !== "object" || def == null)
980
1009
  return false;
981
- const d = def;
982
- if (typeof d["domain"] !== "string" || !Array.isArray(d["allDomains"]))
1010
+ const d2 = def;
1011
+ if (typeof d2["domain"] !== "string" || !Array.isArray(d2["allDomains"]))
983
1012
  return false;
984
- const errorData = o["errorData"];
1013
+ const errorData = o2["errorData"];
985
1014
  if (errorData != null) {
986
1015
  if (typeof errorData !== "object")
987
1016
  return false;
@@ -990,8 +1019,8 @@ function isNiceErrorObject(obj) {
990
1019
  continue;
991
1020
  if (typeof entry !== "object")
992
1021
  return false;
993
- const e = entry;
994
- const state = e["contextState"];
1022
+ const e2 = entry;
1023
+ const state = e2["contextState"];
995
1024
  if (state == null || typeof state !== "object")
996
1025
  return false;
997
1026
  const kind = state["kind"];
@@ -1006,8 +1035,8 @@ function isNiceErrorObject(obj) {
1006
1035
  function isRegularErrorJsonObject(obj) {
1007
1036
  if (typeof obj !== "object" || obj == null)
1008
1037
  return false;
1009
- const o = obj;
1010
- return typeof o["name"] === "string" && typeof o["message"] === "string";
1038
+ const o2 = obj;
1039
+ return typeof o2["name"] === "string" && typeof o2["message"] === "string";
1011
1040
  }
1012
1041
 
1013
1042
  // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/urlToObj.js
@@ -1093,8 +1122,8 @@ function formatTemplate(settings, template, values, hideUnsetPlaceholder = false
1093
1122
  }
1094
1123
  };
1095
1124
  const defaultStyle = null;
1096
- return templateString.replace(/{{(.+?)}}/g, (_, placeholder) => {
1097
- const value = values[placeholder] != null ? String(values[placeholder]) : hideUnsetPlaceholder ? "" : _;
1125
+ return templateString.replace(/{{(.+?)}}/g, (_2, placeholder) => {
1126
+ const value = values[placeholder] != null ? String(values[placeholder]) : hideUnsetPlaceholder ? "" : _2;
1098
1127
  return settings.stylePrettyLogs ? styleWrap(value, settings?.prettyLogStyles?.[placeholder] ?? defaultStyle) + ansiColorWrap("", prettyLogStyles.reset) : value;
1099
1128
  });
1100
1129
  }
@@ -1343,14 +1372,14 @@ function isRegExp(re) {
1343
1372
  function isObject(arg) {
1344
1373
  return typeof arg === "object" && arg !== null;
1345
1374
  }
1346
- function isError(e) {
1347
- return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error);
1375
+ function isError(e2) {
1376
+ return isObject(e2) && (objectToString(e2) === "[object Error]" || e2 instanceof Error);
1348
1377
  }
1349
- function isDate(d) {
1350
- return isObject(d) && objectToString(d) === "[object Date]";
1378
+ function isDate(d2) {
1379
+ return isObject(d2) && objectToString(d2) === "[object Date]";
1351
1380
  }
1352
- function objectToString(o) {
1353
- return Object.prototype.toString.call(o);
1381
+ function objectToString(o2) {
1382
+ return Object.prototype.toString.call(o2);
1354
1383
  }
1355
1384
  function arrayToHash(array) {
1356
1385
  const hash = {};
@@ -1361,9 +1390,9 @@ function arrayToHash(array) {
1361
1390
  }
1362
1391
  function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
1363
1392
  const output = [];
1364
- for (let i = 0, l = value.length;i < l; ++i) {
1365
- if (hasOwn(value, String(i))) {
1366
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
1393
+ for (let i2 = 0, l2 = value.length;i2 < l2; ++i2) {
1394
+ if (hasOwn(value, String(i2))) {
1395
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i2), true));
1367
1396
  } else {
1368
1397
  output.push("");
1369
1398
  }
@@ -1434,8 +1463,8 @@ function formatValue(ctx, value, recurseTimes = 0) {
1434
1463
  ]`];
1435
1464
  }
1436
1465
  if (isFunction(value)) {
1437
- const n = value.name ? ": " + value.name : "";
1438
- base = " [Function" + n + "]";
1466
+ const n2 = value.name ? ": " + value.name : "";
1467
+ base = " [Function" + n2 + "]";
1439
1468
  }
1440
1469
  if (isRegExp(value)) {
1441
1470
  base = " " + RegExp.prototype.toString.call(value);
@@ -1561,9 +1590,9 @@ function _extend(origin, add) {
1561
1590
  return origin;
1562
1591
  const clonedAdd = { ...add };
1563
1592
  const keys = Object.keys(add);
1564
- let i = keys.length;
1565
- while (i--) {
1566
- typedOrigin[keys[i]] = clonedAdd[keys[i]];
1593
+ let i2 = keys.length;
1594
+ while (i2--) {
1595
+ typedOrigin[keys[i2]] = clonedAdd[keys[i2]];
1567
1596
  }
1568
1597
  return typedOrigin;
1569
1598
  }
@@ -1576,7 +1605,7 @@ function formatWithOptions(inspectOptions, ...args) {
1576
1605
  _extend(ctx, inspectOptions);
1577
1606
  }
1578
1607
  const first = args[0];
1579
- let a = 0;
1608
+ let a2 = 0;
1580
1609
  let str = "";
1581
1610
  let join = "";
1582
1611
  if (typeof first === "string") {
@@ -1585,13 +1614,13 @@ function formatWithOptions(inspectOptions, ...args) {
1585
1614
  }
1586
1615
  let tempStr;
1587
1616
  let lastPos = 0;
1588
- for (let i = 0;i < first.length - 1; i++) {
1589
- if (first.charCodeAt(i) === 37) {
1590
- const nextChar = first.charCodeAt(++i);
1591
- if (a + 1 !== args.length) {
1617
+ for (let i2 = 0;i2 < first.length - 1; i2++) {
1618
+ if (first.charCodeAt(i2) === 37) {
1619
+ const nextChar = first.charCodeAt(++i2);
1620
+ if (a2 + 1 !== args.length) {
1592
1621
  switch (nextChar) {
1593
1622
  case 115: {
1594
- const tempArg = args[++a];
1623
+ const tempArg = args[++a2];
1595
1624
  if (typeof tempArg === "number") {
1596
1625
  tempStr = formatPrimitive(ctx, tempArg);
1597
1626
  } else if (typeof tempArg === "bigint") {
@@ -1609,10 +1638,10 @@ function formatWithOptions(inspectOptions, ...args) {
1609
1638
  break;
1610
1639
  }
1611
1640
  case 106:
1612
- tempStr = jsonStringifyRecursive(args[++a]);
1641
+ tempStr = jsonStringifyRecursive(args[++a2]);
1613
1642
  break;
1614
1643
  case 100: {
1615
- const tempNum = args[++a];
1644
+ const tempNum = args[++a2];
1616
1645
  if (typeof tempNum === "bigint") {
1617
1646
  tempStr = formatPrimitive(ctx, tempNum);
1618
1647
  } else if (typeof tempNum === "symbol") {
@@ -1623,10 +1652,10 @@ function formatWithOptions(inspectOptions, ...args) {
1623
1652
  break;
1624
1653
  }
1625
1654
  case 79:
1626
- tempStr = inspect(args[++a], inspectOptions);
1655
+ tempStr = inspect(args[++a2], inspectOptions);
1627
1656
  break;
1628
1657
  case 111:
1629
- tempStr = inspect(args[++a], {
1658
+ tempStr = inspect(args[++a2], {
1630
1659
  ...inspectOptions,
1631
1660
  showHidden: true,
1632
1661
  showProxy: true,
@@ -1634,7 +1663,7 @@ function formatWithOptions(inspectOptions, ...args) {
1634
1663
  });
1635
1664
  break;
1636
1665
  case 105: {
1637
- const tempInteger = args[++a];
1666
+ const tempInteger = args[++a2];
1638
1667
  if (typeof tempInteger === "bigint") {
1639
1668
  tempStr = formatPrimitive(ctx, tempInteger);
1640
1669
  } else if (typeof tempInteger === "symbol") {
@@ -1645,7 +1674,7 @@ function formatWithOptions(inspectOptions, ...args) {
1645
1674
  break;
1646
1675
  }
1647
1676
  case 102: {
1648
- const tempFloat = args[++a];
1677
+ const tempFloat = args[++a2];
1649
1678
  if (typeof tempFloat === "symbol") {
1650
1679
  tempStr = "NaN";
1651
1680
  } else {
@@ -1654,41 +1683,41 @@ function formatWithOptions(inspectOptions, ...args) {
1654
1683
  break;
1655
1684
  }
1656
1685
  case 99:
1657
- a += 1;
1686
+ a2 += 1;
1658
1687
  tempStr = "";
1659
1688
  break;
1660
1689
  case 37:
1661
- str += first.slice(lastPos, i);
1662
- lastPos = i + 1;
1690
+ str += first.slice(lastPos, i2);
1691
+ lastPos = i2 + 1;
1663
1692
  continue;
1664
1693
  default:
1665
1694
  continue;
1666
1695
  }
1667
- if (lastPos !== i - 1) {
1668
- str += first.slice(lastPos, i - 1);
1696
+ if (lastPos !== i2 - 1) {
1697
+ str += first.slice(lastPos, i2 - 1);
1669
1698
  }
1670
1699
  str += tempStr;
1671
- lastPos = i + 1;
1700
+ lastPos = i2 + 1;
1672
1701
  } else if (nextChar === 37) {
1673
- str += first.slice(lastPos, i);
1674
- lastPos = i + 1;
1702
+ str += first.slice(lastPos, i2);
1703
+ lastPos = i2 + 1;
1675
1704
  }
1676
1705
  }
1677
1706
  }
1678
1707
  if (lastPos !== 0) {
1679
- a++;
1708
+ a2++;
1680
1709
  join = " ";
1681
1710
  if (lastPos < first.length) {
1682
1711
  str += first.slice(lastPos);
1683
1712
  }
1684
1713
  }
1685
1714
  }
1686
- while (a < args.length) {
1687
- const value = args[a];
1715
+ while (a2 < args.length) {
1716
+ const value = args[a2];
1688
1717
  str += join;
1689
1718
  str += typeof value !== "string" ? inspect(value, inspectOptions) : value;
1690
1719
  join = " ";
1691
- a++;
1720
+ a2++;
1692
1721
  }
1693
1722
  return str;
1694
1723
  }
@@ -2455,16 +2484,16 @@ error stack:
2455
2484
  return urlToObject(source);
2456
2485
  } else if (source !== null && typeof source === "object") {
2457
2486
  const baseObject = runtime.isError(source) ? this._cloneError(source) : Object.create(Object.getPrototypeOf(source));
2458
- return Object.getOwnPropertyNames(source).reduce((o, prop) => {
2487
+ return Object.getOwnPropertyNames(source).reduce((o2, prop) => {
2459
2488
  const lookupKey = this.settings?.maskValuesOfKeysCaseInsensitive !== true ? prop : typeof prop === "string" ? prop.toLowerCase() : String(prop).toLowerCase();
2460
- o[prop] = keys.includes(lookupKey) ? this.settings.maskPlaceholder : (() => {
2489
+ o2[prop] = keys.includes(lookupKey) ? this.settings.maskPlaceholder : (() => {
2461
2490
  try {
2462
2491
  return this._recursiveCloneAndMaskValuesOfKeys(source[prop], keys, seen);
2463
2492
  } catch {
2464
2493
  return null;
2465
2494
  }
2466
2495
  })();
2467
- return o;
2496
+ return o2;
2468
2497
  }, baseObject);
2469
2498
  } else {
2470
2499
  if (typeof source === "string") {
@@ -2489,14 +2518,14 @@ error stack:
2489
2518
  } else if (source instanceof Date) {
2490
2519
  return new Date(source.getTime());
2491
2520
  } else if (this.isObject(source)) {
2492
- return Object.getOwnPropertyNames(source).reduce((o, prop) => {
2521
+ return Object.getOwnPropertyNames(source).reduce((o2, prop) => {
2493
2522
  const descriptor = Object.getOwnPropertyDescriptor(source, prop);
2494
2523
  if (descriptor) {
2495
- Object.defineProperty(o, prop, descriptor);
2524
+ Object.defineProperty(o2, prop, descriptor);
2496
2525
  const value = source[prop];
2497
- o[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
2526
+ o2[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
2498
2527
  }
2499
- return o;
2528
+ return o2;
2500
2529
  }, Object.create(Object.getPrototypeOf(source)));
2501
2530
  } else {
2502
2531
  return source;
@@ -2786,16 +2815,20 @@ var castNiceError = (error) => {
2786
2815
  var EErrId_NiceAction;
2787
2816
  ((EErrId_NiceAction2) => {
2788
2817
  EErrId_NiceAction2["action_id_not_in_domain"] = "action_id_not_in_domain";
2789
- EErrId_NiceAction2["domain_action_requester_conflict"] = "domain_action_handler_conflict";
2818
+ EErrId_NiceAction2["domain_already_exists_in_hierarchy"] = "domain_already_exists_in_hierarchy";
2790
2819
  EErrId_NiceAction2["domain_no_handler"] = "domain_no_handler";
2791
2820
  EErrId_NiceAction2["hydration_domain_mismatch"] = "hydration_domain_mismatch";
2792
2821
  EErrId_NiceAction2["hydration_action_state_mismatch"] = "hydration_action_state_mismatch";
2793
2822
  EErrId_NiceAction2["hydration_action_id_not_found"] = "hydration_action_id_not_found";
2794
- EErrId_NiceAction2["resolver_domain_not_registered"] = "resolver_domain_not_registered";
2795
- EErrId_NiceAction2["resolver_action_not_registered"] = "resolver_action_not_registered";
2796
- EErrId_NiceAction2["action_environment_not_found"] = "action_environment_not_found";
2823
+ EErrId_NiceAction2["no_action_execution_handler"] = "no_action_execution_handler";
2824
+ EErrId_NiceAction2["wire_action_not_primed_or_response"] = "wire_action_not_primed_or_response";
2825
+ EErrId_NiceAction2["wire_not_action_data"] = "wire_not_action_data";
2826
+ EErrId_NiceAction2["action_tag_handler_not_found"] = "action_tag_handler_not_found";
2797
2827
  EErrId_NiceAction2["environment_already_registered"] = "environment_already_registered";
2798
2828
  EErrId_NiceAction2["action_input_validation_failed"] = "action_input_validation_failed";
2829
+ EErrId_NiceAction2["action_input_validation_promise"] = "action_input_validation_promise";
2830
+ EErrId_NiceAction2["action_output_validation_failed"] = "action_output_validation_failed";
2831
+ EErrId_NiceAction2["action_output_validation_promise"] = "action_output_validation_promise";
2799
2832
  })(EErrId_NiceAction ||= {});
2800
2833
  var err_nice_action = err_nice.createChildDomain({
2801
2834
  domain: "err_nice_action",
@@ -2804,11 +2837,11 @@ var err_nice_action = err_nice.createChildDomain({
2804
2837
  ["action_id_not_in_domain" /* action_id_not_in_domain */]: err({
2805
2838
  message: ({ actionId, domain }) => `Action with id "${actionId}" does not exist in domain "${domain}".`
2806
2839
  }),
2807
- ["domain_action_handler_conflict" /* domain_action_requester_conflict */]: err({
2808
- message: ({ domain }) => `Domain "${domain}" already has a handler set. Multiple handlers for the same domain are not allowed.`
2840
+ ["domain_already_exists_in_hierarchy" /* domain_already_exists_in_hierarchy */]: err({
2841
+ message: ({ domain, allParentDomains, parentDomain }) => `Domain "${domain}" already exists in the hierarchy under the parent "${parentDomain}". All parent domains ["${allParentDomains.join(", ")}"]`
2809
2842
  }),
2810
2843
  ["domain_no_handler" /* domain_no_handler */]: err({
2811
- message: ({ domain }) => `Domain "${domain}" has no action handler registered. Call setActionHandler() before executing actions.`
2844
+ message: ({ domain }) => `Domain "${domain}" has no action handler registered. Set a runtime environment via setRuntimeEnvironment() and add handlers before executing actions.`
2812
2845
  }),
2813
2846
  ["hydration_domain_mismatch" /* hydration_domain_mismatch */]: err({
2814
2847
  message: ({ expected, received }) => `Cannot hydrate action: domain mismatch. Expected "${expected}", got "${received}".`
@@ -2819,440 +2852,158 @@ var err_nice_action = err_nice.createChildDomain({
2819
2852
  ["hydration_action_id_not_found" /* hydration_action_id_not_found */]: err({
2820
2853
  message: ({ domain, actionId }) => `Cannot hydrate action: id "${actionId}" does not exist in domain "${domain}".`
2821
2854
  }),
2822
- ["resolver_domain_not_registered" /* resolver_domain_not_registered */]: err({
2823
- message: ({ domain }) => `No resolver registered for domain "${domain}". Add a NiceActionDomainResolver for this domain to the environment.`
2855
+ ["no_action_execution_handler" /* no_action_execution_handler */]: err({
2856
+ message: ({ domain, actionId }) => `No action handler registered for "${actionId}" in domain "${domain}": no execution handler matched.`
2857
+ }),
2858
+ ["wire_action_not_primed_or_response" /* wire_action_not_primed_or_response */]: err({
2859
+ message: ({ domain, actionId, actionState }) => `Cannot handle wire for action "${actionId}" in domain "${domain}": expected action type of "primed" or "resolved", got "${actionState}".`
2824
2860
  }),
2825
- ["resolver_action_not_registered" /* resolver_action_not_registered */]: err({
2826
- message: ({ domain, actionId }) => `No resolver registered for action "${actionId}" in domain "${domain}". Call .resolve("${actionId}", fn) on the domain resolver.`
2861
+ ["wire_not_action_data" /* wire_not_action_data */]: err({
2862
+ message: () => `Cannot handle wire for action: expected an object with a "domain" property of type string and a "type" property of "primed" or "resolved".`
2827
2863
  }),
2828
- ["action_environment_not_found" /* action_environment_not_found */]: err({
2829
- message: ({ domain, envId }) => `No handler or resolver registered with environment id "${envId}" on domain "${domain}".`
2864
+ ["action_tag_handler_not_found" /* action_tag_handler_not_found */]: err({
2865
+ message: ({ domain, matchTag }) => `No handler registered for tag "${matchTag}" on domain "${domain}".`
2830
2866
  }),
2831
2867
  ["environment_already_registered" /* environment_already_registered */]: err({
2832
- message: ({ domain, envId }) => `Environment "${envId}" is already registered on domain "${domain}". Each environment id may only be registered once.`
2868
+ message: ({ domain, matchTag }) => `Environment "${matchTag}" is already registered on domain "${domain}". Each environment id may only be registered once.`
2833
2869
  }),
2834
2870
  ["action_input_validation_failed" /* action_input_validation_failed */]: err({
2835
2871
  message: ({ domain, actionId, validationMessage }) => `Input validation failed for action "${actionId}" in domain "${domain}":
2836
2872
  ${validationMessage}`,
2837
2873
  httpStatusCode: 400
2874
+ }),
2875
+ ["action_input_validation_promise" /* action_input_validation_promise */]: err({
2876
+ message: ({ domain, actionId }) => `Input validation for action "${actionId}" in domain "${domain}" returned a promise, which is not supported.`,
2877
+ httpStatusCode: 400
2878
+ }),
2879
+ ["action_output_validation_failed" /* action_output_validation_failed */]: err({
2880
+ message: ({ domain, actionId, validationMessage }) => `Output validation failed for action "${actionId}" in domain "${domain}":
2881
+ ${validationMessage}`,
2882
+ httpStatusCode: 500
2883
+ }),
2884
+ ["action_output_validation_promise" /* action_output_validation_promise */]: err({
2885
+ message: ({ domain, actionId }) => `Output validation for action "${actionId}" in domain "${domain}" returned a promise, which is not supported.`,
2886
+ httpStatusCode: 500
2838
2887
  })
2839
2888
  }
2840
2889
  });
2841
2890
 
2842
- // ../../node_modules/.bun/nanoid@5.1.9/node_modules/nanoid/url-alphabet/index.js
2843
- var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
2891
+ // src/NiceAction/NiceAction.enums.ts
2892
+ var EActionState;
2893
+ ((EActionState2) => {
2894
+ EActionState2["empty"] = "empty";
2895
+ EActionState2["primed"] = "primed";
2896
+ EActionState2["resolved"] = "resolved";
2897
+ })(EActionState ||= {});
2844
2898
 
2845
- // ../../node_modules/.bun/nanoid@5.1.9/node_modules/nanoid/index.browser.js
2846
- var nanoid = (size = 21) => {
2847
- let id = "";
2848
- let bytes = crypto.getRandomValues(new Uint8Array(size |= 0));
2849
- while (size--) {
2850
- id += urlAlphabet[bytes[size] & 63];
2899
+ // src/NiceAction/NiceActionPrimed.ts
2900
+ class NiceActionPrimed {
2901
+ coreAction;
2902
+ _input;
2903
+ type = "primed" /* primed */;
2904
+ domain;
2905
+ allDomains;
2906
+ id;
2907
+ timePrimed;
2908
+ cuid;
2909
+ schema;
2910
+ timeCreated;
2911
+ constructor(coreAction, _input, hydrationData) {
2912
+ this.coreAction = coreAction;
2913
+ this._input = _input;
2914
+ this.domain = coreAction.domain;
2915
+ this.allDomains = coreAction.allDomains;
2916
+ this.id = coreAction.id;
2917
+ this.timePrimed = hydrationData?.timePrimed ?? Date.now();
2918
+ this.cuid = coreAction.cuid;
2919
+ this.schema = coreAction.schema;
2920
+ this.timeCreated = coreAction.timeCreated;
2851
2921
  }
2852
- return id;
2853
- };
2854
-
2855
- // ../../node_modules/.bun/valibot@1.3.1+8e24a2f921b8d7be/node_modules/valibot/dist/index.mjs
2856
- var store$4;
2857
- function getGlobalConfig(config$1) {
2858
- return {
2859
- lang: config$1?.lang ?? store$4?.lang,
2860
- message: config$1?.message,
2861
- abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
2862
- abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
2863
- };
2864
- }
2865
- var store$3;
2866
- function getGlobalMessage(lang) {
2867
- return store$3?.get(lang);
2868
- }
2869
- var store$2;
2870
- function getSchemaMessage(lang) {
2871
- return store$2?.get(lang);
2872
- }
2873
- var store$1;
2874
- function getSpecificMessage(reference, lang) {
2875
- return store$1?.get(reference)?.get(lang);
2876
- }
2877
- function _stringify(input) {
2878
- const type = typeof input;
2879
- if (type === "string")
2880
- return `"${input}"`;
2881
- if (type === "number" || type === "bigint" || type === "boolean")
2882
- return `${input}`;
2883
- if (type === "object" || type === "function")
2884
- return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
2885
- return type;
2886
- }
2887
- function _addIssue(context, label, dataset, config$1, other) {
2888
- const input = other && "input" in other ? other.input : dataset.value;
2889
- const expected = other?.expected ?? context.expects ?? null;
2890
- const received = other?.received ?? /* @__PURE__ */ _stringify(input);
2891
- const issue = {
2892
- kind: context.kind,
2893
- type: context.type,
2894
- input,
2895
- expected,
2896
- received,
2897
- message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
2898
- requirement: context.requirement,
2899
- path: other?.path,
2900
- issues: other?.issues,
2901
- lang: config$1.lang,
2902
- abortEarly: config$1.abortEarly,
2903
- abortPipeEarly: config$1.abortPipeEarly
2904
- };
2905
- const isSchema = context.kind === "schema";
2906
- const message$1 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config$1.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
2907
- if (message$1 !== undefined)
2908
- issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
2909
- if (isSchema)
2910
- dataset.typed = false;
2911
- if (dataset.issues)
2912
- dataset.issues.push(issue);
2913
- else
2914
- dataset.issues = [issue];
2915
- }
2916
- function _getStandardProps(context) {
2917
- return {
2918
- version: 1,
2919
- vendor: "valibot",
2920
- validate(value$1) {
2921
- return context["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig());
2922
- }
2923
- };
2924
- }
2925
- function includes(requirement, message$1) {
2926
- const expects = /* @__PURE__ */ _stringify(requirement);
2927
- return {
2928
- kind: "validation",
2929
- type: "includes",
2930
- reference: includes,
2931
- async: false,
2932
- expects,
2933
- requirement,
2934
- message: message$1,
2935
- "~run"(dataset, config$1) {
2936
- if (dataset.typed && !dataset.value.includes(this.requirement))
2937
- _addIssue(this, "content", dataset, config$1, { received: `!${expects}` });
2938
- return dataset;
2939
- }
2940
- };
2941
- }
2942
- function length(requirement, message$1) {
2943
- return {
2944
- kind: "validation",
2945
- type: "length",
2946
- reference: length,
2947
- async: false,
2948
- expects: `${requirement}`,
2949
- requirement,
2950
- message: message$1,
2951
- "~run"(dataset, config$1) {
2952
- if (dataset.typed && dataset.value.length !== this.requirement)
2953
- _addIssue(this, "length", dataset, config$1, { received: `${dataset.value.length}` });
2954
- return dataset;
2955
- }
2956
- };
2957
- }
2958
- var _LruCache = class {
2959
- constructor(config$1) {
2960
- this.refCount = 0;
2961
- this.maxSize = config$1?.maxSize ?? 1000;
2962
- this.maxAge = config$1?.maxAge ?? Infinity;
2963
- this.hasMaxAge = isFinite(this.maxAge);
2964
- }
2965
- #stringify(input) {
2966
- const type = typeof input;
2967
- if (type === "string")
2968
- return `"${input}"`;
2969
- if (type === "number" || type === "boolean")
2970
- return `${input}`;
2971
- if (type === "bigint")
2972
- return `${input}n`;
2973
- if (type === "object" || type === "function") {
2974
- if (input) {
2975
- this.refIds ??= /* @__PURE__ */ new WeakMap;
2976
- let id = this.refIds.get(input);
2977
- if (!id) {
2978
- id = ++this.refCount;
2979
- this.refIds.set(input, id);
2980
- }
2981
- return `#${id}`;
2982
- }
2983
- return "null";
2984
- }
2985
- return type;
2922
+ get input() {
2923
+ return this._input;
2986
2924
  }
2987
- key(input, config$1 = {}) {
2988
- return `${this.#stringify(input)}|${this.#stringify(config$1.lang)}|${this.#stringify(config$1.message)}|${this.#stringify(config$1.abortEarly)}|${this.#stringify(config$1.abortPipeEarly)}`;
2925
+ getEnvironmentMeta() {
2926
+ return this.coreAction.actionDomain.getEnvironmentMeta();
2989
2927
  }
2990
- get(key) {
2991
- if (!this.store)
2992
- return;
2993
- const entry = this.store.get(key);
2994
- if (!entry)
2995
- return;
2996
- if (this.hasMaxAge && Date.now() - entry[1] > this.maxAge) {
2997
- this.store.delete(key);
2998
- return;
2999
- }
3000
- this.store.delete(key);
3001
- this.store.set(key, entry);
3002
- return entry[0];
2928
+ toJsonObject() {
2929
+ return {
2930
+ ...this.coreAction.toJsonObject(),
2931
+ type: "primed" /* primed */,
2932
+ input: this.coreAction.schema.serializeInput(this.input),
2933
+ timePrimed: this.timePrimed
2934
+ };
3003
2935
  }
3004
- set(key, value$1) {
3005
- this.store ??= /* @__PURE__ */ new Map;
3006
- this.store.delete(key);
3007
- const timestamp = this.hasMaxAge ? Date.now() : 0;
3008
- this.store.set(key, [value$1, timestamp]);
3009
- if (this.store.size > this.maxSize)
3010
- this.store.delete(this.store.keys().next().value);
2936
+ toJsonString() {
2937
+ return JSON.stringify(this.toJsonObject());
3011
2938
  }
3012
- clear() {
3013
- this.store?.clear();
2939
+ hydratePrimeJson(wire) {
2940
+ return this.coreAction.actionDomain.hydratePrimed(wire);
3014
2941
  }
3015
- };
3016
- function getFallback(schema, dataset, config$1) {
3017
- return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
3018
- }
3019
- function getDefault(schema, dataset, config$1) {
3020
- return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
3021
- }
3022
- function array(item, message$1) {
3023
- return {
3024
- kind: "schema",
3025
- type: "array",
3026
- reference: array,
3027
- expects: "Array",
3028
- async: false,
3029
- item,
3030
- message: message$1,
3031
- get "~standard"() {
3032
- return /* @__PURE__ */ _getStandardProps(this);
3033
- },
3034
- "~run"(dataset, config$1) {
3035
- const input = dataset.value;
3036
- if (Array.isArray(input)) {
3037
- dataset.typed = true;
3038
- dataset.value = [];
3039
- for (let key = 0;key < input.length; key++) {
3040
- const value$1 = input[key];
3041
- const itemDataset = this.item["~run"]({ value: value$1 }, config$1);
3042
- if (itemDataset.issues) {
3043
- const pathItem = {
3044
- type: "array",
3045
- origin: "value",
3046
- input,
3047
- key,
3048
- value: value$1
3049
- };
3050
- for (const issue of itemDataset.issues) {
3051
- if (issue.path)
3052
- issue.path.unshift(pathItem);
3053
- else
3054
- issue.path = [pathItem];
3055
- dataset.issues?.push(issue);
3056
- }
3057
- if (!dataset.issues)
3058
- dataset.issues = itemDataset.issues;
3059
- if (config$1.abortEarly) {
3060
- dataset.typed = false;
3061
- break;
3062
- }
3063
- }
3064
- if (!itemDataset.typed)
3065
- dataset.typed = false;
3066
- dataset.value.push(itemDataset.value);
3067
- }
3068
- } else
3069
- _addIssue(this, "type", dataset, config$1);
3070
- return dataset;
3071
- }
3072
- };
3073
- }
3074
- function literal(literal_, message$1) {
3075
- return {
3076
- kind: "schema",
3077
- type: "literal",
3078
- reference: literal,
3079
- expects: /* @__PURE__ */ _stringify(literal_),
3080
- async: false,
3081
- literal: literal_,
3082
- message: message$1,
3083
- get "~standard"() {
3084
- return /* @__PURE__ */ _getStandardProps(this);
3085
- },
3086
- "~run"(dataset, config$1) {
3087
- if (dataset.value === this.literal)
3088
- dataset.typed = true;
3089
- else
3090
- _addIssue(this, "type", dataset, config$1);
3091
- return dataset;
3092
- }
3093
- };
3094
- }
3095
- function nullish(wrapped, default_) {
3096
- return {
3097
- kind: "schema",
3098
- type: "nullish",
3099
- reference: nullish,
3100
- expects: `(${wrapped.expects} | null | undefined)`,
3101
- async: false,
3102
- wrapped,
3103
- default: default_,
3104
- get "~standard"() {
3105
- return /* @__PURE__ */ _getStandardProps(this);
3106
- },
3107
- "~run"(dataset, config$1) {
3108
- if (dataset.value === null || dataset.value === undefined) {
3109
- if (this.default !== undefined)
3110
- dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
3111
- if (dataset.value === null || dataset.value === undefined) {
3112
- dataset.typed = true;
3113
- return dataset;
3114
- }
3115
- }
3116
- return this.wrapped["~run"](dataset, config$1);
3117
- }
3118
- };
3119
- }
3120
- function object(entries$1, message$1) {
3121
- return {
3122
- kind: "schema",
3123
- type: "object",
3124
- reference: object,
3125
- expects: "Object",
3126
- async: false,
3127
- entries: entries$1,
3128
- message: message$1,
3129
- get "~standard"() {
3130
- return /* @__PURE__ */ _getStandardProps(this);
3131
- },
3132
- "~run"(dataset, config$1) {
3133
- const input = dataset.value;
3134
- if (input && typeof input === "object") {
3135
- dataset.typed = true;
3136
- dataset.value = {};
3137
- for (const key in this.entries) {
3138
- const valueSchema = this.entries[key];
3139
- if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== undefined) {
3140
- const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
3141
- const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
3142
- if (valueDataset.issues) {
3143
- const pathItem = {
3144
- type: "object",
3145
- origin: "value",
3146
- input,
3147
- key,
3148
- value: value$1
3149
- };
3150
- for (const issue of valueDataset.issues) {
3151
- if (issue.path)
3152
- issue.path.unshift(pathItem);
3153
- else
3154
- issue.path = [pathItem];
3155
- dataset.issues?.push(issue);
3156
- }
3157
- if (!dataset.issues)
3158
- dataset.issues = valueDataset.issues;
3159
- if (config$1.abortEarly) {
3160
- dataset.typed = false;
3161
- break;
3162
- }
3163
- }
3164
- if (!valueDataset.typed)
3165
- dataset.typed = false;
3166
- dataset.value[key] = valueDataset.value;
3167
- } else if (valueSchema.fallback !== undefined)
3168
- dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
3169
- else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
3170
- _addIssue(this, "key", dataset, config$1, {
3171
- input: undefined,
3172
- expected: `"${key}"`,
3173
- path: [{
3174
- type: "object",
3175
- origin: "key",
3176
- input,
3177
- key,
3178
- value: input[key]
3179
- }]
3180
- });
3181
- if (config$1.abortEarly)
3182
- break;
3183
- }
3184
- }
3185
- } else
3186
- _addIssue(this, "type", dataset, config$1);
3187
- return dataset;
3188
- }
3189
- };
3190
- }
3191
- function string(message$1) {
3192
- return {
3193
- kind: "schema",
3194
- type: "string",
3195
- reference: string,
3196
- expects: "string",
3197
- async: false,
3198
- message: message$1,
3199
- get "~standard"() {
3200
- return /* @__PURE__ */ _getStandardProps(this);
3201
- },
3202
- "~run"(dataset, config$1) {
3203
- if (typeof dataset.value === "string")
3204
- dataset.typed = true;
3205
- else
3206
- _addIssue(this, "type", dataset, config$1);
3207
- return dataset;
3208
- }
3209
- };
3210
- }
3211
- function pipe(...pipe$1) {
3212
- return {
3213
- ...pipe$1[0],
3214
- pipe: pipe$1,
3215
- get "~standard"() {
3216
- return /* @__PURE__ */ _getStandardProps(this);
3217
- },
3218
- "~run"(dataset, config$1) {
3219
- for (const item of pipe$1)
3220
- if (item.kind !== "metadata") {
3221
- if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
3222
- dataset.typed = false;
3223
- break;
3224
- }
3225
- if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly)
3226
- dataset = item["~run"](dataset, config$1);
3227
- }
3228
- return dataset;
2942
+ hydrateResponseJson(wire) {
2943
+ return this.coreAction.actionDomain.hydrateResponse(wire);
2944
+ }
2945
+ errorResponse(err3) {
2946
+ return new NiceActionResponse(this, { ok: false, error: err3 });
2947
+ }
2948
+ toHttpResponse() {
2949
+ return new Response(this.toJsonString(), {
2950
+ status: 200,
2951
+ headers: { "Content-Type": "application/json" }
2952
+ });
2953
+ }
2954
+ setResponse(...args) {
2955
+ const output = args[0];
2956
+ const finalOutput = this.coreAction.schema.validateOutput(output, {
2957
+ domain: this.domain,
2958
+ actionId: this.id
2959
+ });
2960
+ return new NiceActionResponse(this, { ok: true, output: finalOutput });
2961
+ }
2962
+ async execute(meta) {
2963
+ return this.coreAction.actionDomain._executeAction(this, { actionMeta: meta ?? {} });
2964
+ }
2965
+ async executeSafe(meta) {
2966
+ try {
2967
+ const value = await this.execute(meta);
2968
+ return { ok: true, output: value };
2969
+ } catch (error) {
2970
+ return { ok: false, error };
3229
2971
  }
3230
- };
2972
+ }
3231
2973
  }
3232
2974
 
3233
2975
  // src/NiceAction/NiceActionResponse.ts
3234
2976
  class NiceActionResponse {
3235
- type = "response" /* response */;
2977
+ type = "resolved" /* resolved */;
3236
2978
  domain;
3237
2979
  allDomains;
3238
2980
  id;
3239
2981
  primed;
3240
2982
  result;
3241
2983
  timeResponded;
2984
+ cuid;
2985
+ schema;
2986
+ timeCreated;
3242
2987
  constructor(primed, result, hydrationData) {
3243
2988
  this.primed = primed;
3244
2989
  this.result = result;
3245
2990
  this.domain = primed.coreAction.domain;
3246
2991
  this.allDomains = primed.coreAction.allDomains;
3247
2992
  this.id = primed.coreAction.id;
2993
+ this.cuid = primed.coreAction.cuid;
2994
+ this.schema = primed.coreAction.schema;
2995
+ this.timeCreated = primed.coreAction.timeCreated;
3248
2996
  this.timeResponded = hydrationData?.timeResponded ?? Date.now();
3249
2997
  }
2998
+ getEnvironmentMeta() {
2999
+ return this.primed.coreAction.actionDomain.getEnvironmentMeta();
3000
+ }
3250
3001
  toJsonObject() {
3251
3002
  const base = this.primed.toJsonObject();
3252
3003
  if (this.result.ok) {
3253
3004
  return {
3254
3005
  ...base,
3255
- type: "response" /* response */,
3006
+ type: "resolved" /* resolved */,
3256
3007
  ok: true,
3257
3008
  output: this.primed.coreAction.schema.serializeOutput(this.result.output),
3258
3009
  timeResponded: this.timeResponded
@@ -3260,7 +3011,7 @@ class NiceActionResponse {
3260
3011
  }
3261
3012
  return {
3262
3013
  ...base,
3263
- type: "response" /* response */,
3014
+ type: "resolved" /* resolved */,
3264
3015
  ok: false,
3265
3016
  error: this.result.error.toJsonObject(),
3266
3017
  timeResponded: this.timeResponded
@@ -3269,9 +3020,12 @@ class NiceActionResponse {
3269
3020
  toJsonString() {
3270
3021
  return JSON.stringify(this.toJsonObject());
3271
3022
  }
3272
- toHttpResponse() {
3023
+ hydrateResponseJson(wire) {
3024
+ return this.primed.hydrateResponseJson(wire);
3025
+ }
3026
+ toHttpResponse({ useErrorStatus = true } = {}) {
3273
3027
  return new Response(this.toJsonString(), {
3274
- status: 200,
3028
+ status: this.result.ok ? 200 : useErrorStatus ? this.result.error.httpStatusCode : 500,
3275
3029
  headers: { "Content-Type": "application/json" }
3276
3030
  });
3277
3031
  }
@@ -3286,78 +3040,38 @@ function hydrateNiceActionResponse(wire, coreAction) {
3286
3040
  return new NiceActionResponse(primed, { ok: false, error: castNiceError(wire.error) }, { timeResponded: wire.timeResponded });
3287
3041
  }
3288
3042
 
3289
- // src/NiceAction/NiceActionPrimed.ts
3290
- class NiceActionPrimed {
3291
- coreAction;
3292
- input;
3293
- type = "primed" /* primed */;
3294
- domain;
3295
- allDomains;
3296
- id;
3297
- timePrimed;
3298
- constructor(coreAction, input, hydrationData) {
3299
- this.coreAction = coreAction;
3300
- this.input = input;
3301
- this.domain = coreAction.domain;
3302
- this.allDomains = coreAction.allDomains;
3303
- this.id = coreAction.id;
3304
- this.timePrimed = hydrationData?.timePrimed ?? Date.now();
3305
- }
3306
- toJsonObject() {
3307
- return {
3308
- ...this.coreAction.toJsonObject(),
3309
- type: "primed" /* primed */,
3310
- input: this.coreAction.schema.serializeInput(this.input),
3311
- timePrimed: this.timePrimed
3312
- };
3313
- }
3314
- toJsonString() {
3315
- return JSON.stringify(this.toJsonObject());
3316
- }
3317
- toHttpResponse() {
3318
- return new Response(this.toJsonString(), {
3319
- status: 200,
3320
- headers: { "Content-Type": "application/json" }
3321
- });
3322
- }
3323
- setOutput(output) {
3324
- return new NiceActionResponse(this, { ok: true, output });
3325
- }
3326
- processResponse(wire) {
3327
- if (!wire.ok) {
3328
- throw castNiceError(wire.error);
3329
- }
3330
- return this.coreAction.schema.deserializeOutput(wire.output);
3331
- }
3332
- async execute(envId) {
3333
- return this.coreAction._actionDomain._dispatchAction(this, envId);
3334
- }
3335
- async executeSafe(envId) {
3336
- try {
3337
- const value = await this.execute(envId);
3338
- return { ok: true, output: value };
3339
- } catch (error) {
3340
- return { ok: false, error };
3341
- }
3043
+ // src/utils/isActionResponseJsonObject.ts
3044
+ var isActionResponseJsonObject = (obj) => {
3045
+ return typeof obj === "object" && obj !== null && typeof obj.domain === "string" && typeof obj.id === "string" && "input" in obj && (("output" in obj) || ("error" in obj)) && typeof obj.ok === "boolean" && obj.type === "resolved" /* resolved */;
3046
+ };
3047
+
3048
+ // ../../node_modules/.bun/nanoid@5.1.9/node_modules/nanoid/url-alphabet/index.js
3049
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
3050
+
3051
+ // ../../node_modules/.bun/nanoid@5.1.9/node_modules/nanoid/index.browser.js
3052
+ var nanoid = (size = 21) => {
3053
+ let id = "";
3054
+ let bytes = crypto.getRandomValues(new Uint8Array(size |= 0));
3055
+ while (size--) {
3056
+ id += urlAlphabet[bytes[size] & 63];
3342
3057
  }
3343
- }
3058
+ return id;
3059
+ };
3344
3060
 
3345
3061
  // src/NiceAction/NiceAction.ts
3346
3062
  class NiceAction {
3347
3063
  actionDomain;
3348
3064
  schema;
3349
- id;
3350
3065
  type = "empty" /* empty */;
3066
+ id;
3351
3067
  domain;
3352
3068
  allDomains;
3353
- _actionDomain;
3354
3069
  timeCreated;
3355
3070
  cuid;
3356
3071
  constructor(actionDomain, schema, id, hydrationData) {
3357
3072
  this.actionDomain = actionDomain;
3358
3073
  this.schema = schema;
3359
3074
  this.id = id;
3360
- this._actionDomain = actionDomain;
3361
3075
  this.domain = actionDomain.domain;
3362
3076
  this.allDomains = actionDomain.allDomains;
3363
3077
  this.timeCreated = hydrationData?.timeCreated ?? Date.now();
@@ -3382,57 +3096,105 @@ class NiceAction {
3382
3096
  headers: { "Content-Type": "application/json" }
3383
3097
  });
3384
3098
  }
3385
- toValidationSchema() {
3386
- return object({
3387
- domain: literal(this.domain),
3388
- allDomains: pipe(array(string()), length(this.allDomains.length), includes(this.domain)),
3389
- id: literal(this.id)
3390
- });
3391
- }
3392
3099
  is(action) {
3393
3100
  return action instanceof NiceActionPrimed && action.coreAction.domain === this.domain && action.coreAction.id === this.id;
3394
3101
  }
3395
3102
  prime(input, hydrationData) {
3396
- return new NiceActionPrimed(this, input, hydrationData);
3103
+ const validatedInput = this.schema.validateInput(input, {
3104
+ actionId: this.id,
3105
+ domain: this.domain
3106
+ });
3107
+ return new NiceActionPrimed(this, validatedInput, hydrationData);
3397
3108
  }
3398
- async execute(input, envId) {
3399
- const primed = new NiceActionPrimed(this, input);
3400
- return this._actionDomain._dispatchAction(primed, envId);
3109
+ async execute(input, meta) {
3110
+ const primed = this.prime(input);
3111
+ return this.actionDomain._executeAction(primed, { actionMeta: meta ?? {} });
3401
3112
  }
3402
- async executeSafe(input, envId) {
3113
+ async executeSafe(input, meta) {
3403
3114
  try {
3404
- const value = await this.execute(input, envId);
3115
+ const value = await this.execute(input, meta);
3405
3116
  return { ok: true, output: value };
3406
3117
  } catch (error) {
3407
3118
  return { ok: false, error };
3408
3119
  }
3409
3120
  }
3410
- async executeToResponse(input, envId) {
3121
+ async executeToResponse(input, meta) {
3411
3122
  const primed = this.prime(input);
3412
- const result = await this.executeSafe(input, envId);
3123
+ const result = await primed.executeSafe(meta);
3413
3124
  return new NiceActionResponse(primed, result);
3414
3125
  }
3126
+ deserializeInput(serialized) {
3127
+ return this.schema.deserializeInput(serialized);
3128
+ }
3129
+ serializeInput(raw) {
3130
+ return this.schema.serializeInput(raw);
3131
+ }
3132
+ validateInput(input) {
3133
+ return this.schema.validateInput(input, {
3134
+ domain: this.domain,
3135
+ actionId: this.id
3136
+ });
3137
+ }
3138
+ validateOutput(output) {
3139
+ return this.schema.validateOutput(output, {
3140
+ domain: this.domain,
3141
+ actionId: this.id
3142
+ });
3143
+ }
3415
3144
  }
3416
3145
 
3417
- // src/ActionDomain/NiceActionDomain.ts
3418
- class NiceActionDomain {
3146
+ // src/NiceAction/utils/isNiceActionInstance.ts
3147
+ function isNiceActionInstance(value) {
3148
+ return value != null && typeof value === "object" && "domain" in value && typeof value.domain === "string" && "id" in value && typeof value.id === "string" && "type" in value && typeof value.type === "string" && ["empty" /* empty */, "primed" /* primed */, "resolved" /* resolved */].includes(value.type);
3149
+ }
3150
+
3151
+ // src/ActionDomain/NiceActionDomainBase.ts
3152
+ class NiceActionDomainBase {
3419
3153
  domain;
3420
3154
  allDomains;
3421
3155
  actions;
3422
3156
  _listeners = [];
3423
- _requesters = new Map;
3424
- _responders = new Map;
3425
3157
  constructor(definition) {
3426
3158
  this.domain = definition.domain;
3427
3159
  this.allDomains = definition.allDomains;
3428
3160
  this.actions = definition.actions;
3429
3161
  }
3162
+ addActionListener(listener) {
3163
+ this._listeners.push(listener);
3164
+ return () => {
3165
+ this._listeners = this._listeners.filter((l2) => l2 !== listener);
3166
+ };
3167
+ }
3168
+ }
3169
+
3170
+ // src/ActionDomain/NiceActionDomain.ts
3171
+ class NiceActionDomain extends NiceActionDomainBase {
3172
+ _rootDomain;
3173
+ constructor(definition, {
3174
+ rootDomain
3175
+ }) {
3176
+ super(definition);
3177
+ this._rootDomain = rootDomain;
3178
+ }
3179
+ get rootDomain() {
3180
+ return this._rootDomain;
3181
+ }
3182
+ getEnvironmentMeta() {
3183
+ return this.rootDomain.getEnvironmentMeta();
3184
+ }
3430
3185
  createChildDomain(subDomainDef) {
3186
+ if (this.allDomains.includes(subDomainDef.domain)) {
3187
+ throw err_nice_action.fromId("domain_already_exists_in_hierarchy" /* domain_already_exists_in_hierarchy */, {
3188
+ domain: subDomainDef.domain,
3189
+ allParentDomains: this.allDomains,
3190
+ parentDomain: this.domain
3191
+ });
3192
+ }
3431
3193
  return new NiceActionDomain({
3432
3194
  allDomains: [subDomainDef.domain, ...this.allDomains],
3433
3195
  domain: subDomainDef.domain,
3434
3196
  actions: subDomainDef.actions
3435
- });
3197
+ }, { rootDomain: this._rootDomain });
3436
3198
  }
3437
3199
  primeUnknown(actionId, input) {
3438
3200
  const action = this.action(actionId).prime(input);
@@ -3451,68 +3213,8 @@ class NiceActionDomain {
3451
3213
  }
3452
3214
  return new NiceAction(this, actionSchema, id, hydrationData);
3453
3215
  }
3454
- isExactActionDomain(action) {
3455
- return action instanceof NiceActionPrimed && this.domain === action.domain;
3456
- }
3457
- matchAction(action, id) {
3458
- if (this.isExactActionDomain(action) && action.coreAction.id === id) {
3459
- return action;
3460
- }
3461
- return null;
3462
- }
3463
- addActionListener(listener) {
3464
- this._listeners.push(listener);
3465
- return () => {
3466
- this._listeners = this._listeners.filter((l) => l !== listener);
3467
- };
3468
- }
3469
- async _dispatchAction(primed, envId) {
3470
- if (envId != null) {
3471
- const envRequester = this._requesters.get(envId);
3472
- if (envRequester) {
3473
- const validatedPrimed = await this._withValidatedInput(primed);
3474
- const result = await envRequester.handleAction(validatedPrimed);
3475
- for (const listener of this._listeners)
3476
- await listener(validatedPrimed);
3477
- return result;
3478
- }
3479
- const envResponder = this._responders.get(envId);
3480
- if (envResponder) {
3481
- const result = await envResponder._resolvePrimed(primed);
3482
- for (const listener of this._listeners)
3483
- await listener(primed);
3484
- return result;
3485
- }
3486
- }
3487
- const defaultRequester = this._requesters.get(undefined);
3488
- if (defaultRequester) {
3489
- const validatedPrimed = await this._withValidatedInput(primed);
3490
- const result = await defaultRequester.handleAction(validatedPrimed);
3491
- for (const listener of this._listeners)
3492
- await listener(validatedPrimed);
3493
- return result;
3494
- }
3495
- const defaultResponder = this._responders.get(undefined);
3496
- if (defaultResponder) {
3497
- const result = await defaultResponder._resolvePrimed(primed);
3498
- for (const listener of this._listeners)
3499
- await listener(primed);
3500
- return result;
3501
- }
3502
- if (envId != null) {
3503
- throw err_nice_action.fromId("action_environment_not_found" /* action_environment_not_found */, {
3504
- domain: this.domain,
3505
- envId
3506
- });
3507
- }
3508
- throw err_nice_action.fromId("domain_no_handler" /* domain_no_handler */, { domain: this.domain });
3509
- }
3510
- async _withValidatedInput(primed) {
3511
- const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3512
- domain: this.domain,
3513
- actionId: primed.coreAction.id
3514
- });
3515
- return primed.coreAction.prime(validatedInput);
3216
+ isDomainAction(action) {
3217
+ return isNiceActionInstance(action) && action.domain === this.domain;
3516
3218
  }
3517
3219
  hydratePrimed(serialized) {
3518
3220
  if (serialized.type !== "primed" /* primed */) {
@@ -3538,15 +3240,15 @@ class NiceActionDomain {
3538
3240
  cuid: serialized.cuid,
3539
3241
  timeCreated: serialized.timeCreated
3540
3242
  });
3541
- const rawInput = coreAction.schema.deserializeInput(serialized.input);
3243
+ const rawInput = coreAction.validateInput(coreAction.deserializeInput(serialized.input));
3542
3244
  return new NiceActionPrimed(coreAction, rawInput, {
3543
3245
  timePrimed: serialized.timePrimed
3544
3246
  });
3545
3247
  }
3546
3248
  hydrateResponse(serialized) {
3547
- if (serialized.type !== "response" /* response */) {
3249
+ if (serialized.type !== "resolved" /* resolved */) {
3548
3250
  throw err_nice_action.fromId("hydration_action_state_mismatch" /* hydration_action_state_mismatch */, {
3549
- expected: "response" /* response */,
3251
+ expected: "resolved" /* resolved */,
3550
3252
  received: serialized.type
3551
3253
  });
3552
3254
  }
@@ -3569,124 +3271,724 @@ class NiceActionDomain {
3569
3271
  });
3570
3272
  return hydrateNiceActionResponse(serialized, coreAction);
3571
3273
  }
3572
- setActionRequester(options, handler) {
3573
- const envId = options?.envId;
3574
- if (this._requesters.has(envId)) {
3575
- if (envId != null) {
3576
- throw err_nice_action.fromId("environment_already_registered" /* environment_already_registered */, {
3577
- domain: this.domain,
3578
- envId
3579
- });
3580
- }
3581
- throw err_nice_action.fromId("domain_action_handler_conflict" /* domain_action_requester_conflict */, {
3582
- domain: this.domain
3274
+ async _executeAction(primed, {
3275
+ actionMeta,
3276
+ listeners
3277
+ }) {
3278
+ const allListeners = [
3279
+ ...listeners ?? [],
3280
+ ...this._listeners
3281
+ ];
3282
+ const output = await this._rootDomain._executeAction(primed, {
3283
+ actionMeta,
3284
+ listeners: allListeners
3285
+ });
3286
+ return output;
3287
+ }
3288
+ }
3289
+
3290
+ // src/ActionDomain/RootDomain/NiceActionRootDomain.ts
3291
+ class NiceActionRootDomain extends NiceActionDomainBase {
3292
+ domainDefinition;
3293
+ _runtimeEnvironment;
3294
+ constructor(domainDefinition) {
3295
+ const domainId = domainDefinition.domain;
3296
+ super({
3297
+ domain: domainId,
3298
+ allDomains: [domainId],
3299
+ actions: {}
3300
+ });
3301
+ this.domainDefinition = domainDefinition;
3302
+ }
3303
+ getEnvironmentMeta() {
3304
+ return {
3305
+ envId: this._runtimeEnvironment?.envId,
3306
+ runtimeInfo: this._runtimeEnvironment?.runtimeInfo ?? getAssumedRuntimeInfo()
3307
+ };
3308
+ }
3309
+ createChildDomain(subDomainDef) {
3310
+ if (this.allDomains.includes(subDomainDef.domain)) {
3311
+ throw err_nice_action.fromId("domain_already_exists_in_hierarchy" /* domain_already_exists_in_hierarchy */, {
3312
+ domain: subDomainDef.domain,
3313
+ allParentDomains: this.allDomains,
3314
+ parentDomain: this.domain
3583
3315
  });
3584
3316
  }
3585
- const h = handler ?? new NiceActionRequester;
3586
- this._requesters.set(envId, h);
3587
- return h;
3317
+ return new NiceActionDomain({
3318
+ allDomains: [subDomainDef.domain, ...this.allDomains],
3319
+ domain: subDomainDef.domain,
3320
+ actions: subDomainDef.actions
3321
+ }, { rootDomain: this });
3588
3322
  }
3589
- registerResponder(resolver, options) {
3590
- const envId = options?.envId;
3591
- if (this._responders.has(envId)) {
3323
+ setRuntimeEnvironment(runtime2) {
3324
+ if (this._runtimeEnvironment != null) {
3592
3325
  throw err_nice_action.fromId("environment_already_registered" /* environment_already_registered */, {
3593
3326
  domain: this.domain,
3594
- envId: envId ?? "(default)"
3327
+ matchTag: this._runtimeEnvironment.envId
3595
3328
  });
3596
3329
  }
3597
- this._responders.set(envId, resolver);
3330
+ this._runtimeEnvironment = runtime2;
3598
3331
  return this;
3599
3332
  }
3333
+ async _executeAction(primed, {
3334
+ actionMeta,
3335
+ listeners
3336
+ }) {
3337
+ if (this._runtimeEnvironment != null) {
3338
+ const envData = {
3339
+ tag: actionMeta?.tag,
3340
+ meta: actionMeta?.meta,
3341
+ runtime: this.getEnvironmentMeta()
3342
+ };
3343
+ const handler = this._runtimeEnvironment.getHandlerForAction(primed, actionMeta?.tag);
3344
+ const defaultExecution = handler == null ? this._runtimeEnvironment.getDefaultHandler(actionMeta?.tag)?.execution : undefined;
3345
+ if (handler != null || defaultExecution != null) {
3346
+ const allListeners = [...this._listeners, ...listeners ?? []];
3347
+ for (const listener of allListeners) {
3348
+ listener.execution?.(primed, envData);
3349
+ }
3350
+ let response;
3351
+ if (handler != null) {
3352
+ response = await handler.dispatchAction(primed);
3353
+ } else {
3354
+ const rawResult = await defaultExecution(primed, envData);
3355
+ if (rawResult instanceof NiceActionResponse) {
3356
+ response = rawResult;
3357
+ } else if (rawResult != null && isActionResponseJsonObject(rawResult)) {
3358
+ response = primed.coreAction.actionDomain.hydrateResponse(rawResult);
3359
+ } else {
3360
+ response = primed.setResponse(rawResult);
3361
+ }
3362
+ }
3363
+ for (const listener of allListeners) {
3364
+ listener.response?.(response, envData);
3365
+ }
3366
+ if (response.result.ok)
3367
+ return response.result.output;
3368
+ throw response.result.error;
3369
+ }
3370
+ }
3371
+ if (actionMeta.tag != null) {
3372
+ throw err_nice_action.fromId("action_tag_handler_not_found" /* action_tag_handler_not_found */, {
3373
+ domain: this.domain,
3374
+ matchTag: actionMeta.tag
3375
+ });
3376
+ }
3377
+ throw err_nice_action.fromId("domain_no_handler" /* domain_no_handler */, { domain: this.domain });
3378
+ }
3600
3379
  }
3601
3380
 
3602
- // src/ActionDomain/createActionDomain.ts
3603
- var createActionDomain = (definition) => {
3604
- return new NiceActionDomain({
3605
- ...definition,
3606
- allDomains: [definition.domain]
3607
- });
3381
+ // src/ActionDomain/helpers/createRootActionDomain.ts
3382
+ var createActionRootDomain = (definition) => {
3383
+ return new NiceActionRootDomain(definition);
3608
3384
  };
3609
- // src/ActionRequestResponse/ActionResponder/NiceActionResponder.ts
3610
- class NiceActionDomainResponder {
3611
- _domain;
3612
- _responders = new Map;
3613
- constructor(domain) {
3614
- this._domain = domain;
3615
- }
3616
- get domainId() {
3617
- return this._domain.domain;
3618
- }
3619
- resolveAction(actionId, fn) {
3620
- this._responders.set(actionId, fn);
3385
+ // src/ActionRuntimeEnvironment/ActionConnect/err_nice_connect.ts
3386
+ var err_nice_connect = err_nice_action.createChildDomain({
3387
+ domain: "err_nice_connect",
3388
+ schema: {}
3389
+ });
3390
+
3391
+ // src/ActionRuntimeEnvironment/ActionConnect/Transport/err_nice_transport.ts
3392
+ var EErrId_NiceTransport;
3393
+ ((EErrId_NiceTransport2) => {
3394
+ EErrId_NiceTransport2["timeout"] = "timeout";
3395
+ EErrId_NiceTransport2["not_found"] = "not_found";
3396
+ EErrId_NiceTransport2["initialization_failed"] = "initialization_failed";
3397
+ EErrId_NiceTransport2["send_failed"] = "send_failed";
3398
+ EErrId_NiceTransport2["invalid_action_response"] = "invalid_action_response";
3399
+ })(EErrId_NiceTransport ||= {});
3400
+ var err_nice_transport = err_nice_connect.createChildDomain({
3401
+ domain: "err_nice_transport",
3402
+ schema: {
3403
+ ["timeout" /* timeout */]: err({
3404
+ message: ({ timeout }) => `ActionConnect transport timed out after ${timeout}ms.`
3405
+ }),
3406
+ ["not_found" /* not_found */]: err({
3407
+ message: ({ actionId, routeKey, tag }) => `No connected transport found for action "${actionId}"${routeKey ? ` with route key "${routeKey}"` : ``}${tag ? ` and action tag "${tag}"` : ""}.`
3408
+ }),
3409
+ ["initialization_failed" /* initialization_failed */]: err({
3410
+ message: ({ actionId, routeKey, tag }) => `Transports found for action "${actionId}"${routeKey ? ` with route key "${routeKey}"` : ""}${tag ? ` and action tag "${tag}"` : ""}, but none are ready.`
3411
+ }),
3412
+ ["send_failed" /* send_failed */]: err({
3413
+ message: ({ actionId, httpStatusCode, message }) => `Failed to send action "${actionId}" [${httpStatusCode ?? "Unknown status"}]: ${message ?? "Unknown error"}.`,
3414
+ httpStatusCode: ({ httpStatusCode }) => httpStatusCode ?? 500
3415
+ }),
3416
+ ["invalid_action_response" /* invalid_action_response */]: err({
3417
+ message: ({ actionId }) => `Invalid action response JSON structure for action "${actionId}"`
3418
+ })
3419
+ }
3420
+ });
3421
+
3422
+ // src/ActionRuntimeEnvironment/ActionConnect/ActionConnect.ts
3423
+ var DEFAULT_TIMEOUT = 30000;
3424
+
3425
+ class ActionConnect {
3426
+ tag;
3427
+ handlerType = "connect" /* connect */;
3428
+ cuid;
3429
+ _config;
3430
+ _connections = new Map;
3431
+ _connectionByMatchKey = new Map;
3432
+ _handlerKeys = new Set;
3433
+ constructor(connectionConfigs, config = {}) {
3434
+ this.tag = config.tag ?? "_";
3435
+ this.cuid = nanoid();
3436
+ this._config = { requestTimeout: DEFAULT_TIMEOUT, ...config };
3437
+ for (const conn of connectionConfigs) {
3438
+ this._connections.set(conn.routeKey ?? "_", conn);
3439
+ }
3440
+ }
3441
+ get allHandlerKeys() {
3442
+ return [...this._handlerKeys];
3443
+ }
3444
+ routeDomain(domain, route = {}) {
3445
+ this._connectionByMatchKey.set(`${domain.domain}::_`, route);
3446
+ this._handlerKeys.add(`${this.tag}::${domain.domain}::_`);
3621
3447
  return this;
3622
3448
  }
3623
- async _resolvePrimed(primed) {
3624
- const resolver = this._responders.get(primed.coreAction.id);
3625
- if (resolver == null) {
3626
- throw err_nice_action.fromId("resolver_action_not_registered" /* resolver_action_not_registered */, {
3627
- domain: primed.domain,
3628
- actionId: primed.coreAction.id
3629
- });
3449
+ routeAction(domain, id, route = {}) {
3450
+ this._connectionByMatchKey.set(`${domain.domain}::${id}`, route);
3451
+ this._handlerKeys.add(`${this.tag}::${domain.domain}::${id}`);
3452
+ return this;
3453
+ }
3454
+ routeActionIds(domain, ids, route = {}) {
3455
+ for (const id of ids) {
3456
+ this.routeAction(domain, id, route);
3457
+ }
3458
+ return this;
3459
+ }
3460
+ async dispatchAction(primed) {
3461
+ const route = this._connectionByMatchKey.get(`${primed.domain}::${primed.id}`) ?? this._connectionByMatchKey.get(`${primed.domain}::_`);
3462
+ return this._dispatchViaRoute(primed, route);
3463
+ }
3464
+ disconnect() {
3465
+ for (const conn of this._connections.values()) {
3466
+ conn.disconnect();
3467
+ }
3468
+ }
3469
+ async _dispatchViaRoute(primed, route) {
3470
+ const conn = this._connections.get(route?.routeKey ?? "_");
3471
+ if (conn == null) {
3472
+ return Promise.reject(err_nice_transport.fromId("not_found" /* not_found */, {
3473
+ actionId: primed.id,
3474
+ routeKey: route?.routeKey,
3475
+ tag: this.tag !== "_" ? this.tag : undefined
3476
+ }));
3477
+ }
3478
+ const response = await conn.dispatch(primed, this._config.requestTimeout ?? DEFAULT_TIMEOUT);
3479
+ if (route?.onResponse) {
3480
+ route.onResponse(response);
3630
3481
  }
3631
- const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3632
- domain: primed.domain,
3633
- actionId: primed.coreAction.id
3634
- });
3635
- const response = await resolver(validatedInput);
3636
3482
  return response;
3637
3483
  }
3638
- async _dispatch(wire) {
3639
- const primed = this._domain.hydratePrimed(wire);
3640
- const resolverFn = this._responders.get(wire.id);
3641
- if (resolverFn == null) {
3642
- throw err_nice_action.fromId("resolver_action_not_registered" /* resolver_action_not_registered */, {
3643
- domain: wire.domain,
3644
- actionId: wire.id
3484
+ }
3485
+ // src/ActionRuntimeEnvironment/ActionConnect/Transport/Transport.ts
3486
+ class Transport {
3487
+ def;
3488
+ type;
3489
+ requestResolvers = new Map;
3490
+ constructor(def) {
3491
+ this.def = def;
3492
+ this.type = def.type;
3493
+ }
3494
+ get status() {
3495
+ return this._status;
3496
+ }
3497
+ checkAndPrepare() {
3498
+ return this._status;
3499
+ }
3500
+ respond(response) {
3501
+ const resolver = this.requestResolvers.get(response.cuid);
3502
+ if (resolver) {
3503
+ resolver.resolve(response);
3504
+ clearTimeout(resolver.timer);
3505
+ this.requestResolvers.delete(response.cuid);
3506
+ }
3507
+ }
3508
+ makeRequest(primed, connectionDefaultTimeout) {
3509
+ const timeout = this.def.timeout ?? connectionDefaultTimeout;
3510
+ return new Promise((resolve, reject) => {
3511
+ const timer = setTimeout(() => {
3512
+ this.requestResolvers.delete(primed.cuid);
3513
+ reject(err_nice_transport.fromId("timeout" /* timeout */, { timeout }));
3514
+ }, timeout);
3515
+ this.requestResolvers.set(primed.cuid, {
3516
+ type: this.type,
3517
+ resolve,
3518
+ reject,
3519
+ timer,
3520
+ primed
3645
3521
  });
3646
- }
3522
+ this.send(primed).catch((err3) => {
3523
+ this.requestResolvers.delete(primed.cuid);
3524
+ clearTimeout(timer);
3525
+ reject(err3);
3526
+ });
3527
+ });
3528
+ }
3529
+ }
3530
+
3531
+ // src/ActionRuntimeEnvironment/ActionConnect/Transport/TransportHttp.ts
3532
+ class TransportHttp extends Transport {
3533
+ abortControllers = new Map;
3534
+ _status = {
3535
+ status: "ready" /* ready */
3536
+ };
3537
+ async send(primed) {
3538
+ const wire = primed.toJsonObject();
3539
+ const ac = new AbortController;
3540
+ this.abortControllers.set(primed.cuid, ac);
3647
3541
  try {
3648
- const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3649
- domain: wire.domain,
3650
- actionId: wire.id
3542
+ const res = await fetch(this.def.url, {
3543
+ method: "POST",
3544
+ headers: { "Content-Type": "application/json" },
3545
+ body: JSON.stringify(wire),
3546
+ signal: ac.signal
3651
3547
  });
3652
- const output = await resolverFn(validatedInput);
3653
- return new NiceActionResponse(primed, {
3654
- ok: true,
3655
- output
3548
+ if (!res.ok) {
3549
+ try {
3550
+ const jsonData = await res.json();
3551
+ if (isActionResponseJsonObject(jsonData)) {
3552
+ this.respond(primed.coreAction.actionDomain.hydrateResponse(jsonData));
3553
+ } else {
3554
+ this.respond(primed.errorResponse(castNiceError(jsonData)));
3555
+ }
3556
+ return;
3557
+ } catch (e2) {
3558
+ throw err_nice_transport.fromId("send_failed" /* send_failed */, {
3559
+ actionId: primed.id,
3560
+ httpStatusCode: res.status,
3561
+ message: e2.message
3562
+ }).withOriginError(e2);
3563
+ }
3564
+ }
3565
+ const json = await res.json();
3566
+ if (!isActionResponseJsonObject(json)) {
3567
+ throw err_nice_transport.fromId("invalid_action_response" /* invalid_action_response */, {
3568
+ actionId: primed.id
3569
+ });
3570
+ }
3571
+ this.respond(primed.coreAction.actionDomain.hydrateResponse(json));
3572
+ } finally {
3573
+ this.abortControllers.delete(primed.cuid);
3574
+ }
3575
+ }
3576
+ disconnect() {
3577
+ for (const [, ac] of this.abortControllers) {
3578
+ ac.abort();
3579
+ }
3580
+ this.abortControllers.clear();
3581
+ }
3582
+ }
3583
+
3584
+ // src/ActionRuntimeEnvironment/ActionConnect/Transport/err_nice_transport_ws.ts
3585
+ var EErrId_NiceTransport_WebSocket;
3586
+ ((EErrId_NiceTransport_WebSocket2) => {
3587
+ EErrId_NiceTransport_WebSocket2["ws_disconnected"] = "ws_disconnected";
3588
+ EErrId_NiceTransport_WebSocket2["ws_create_failed"] = "ws_create_failed";
3589
+ EErrId_NiceTransport_WebSocket2["ws_error"] = "ws_error";
3590
+ })(EErrId_NiceTransport_WebSocket ||= {});
3591
+ var err_nice_transport_ws = err_nice_transport.createChildDomain({
3592
+ domain: "ws_transport",
3593
+ schema: {
3594
+ ["ws_disconnected" /* ws_disconnected */]: err({
3595
+ message: () => `WebSocket transport disconnected.`
3596
+ }),
3597
+ ["ws_create_failed" /* ws_create_failed */]: err({
3598
+ message: ({ originalError }) => `Failed to create WebSocket transport.${originalError ? ` Original error: ${originalError.message}` : ""}`
3599
+ }),
3600
+ ["ws_error" /* ws_error */]: err({
3601
+ message: ({ originalError }) => `WebSocket transport error.${originalError ? ` Original error: ${originalError.message}` : ""}`
3602
+ })
3603
+ }
3604
+ });
3605
+
3606
+ // src/ActionRuntimeEnvironment/ActionConnect/Transport/TransportWebSocket.ts
3607
+ class TransportWebSocket extends Transport {
3608
+ websocket;
3609
+ _status = { status: "uninitialized" /* uninitialized */ };
3610
+ constructor(def) {
3611
+ super(def);
3612
+ }
3613
+ checkAndPrepare() {
3614
+ if (this._status.status === "uninitialized" /* uninitialized */) {
3615
+ this._status = this.startInitializing();
3616
+ }
3617
+ return this._status;
3618
+ }
3619
+ startInitializing() {
3620
+ let resolveInit;
3621
+ const waitForInitialization = new Promise((resolve) => {
3622
+ resolveInit = resolve;
3623
+ });
3624
+ this._connect(resolveInit);
3625
+ return {
3626
+ status: "initializing" /* initializing */,
3627
+ timeStarted: Date.now(),
3628
+ waitForInitialization
3629
+ };
3630
+ }
3631
+ handleMessage(data) {
3632
+ let json;
3633
+ try {
3634
+ json = JSON.parse(data);
3635
+ } catch {
3636
+ return;
3637
+ }
3638
+ if (!isActionResponseJsonObject(json)) {
3639
+ return;
3640
+ }
3641
+ const pending = this.requestResolvers.get(json.cuid);
3642
+ if (pending == null) {
3643
+ return;
3644
+ }
3645
+ this.respond(pending.primed.coreAction.actionDomain.hydrateResponse(json));
3646
+ }
3647
+ rejectPendingWebSocketRequests(error) {
3648
+ for (const [, pending] of this.requestResolvers) {
3649
+ if (pending.type === this.type) {
3650
+ clearTimeout(pending.timer);
3651
+ pending.reject(error);
3652
+ this.requestResolvers.delete(pending.primed.cuid);
3653
+ }
3654
+ }
3655
+ }
3656
+ async _connect(onInitialized) {
3657
+ let initNotified = false;
3658
+ const notifyInit = (newStatus) => {
3659
+ if (!initNotified) {
3660
+ initNotified = true;
3661
+ onInitialized({ transport: this, newStatus });
3662
+ }
3663
+ };
3664
+ try {
3665
+ this.websocket = await this.def.createWebSocket();
3666
+ } catch (e2) {
3667
+ console.error("Failed to create WebSocket:", e2);
3668
+ const error = err_nice_transport_ws.fromId("ws_create_failed" /* ws_create_failed */, {
3669
+ originalError: e2 instanceof Error ? e2 : undefined
3656
3670
  });
3657
- } catch (e) {
3658
- return new NiceActionResponse(primed, {
3659
- ok: false,
3660
- error: castNiceError(e)
3671
+ const failedStatus = {
3672
+ status: "failed" /* failed */,
3673
+ error,
3674
+ timeFailed: Date.now()
3675
+ };
3676
+ this._status = failedStatus;
3677
+ notifyInit(failedStatus);
3678
+ this.rejectPendingWebSocketRequests(error);
3679
+ return;
3680
+ }
3681
+ this.websocket.addEventListener("open", () => {
3682
+ const readyStatus = {
3683
+ status: "ready" /* ready */
3684
+ };
3685
+ this._status = readyStatus;
3686
+ notifyInit(readyStatus);
3687
+ });
3688
+ this.websocket.addEventListener("message", (event) => {
3689
+ if (typeof event.data === "string") {
3690
+ this.handleMessage(event.data);
3691
+ }
3692
+ });
3693
+ this.websocket.addEventListener("close", (event) => {
3694
+ if (this._status.status === "uninitialized" /* uninitialized */)
3695
+ return;
3696
+ if (this._status.status !== "failed" /* failed */) {
3697
+ console.error("WebSocket closed:", event);
3698
+ const error = err_nice_transport_ws.fromId("ws_disconnected" /* ws_disconnected */);
3699
+ const failedStatus = {
3700
+ status: "failed" /* failed */,
3701
+ error,
3702
+ timeFailed: Date.now()
3703
+ };
3704
+ this._status = failedStatus;
3705
+ notifyInit(failedStatus);
3706
+ this.rejectPendingWebSocketRequests(error);
3707
+ }
3708
+ });
3709
+ this.websocket.addEventListener("error", (event) => {
3710
+ console.error("WebSocket error:", event);
3711
+ const error = err_nice_transport_ws.fromId("ws_error" /* ws_error */, {
3712
+ originalError: event instanceof Error ? event : undefined
3661
3713
  });
3714
+ const failedStatus = {
3715
+ status: "failed" /* failed */,
3716
+ error,
3717
+ timeFailed: Date.now()
3718
+ };
3719
+ this._status = failedStatus;
3720
+ notifyInit(failedStatus);
3721
+ this.rejectPendingWebSocketRequests(error);
3722
+ });
3723
+ }
3724
+ async send(primed) {
3725
+ if (this.websocket == null) {
3726
+ throw err_nice_transport_ws.fromId("ws_disconnected" /* ws_disconnected */);
3662
3727
  }
3728
+ this.websocket.send(primed.toJsonString());
3729
+ }
3730
+ disconnect() {
3731
+ const error = err_nice_transport_ws.fromId("ws_disconnected" /* ws_disconnected */);
3732
+ this._status = { status: "uninitialized" /* uninitialized */ };
3733
+ this.rejectPendingWebSocketRequests(error);
3734
+ this.websocket?.close();
3735
+ this.websocket = undefined;
3663
3736
  }
3664
3737
  }
3665
- function createDomainResolver(domain) {
3666
- return new NiceActionDomainResponder(domain);
3738
+ // src/ActionRuntimeEnvironment/ActionConnect/ConnectionConfig/ConnectionConfig.ts
3739
+ class ConnectionConfig {
3740
+ config;
3741
+ routeKey;
3742
+ _transports = [];
3743
+ constructor(input, routeKey) {
3744
+ this.config = input;
3745
+ this.routeKey = routeKey;
3746
+ for (const def of this.config.transports) {
3747
+ if (def.type === "ws" /* ws */) {
3748
+ this._transports.push(new TransportWebSocket(def));
3749
+ } else if (def.type === "http" /* http */) {
3750
+ this._transports.push(new TransportHttp(def));
3751
+ } else {
3752
+ throw new Error(`Unsupported transport type: ${def.type}`);
3753
+ }
3754
+ }
3755
+ }
3756
+ get connected() {
3757
+ return this._transports.some((t2) => t2.status.status === "ready" /* ready */);
3758
+ }
3759
+ async dispatch(primed, defaultTimeout) {
3760
+ const timeout = this.config.defaultTimeout ?? defaultTimeout;
3761
+ const initializingWaiters = [];
3762
+ for (const transport of this._transports) {
3763
+ const statusInfo = transport.checkAndPrepare();
3764
+ if (statusInfo.status === "ready" /* ready */) {
3765
+ return transport.makeRequest(primed, timeout);
3766
+ }
3767
+ if (statusInfo.status === "initializing" /* initializing */) {
3768
+ initializingWaiters.push(statusInfo.waitForInitialization.then((info) => {
3769
+ if (info.newStatus.status !== "ready" /* ready */) {
3770
+ throw info.newStatus;
3771
+ }
3772
+ return transport;
3773
+ }));
3774
+ }
3775
+ }
3776
+ if (initializingWaiters.length === 0) {
3777
+ throw err_nice_transport.fromId("not_found" /* not_found */, {
3778
+ actionId: primed.id
3779
+ });
3780
+ }
3781
+ try {
3782
+ const firstReady = await Promise.any(initializingWaiters);
3783
+ return firstReady.makeRequest(primed, timeout);
3784
+ } catch (e2) {
3785
+ throw err_nice_transport.fromId("initialization_failed" /* initialization_failed */, {
3786
+ actionId: primed.id
3787
+ }).withOriginError(e2);
3788
+ }
3789
+ }
3790
+ disconnect() {
3791
+ for (const transport of this._transports) {
3792
+ transport.disconnect();
3793
+ }
3794
+ }
3667
3795
  }
3668
- // src/ActionRequestResponse/ActionResponder/NiceActionResponderEnvironment.ts
3669
- class NiceActionResponderEnvironment {
3670
- _resolvers = new Map;
3671
- constructor(resolvers) {
3672
- for (const resolver of resolvers) {
3673
- this._resolvers.set(resolver.domainId, resolver);
3796
+ // src/ActionRuntimeEnvironment/ActionHandler/ActionHandler.ts
3797
+ class ActionHandler {
3798
+ tag;
3799
+ handlerType = "custom" /* custom */;
3800
+ cuid;
3801
+ _domains = new Map;
3802
+ _handlersByKey = new Map;
3803
+ constructor(config = {}) {
3804
+ this.tag = config.tag ?? "_";
3805
+ this.cuid = nanoid();
3806
+ }
3807
+ get allHandlerKeys() {
3808
+ return [...this._handlersByKey.keys()];
3809
+ }
3810
+ getHandlersForAction(action, matchTag = "_") {
3811
+ if (matchTag !== this.tag) {
3812
+ return;
3813
+ }
3814
+ const keys = [
3815
+ `${matchTag}::${action.domain}::${action.id}`,
3816
+ `${matchTag}::${action.domain}::_`
3817
+ ];
3818
+ for (const key of keys) {
3819
+ const handler = this._handlersByKey.get(key);
3820
+ if (handler != null) {
3821
+ return handler;
3822
+ }
3823
+ }
3824
+ }
3825
+ forDomain(domain, handlers) {
3826
+ this._domains.set(domain.domain, domain);
3827
+ const matchKey = `${this.tag}::${domain.domain}::_`;
3828
+ this._handlersByKey.set(matchKey, handlers);
3829
+ return this;
3830
+ }
3831
+ forAction(domain, id, handlers) {
3832
+ this._domains.set(domain.domain, domain);
3833
+ const matchKey = `${this.tag}::${domain.domain}::${id}`;
3834
+ this._handlersByKey.set(matchKey, handlers);
3835
+ return this;
3836
+ }
3837
+ forActionIds(domain, ids, handlers) {
3838
+ this._domains.set(domain.domain, domain);
3839
+ for (const id of ids) {
3840
+ this.forAction(domain, id, handlers);
3841
+ }
3842
+ return this;
3843
+ }
3844
+ forDomainActionCases(domain, cases) {
3845
+ this._domains.set(domain.domain, domain);
3846
+ for (const id of Object.keys(cases)) {
3847
+ const handlers = cases[id];
3848
+ if (handlers != null) {
3849
+ const matchKey = `${this.tag}::${domain.domain}::${id}`;
3850
+ this._handlersByKey.set(matchKey, handlers);
3851
+ }
3852
+ }
3853
+ return this;
3854
+ }
3855
+ async _tryHandleResponse(response) {
3856
+ const handlers = this.getHandlersForAction(response.primed.coreAction, this.tag);
3857
+ if (handlers?.response) {
3858
+ const result = await handlers.response(response, {
3859
+ tag: this.tag,
3860
+ runtime: response.getEnvironmentMeta()
3861
+ });
3862
+ if (result === undefined) {
3863
+ return { handled: true, response };
3864
+ }
3865
+ if (result instanceof NiceActionResponse) {
3866
+ return { handled: true, response: result };
3867
+ }
3868
+ const domain = this._domains.get(response.domain);
3869
+ if (domain == null) {
3870
+ throw err_nice_action.fromId("domain_no_handler" /* domain_no_handler */, {
3871
+ domain: response.domain
3872
+ });
3873
+ }
3874
+ return { handled: true, response: domain.hydrateResponse(result) };
3875
+ }
3876
+ return { handled: false };
3877
+ }
3878
+ async _tryExecute(primed) {
3879
+ const handlers = this.getHandlersForAction(primed.coreAction, this.tag);
3880
+ if (handlers?.execution == null) {
3881
+ return { handled: false };
3882
+ }
3883
+ const rawResult = await handlers.execution(primed, {
3884
+ tag: this.tag,
3885
+ runtime: primed.getEnvironmentMeta()
3886
+ });
3887
+ let response;
3888
+ if (rawResult instanceof NiceActionResponse) {
3889
+ response = rawResult;
3890
+ } else if (rawResult != null && isActionResponseJsonObject(rawResult)) {
3891
+ const domain = this._domains.get(primed.domain);
3892
+ if (domain == null) {
3893
+ throw err_nice_action.fromId("domain_no_handler" /* domain_no_handler */, {
3894
+ domain: primed.domain
3895
+ });
3896
+ }
3897
+ response = domain.hydrateResponse(rawResult);
3898
+ } else {
3899
+ response = primed.setResponse(rawResult);
3674
3900
  }
3901
+ return { handled: true, response };
3675
3902
  }
3676
- async dispatch(wire) {
3677
- const resolver = this._resolvers.get(wire.domain);
3678
- if (resolver == null) {
3679
- throw err_nice_action.fromId("resolver_domain_not_registered" /* resolver_domain_not_registered */, {
3680
- domain: wire.domain
3903
+ async dispatchAction(primed) {
3904
+ const result = await this._tryExecute(primed);
3905
+ if (result.handled)
3906
+ return result.response;
3907
+ throw err_nice_action.fromId("no_action_execution_handler" /* no_action_execution_handler */, {
3908
+ domain: primed.domain,
3909
+ actionId: primed.id
3910
+ });
3911
+ }
3912
+ async handleWire(wire) {
3913
+ if (typeof wire !== "object" || wire == null || typeof wire["domain"] !== "string") {
3914
+ throw err_nice_action.fromId("wire_not_action_data" /* wire_not_action_data */);
3915
+ }
3916
+ const typedWire = wire;
3917
+ const domain = this._domains.get(typedWire.domain);
3918
+ if (domain == null) {
3919
+ throw err_nice_action.fromId("domain_no_handler" /* domain_no_handler */, {
3920
+ domain: typedWire.domain
3681
3921
  });
3682
3922
  }
3683
- const response = await resolver._dispatch(wire);
3684
- return response.toJsonObject();
3923
+ if (typedWire.type === "primed" /* primed */) {
3924
+ const primed = domain.hydratePrimed(typedWire);
3925
+ return await this._tryExecute(primed);
3926
+ }
3927
+ if (typedWire.type === "resolved" /* resolved */) {
3928
+ const response = domain.hydrateResponse(typedWire);
3929
+ return await this._tryHandleResponse(response);
3930
+ }
3931
+ const unknownWire = typedWire;
3932
+ throw err_nice_action.fromId("wire_action_not_primed_or_response" /* wire_action_not_primed_or_response */, {
3933
+ domain: unknownWire.domain,
3934
+ actionId: unknownWire.id,
3935
+ actionState: unknownWire.type
3936
+ });
3685
3937
  }
3686
3938
  }
3687
- function createResponderEnvironment(resolvers) {
3688
- return new NiceActionResponderEnvironment(resolvers);
3939
+ var createHandler = (config = {}) => {
3940
+ return new ActionHandler(config);
3941
+ };
3942
+ // src/ActionRuntimeEnvironment/ActionRuntimeEnvironment.ts
3943
+ class ActionRuntimeEnvironment {
3944
+ envId;
3945
+ memCuid;
3946
+ timeCreated;
3947
+ runtimeInfo = getAssumedRuntimeInfo();
3948
+ _handlersByTag = new Map;
3949
+ _defaultHandlers = new Map;
3950
+ constructor(input) {
3951
+ this.envId = input.envId;
3952
+ this.memCuid = `${input.envId}::${nanoid(8)}`;
3953
+ this.timeCreated = Date.now();
3954
+ }
3955
+ addHandlers(handlers) {
3956
+ for (const handler of handlers) {
3957
+ for (const matchKey of handler.allHandlerKeys) {
3958
+ if (!this._handlersByTag.has(matchKey)) {
3959
+ this._handlersByTag.set(matchKey, []);
3960
+ } else if (this._handlersByTag.get(matchKey)?.some((h2) => h2.cuid === handler.cuid) === true) {
3961
+ continue;
3962
+ }
3963
+ const handlersForKey = this._handlersByTag.get(matchKey);
3964
+ this._handlersByTag.set(matchKey, [...handlersForKey, handler]);
3965
+ }
3966
+ }
3967
+ return this;
3968
+ }
3969
+ setDefaultHandler(handler, tag = "_") {
3970
+ this._defaultHandlers.set(tag, handler);
3971
+ return this;
3972
+ }
3973
+ getDefaultHandler(tag = "_") {
3974
+ return this._defaultHandlers.get(tag);
3975
+ }
3976
+ getHandlerForAction(action, tag) {
3977
+ const matchTag = tag ?? "_";
3978
+ return this._handlersByTag.get(`${matchTag}::${action.domain}::${action.id}`)?.[0] ?? this._handlersByTag.get(`${matchTag}::${action.domain}::_`)?.[0];
3979
+ }
3980
+ toJsonObject() {
3981
+ return {
3982
+ envId: this.envId,
3983
+ memCuid: this.memCuid,
3984
+ timeCreated: this.timeCreated,
3985
+ runtimeInfo: this.runtimeInfo
3986
+ };
3987
+ }
3689
3988
  }
3989
+ var createActionRuntime = (config) => {
3990
+ return new ActionRuntimeEnvironment(config);
3991
+ };
3690
3992
  // ../common-errors/src/validation/standard_schema/extractMessageFromStandardSchema.ts
3691
3993
  function extractPathFromIssue(issue) {
3692
3994
  let pathString = "";
@@ -3740,10 +4042,10 @@ class NiceActionSchema {
3740
4042
  inputOptions;
3741
4043
  outputOptions;
3742
4044
  get inputSchema() {
3743
- return nullish(this.inputOptions?.schema);
4045
+ return this.inputOptions?.schema;
3744
4046
  }
3745
4047
  get outputSchema() {
3746
- return nullish(this.outputOptions?.schema);
4048
+ return this.outputOptions?.schema;
3747
4049
  }
3748
4050
  input(options, serialize, deserialize) {
3749
4051
  if (serialize != null && deserialize != null) {
@@ -3777,11 +4079,17 @@ class NiceActionSchema {
3777
4079
  }
3778
4080
  return serialized;
3779
4081
  }
3780
- async validateInput(value, meta) {
4082
+ validateInput(value, meta) {
3781
4083
  if (this.inputOptions?.schema == null) {
3782
4084
  return value;
3783
4085
  }
3784
- const result = await this.inputOptions.schema["~standard"].validate(value);
4086
+ const result = this.inputOptions.schema["~standard"].validate(value);
4087
+ if (result instanceof Promise) {
4088
+ throw err_nice_action.fromId("action_input_validation_promise" /* action_input_validation_promise */, {
4089
+ domain: meta.domain,
4090
+ actionId: meta.actionId
4091
+ });
4092
+ }
3785
4093
  if (result.issues != null) {
3786
4094
  throw err_nice_action.fromId("action_input_validation_failed" /* action_input_validation_failed */, {
3787
4095
  domain: meta.domain,
@@ -3791,6 +4099,26 @@ class NiceActionSchema {
3791
4099
  }
3792
4100
  return result.value;
3793
4101
  }
4102
+ validateOutput(value, meta) {
4103
+ if (this.outputOptions?.schema == null) {
4104
+ return value;
4105
+ }
4106
+ const result = this.outputOptions.schema["~standard"].validate(value);
4107
+ if (result instanceof Promise) {
4108
+ throw err_nice_action.fromId("action_output_validation_promise" /* action_output_validation_promise */, {
4109
+ domain: meta.domain,
4110
+ actionId: meta.actionId
4111
+ });
4112
+ }
4113
+ if (result.issues != null) {
4114
+ throw err_nice_action.fromId("action_output_validation_failed" /* action_output_validation_failed */, {
4115
+ domain: meta.domain,
4116
+ actionId: meta.actionId,
4117
+ validationMessage: extractMessageFromStandardSchema(result)
4118
+ });
4119
+ }
4120
+ return result.value;
4121
+ }
3794
4122
  serializeOutput(rawOutput) {
3795
4123
  if (this.outputOptions?.serialization) {
3796
4124
  return this.outputOptions.serialization.serialize(rawOutput);
@@ -3809,29 +4137,80 @@ class NiceActionSchema {
3809
4137
  var action = () => {
3810
4138
  return new NiceActionSchema;
3811
4139
  };
3812
- // src/utils/isActionResponseJsonObject.ts
3813
- var isActionResponseJsonObject = (obj) => {
3814
- return typeof obj === "object" && obj !== null && typeof obj.domain === "string" && typeof obj.id === "string" && "input" in obj && (("output" in obj) || ("error" in obj)) && typeof obj.ok === "boolean";
3815
- };
4140
+ // src/NiceAction/MatchAction/MatchAction.ts
4141
+ class MatchAction {
4142
+ action;
4143
+ _entries = [];
4144
+ _otherwise;
4145
+ constructor(action2) {
4146
+ this.action = action2;
4147
+ }
4148
+ with(opts) {
4149
+ this._entries.push({ domainStr: opts.domain.domain, id: opts.id, handler: opts.handler });
4150
+ return this;
4151
+ }
4152
+ otherwise(handler) {
4153
+ this._otherwise = handler;
4154
+ return this;
4155
+ }
4156
+ _findMatch() {
4157
+ const { action: action2 } = this;
4158
+ for (const entry of this._entries) {
4159
+ const domainMatches = action2.domain === entry.domainStr;
4160
+ const idMatches = entry.id == null || action2.id === entry.id;
4161
+ if (domainMatches && idMatches) {
4162
+ return { matched: true, handler: entry.handler };
4163
+ }
4164
+ }
4165
+ if (this._otherwise != null) {
4166
+ return { matched: true, handler: this._otherwise };
4167
+ }
4168
+ return { matched: false };
4169
+ }
4170
+ run() {
4171
+ const result = this._findMatch();
4172
+ if (result.matched) {
4173
+ result.handler(this.action);
4174
+ }
4175
+ return result.matched;
4176
+ }
4177
+ async runAsync() {
4178
+ const result = this._findMatch();
4179
+ if (result.matched) {
4180
+ await result.handler(this.action);
4181
+ return true;
4182
+ }
4183
+ return false;
4184
+ }
4185
+ }
4186
+ var matchAction = (action2) => new MatchAction(action2);
3816
4187
  // src/utils/isPrimedActionJsonObject.ts
3817
4188
  var isPrimedActionJsonObject = (obj) => {
3818
- return typeof obj === "object" && obj !== null && typeof obj.domain === "string" && typeof obj.id === "string" && "input" in obj;
4189
+ return typeof obj === "object" && obj !== null && typeof obj.domain === "string" && typeof obj.id === "string" && "input" in obj && obj.type === "primed" /* primed */;
3819
4190
  };
3820
4191
  export {
4192
+ matchAction,
3821
4193
  isPrimedActionJsonObject,
3822
4194
  isActionResponseJsonObject,
4195
+ err_nice_transport_ws,
4196
+ err_nice_transport,
4197
+ err_nice_connect,
3823
4198
  err_nice_action,
3824
- createResponderEnvironment,
3825
- createDomainResolver,
3826
- createActionDomain,
4199
+ createHandler,
4200
+ createActionRuntime,
4201
+ createActionRootDomain,
3827
4202
  action,
4203
+ ConnectionConfig as Transport,
3828
4204
  NiceActionSchema,
3829
4205
  NiceActionResponse,
3830
- NiceActionResponderEnvironment,
3831
- NiceActionRequester,
3832
4206
  NiceActionPrimed,
3833
- NiceActionDomainResponder,
3834
4207
  NiceActionDomain,
3835
4208
  NiceAction,
3836
- EErrId_NiceAction
4209
+ EErrId_NiceTransport_WebSocket,
4210
+ EErrId_NiceTransport,
4211
+ EErrId_NiceAction,
4212
+ EActionState,
4213
+ ActionRuntimeEnvironment,
4214
+ ActionHandler,
4215
+ ActionConnect
3837
4216
  };