@nice-code/action 0.0.20 → 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 +1235 -772
  2. package/build/react-query/index.js +3129 -0
  3. package/build/types/ActionDomain/NiceActionDomain.d.ts +18 -45
  4. package/build/types/ActionDomain/NiceActionDomain.types.d.ts +9 -50
  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 +14 -10
  25. package/build/types/ActionSchema/NiceActionSchema.types.d.ts +4 -4
  26. package/build/types/NiceAction/MatchAction/MatchAction.d.ts +26 -0
  27. package/build/types/NiceAction/NiceAction.d.ts +20 -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 +20 -36
  32. package/build/types/NiceAction/NiceActionResponse.d.ts +15 -5
  33. package/build/types/NiceAction/utils/isNiceActionInstance.d.ts +3 -0
  34. package/build/types/errors/err_nice_action.d.ts +35 -13
  35. package/build/types/index.d.ts +16 -8
  36. package/build/types/react-query/index.d.ts +73 -0
  37. package/package.json +15 -5
  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
@@ -1,44 +1,105 @@
1
- // src/ActionRequestResponse/ActionRequester/NiceActionRequester.ts
2
- class NiceActionRequester {
3
- cases = [];
4
- _defaultRequester;
5
- async handleAction(action) {
6
- for (const actionCase of this.cases) {
7
- if (!actionCase._matcher(action))
8
- continue;
9
- return await actionCase._requester(action);
10
- }
11
- if (this._defaultRequester) {
12
- return await this._defaultRequester(action);
13
- }
14
- throw new Error(`No handler found for action "${action.coreAction.id}" in domain "${action.coreAction.domain}"`);
15
- }
16
- forDomain(domain, handler) {
17
- this.cases.push({
18
- _matcher: (action) => domain.isExactActionDomain(action),
19
- _requester: handler
20
- });
21
- return this;
22
- }
23
- forActionId(domain, id, handler) {
24
- this.cases.push({
25
- _matcher: (action) => domain.isExactActionDomain(action) && action.coreAction.id === id,
26
- _requester: handler
27
- });
28
- return this;
29
- }
30
- forActionIds(domain, ids, handler) {
31
- this.cases.push({
32
- _matcher: (action) => domain.isExactActionDomain(action) && ids.includes(action.coreAction.id),
33
- _requester: handler
34
- });
35
- return this;
36
- }
37
- setDefaultHandler(handler) {
38
- this._defaultRequester = handler;
39
- return this;
40
- }
1
+ var __create = Object.create;
2
+ var __getProtoOf = Object.getPrototypeOf;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ function __accessProp(key) {
7
+ return this[key];
8
+ }
9
+ var __toESMCache_node;
10
+ var __toESMCache_esm;
11
+ var __toESM = (mod, isNodeMode, target) => {
12
+ var canCache = mod != null && typeof mod === "object";
13
+ if (canCache) {
14
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
15
+ var cached = cache.get(mod);
16
+ if (cached)
17
+ return cached;
18
+ }
19
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
20
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
21
+ for (let key of __getOwnPropNames(mod))
22
+ if (!__hasOwnProp.call(to, key))
23
+ __defProp(to, key, {
24
+ get: __accessProp.bind(mod, key),
25
+ enumerable: true
26
+ });
27
+ if (canCache)
28
+ cache.set(mod, to);
29
+ return to;
30
+ };
31
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
32
+
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
+ };
41
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
+ };
42
103
 
43
104
  // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/legacy.js
44
105
  var ACCEPTED = 202;
@@ -353,14 +414,14 @@ var StatusCodes;
353
414
  })(StatusCodes || (StatusCodes = {}));
354
415
  // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/index.js
355
416
  var __assign = function() {
356
- __assign = Object.assign || function(t) {
357
- for (var s, i = 1, n = arguments.length;i < n; i++) {
358
- s = arguments[i];
359
- for (var p in s)
360
- if (Object.prototype.hasOwnProperty.call(s, p))
361
- t[p] = s[p];
362
- }
363
- 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;
364
425
  };
365
426
  return __assign.apply(this, arguments);
366
427
  };
@@ -422,6 +483,7 @@ class NiceError extends Error {
422
483
  ids;
423
484
  wasntNice;
424
485
  httpStatusCode;
486
+ timeCreated;
425
487
  originError;
426
488
  _packedState;
427
489
  _errorDataMap;
@@ -435,6 +497,7 @@ class NiceError extends Error {
435
497
  if (options.originError != null) {
436
498
  this.originError = options.originError;
437
499
  }
500
+ this.timeCreated = options.timeCreated ?? Date.now();
438
501
  }
439
502
  hasId(id) {
440
503
  return id in this._errorDataMap;
@@ -478,7 +541,7 @@ class NiceError extends Error {
478
541
  const otherIds = other.getIds().map(String).sort();
479
542
  if (myIds.length !== otherIds.length)
480
543
  return false;
481
- return myIds.every((id, i) => id === otherIds[i]);
544
+ return myIds.every((id, i2) => id === otherIds[i2]);
482
545
  }
483
546
  toJsonObject() {
484
547
  const originError = this.originError ? {
@@ -512,7 +575,12 @@ class NiceError extends Error {
512
575
  } else {
513
576
  contextState = data.contextState;
514
577
  }
515
- errorData[id] = { contextState, message: data.message, httpStatusCode: data.httpStatusCode };
578
+ errorData[id] = {
579
+ contextState,
580
+ message: data.message,
581
+ httpStatusCode: data.httpStatusCode,
582
+ timeAdded: data.timeAdded
583
+ };
516
584
  }
517
585
  return {
518
586
  name: "NiceError",
@@ -522,34 +590,49 @@ class NiceError extends Error {
522
590
  wasntNice: this.wasntNice,
523
591
  message: this.message,
524
592
  httpStatusCode: this.httpStatusCode,
593
+ timeCreated: this.timeCreated,
525
594
  ...this.stack != null ? { stack: this.stack } : {},
526
595
  originError
527
596
  };
528
597
  }
598
+ toJsonString() {
599
+ return JSON.stringify(this.toJsonObject());
600
+ }
601
+ toHttpResponse() {
602
+ return new Response(this.toJsonString(), {
603
+ status: this.httpStatusCode,
604
+ headers: { "Content-Type": "application/json" }
605
+ });
606
+ }
529
607
  hydrate(definedNiceError) {
530
608
  return definedNiceError.hydrate(this);
531
609
  }
532
- handleWith(cases) {
533
- for (const c of cases) {
534
- if (!c._domain.isExact(this))
535
- continue;
536
- if (c._ids != null && !this.hasOneOfIds(c._ids))
537
- continue;
538
- c._handler(c._domain.hydrate(this));
539
- return true;
610
+ handleWithSync(handlerInput, handlerOptions = {}) {
611
+ const handlersArray = Array.isArray(handlerInput) ? handlerInput : [handlerInput];
612
+ for (const handler of handlersArray) {
613
+ const result = handler.handleErrorWithPromiseInspection(this, handlerOptions);
614
+ if (result.matched) {
615
+ if (result.isPromise) {
616
+ console.warn(`[NiceError.handleWith] Handler ${result.target.identifier} returned a Promise but was called via \`handleWith\` (synchronous). ` + `The Promise will not be awaited. Use \`handleWithAsync\` for async handlers.`);
617
+ }
618
+ return result.isPromise ? undefined : result.handlerResponse;
619
+ }
540
620
  }
541
- return false;
621
+ if (handlerOptions.throwOnUnhandled === true)
622
+ throw this;
623
+ return;
542
624
  }
543
- async handleWithAsync(cases) {
544
- for (const c of cases) {
545
- if (!c._domain.isExact(this))
546
- continue;
547
- if (c._ids != null && !this.hasOneOfIds(c._ids))
548
- continue;
549
- await c._handler(c._domain.hydrate(this));
550
- return true;
625
+ async handleWithAsync(handlerInput, handlerOptions = {}) {
626
+ const handlersArray = Array.isArray(handlerInput) ? handlerInput : [handlerInput];
627
+ for (const handler of handlersArray) {
628
+ const result = handler.handleErrorWithPromiseInspection(this, handlerOptions);
629
+ if (result.matched) {
630
+ return result.isPromise ? await result.handlerPromise : result.handlerResponse;
631
+ }
551
632
  }
552
- return false;
633
+ if (handlerOptions.throwOnUnhandled === true)
634
+ throw this;
635
+ return;
553
636
  }
554
637
  get isPacked() {
555
638
  return this._packedState != null;
@@ -629,7 +712,7 @@ class NiceErrorHydrated extends NiceError {
629
712
  }
630
713
 
631
714
  // ../nice-error/src/NiceErrorDefined/NiceErrorDefined.ts
632
- class NiceErrorDefined {
715
+ class NiceErrorDomain {
633
716
  domain;
634
717
  allDomains;
635
718
  defaultHttpStatusCode;
@@ -654,7 +737,7 @@ class NiceErrorDefined {
654
737
  }
655
738
  }
656
739
  createChildDomain(subErrorDef) {
657
- const child = new NiceErrorDefined({
740
+ const child = new NiceErrorDomain({
658
741
  domain: subErrorDef.domain,
659
742
  allDomains: [subErrorDef.domain, ...this.allDomains],
660
743
  schema: subErrorDef.schema,
@@ -710,9 +793,10 @@ class NiceErrorDefined {
710
793
  if (errDef.domain !== this.domain) {
711
794
  throw new Error(`[NiceErrorDefined.hydrate] Domain mismatch: this definition is "${this.domain}" ` + `but the error belongs to "${errDef.domain}". ` + `Call \`niceErrorDefined.is(error)\` before hydrating to ensure compatibility.`);
712
795
  }
796
+ const finalError = error instanceof NiceError ? error : new NiceError(error);
713
797
  const reconciledErrorData = {};
714
- for (const id of error.getIds()) {
715
- const existingData = error.getErrorDataForId(id);
798
+ for (const id of finalError.getIds()) {
799
+ const existingData = finalError.getErrorDataForId(id);
716
800
  if (existingData == null)
717
801
  continue;
718
802
  let contextState = existingData.contextState;
@@ -730,18 +814,20 @@ class NiceErrorDefined {
730
814
  reconciledErrorData[id] = {
731
815
  contextState,
732
816
  message: existingData.message,
733
- httpStatusCode: existingData.httpStatusCode
817
+ httpStatusCode: existingData.httpStatusCode,
818
+ timeAdded: existingData.timeAdded
734
819
  };
735
820
  }
736
821
  return new NiceErrorHydrated({
737
822
  def: this._buildDef(),
738
823
  niceErrorDefined: this,
739
- ids: error.ids,
824
+ ids: finalError.ids,
740
825
  errorData: reconciledErrorData,
741
- message: error.message,
742
- httpStatusCode: error.httpStatusCode,
743
- wasntNice: error.wasntNice,
744
- originError: error.originError
826
+ message: finalError.message,
827
+ httpStatusCode: finalError.httpStatusCode,
828
+ wasntNice: finalError.wasntNice,
829
+ originError: finalError.originError,
830
+ timeCreated: finalError.timeCreated
745
831
  });
746
832
  }
747
833
  fromId(...args) {
@@ -832,13 +918,13 @@ class NiceErrorDefined {
832
918
  } else {
833
919
  contextState = { kind: "serde_unset" /* serde_unset */, value: context };
834
920
  }
835
- return { contextState, message, httpStatusCode };
921
+ return { contextState, message, httpStatusCode, timeAdded: Date.now() };
836
922
  }
837
923
  }
838
924
 
839
925
  // ../nice-error/src/NiceErrorDefined/defineNiceError.ts
840
926
  var defineNiceError = (definition) => {
841
- return new NiceErrorDefined({
927
+ return new NiceErrorDomain({
842
928
  domain: definition.domain,
843
929
  allDomains: [definition.domain],
844
930
  schema: definition.schema,
@@ -906,21 +992,25 @@ var err_cast_not_nice = err_nice.createChildDomain({
906
992
  })
907
993
  }
908
994
  });
995
+ var err_nice_handler = err_nice.createChildDomain({
996
+ domain: "err_nice_handler",
997
+ schema: {}
998
+ });
909
999
  // ../nice-error/src/utils/isNiceErrorObject.ts
910
1000
  function isNiceErrorObject(obj) {
911
1001
  if (typeof obj !== "object" || obj == null)
912
1002
  return false;
913
- const o = obj;
914
- 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") {
915
1005
  return false;
916
1006
  }
917
- const def = o["def"];
1007
+ const def = o2["def"];
918
1008
  if (typeof def !== "object" || def == null)
919
1009
  return false;
920
- const d = def;
921
- if (typeof d["domain"] !== "string" || !Array.isArray(d["allDomains"]))
1010
+ const d2 = def;
1011
+ if (typeof d2["domain"] !== "string" || !Array.isArray(d2["allDomains"]))
922
1012
  return false;
923
- const errorData = o["errorData"];
1013
+ const errorData = o2["errorData"];
924
1014
  if (errorData != null) {
925
1015
  if (typeof errorData !== "object")
926
1016
  return false;
@@ -929,8 +1019,8 @@ function isNiceErrorObject(obj) {
929
1019
  continue;
930
1020
  if (typeof entry !== "object")
931
1021
  return false;
932
- const e = entry;
933
- const state = e["contextState"];
1022
+ const e2 = entry;
1023
+ const state = e2["contextState"];
934
1024
  if (state == null || typeof state !== "object")
935
1025
  return false;
936
1026
  const kind = state["kind"];
@@ -945,8 +1035,8 @@ function isNiceErrorObject(obj) {
945
1035
  function isRegularErrorJsonObject(obj) {
946
1036
  if (typeof obj !== "object" || obj == null)
947
1037
  return false;
948
- const o = obj;
949
- return typeof o["name"] === "string" && typeof o["message"] === "string";
1038
+ const o2 = obj;
1039
+ return typeof o2["name"] === "string" && typeof o2["message"] === "string";
950
1040
  }
951
1041
 
952
1042
  // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/urlToObj.js
@@ -1032,8 +1122,8 @@ function formatTemplate(settings, template, values, hideUnsetPlaceholder = false
1032
1122
  }
1033
1123
  };
1034
1124
  const defaultStyle = null;
1035
- return templateString.replace(/{{(.+?)}}/g, (_, placeholder) => {
1036
- 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;
1037
1127
  return settings.stylePrettyLogs ? styleWrap(value, settings?.prettyLogStyles?.[placeholder] ?? defaultStyle) + ansiColorWrap("", prettyLogStyles.reset) : value;
1038
1128
  });
1039
1129
  }
@@ -1282,14 +1372,14 @@ function isRegExp(re) {
1282
1372
  function isObject(arg) {
1283
1373
  return typeof arg === "object" && arg !== null;
1284
1374
  }
1285
- function isError(e) {
1286
- 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);
1287
1377
  }
1288
- function isDate(d) {
1289
- return isObject(d) && objectToString(d) === "[object Date]";
1378
+ function isDate(d2) {
1379
+ return isObject(d2) && objectToString(d2) === "[object Date]";
1290
1380
  }
1291
- function objectToString(o) {
1292
- return Object.prototype.toString.call(o);
1381
+ function objectToString(o2) {
1382
+ return Object.prototype.toString.call(o2);
1293
1383
  }
1294
1384
  function arrayToHash(array) {
1295
1385
  const hash = {};
@@ -1300,9 +1390,9 @@ function arrayToHash(array) {
1300
1390
  }
1301
1391
  function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
1302
1392
  const output = [];
1303
- for (let i = 0, l = value.length;i < l; ++i) {
1304
- if (hasOwn(value, String(i))) {
1305
- 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));
1306
1396
  } else {
1307
1397
  output.push("");
1308
1398
  }
@@ -1373,8 +1463,8 @@ function formatValue(ctx, value, recurseTimes = 0) {
1373
1463
  ]`];
1374
1464
  }
1375
1465
  if (isFunction(value)) {
1376
- const n = value.name ? ": " + value.name : "";
1377
- base = " [Function" + n + "]";
1466
+ const n2 = value.name ? ": " + value.name : "";
1467
+ base = " [Function" + n2 + "]";
1378
1468
  }
1379
1469
  if (isRegExp(value)) {
1380
1470
  base = " " + RegExp.prototype.toString.call(value);
@@ -1500,9 +1590,9 @@ function _extend(origin, add) {
1500
1590
  return origin;
1501
1591
  const clonedAdd = { ...add };
1502
1592
  const keys = Object.keys(add);
1503
- let i = keys.length;
1504
- while (i--) {
1505
- typedOrigin[keys[i]] = clonedAdd[keys[i]];
1593
+ let i2 = keys.length;
1594
+ while (i2--) {
1595
+ typedOrigin[keys[i2]] = clonedAdd[keys[i2]];
1506
1596
  }
1507
1597
  return typedOrigin;
1508
1598
  }
@@ -1515,7 +1605,7 @@ function formatWithOptions(inspectOptions, ...args) {
1515
1605
  _extend(ctx, inspectOptions);
1516
1606
  }
1517
1607
  const first = args[0];
1518
- let a = 0;
1608
+ let a2 = 0;
1519
1609
  let str = "";
1520
1610
  let join = "";
1521
1611
  if (typeof first === "string") {
@@ -1524,13 +1614,13 @@ function formatWithOptions(inspectOptions, ...args) {
1524
1614
  }
1525
1615
  let tempStr;
1526
1616
  let lastPos = 0;
1527
- for (let i = 0;i < first.length - 1; i++) {
1528
- if (first.charCodeAt(i) === 37) {
1529
- const nextChar = first.charCodeAt(++i);
1530
- 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) {
1531
1621
  switch (nextChar) {
1532
1622
  case 115: {
1533
- const tempArg = args[++a];
1623
+ const tempArg = args[++a2];
1534
1624
  if (typeof tempArg === "number") {
1535
1625
  tempStr = formatPrimitive(ctx, tempArg);
1536
1626
  } else if (typeof tempArg === "bigint") {
@@ -1548,10 +1638,10 @@ function formatWithOptions(inspectOptions, ...args) {
1548
1638
  break;
1549
1639
  }
1550
1640
  case 106:
1551
- tempStr = jsonStringifyRecursive(args[++a]);
1641
+ tempStr = jsonStringifyRecursive(args[++a2]);
1552
1642
  break;
1553
1643
  case 100: {
1554
- const tempNum = args[++a];
1644
+ const tempNum = args[++a2];
1555
1645
  if (typeof tempNum === "bigint") {
1556
1646
  tempStr = formatPrimitive(ctx, tempNum);
1557
1647
  } else if (typeof tempNum === "symbol") {
@@ -1562,10 +1652,10 @@ function formatWithOptions(inspectOptions, ...args) {
1562
1652
  break;
1563
1653
  }
1564
1654
  case 79:
1565
- tempStr = inspect(args[++a], inspectOptions);
1655
+ tempStr = inspect(args[++a2], inspectOptions);
1566
1656
  break;
1567
1657
  case 111:
1568
- tempStr = inspect(args[++a], {
1658
+ tempStr = inspect(args[++a2], {
1569
1659
  ...inspectOptions,
1570
1660
  showHidden: true,
1571
1661
  showProxy: true,
@@ -1573,7 +1663,7 @@ function formatWithOptions(inspectOptions, ...args) {
1573
1663
  });
1574
1664
  break;
1575
1665
  case 105: {
1576
- const tempInteger = args[++a];
1666
+ const tempInteger = args[++a2];
1577
1667
  if (typeof tempInteger === "bigint") {
1578
1668
  tempStr = formatPrimitive(ctx, tempInteger);
1579
1669
  } else if (typeof tempInteger === "symbol") {
@@ -1584,7 +1674,7 @@ function formatWithOptions(inspectOptions, ...args) {
1584
1674
  break;
1585
1675
  }
1586
1676
  case 102: {
1587
- const tempFloat = args[++a];
1677
+ const tempFloat = args[++a2];
1588
1678
  if (typeof tempFloat === "symbol") {
1589
1679
  tempStr = "NaN";
1590
1680
  } else {
@@ -1593,41 +1683,41 @@ function formatWithOptions(inspectOptions, ...args) {
1593
1683
  break;
1594
1684
  }
1595
1685
  case 99:
1596
- a += 1;
1686
+ a2 += 1;
1597
1687
  tempStr = "";
1598
1688
  break;
1599
1689
  case 37:
1600
- str += first.slice(lastPos, i);
1601
- lastPos = i + 1;
1690
+ str += first.slice(lastPos, i2);
1691
+ lastPos = i2 + 1;
1602
1692
  continue;
1603
1693
  default:
1604
1694
  continue;
1605
1695
  }
1606
- if (lastPos !== i - 1) {
1607
- str += first.slice(lastPos, i - 1);
1696
+ if (lastPos !== i2 - 1) {
1697
+ str += first.slice(lastPos, i2 - 1);
1608
1698
  }
1609
1699
  str += tempStr;
1610
- lastPos = i + 1;
1700
+ lastPos = i2 + 1;
1611
1701
  } else if (nextChar === 37) {
1612
- str += first.slice(lastPos, i);
1613
- lastPos = i + 1;
1702
+ str += first.slice(lastPos, i2);
1703
+ lastPos = i2 + 1;
1614
1704
  }
1615
1705
  }
1616
1706
  }
1617
1707
  if (lastPos !== 0) {
1618
- a++;
1708
+ a2++;
1619
1709
  join = " ";
1620
1710
  if (lastPos < first.length) {
1621
1711
  str += first.slice(lastPos);
1622
1712
  }
1623
1713
  }
1624
1714
  }
1625
- while (a < args.length) {
1626
- const value = args[a];
1715
+ while (a2 < args.length) {
1716
+ const value = args[a2];
1627
1717
  str += join;
1628
1718
  str += typeof value !== "string" ? inspect(value, inspectOptions) : value;
1629
1719
  join = " ";
1630
- a++;
1720
+ a2++;
1631
1721
  }
1632
1722
  return str;
1633
1723
  }
@@ -2394,16 +2484,16 @@ error stack:
2394
2484
  return urlToObject(source);
2395
2485
  } else if (source !== null && typeof source === "object") {
2396
2486
  const baseObject = runtime.isError(source) ? this._cloneError(source) : Object.create(Object.getPrototypeOf(source));
2397
- return Object.getOwnPropertyNames(source).reduce((o, prop) => {
2487
+ return Object.getOwnPropertyNames(source).reduce((o2, prop) => {
2398
2488
  const lookupKey = this.settings?.maskValuesOfKeysCaseInsensitive !== true ? prop : typeof prop === "string" ? prop.toLowerCase() : String(prop).toLowerCase();
2399
- o[prop] = keys.includes(lookupKey) ? this.settings.maskPlaceholder : (() => {
2489
+ o2[prop] = keys.includes(lookupKey) ? this.settings.maskPlaceholder : (() => {
2400
2490
  try {
2401
2491
  return this._recursiveCloneAndMaskValuesOfKeys(source[prop], keys, seen);
2402
2492
  } catch {
2403
2493
  return null;
2404
2494
  }
2405
2495
  })();
2406
- return o;
2496
+ return o2;
2407
2497
  }, baseObject);
2408
2498
  } else {
2409
2499
  if (typeof source === "string") {
@@ -2428,14 +2518,14 @@ error stack:
2428
2518
  } else if (source instanceof Date) {
2429
2519
  return new Date(source.getTime());
2430
2520
  } else if (this.isObject(source)) {
2431
- return Object.getOwnPropertyNames(source).reduce((o, prop) => {
2521
+ return Object.getOwnPropertyNames(source).reduce((o2, prop) => {
2432
2522
  const descriptor = Object.getOwnPropertyDescriptor(source, prop);
2433
2523
  if (descriptor) {
2434
- Object.defineProperty(o, prop, descriptor);
2524
+ Object.defineProperty(o2, prop, descriptor);
2435
2525
  const value = source[prop];
2436
- o[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
2526
+ o2[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
2437
2527
  }
2438
- return o;
2528
+ return o2;
2439
2529
  }, Object.create(Object.getPrototypeOf(source)));
2440
2530
  } else {
2441
2531
  return source;
@@ -2725,16 +2815,20 @@ var castNiceError = (error) => {
2725
2815
  var EErrId_NiceAction;
2726
2816
  ((EErrId_NiceAction2) => {
2727
2817
  EErrId_NiceAction2["action_id_not_in_domain"] = "action_id_not_in_domain";
2728
- EErrId_NiceAction2["domain_action_requester_conflict"] = "domain_action_handler_conflict";
2818
+ EErrId_NiceAction2["domain_already_exists_in_hierarchy"] = "domain_already_exists_in_hierarchy";
2729
2819
  EErrId_NiceAction2["domain_no_handler"] = "domain_no_handler";
2730
2820
  EErrId_NiceAction2["hydration_domain_mismatch"] = "hydration_domain_mismatch";
2731
2821
  EErrId_NiceAction2["hydration_action_state_mismatch"] = "hydration_action_state_mismatch";
2732
2822
  EErrId_NiceAction2["hydration_action_id_not_found"] = "hydration_action_id_not_found";
2733
- EErrId_NiceAction2["resolver_domain_not_registered"] = "resolver_domain_not_registered";
2734
- EErrId_NiceAction2["resolver_action_not_registered"] = "resolver_action_not_registered";
2735
- 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";
2736
2827
  EErrId_NiceAction2["environment_already_registered"] = "environment_already_registered";
2737
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";
2738
2832
  })(EErrId_NiceAction ||= {});
2739
2833
  var err_nice_action = err_nice.createChildDomain({
2740
2834
  domain: "err_nice_action",
@@ -2743,11 +2837,11 @@ var err_nice_action = err_nice.createChildDomain({
2743
2837
  ["action_id_not_in_domain" /* action_id_not_in_domain */]: err({
2744
2838
  message: ({ actionId, domain }) => `Action with id "${actionId}" does not exist in domain "${domain}".`
2745
2839
  }),
2746
- ["domain_action_handler_conflict" /* domain_action_requester_conflict */]: err({
2747
- 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(", ")}"]`
2748
2842
  }),
2749
2843
  ["domain_no_handler" /* domain_no_handler */]: err({
2750
- 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.`
2751
2845
  }),
2752
2846
  ["hydration_domain_mismatch" /* hydration_domain_mismatch */]: err({
2753
2847
  message: ({ expected, received }) => `Cannot hydrate action: domain mismatch. Expected "${expected}", got "${received}".`
@@ -2758,440 +2852,158 @@ var err_nice_action = err_nice.createChildDomain({
2758
2852
  ["hydration_action_id_not_found" /* hydration_action_id_not_found */]: err({
2759
2853
  message: ({ domain, actionId }) => `Cannot hydrate action: id "${actionId}" does not exist in domain "${domain}".`
2760
2854
  }),
2761
- ["resolver_domain_not_registered" /* resolver_domain_not_registered */]: err({
2762
- 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.`
2763
2857
  }),
2764
- ["resolver_action_not_registered" /* resolver_action_not_registered */]: err({
2765
- message: ({ domain, actionId }) => `No resolver registered for action "${actionId}" in domain "${domain}". Call .resolve("${actionId}", fn) on the domain resolver.`
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}".`
2766
2860
  }),
2767
- ["action_environment_not_found" /* action_environment_not_found */]: err({
2768
- message: ({ domain, envId }) => `No handler or resolver registered with environment id "${envId}" on domain "${domain}".`
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".`
2863
+ }),
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}".`
2769
2866
  }),
2770
2867
  ["environment_already_registered" /* environment_already_registered */]: err({
2771
- 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.`
2772
2869
  }),
2773
2870
  ["action_input_validation_failed" /* action_input_validation_failed */]: err({
2774
2871
  message: ({ domain, actionId, validationMessage }) => `Input validation failed for action "${actionId}" in domain "${domain}":
2775
2872
  ${validationMessage}`,
2776
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
2777
2887
  })
2778
2888
  }
2779
2889
  });
2780
2890
 
2781
- // ../../node_modules/.bun/nanoid@5.1.9/node_modules/nanoid/url-alphabet/index.js
2782
- 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 ||= {});
2783
2898
 
2784
- // ../../node_modules/.bun/nanoid@5.1.9/node_modules/nanoid/index.browser.js
2785
- var nanoid = (size = 21) => {
2786
- let id = "";
2787
- let bytes = crypto.getRandomValues(new Uint8Array(size |= 0));
2788
- while (size--) {
2789
- 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;
2790
2921
  }
2791
- return id;
2792
- };
2793
-
2794
- // ../../node_modules/.bun/valibot@1.3.1+8e24a2f921b8d7be/node_modules/valibot/dist/index.mjs
2795
- var store$4;
2796
- function getGlobalConfig(config$1) {
2797
- return {
2798
- lang: config$1?.lang ?? store$4?.lang,
2799
- message: config$1?.message,
2800
- abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
2801
- abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
2802
- };
2803
- }
2804
- var store$3;
2805
- function getGlobalMessage(lang) {
2806
- return store$3?.get(lang);
2807
- }
2808
- var store$2;
2809
- function getSchemaMessage(lang) {
2810
- return store$2?.get(lang);
2811
- }
2812
- var store$1;
2813
- function getSpecificMessage(reference, lang) {
2814
- return store$1?.get(reference)?.get(lang);
2815
- }
2816
- function _stringify(input) {
2817
- const type = typeof input;
2818
- if (type === "string")
2819
- return `"${input}"`;
2820
- if (type === "number" || type === "bigint" || type === "boolean")
2821
- return `${input}`;
2822
- if (type === "object" || type === "function")
2823
- return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
2824
- return type;
2825
- }
2826
- function _addIssue(context, label, dataset, config$1, other) {
2827
- const input = other && "input" in other ? other.input : dataset.value;
2828
- const expected = other?.expected ?? context.expects ?? null;
2829
- const received = other?.received ?? /* @__PURE__ */ _stringify(input);
2830
- const issue = {
2831
- kind: context.kind,
2832
- type: context.type,
2833
- input,
2834
- expected,
2835
- received,
2836
- message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
2837
- requirement: context.requirement,
2838
- path: other?.path,
2839
- issues: other?.issues,
2840
- lang: config$1.lang,
2841
- abortEarly: config$1.abortEarly,
2842
- abortPipeEarly: config$1.abortPipeEarly
2843
- };
2844
- const isSchema = context.kind === "schema";
2845
- 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);
2846
- if (message$1 !== undefined)
2847
- issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
2848
- if (isSchema)
2849
- dataset.typed = false;
2850
- if (dataset.issues)
2851
- dataset.issues.push(issue);
2852
- else
2853
- dataset.issues = [issue];
2854
- }
2855
- function _getStandardProps(context) {
2856
- return {
2857
- version: 1,
2858
- vendor: "valibot",
2859
- validate(value$1) {
2860
- return context["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig());
2861
- }
2862
- };
2863
- }
2864
- function includes(requirement, message$1) {
2865
- const expects = /* @__PURE__ */ _stringify(requirement);
2866
- return {
2867
- kind: "validation",
2868
- type: "includes",
2869
- reference: includes,
2870
- async: false,
2871
- expects,
2872
- requirement,
2873
- message: message$1,
2874
- "~run"(dataset, config$1) {
2875
- if (dataset.typed && !dataset.value.includes(this.requirement))
2876
- _addIssue(this, "content", dataset, config$1, { received: `!${expects}` });
2877
- return dataset;
2878
- }
2879
- };
2880
- }
2881
- function length(requirement, message$1) {
2882
- return {
2883
- kind: "validation",
2884
- type: "length",
2885
- reference: length,
2886
- async: false,
2887
- expects: `${requirement}`,
2888
- requirement,
2889
- message: message$1,
2890
- "~run"(dataset, config$1) {
2891
- if (dataset.typed && dataset.value.length !== this.requirement)
2892
- _addIssue(this, "length", dataset, config$1, { received: `${dataset.value.length}` });
2893
- return dataset;
2894
- }
2895
- };
2896
- }
2897
- var _LruCache = class {
2898
- constructor(config$1) {
2899
- this.refCount = 0;
2900
- this.maxSize = config$1?.maxSize ?? 1000;
2901
- this.maxAge = config$1?.maxAge ?? Infinity;
2902
- this.hasMaxAge = isFinite(this.maxAge);
2903
- }
2904
- #stringify(input) {
2905
- const type = typeof input;
2906
- if (type === "string")
2907
- return `"${input}"`;
2908
- if (type === "number" || type === "boolean")
2909
- return `${input}`;
2910
- if (type === "bigint")
2911
- return `${input}n`;
2912
- if (type === "object" || type === "function") {
2913
- if (input) {
2914
- this.refIds ??= /* @__PURE__ */ new WeakMap;
2915
- let id = this.refIds.get(input);
2916
- if (!id) {
2917
- id = ++this.refCount;
2918
- this.refIds.set(input, id);
2919
- }
2920
- return `#${id}`;
2921
- }
2922
- return "null";
2923
- }
2924
- return type;
2922
+ get input() {
2923
+ return this._input;
2925
2924
  }
2926
- key(input, config$1 = {}) {
2927
- 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();
2928
2927
  }
2929
- get(key) {
2930
- if (!this.store)
2931
- return;
2932
- const entry = this.store.get(key);
2933
- if (!entry)
2934
- return;
2935
- if (this.hasMaxAge && Date.now() - entry[1] > this.maxAge) {
2936
- this.store.delete(key);
2937
- return;
2938
- }
2939
- this.store.delete(key);
2940
- this.store.set(key, entry);
2941
- 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
+ };
2942
2935
  }
2943
- set(key, value$1) {
2944
- this.store ??= /* @__PURE__ */ new Map;
2945
- this.store.delete(key);
2946
- const timestamp = this.hasMaxAge ? Date.now() : 0;
2947
- this.store.set(key, [value$1, timestamp]);
2948
- if (this.store.size > this.maxSize)
2949
- this.store.delete(this.store.keys().next().value);
2936
+ toJsonString() {
2937
+ return JSON.stringify(this.toJsonObject());
2950
2938
  }
2951
- clear() {
2952
- this.store?.clear();
2939
+ hydratePrimeJson(wire) {
2940
+ return this.coreAction.actionDomain.hydratePrimed(wire);
2953
2941
  }
2954
- };
2955
- function getFallback(schema, dataset, config$1) {
2956
- return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
2957
- }
2958
- function getDefault(schema, dataset, config$1) {
2959
- return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
2960
- }
2961
- function array(item, message$1) {
2962
- return {
2963
- kind: "schema",
2964
- type: "array",
2965
- reference: array,
2966
- expects: "Array",
2967
- async: false,
2968
- item,
2969
- message: message$1,
2970
- get "~standard"() {
2971
- return /* @__PURE__ */ _getStandardProps(this);
2972
- },
2973
- "~run"(dataset, config$1) {
2974
- const input = dataset.value;
2975
- if (Array.isArray(input)) {
2976
- dataset.typed = true;
2977
- dataset.value = [];
2978
- for (let key = 0;key < input.length; key++) {
2979
- const value$1 = input[key];
2980
- const itemDataset = this.item["~run"]({ value: value$1 }, config$1);
2981
- if (itemDataset.issues) {
2982
- const pathItem = {
2983
- type: "array",
2984
- origin: "value",
2985
- input,
2986
- key,
2987
- value: value$1
2988
- };
2989
- for (const issue of itemDataset.issues) {
2990
- if (issue.path)
2991
- issue.path.unshift(pathItem);
2992
- else
2993
- issue.path = [pathItem];
2994
- dataset.issues?.push(issue);
2995
- }
2996
- if (!dataset.issues)
2997
- dataset.issues = itemDataset.issues;
2998
- if (config$1.abortEarly) {
2999
- dataset.typed = false;
3000
- break;
3001
- }
3002
- }
3003
- if (!itemDataset.typed)
3004
- dataset.typed = false;
3005
- dataset.value.push(itemDataset.value);
3006
- }
3007
- } else
3008
- _addIssue(this, "type", dataset, config$1);
3009
- return dataset;
3010
- }
3011
- };
3012
- }
3013
- function literal(literal_, message$1) {
3014
- return {
3015
- kind: "schema",
3016
- type: "literal",
3017
- reference: literal,
3018
- expects: /* @__PURE__ */ _stringify(literal_),
3019
- async: false,
3020
- literal: literal_,
3021
- message: message$1,
3022
- get "~standard"() {
3023
- return /* @__PURE__ */ _getStandardProps(this);
3024
- },
3025
- "~run"(dataset, config$1) {
3026
- if (dataset.value === this.literal)
3027
- dataset.typed = true;
3028
- else
3029
- _addIssue(this, "type", dataset, config$1);
3030
- return dataset;
3031
- }
3032
- };
3033
- }
3034
- function nullish(wrapped, default_) {
3035
- return {
3036
- kind: "schema",
3037
- type: "nullish",
3038
- reference: nullish,
3039
- expects: `(${wrapped.expects} | null | undefined)`,
3040
- async: false,
3041
- wrapped,
3042
- default: default_,
3043
- get "~standard"() {
3044
- return /* @__PURE__ */ _getStandardProps(this);
3045
- },
3046
- "~run"(dataset, config$1) {
3047
- if (dataset.value === null || dataset.value === undefined) {
3048
- if (this.default !== undefined)
3049
- dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
3050
- if (dataset.value === null || dataset.value === undefined) {
3051
- dataset.typed = true;
3052
- return dataset;
3053
- }
3054
- }
3055
- return this.wrapped["~run"](dataset, config$1);
3056
- }
3057
- };
3058
- }
3059
- function object(entries$1, message$1) {
3060
- return {
3061
- kind: "schema",
3062
- type: "object",
3063
- reference: object,
3064
- expects: "Object",
3065
- async: false,
3066
- entries: entries$1,
3067
- message: message$1,
3068
- get "~standard"() {
3069
- return /* @__PURE__ */ _getStandardProps(this);
3070
- },
3071
- "~run"(dataset, config$1) {
3072
- const input = dataset.value;
3073
- if (input && typeof input === "object") {
3074
- dataset.typed = true;
3075
- dataset.value = {};
3076
- for (const key in this.entries) {
3077
- const valueSchema = this.entries[key];
3078
- if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== undefined) {
3079
- const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
3080
- const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
3081
- if (valueDataset.issues) {
3082
- const pathItem = {
3083
- type: "object",
3084
- origin: "value",
3085
- input,
3086
- key,
3087
- value: value$1
3088
- };
3089
- for (const issue of valueDataset.issues) {
3090
- if (issue.path)
3091
- issue.path.unshift(pathItem);
3092
- else
3093
- issue.path = [pathItem];
3094
- dataset.issues?.push(issue);
3095
- }
3096
- if (!dataset.issues)
3097
- dataset.issues = valueDataset.issues;
3098
- if (config$1.abortEarly) {
3099
- dataset.typed = false;
3100
- break;
3101
- }
3102
- }
3103
- if (!valueDataset.typed)
3104
- dataset.typed = false;
3105
- dataset.value[key] = valueDataset.value;
3106
- } else if (valueSchema.fallback !== undefined)
3107
- dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
3108
- else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
3109
- _addIssue(this, "key", dataset, config$1, {
3110
- input: undefined,
3111
- expected: `"${key}"`,
3112
- path: [{
3113
- type: "object",
3114
- origin: "key",
3115
- input,
3116
- key,
3117
- value: input[key]
3118
- }]
3119
- });
3120
- if (config$1.abortEarly)
3121
- break;
3122
- }
3123
- }
3124
- } else
3125
- _addIssue(this, "type", dataset, config$1);
3126
- return dataset;
3127
- }
3128
- };
3129
- }
3130
- function string(message$1) {
3131
- return {
3132
- kind: "schema",
3133
- type: "string",
3134
- reference: string,
3135
- expects: "string",
3136
- async: false,
3137
- message: message$1,
3138
- get "~standard"() {
3139
- return /* @__PURE__ */ _getStandardProps(this);
3140
- },
3141
- "~run"(dataset, config$1) {
3142
- if (typeof dataset.value === "string")
3143
- dataset.typed = true;
3144
- else
3145
- _addIssue(this, "type", dataset, config$1);
3146
- return dataset;
3147
- }
3148
- };
3149
- }
3150
- function pipe(...pipe$1) {
3151
- return {
3152
- ...pipe$1[0],
3153
- pipe: pipe$1,
3154
- get "~standard"() {
3155
- return /* @__PURE__ */ _getStandardProps(this);
3156
- },
3157
- "~run"(dataset, config$1) {
3158
- for (const item of pipe$1)
3159
- if (item.kind !== "metadata") {
3160
- if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
3161
- dataset.typed = false;
3162
- break;
3163
- }
3164
- if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly)
3165
- dataset = item["~run"](dataset, config$1);
3166
- }
3167
- 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 };
3168
2971
  }
3169
- };
2972
+ }
3170
2973
  }
3171
2974
 
3172
2975
  // src/NiceAction/NiceActionResponse.ts
3173
2976
  class NiceActionResponse {
3174
- type = "response" /* response */;
2977
+ type = "resolved" /* resolved */;
3175
2978
  domain;
3176
2979
  allDomains;
3177
2980
  id;
3178
2981
  primed;
3179
2982
  result;
3180
2983
  timeResponded;
2984
+ cuid;
2985
+ schema;
2986
+ timeCreated;
3181
2987
  constructor(primed, result, hydrationData) {
3182
2988
  this.primed = primed;
3183
2989
  this.result = result;
3184
2990
  this.domain = primed.coreAction.domain;
3185
2991
  this.allDomains = primed.coreAction.allDomains;
3186
2992
  this.id = primed.coreAction.id;
2993
+ this.cuid = primed.coreAction.cuid;
2994
+ this.schema = primed.coreAction.schema;
2995
+ this.timeCreated = primed.coreAction.timeCreated;
3187
2996
  this.timeResponded = hydrationData?.timeResponded ?? Date.now();
3188
2997
  }
2998
+ getEnvironmentMeta() {
2999
+ return this.primed.coreAction.actionDomain.getEnvironmentMeta();
3000
+ }
3189
3001
  toJsonObject() {
3190
3002
  const base = this.primed.toJsonObject();
3191
3003
  if (this.result.ok) {
3192
3004
  return {
3193
3005
  ...base,
3194
- type: "response" /* response */,
3006
+ type: "resolved" /* resolved */,
3195
3007
  ok: true,
3196
3008
  output: this.primed.coreAction.schema.serializeOutput(this.result.output),
3197
3009
  timeResponded: this.timeResponded
@@ -3199,7 +3011,7 @@ class NiceActionResponse {
3199
3011
  }
3200
3012
  return {
3201
3013
  ...base,
3202
- type: "response" /* response */,
3014
+ type: "resolved" /* resolved */,
3203
3015
  ok: false,
3204
3016
  error: this.result.error.toJsonObject(),
3205
3017
  timeResponded: this.timeResponded
@@ -3208,6 +3020,15 @@ class NiceActionResponse {
3208
3020
  toJsonString() {
3209
3021
  return JSON.stringify(this.toJsonObject());
3210
3022
  }
3023
+ hydrateResponseJson(wire) {
3024
+ return this.primed.hydrateResponseJson(wire);
3025
+ }
3026
+ toHttpResponse({ useErrorStatus = true } = {}) {
3027
+ return new Response(this.toJsonString(), {
3028
+ status: this.result.ok ? 200 : useErrorStatus ? this.result.error.httpStatusCode : 500,
3029
+ headers: { "Content-Type": "application/json" }
3030
+ });
3031
+ }
3211
3032
  }
3212
3033
  function hydrateNiceActionResponse(wire, coreAction) {
3213
3034
  const rawInput = coreAction.schema.deserializeInput(wire.input);
@@ -3219,72 +3040,38 @@ function hydrateNiceActionResponse(wire, coreAction) {
3219
3040
  return new NiceActionResponse(primed, { ok: false, error: castNiceError(wire.error) }, { timeResponded: wire.timeResponded });
3220
3041
  }
3221
3042
 
3222
- // src/NiceAction/NiceActionPrimed.ts
3223
- class NiceActionPrimed {
3224
- coreAction;
3225
- input;
3226
- type = "primed" /* primed */;
3227
- domain;
3228
- allDomains;
3229
- id;
3230
- timePrimed;
3231
- constructor(coreAction, input, hydrationData) {
3232
- this.coreAction = coreAction;
3233
- this.input = input;
3234
- this.domain = coreAction.domain;
3235
- this.allDomains = coreAction.allDomains;
3236
- this.id = coreAction.id;
3237
- this.timePrimed = hydrationData?.timePrimed ?? Date.now();
3238
- }
3239
- toJsonObject() {
3240
- return {
3241
- ...this.coreAction.toJsonObject(),
3242
- type: "primed" /* primed */,
3243
- input: this.coreAction.schema.serializeInput(this.input),
3244
- timePrimed: this.timePrimed
3245
- };
3246
- }
3247
- toJsonString() {
3248
- return JSON.stringify(this.toJsonObject());
3249
- }
3250
- setOutput(output) {
3251
- return new NiceActionResponse(this, { ok: true, output });
3252
- }
3253
- processResponse(wire) {
3254
- if (!wire.ok) {
3255
- throw castNiceError(wire.error);
3256
- }
3257
- return this.coreAction.schema.deserializeOutput(wire.output);
3258
- }
3259
- async execute(envId) {
3260
- return this.coreAction._actionDomain._dispatchAction(this, envId);
3261
- }
3262
- async executeSafe(envId) {
3263
- try {
3264
- const value = await this.execute(envId);
3265
- return { ok: true, output: value };
3266
- } catch (error) {
3267
- return { ok: false, error };
3268
- }
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];
3269
3057
  }
3270
- }
3058
+ return id;
3059
+ };
3271
3060
 
3272
3061
  // src/NiceAction/NiceAction.ts
3273
3062
  class NiceAction {
3274
3063
  actionDomain;
3275
3064
  schema;
3276
- id;
3277
3065
  type = "empty" /* empty */;
3066
+ id;
3278
3067
  domain;
3279
3068
  allDomains;
3280
- _actionDomain;
3281
3069
  timeCreated;
3282
3070
  cuid;
3283
3071
  constructor(actionDomain, schema, id, hydrationData) {
3284
3072
  this.actionDomain = actionDomain;
3285
3073
  this.schema = schema;
3286
3074
  this.id = id;
3287
- this._actionDomain = actionDomain;
3288
3075
  this.domain = actionDomain.domain;
3289
3076
  this.allDomains = actionDomain.allDomains;
3290
3077
  this.timeCreated = hydrationData?.timeCreated ?? Date.now();
@@ -3300,57 +3087,114 @@ class NiceAction {
3300
3087
  cuid: this.cuid
3301
3088
  };
3302
3089
  }
3303
- toValidationSchema() {
3304
- return object({
3305
- domain: literal(this.domain),
3306
- allDomains: pipe(array(string()), length(this.allDomains.length), includes(this.domain)),
3307
- id: literal(this.id)
3090
+ toJsonString() {
3091
+ return JSON.stringify(this.toJsonObject());
3092
+ }
3093
+ toHttpResponse() {
3094
+ return new Response(this.toJsonString(), {
3095
+ status: 200,
3096
+ headers: { "Content-Type": "application/json" }
3308
3097
  });
3309
3098
  }
3310
3099
  is(action) {
3311
3100
  return action instanceof NiceActionPrimed && action.coreAction.domain === this.domain && action.coreAction.id === this.id;
3312
3101
  }
3313
3102
  prime(input, hydrationData) {
3314
- 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);
3315
3108
  }
3316
- async execute(input, envId) {
3317
- const primed = new NiceActionPrimed(this, input);
3318
- 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 ?? {} });
3319
3112
  }
3320
- async executeSafe(input, envId) {
3113
+ async executeSafe(input, meta) {
3321
3114
  try {
3322
- const value = await this.execute(input, envId);
3115
+ const value = await this.execute(input, meta);
3323
3116
  return { ok: true, output: value };
3324
3117
  } catch (error) {
3325
3118
  return { ok: false, error };
3326
3119
  }
3327
3120
  }
3328
- async executeToResponse(input, envId) {
3121
+ async executeToResponse(input, meta) {
3329
3122
  const primed = this.prime(input);
3330
- const result = await this.executeSafe(input, envId);
3123
+ const result = await primed.executeSafe(meta);
3331
3124
  return new NiceActionResponse(primed, result);
3332
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
+ }
3333
3144
  }
3334
3145
 
3335
- // src/ActionDomain/NiceActionDomain.ts
3336
- 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 {
3337
3153
  domain;
3338
3154
  allDomains;
3339
3155
  actions;
3340
3156
  _listeners = [];
3341
- _requesters = new Map;
3342
- _responders = new Map;
3343
3157
  constructor(definition) {
3344
3158
  this.domain = definition.domain;
3345
3159
  this.allDomains = definition.allDomains;
3346
3160
  this.actions = definition.actions;
3347
3161
  }
3348
- createChildDomain(subDomainDef) {
3349
- return new NiceActionDomain({
3350
- allDomains: [subDomainDef.domain, ...this.allDomains],
3351
- domain: subDomainDef.domain,
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
+ }
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
+ }
3193
+ return new NiceActionDomain({
3194
+ allDomains: [subDomainDef.domain, ...this.allDomains],
3195
+ domain: subDomainDef.domain,
3352
3196
  actions: subDomainDef.actions
3353
- });
3197
+ }, { rootDomain: this._rootDomain });
3354
3198
  }
3355
3199
  primeUnknown(actionId, input) {
3356
3200
  const action = this.action(actionId).prime(input);
@@ -3369,66 +3213,8 @@ class NiceActionDomain {
3369
3213
  }
3370
3214
  return new NiceAction(this, actionSchema, id, hydrationData);
3371
3215
  }
3372
- isExactActionDomain(action) {
3373
- return action instanceof NiceActionPrimed && this.domain === action.domain;
3374
- }
3375
- matchAction(action, id) {
3376
- if (this.isExactActionDomain(action) && action.coreAction.id === id) {
3377
- return action;
3378
- }
3379
- return null;
3380
- }
3381
- addActionListener(listener) {
3382
- this._listeners.push(listener);
3383
- return () => {
3384
- this._listeners = this._listeners.filter((l) => l !== listener);
3385
- };
3386
- }
3387
- async _dispatchAction(primed, envId) {
3388
- if (envId != null) {
3389
- const requester = this._requesters.get(envId);
3390
- if (requester) {
3391
- const validatedPrimed = await this._withValidatedInput(primed);
3392
- const result = await requester.handleAction(validatedPrimed);
3393
- for (const listener of this._listeners)
3394
- await listener(validatedPrimed);
3395
- return result;
3396
- }
3397
- const responder = this._responders.get(envId);
3398
- if (responder) {
3399
- const result = await responder._resolvePrimed(primed);
3400
- for (const listener of this._listeners)
3401
- await listener(primed);
3402
- return result;
3403
- }
3404
- throw err_nice_action.fromId("action_environment_not_found" /* action_environment_not_found */, {
3405
- domain: this.domain,
3406
- envId
3407
- });
3408
- }
3409
- const defaultHandler = this._requesters.get(undefined);
3410
- if (defaultHandler) {
3411
- const validatedPrimed = await this._withValidatedInput(primed);
3412
- const result = await defaultHandler.handleAction(validatedPrimed);
3413
- for (const listener of this._listeners)
3414
- await listener(validatedPrimed);
3415
- return result;
3416
- }
3417
- const defaultResolver = this._responders.get(undefined);
3418
- if (defaultResolver) {
3419
- const result = await defaultResolver._resolvePrimed(primed);
3420
- for (const listener of this._listeners)
3421
- await listener(primed);
3422
- return result;
3423
- }
3424
- throw err_nice_action.fromId("domain_no_handler" /* domain_no_handler */, { domain: this.domain });
3425
- }
3426
- async _withValidatedInput(primed) {
3427
- const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3428
- domain: this.domain,
3429
- actionId: primed.coreAction.id
3430
- });
3431
- return primed.coreAction.prime(validatedInput);
3216
+ isDomainAction(action) {
3217
+ return isNiceActionInstance(action) && action.domain === this.domain;
3432
3218
  }
3433
3219
  hydratePrimed(serialized) {
3434
3220
  if (serialized.type !== "primed" /* primed */) {
@@ -3454,15 +3240,15 @@ class NiceActionDomain {
3454
3240
  cuid: serialized.cuid,
3455
3241
  timeCreated: serialized.timeCreated
3456
3242
  });
3457
- const rawInput = coreAction.schema.deserializeInput(serialized.input);
3243
+ const rawInput = coreAction.validateInput(coreAction.deserializeInput(serialized.input));
3458
3244
  return new NiceActionPrimed(coreAction, rawInput, {
3459
3245
  timePrimed: serialized.timePrimed
3460
3246
  });
3461
3247
  }
3462
3248
  hydrateResponse(serialized) {
3463
- if (serialized.type !== "response" /* response */) {
3249
+ if (serialized.type !== "resolved" /* resolved */) {
3464
3250
  throw err_nice_action.fromId("hydration_action_state_mismatch" /* hydration_action_state_mismatch */, {
3465
- expected: "response" /* response */,
3251
+ expected: "resolved" /* resolved */,
3466
3252
  received: serialized.type
3467
3253
  });
3468
3254
  }
@@ -3485,124 +3271,724 @@ class NiceActionDomain {
3485
3271
  });
3486
3272
  return hydrateNiceActionResponse(serialized, coreAction);
3487
3273
  }
3488
- setActionRequester(handler, options) {
3489
- const envId = options?.envId;
3490
- if (this._requesters.has(envId)) {
3491
- if (envId != null) {
3492
- throw err_nice_action.fromId("environment_already_registered" /* environment_already_registered */, {
3493
- domain: this.domain,
3494
- envId
3495
- });
3496
- }
3497
- throw err_nice_action.fromId("domain_action_handler_conflict" /* domain_action_requester_conflict */, {
3498
- 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
3499
3315
  });
3500
3316
  }
3501
- const h = handler ?? new NiceActionRequester;
3502
- this._requesters.set(envId, h);
3503
- return h;
3317
+ return new NiceActionDomain({
3318
+ allDomains: [subDomainDef.domain, ...this.allDomains],
3319
+ domain: subDomainDef.domain,
3320
+ actions: subDomainDef.actions
3321
+ }, { rootDomain: this });
3504
3322
  }
3505
- registerResponder(resolver, options) {
3506
- const envId = options?.envId;
3507
- if (this._responders.has(envId)) {
3323
+ setRuntimeEnvironment(runtime2) {
3324
+ if (this._runtimeEnvironment != null) {
3508
3325
  throw err_nice_action.fromId("environment_already_registered" /* environment_already_registered */, {
3509
3326
  domain: this.domain,
3510
- envId: envId ?? "(default)"
3327
+ matchTag: this._runtimeEnvironment.envId
3511
3328
  });
3512
3329
  }
3513
- this._responders.set(envId, resolver);
3330
+ this._runtimeEnvironment = runtime2;
3514
3331
  return this;
3515
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
+ }
3516
3379
  }
3517
3380
 
3518
- // src/ActionDomain/createActionDomain.ts
3519
- var createActionDomain = (definition) => {
3520
- return new NiceActionDomain({
3521
- ...definition,
3522
- allDomains: [definition.domain]
3523
- });
3381
+ // src/ActionDomain/helpers/createRootActionDomain.ts
3382
+ var createActionRootDomain = (definition) => {
3383
+ return new NiceActionRootDomain(definition);
3524
3384
  };
3525
- // src/ActionRequestResponse/ActionResponder/NiceActionResponder.ts
3526
- class NiceActionDomainResponder {
3527
- _domain;
3528
- _responders = new Map;
3529
- constructor(domain) {
3530
- this._domain = domain;
3531
- }
3532
- get domainId() {
3533
- return this._domain.domain;
3534
- }
3535
- resolveAction(actionId, fn) {
3536
- 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}::_`);
3537
3447
  return this;
3538
3448
  }
3539
- async _resolvePrimed(primed) {
3540
- const resolver = this._responders.get(primed.coreAction.id);
3541
- if (resolver == null) {
3542
- throw err_nice_action.fromId("resolver_action_not_registered" /* resolver_action_not_registered */, {
3543
- domain: primed.domain,
3544
- actionId: primed.coreAction.id
3545
- });
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);
3546
3481
  }
3547
- const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3548
- domain: primed.domain,
3549
- actionId: primed.coreAction.id
3550
- });
3551
- const response = await resolver(validatedInput);
3552
3482
  return response;
3553
3483
  }
3554
- async _dispatch(wire) {
3555
- const primed = this._domain.hydratePrimed(wire);
3556
- const resolverFn = this._responders.get(wire.id);
3557
- if (resolverFn == null) {
3558
- throw err_nice_action.fromId("resolver_action_not_registered" /* resolver_action_not_registered */, {
3559
- domain: wire.domain,
3560
- 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
3561
3521
  });
3562
- }
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);
3563
3541
  try {
3564
- const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3565
- domain: wire.domain,
3566
- 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
3567
3547
  });
3568
- const output = await resolverFn(validatedInput);
3569
- return new NiceActionResponse(primed, {
3570
- ok: true,
3571
- 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
3572
3670
  });
3573
- } catch (e) {
3574
- return new NiceActionResponse(primed, {
3575
- ok: false,
3576
- 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
3577
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 */);
3578
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;
3579
3736
  }
3580
3737
  }
3581
- function createDomainResolver(domain) {
3582
- 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
+ }
3583
3795
  }
3584
- // src/ActionRequestResponse/ActionResponder/NiceActionResponderEnvironment.ts
3585
- class NiceActionResponderEnvironment {
3586
- _resolvers = new Map;
3587
- constructor(resolvers) {
3588
- for (const resolver of resolvers) {
3589
- 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;
3590
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;
3591
3830
  }
3592
- async dispatch(wire) {
3593
- const resolver = this._resolvers.get(wire.domain);
3594
- if (resolver == null) {
3595
- throw err_nice_action.fromId("resolver_domain_not_registered" /* resolver_domain_not_registered */, {
3596
- domain: wire.domain
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()
3597
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) };
3598
3875
  }
3599
- const response = await resolver._dispatch(wire);
3600
- return response.toJsonObject();
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);
3900
+ }
3901
+ return { handled: true, response };
3902
+ }
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
3921
+ });
3922
+ }
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
+ });
3601
3937
  }
3602
3938
  }
3603
- function createResponderEnvironment(resolvers) {
3604
- 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
+ }
3605
3988
  }
3989
+ var createActionRuntime = (config) => {
3990
+ return new ActionRuntimeEnvironment(config);
3991
+ };
3606
3992
  // ../common-errors/src/validation/standard_schema/extractMessageFromStandardSchema.ts
3607
3993
  function extractPathFromIssue(issue) {
3608
3994
  let pathString = "";
@@ -3656,10 +4042,10 @@ class NiceActionSchema {
3656
4042
  inputOptions;
3657
4043
  outputOptions;
3658
4044
  get inputSchema() {
3659
- return nullish(this.inputOptions?.schema);
4045
+ return this.inputOptions?.schema;
3660
4046
  }
3661
4047
  get outputSchema() {
3662
- return nullish(this.outputOptions?.schema);
4048
+ return this.outputOptions?.schema;
3663
4049
  }
3664
4050
  input(options, serialize, deserialize) {
3665
4051
  if (serialize != null && deserialize != null) {
@@ -3693,11 +4079,17 @@ class NiceActionSchema {
3693
4079
  }
3694
4080
  return serialized;
3695
4081
  }
3696
- async validateInput(value, meta) {
4082
+ validateInput(value, meta) {
3697
4083
  if (this.inputOptions?.schema == null) {
3698
4084
  return value;
3699
4085
  }
3700
- 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
+ }
3701
4093
  if (result.issues != null) {
3702
4094
  throw err_nice_action.fromId("action_input_validation_failed" /* action_input_validation_failed */, {
3703
4095
  domain: meta.domain,
@@ -3707,6 +4099,26 @@ class NiceActionSchema {
3707
4099
  }
3708
4100
  return result.value;
3709
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
+ }
3710
4122
  serializeOutput(rawOutput) {
3711
4123
  if (this.outputOptions?.serialization) {
3712
4124
  return this.outputOptions.serialization.serialize(rawOutput);
@@ -3725,29 +4137,80 @@ class NiceActionSchema {
3725
4137
  var action = () => {
3726
4138
  return new NiceActionSchema;
3727
4139
  };
3728
- // src/utils/isActionResponseJsonObject.ts
3729
- var isActionResponseJsonObject = (obj) => {
3730
- 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";
3731
- };
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);
3732
4187
  // src/utils/isPrimedActionJsonObject.ts
3733
4188
  var isPrimedActionJsonObject = (obj) => {
3734
- 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 */;
3735
4190
  };
3736
4191
  export {
4192
+ matchAction,
3737
4193
  isPrimedActionJsonObject,
3738
4194
  isActionResponseJsonObject,
4195
+ err_nice_transport_ws,
4196
+ err_nice_transport,
4197
+ err_nice_connect,
3739
4198
  err_nice_action,
3740
- createResponderEnvironment,
3741
- createDomainResolver,
3742
- createActionDomain,
4199
+ createHandler,
4200
+ createActionRuntime,
4201
+ createActionRootDomain,
3743
4202
  action,
4203
+ ConnectionConfig as Transport,
3744
4204
  NiceActionSchema,
3745
4205
  NiceActionResponse,
3746
- NiceActionResponderEnvironment,
3747
- NiceActionRequester,
3748
4206
  NiceActionPrimed,
3749
- NiceActionDomainResponder,
3750
4207
  NiceActionDomain,
3751
4208
  NiceAction,
3752
- EErrId_NiceAction
4209
+ EErrId_NiceTransport_WebSocket,
4210
+ EErrId_NiceTransport,
4211
+ EErrId_NiceAction,
4212
+ EActionState,
4213
+ ActionRuntimeEnvironment,
4214
+ ActionHandler,
4215
+ ActionConnect
3753
4216
  };