@gjermundgaraba/effect-actions 0.30.0 → 0.32.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 (111) hide show
  1. package/README.md +4 -3
  2. package/dist/Action.d.mts +6 -6
  3. package/dist/Action.mjs +12 -14
  4. package/dist/ActionEntity.d.mts +237 -0
  5. package/dist/ActionEntity.mjs +211 -0
  6. package/dist/ActionHttp.d.mts +5 -5
  7. package/dist/ActionHttp.mjs +24 -28
  8. package/dist/ActionMcp.d.mts +2 -3
  9. package/dist/ActionMcp.mjs +7 -10
  10. package/dist/ActionRpc.d.mts +25 -57
  11. package/dist/ActionRpc.mjs +45 -274
  12. package/dist/ActionToolkit.mjs +4 -3
  13. package/dist/Authentication.d.mts +8 -9
  14. package/dist/Authentication.mjs +49 -51
  15. package/dist/Event.d.mts +26 -6
  16. package/dist/Event.mjs +2 -2
  17. package/dist/Stored.d.mts +49 -0
  18. package/dist/Stored.mjs +78 -0
  19. package/dist/Webhook.d.mts +5 -4
  20. package/dist/Webhook.mjs +11 -4
  21. package/dist/authentication/provider.d.mts +2 -2
  22. package/dist/authentication/refusal.mjs +11 -4
  23. package/dist/cli/commands.mjs +8 -8
  24. package/dist/contract/call.mjs +6 -2
  25. package/dist/contract/callback.mjs +6 -1
  26. package/dist/contract/caller.d.mts +2 -6
  27. package/dist/contract/caller.mjs +3 -3
  28. package/dist/contract/digest.mjs +3 -2
  29. package/dist/contract/event-tables.mjs +90 -0
  30. package/dist/contract/feed.d.mts +15 -3
  31. package/dist/contract/feed.mjs +27 -16
  32. package/dist/contract/hub.d.mts +4 -57
  33. package/dist/contract/hub.mjs +12 -15
  34. package/dist/contract/idempotency.d.mts +6 -18
  35. package/dist/contract/idempotency.mjs +6 -14
  36. package/dist/contract/implementation.mjs +10 -21
  37. package/dist/contract/log.d.mts +0 -26
  38. package/dist/contract/log.mjs +16 -8
  39. package/dist/contract/pages.d.mts +30 -2
  40. package/dist/contract/pages.mjs +27 -3
  41. package/dist/contract/push.mjs +3 -5
  42. package/dist/contract/recent.mjs +3 -2
  43. package/dist/contract/serving.mjs +17 -17
  44. package/dist/contract/stream.d.mts +1 -1
  45. package/dist/contract/stream.mjs +14 -2
  46. package/dist/contract/subscribe.mjs +7 -2
  47. package/dist/contract/wake.mjs +9 -0
  48. package/dist/contract/watch.mjs +24 -22
  49. package/dist/contract/webhooks.d.mts +8 -4
  50. package/dist/contract/webhooks.mjs +50 -28
  51. package/dist/entity/forwarded.d.mts +11 -0
  52. package/dist/entity/forwarded.mjs +32 -0
  53. package/dist/entity/wakes.mjs +39 -0
  54. package/dist/http/client.mjs +8 -6
  55. package/dist/http/events.d.mts +1 -12
  56. package/dist/http/events.mjs +5 -25
  57. package/dist/http/redacted.mjs +9 -0
  58. package/dist/http/streamed.d.mts +1 -0
  59. package/dist/http/streamed.mjs +10 -5
  60. package/dist/mcp/bridge.mjs +14 -24
  61. package/dist/mcp/client.mjs +3 -12
  62. package/dist/mcp/events.mjs +1 -1
  63. package/dist/mcp/progress.mjs +11 -1
  64. package/dist/rpc/erased.d.mts +62 -0
  65. package/dist/rpc/erased.mjs +356 -0
  66. package/dist/rpc/watch.mjs +12 -13
  67. package/dist/webhook/health.mjs +25 -28
  68. package/dist/webhook/receiver.mjs +4 -7
  69. package/dist/webhook/stored.mjs +6 -4
  70. package/dist/webhook/subscriptions.mjs +65 -48
  71. package/docs/Action-streams.md +2 -2
  72. package/docs/Action.md +3 -3
  73. package/docs/ActionEntity-failures.md +10 -0
  74. package/docs/ActionEntity.md +165 -0
  75. package/docs/ActionHttp.md +0 -4
  76. package/docs/ActionMcp.md +2 -2
  77. package/docs/ActionRpc-events.md +2 -2
  78. package/docs/ActionRpc.md +1 -1
  79. package/docs/Authentication-failures.md +1 -0
  80. package/docs/Authentication.md +4 -2
  81. package/docs/Event.md +5 -5
  82. package/docs/README.md +5 -2
  83. package/docs/Webhook.md +1 -1
  84. package/docs/setup-failures.md +1 -1
  85. package/docs/setup.md +6 -5
  86. package/examples/README.md +1 -1
  87. package/examples/kitchen-sink/src/admin/Admin.ts +1 -0
  88. package/examples/kitchen-sink/src/identity/Identity.ts +5 -1
  89. package/examples/live-rpc/src/identity/Identity.ts +3 -1
  90. package/examples/notes-service/src/identity/Identity.ts +3 -1
  91. package/examples/shopping-carts/README.md +46 -0
  92. package/examples/shopping-carts/src/Api.ts +9 -0
  93. package/examples/shopping-carts/src/Rpc.ts +6 -0
  94. package/examples/shopping-carts/src/cart/Cart.ts +47 -0
  95. package/examples/shopping-carts/src/cart/handlers.ts +42 -0
  96. package/examples/shopping-carts/src/cart/held.ts +5 -0
  97. package/examples/shopping-carts/src/cart/store.ts +10 -0
  98. package/examples/shopping-carts/src/entities.ts +7 -0
  99. package/examples/shopping-carts/src/identity/Identity.ts +16 -0
  100. package/examples/shopping-carts/src/identity/shoppers.ts +6 -0
  101. package/examples/shopping-carts/src/identity/verifier.ts +21 -0
  102. package/examples/shopping-carts/src/platform/cluster.ts +7 -0
  103. package/examples/shopping-carts/src/platform/sql-carts.ts +30 -0
  104. package/examples/shopping-carts/src/routes.ts +23 -0
  105. package/examples/shopping-carts/src/server.ts +23 -0
  106. package/examples/shopping-carts/test/routes.test.ts +69 -0
  107. package/package.json +12 -9
  108. package/dist/contract/input-check.d.mts +0 -15
  109. package/dist/contract/input-check.mjs +0 -15
  110. package/dist/http/placed.d.mts +0 -34
  111. package/dist/http/placed.mjs +0 -71
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # effect-actions
2
2
 
3
- Define an Effect action once. Serve it over HTTP, MCP and Effect RPC, hand it to a model as a native Toolkit, and run it from a CLI. Same schemas, same handler, Effect's own servers and clients underneath. Events go the same way: watched over HTTP, MCP, Effect RPC and the CLI, or delivered by webhook. A companion package, [effect-actions-cloudflare](packages/cloudflare/), serves the HTTP, MCP and RPC routes, events and webhooks included, from Cloudflare Durable Objects.
3
+ Define an Effect action once. Serve it over HTTP, MCP and Effect RPC, hand it to a model as a native Toolkit, and run it from a CLI. Same schemas, same handler, Effect's own servers and clients underneath. Events go the same way: watched over HTTP, MCP, Effect RPC and the CLI, or delivered by webhook. A companion package, [effect-actions-cloudflare](packages/cloudflare/), runs actions and events in Cloudflare Durable Objects as Effect Cluster entities, which a Worker serves over HTTP and MCP.
4
4
 
5
5
  **If you are a coding agent**, start at [docs/README.md](docs/README.md), not here. It routes every task, protecting an action and limiting request bodies included, to its page and its example.
6
6
 
@@ -76,10 +76,10 @@ Effect.gen(function* () {
76
76
  ## Install
77
77
 
78
78
  ```sh
79
- pnpm add @gjermundgaraba/effect-actions effect@~4.1.1
79
+ pnpm add @gjermundgaraba/effect-actions effect@~4.1.4
80
80
  ```
81
81
 
82
- It needs TypeScript 7 or newer and is ESM only ([docs/setup.md](docs/setup.md#install)). Add `@effect/platform-node@~4.1.1` to serve or run a CLI from Node, and `@types/node` for its `node:` imports. Every module is a subpath import (`.../Action`, `.../ActionHttp`, ...); there is no package root, so a contracts-only bundle never loads a server.
82
+ It needs TypeScript 7 or newer and is ESM only ([docs/setup.md](docs/setup.md#install)). Add `@effect/platform-node@~4.1.4` to serve or run a CLI from Node, and `@types/node` for its `node:` imports. Every module is a subpath import (`.../Action`, `.../ActionHttp`, ...); there is no package root, so a contracts-only bundle never loads a server.
83
83
 
84
84
  ## Examples
85
85
 
@@ -90,6 +90,7 @@ It needs TypeScript 7 or newer and is ESM only ([docs/setup.md](docs/setup.md#in
90
90
  - [mcp-tools](examples/mcp-tools/): an MCP server whose tools wrap an upstream HTTP API.
91
91
  - [assistant](examples/assistant/): no server, the same implementations as a model's tools and as local commands.
92
92
  - [live-rpc](examples/live-rpc/): Effect RPC over a WebSocket.
93
+ - [shopping-carts](examples/shopping-carts/): carts as Effect Cluster entities, reached from JSON routes.
93
94
  - [build-events](examples/build-events/): events watched over MCP, HTTP, RPC, a command line and webhooks, and actions reporting progress and answering a stream.
94
95
  - [kitchen-sink](examples/kitchen-sink/): every module and nearly every option in one application, with an index from each to the file that shows it.
95
96
 
package/dist/Action.d.mts CHANGED
@@ -11,7 +11,6 @@ import { ReportingOf } from "./contract/progress.mjs";
11
11
  import { Answer, Stream, StreamOf } from "./contract/stream.mjs";
12
12
  import { WatchArgs } from "./contract/watch.mjs";
13
13
  import { Image } from "./contract/media.mjs";
14
- import { InputCheck } from "./contract/input-check.mjs";
15
14
  import { Context, Effect, Layer, Schema, Scope, Stream as Stream$1 } from "effect";
16
15
  /**
17
16
  * How the action's tool presents itself over MCP, in MCP's own names; every field is optional
@@ -127,8 +126,8 @@ export interface Options {
127
126
  * the key travels with the input. The caller makes the key at random for the call it means,
128
127
  * and sends it again on each retry; a call without it runs as any other. What is answered
129
128
  * again is kept by `Action.Idempotency`, which an implementation of the action requires at
130
- * startup: provide `Action.layerIdempotency`, which a Durable Object's `make` and `handlers`
131
- * provide over its storage.
129
+ * startup: provide `Action.layerIdempotency`, or `Stored.layerIdempotency` over a
130
+ * `SqlClient`, as a cluster entity does over its own database.
132
131
  *
133
132
  * **Gotchas**
134
133
  *
@@ -138,7 +137,7 @@ export interface Options {
138
137
  * - A repeat answers without the progress the first reported.
139
138
  * - An answer kept before a deployment changed `success` or an error schema, so that it no longer decodes, is ignored: the call runs again.
140
139
  * - An action answering `Action.Stream` throws at `make`: an answer is kept whole.
141
- * - A key is each caller's own only where the surface's authentication has `principal`: without one, as over `Action.client`, `ActionToolkit`, the CLI or a public action, another caller sending it with the same input is given the answer, as a model filling the field in may, so make it at random, never from the input.
140
+ * - A key is each caller's own only on a surface with an authentication, by its `principal`: a public action's callers, and every caller over `Action.client`, `ActionToolkit` or the CLI, share one key space, so another sending it with the same input is given the answer, as a model filling the field in may: make it at random, never from the input.
142
141
  */
143
142
  readonly idempotencyKey?: string | undefined;
144
143
  }
@@ -292,7 +291,8 @@ export declare function implement<const T extends Target, RequestServices extend
292
291
  * The builders of `implementations`, as one layer providing nothing. Surfaces build them
293
292
  * themselves, once per layer graph, but routes under `HttpRouter.serve` or `Testing.layer`
294
293
  * are built in a graph of their own, sharing nothing they build: provided above the server and
295
- * its siblings, it runs each builder once for every surface, with the services it is given.
294
+ * its siblings, it runs each builder once, with the services it is given, for every surface but
295
+ * `ActionEntity.layer`, each of whose entity ids builds its own.
296
296
  *
297
297
  * **Gotchas**
298
298
  *
@@ -352,4 +352,4 @@ export interface ClientOptions<A extends Any | Any$1> {
352
352
  * - `watch` runs as the caller around the stream, authorized when it starts.
353
353
  */
354
354
  export declare function client<const Apps extends Served, const O extends ClientOptions<ActionOf<Member<Apps>> | EventOf<Member<Apps>>> = {}>(implementations: Apps, ...options: OptionalUnless<O, ClientOptions<ActionOf<Member<Apps>> | EventOf<Member<Apps>>> & O & NoInfer<Known<O, ClientOptions<Any>>>>): Effect.Effect<Client<Apps, Offered<O, ActionOf<Member<Apps>>>, Offered<O, EventOf<Member<Apps>>>>, BuildError<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventBuildError<HoldingEvents<Member<Apps>, SelectedEventsOf<O, Apps>>, SelectedEventsOf<O, Apps>>, BuildServices<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventBuildServices<HoldingEvents<Member<Apps>, SelectedEventsOf<O, Apps>>, SelectedEventsOf<O, Apps>> | Scope.Scope>;
355
- export { type AnyImplementation, Anyone, type Authorize, type BuildError, type BuildServices, BuiltIn, Forbidden, Idempotency, Image, type Implementation, InputCheck, InvalidInput, type Issue, Refusal, Stream, type StreamOf, Unauthenticated, layerIdempotency };
355
+ export { type AnyImplementation, Anyone, type Authorize, type BuildError, type BuildServices, BuiltIn, Forbidden, Idempotency, Image, type Implementation, InvalidInput, type Issue, Refusal, Stream, type StreamOf, Unauthenticated, layerIdempotency };
package/dist/Action.mjs CHANGED
@@ -1,21 +1,20 @@
1
1
  import { authorizerOf } from "./contract/authorizer.mjs";
2
- import { inputOf, jsonRoundTrip, onProgressOf, watchInput } from "./contract/call.mjs";
2
+ import { checked, checkedStream, jsonRoundTrip, sentInput } from "./contract/call.mjs";
3
3
  import { Anyone, assertCaller } from "./contract/caller.mjs";
4
4
  import { codecOf } from "./contract/codec.mjs";
5
5
  import { assertDistinctTags, errorList, projectedErrors } from "./contract/declared.mjs";
6
- import { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated } from "./contract/errors.mjs";
7
6
  import { NotServed, SubscriptionError } from "./Event.mjs";
8
- import { acquireFeeds, eventsOf, feedBuilders } from "./contract/feed.mjs";
7
+ import { acquireFeeds, eventsOf } from "./contract/feed.mjs";
9
8
  import { Idempotency, keyed, layerIdempotency } from "./contract/idempotency.mjs";
10
- import { Implementation, acquire, builtWith, elementsOf, memoized, provideBuilders, toList, uniqueKey } from "./contract/implementation.mjs";
9
+ import { Implementation, acquire, builtWith, elementsOf, memoized, toList, uniqueKey } from "./contract/implementation.mjs";
11
10
  import { assertKnown, assertName, assertOnce, heldOnce } from "./contract/names.mjs";
12
11
  import { progressSink } from "./contract/progress.mjs";
13
12
  import { polledOn, queuedPush, readOn } from "./contract/push.mjs";
14
- import { selectFrom } from "./contract/serving.mjs";
13
+ import { buildersOf, provideServed, selectFrom } from "./contract/serving.mjs";
15
14
  import { Stream, elementOf } from "./contract/stream.mjs";
16
15
  import { watching } from "./contract/watch.mjs";
16
+ import { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated } from "./contract/errors.mjs";
17
17
  import { Image } from "./contract/media.mjs";
18
- import { InputCheck } from "./contract/input-check.mjs";
19
18
  import { Array as Array$1, Cause, Effect, Function, Layer, Predicate, Schema, Stream as Stream$1 } from "effect";
20
19
  // src/contract/Action.ts
21
20
  function make(name, options) {
@@ -91,7 +90,7 @@ function implement(actions, handlers, options) {
91
90
  return new Implementation(listed, memoized(recorded), authorizer);
92
91
  }
93
92
  function layer(implementations) {
94
- return Layer.empty.pipe(provideBuilders([...toList(implementations).map((app) => Implementation.layerOf(app)), ...feedBuilders(eventsOf(implementations))]));
93
+ return Layer.empty.pipe(provideServed(toList(implementations), eventsOf(implementations)));
95
94
  }
96
95
  const received = (schema) => {
97
96
  const sent = jsonRoundTrip(schema);
@@ -101,20 +100,19 @@ const mapFailuresInPlace = (cause, failure) => Effect.map(Effect.forEach(cause.r
101
100
  onFailure: (refused) => Cause.combine(Cause.die(refused), Cause.die(reason.error)),
102
101
  onSuccess: (decoded) => Cause.fail(Predicate.isError(reason.error) && Predicate.isError(decoded) ? Object.assign(decoded, { stack: reason.error.stack }) : decoded)
103
102
  }).pipe(Effect.map((mapped) => Cause.annotate(mapped, Cause.reasonAnnotations(reason)))) : Effect.succeed(Cause.fromReasons([reason]))), (causes) => Cause.fromReasons(causes.flatMap(({ reasons }) => reasons)));
103
+ const receivedInput = (action) => received(action.input);
104
104
  const methodOf = (action, run) => {
105
- const input = received(action.input);
106
105
  const element = elementOf(action.success);
107
106
  const success = received(element ?? action.success);
108
107
  const failure = received(Schema.Union(projectedErrors(action)));
109
108
  const declared = (cause) => Effect.flatMap(mapFailuresInPlace(cause, failure), Effect.failCause);
110
- const called = (args) => inputOf(action, args).pipe(Effect.flatMap(input), Effect.mapError(InvalidInput.fromSchemaError), Effect.map((value) => run(value, progressSink(onProgressOf(args)))));
111
- if (element !== void 0) return (...args) => Stream$1.unwrap(Effect.map(called(args), elementsOf)).pipe(Stream$1.catchCause((cause) => Stream$1.fromEffect(declared(cause))), Stream$1.mapEffect((value) => Effect.orDie(success(value))));
112
- return (...args) => called(args).pipe(Effect.flatMap((answer) => Effect.catchCause(answer, declared)), Effect.flatMap((value) => Effect.orDie(success(value))));
109
+ if (element !== void 0) return checkedStream(action, receivedInput, (input, onProgress) => elementsOf(run(input, progressSink(onProgress))).pipe(Stream$1.catchCause((cause) => Stream$1.fromEffect(declared(cause))), Stream$1.mapEffect((value) => Effect.orDie(success(value)))));
110
+ return checked(action, receivedInput, (input, onProgress) => Effect.catchCause(run(input, progressSink(onProgress)), declared).pipe(Effect.flatMap((value) => Effect.orDie(success(value)))));
113
111
  };
114
112
  const watcherOf = (feeds) => (event, input, options) => {
115
113
  const feed = feeds.find((held) => held.event === event);
116
114
  if (feed === void 0) return Stream$1.fail(SubscriptionError.of(event.name, new NotServed()));
117
- return Stream$1.unwrap(Effect.map(watchInput(event, input), ({ value }) => {
115
+ return Stream$1.unwrap(Effect.map(sentInput(event, input), ({ value }) => {
118
116
  const subscriber = uniqueKey();
119
117
  return watching({
120
118
  name: event.name,
@@ -131,9 +129,9 @@ function client(served, options) {
131
129
  const { apps, events } = selectFrom(served, options?.actions);
132
130
  assertOnce("action", apps.flatMap((app) => app.actions), heldOnce);
133
131
  assertOnce("event", events.flatMap((app) => app.events), heldOnce);
134
- return Effect.map(builtWith([...apps.map((app) => Implementation.layerOf(app)), ...feedBuilders(events)], Effect.all([acquire(apps, void 0), acquireFeeds(events)])), ([bound, feeds]) => ({
132
+ return Effect.map(builtWith(buildersOf(apps, events), Effect.all([acquire(apps, void 0), acquireFeeds(events)])), ([bound, feeds]) => ({
135
133
  ...Object.fromEntries(bound.map(([action, run]) => [action.name, methodOf(action, run)])),
136
134
  ...feeds.length === 0 ? {} : { watch: watcherOf(feeds) }
137
135
  }));
138
136
  }
139
- export { Anyone, BuiltIn, Forbidden, Idempotency, Image, InputCheck, InvalidInput, Refusal, Stream, Unauthenticated, allowAll, byName, client, implement, layer, layerIdempotency, make, withErrors };
137
+ export { Anyone, BuiltIn, Forbidden, Idempotency, Image, InvalidInput, Refusal, Stream, Unauthenticated, allowAll, byName, client, implement, layer, layerIdempotency, make, withErrors };
@@ -0,0 +1,237 @@
1
+ import { RemoteRequest, ServedProvider, ServerBuildServices, VerifierError } from "./authentication/provider.mjs";
2
+ import { Any as Any$1, Errors } from "./Action.mjs";
3
+ import { Call } from "./contract/call.mjs";
4
+ import { BuiltIns } from "./contract/errors.mjs";
5
+ import { Any as Any$2, Received, SubscriptionError } from "./Event.mjs";
6
+ import { EventBuildServices, EventImplementation, EventServedRequest, HoldingEvents, ServingEvents } from "./contract/feed.mjs";
7
+ import { Holding, Implementation, Member, Served } from "./contract/implementation.mjs";
8
+ import { Answer } from "./contract/stream.mjs";
9
+ import { WatchArgs } from "./contract/watch.mjs";
10
+ import { Any as Any$3 } from "./ActionRpc.mjs";
11
+ import { erasedOf } from "./rpc/erased.mjs";
12
+ import { forwardedHeaders } from "./entity/forwarded.mjs";
13
+ import { Effect, Layer, Schema, Scope, Stream } from "effect";
14
+ import { ClusterError, Entity as Entity$1, Sharding } from "effect/cluster";
15
+ import { HttpServerRequest } from "effect/http";
16
+ import { Rpc, RpcGroup } from "effect/rpc";
17
+ type Contract<B extends Any$3> = B["actions"][number] | B["events"][number];
18
+ /**
19
+ * The key of the binding `B`'s actions and event types, the id of the entity that serves a call
20
+ * or a subscription, read from its input: one function of every input, `({ room }) => room`.
21
+ */
22
+ export type Key<B extends Any$3> = (input: Contract<B>["input"]["Type"]) => string;
23
+ type ErasedRpc = ReturnType<typeof erasedOf> extends RpcGroup.RpcGroup<infer R> ? R : never;
24
+ /**
25
+ * A cluster `Entity` serving an `ActionRpc` binding: one rpc of JSON per action, and per event
26
+ * type one unary rpc answering a page past a cursor, plus the entity's own native rpcs `N`, the
27
+ * binding and the key of each of its contracts. `layer` serves it, `client` calls its actions,
28
+ * and Effect's own `Entity` functions take it, `Entity.client` calling its native rpcs.
29
+ */
30
+ export interface Entity<Type extends string, B extends Any$3, N extends Rpc.Any = never> extends Entity$1.Entity<Type, ErasedRpc | N> {
31
+ readonly binding: B;
32
+ readonly key: Key<B>;
33
+ }
34
+ /**
35
+ * Any entity `make` returns, as a function accepting every entity reads it: its type, its
36
+ * binding, and its `client`, Effect's `Entity.client`, whose client's methods are keyed by rpc tag.
37
+ */
38
+ export interface Any {
39
+ readonly type: string;
40
+ readonly binding: Any$3;
41
+ readonly client: Effect.Effect<(entityId: string) => object, never, Sharding.Sharding>;
42
+ }
43
+ type WithoutNatives<B extends Any$3> = [RpcGroup.Rpcs<B["rpcs"]>] extends [never] ? unknown : {
44
+ readonly "An entity's binding holds no native rpcs: give them to ActionEntity.make's rpcs": never;
45
+ };
46
+ /** `make`'s options. */
47
+ export interface MakeOptions<B extends Any$3, N extends Rpc.Any> {
48
+ /**
49
+ * The entity id an input names: one function every action and event input of the binding
50
+ * reads, `({ room }) => room`.
51
+ *
52
+ * **Gotchas**
53
+ *
54
+ * - It takes the union of the binding's inputs, so it reads only a field every one declares: a field one input lacks is a type error.
55
+ */
56
+ readonly key: Key<B>;
57
+ /**
58
+ * The entity's own native rpcs, beside its actions and event types, with their own schemas:
59
+ * `RpcGroup.make(Expire)`, such as a persisted tell the entity sends itself with `DeliverAt`.
60
+ * `layer` takes their handlers in its own `rpcs`.
61
+ *
62
+ * **Gotchas**
63
+ *
64
+ * - A native rpc authenticates nothing, whatever the binding's `authentication`: it is for tells the entity and other entities send with `Entity.client`, never for a surface's callers.
65
+ * - A native rpc named after an action, an event type, an event's `<event>/poll`, a protected event's `<event>/subscribe` or `<event>/unsubscribe`, or the entity's wake, `effect-actions/wake`, throws as the entity is made.
66
+ */
67
+ readonly rpcs?: RpcGroup.RpcGroup<N> | undefined;
68
+ }
69
+ /**
70
+ * The cluster entity of type `type` serving the actions and event types of `binding`, an
71
+ * `ActionRpc` binding, each call and subscription in the entity its contract's `key` names for
72
+ * its input. Each event type is a unary rpc named `<event>/poll`, `ActionRpc.pollTag`, taking
73
+ * `{ input, cursor, maxEvents, watch }` and answering a page,
74
+ * `{ events, cursor, truncated, hasMore, nextPollMs, notified }`, an HTTP poll's page and
75
+ * `notified`, `ActionRpc.Page`, as `ActionRpc.layer` serves it too, its subscription hook held
76
+ * for the caller's principal. A protected event type has two more, `<event>/subscribe` and
77
+ * `<event>/unsubscribe`, taking a webhook subscription and its cancellation, and the entity has
78
+ * its wake, `effect-actions/wake`, a persisted tell it sends itself to end a webhook delivery's
79
+ * retry wait. Guide: `docs/ActionEntity.md` in this package.
80
+ *
81
+ * **Gotchas**
82
+ *
83
+ * - The rpcs of its actions, event types and webhook subscriptions are volatile, as `ClusterSchema.Persisted` defaults, and its wake alone is persisted: annotated persisted, each envelope, its caller's headers and credential included, would be stored and replayed with them, on Effect's SQL runners until a `MessageRetention` layer deletes it, and on the Cloudflare runtime, which never prunes `cluster_messages`, for good, its credential headers redacted. `rpcs`' natives are persisted as their own annotations say.
84
+ * - A binding with native rpcs throws: give the entity's own rpcs to `make`'s `rpcs`.
85
+ * - A streaming action, one declaring `progress` or answering `Action.Stream`, is a stream rpc, its frames those `ActionRpc.make` states, `client`'s method handing each progress value to `onProgress` before it answers, and returning a `Stream` of the elements of an `Action.Stream` answer; it holds a slot of the entity's `concurrency`, by default its only one, until its stream ends, but on the Cloudflare runtime, which frees the slot while a frame waits for its client's acknowledgement.
86
+ * - `annotate` and its kin return a plain `Entity`, without `binding` and `key`, which `layer` and `client` do not take.
87
+ */
88
+ export declare const make: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(type: Type, binding: B & WithoutNatives<B>, options: NoInfer<Omit<MakeOptions<B, N>, "rpcs">> & Pick<MakeOptions<B, N>, "rpcs">) => Entity<Type, B, N>;
89
+ /**
90
+ * The rpcs of `entity`'s binding, as its `protocol` holds them without its native rpcs: one per
91
+ * action, and per event type its poll. What a surface outside the
92
+ * cluster may forward to the entity, as the Cloudflare package's socket host does, which
93
+ * `ActionRpc.client`'s watch polls, finding no stream rpc.
94
+ */
95
+ export declare const bindingRpcs: (entity: Any) => RpcGroup.RpcGroup<ErasedRpc>;
96
+ /**
97
+ * `layer`'s options: `Entity.toLayer`'s, which the entity's registration takes, but
98
+ * `disableFatalDefects`, which is always on, and `defectRetryPolicy`, which the Cloudflare
99
+ * runtime would follow to run a call that died again, and `services` and `rpcs`.
100
+ */
101
+ export interface LayerOptions<ROut = never, RIn = never, Handlers = never, RX = never> extends Omit<NonNullable<Parameters<Entity$1.Any["toLayer"]>[1]>, "disableFatalDefects" | "defectRetryPolicy"> {
102
+ /**
103
+ * What each entity id builds for itself as it activates, before its implementations'
104
+ * builders and its native rpcs' handlers, which read it, as its handlers do per call: a store
105
+ * over the entity's own database, its `Event.Events`. It may read `Entity.CurrentAddress` and what the activation
106
+ * provides, such as a Durable Object's `DurableObjectSqlClient`.
107
+ *
108
+ * **Gotchas**
109
+ *
110
+ * - Each entity id builds it again at each activation: what it holds in memory is that activation's alone, as an implementation builder's is, where a service provided to `layer` is the runner's, shared by every entity id.
111
+ * - It fails or dies as a builder does: a defect of the activation, which the runtime handles as the builder's.
112
+ * - A handler reading its output per call, where it is written inline as a `Layer.merge` or another generic combinator's result, is a type error naming that output, which TypeScript infers too late: assign the layer to a `const` first.
113
+ * - A `Webhook.layer` here holds the entity's webhook subscriptions and delivers them from its activation: give it `persist`, so a later activation restores them; each retry wait is a wake the entity sends itself, so a stopped entity is built again to retry, on Effect's SQL runners up to `entityMessagePollInterval` after it is due, each wake a row of the runtime's messages, kept once processed.
114
+ * - A webhook subscription to a check source not `notified` is refused with `Event.SubscriptionError`, reason `Unsupported`, and a warning saying why, its polls and unsubscribes still served: its reads on a timer would be cut by Effect's reaper and keep a Durable Object awake.
115
+ * - A webhook subscription past its expiry ends at its next delivery, and its kept record at the next activation, on no timer: until then it holds its subscription hook.
116
+ * - A `Webhook.layer` here with `persist` needs the binding's authentication to name a `schema` where it serves a protected event whose source is no check source left un-`notified`: without one each activation dies with the library's message naming `schema`, so on Effect's runners each call to the entity waits while the runner builds it again, and on the Cloudflare runtime each fails at once.
117
+ */
118
+ readonly services?: Layer.Layer<ROut, unknown, RIn> | undefined;
119
+ /**
120
+ * The handlers of `make`'s `rpcs`, as `Entity.toLayer` takes them: an `Entity.HandlersFrom` of
121
+ * those rpcs, or an Effect building one as each entity id activates, after `services`, whose
122
+ * output it and the handlers' answers read. Each handler receives Effect's own `Entity.Request`,
123
+ * its `payload`, `headers` and `requestId`, and may answer through `Rpc.fork` or
124
+ * `Rpc.uninterruptible`.
125
+ *
126
+ * **Gotchas**
127
+ *
128
+ * - Required exactly where `make` was given `rpcs`: left out there, or given for an entity without them, it is a type error.
129
+ */
130
+ readonly rpcs?: ([Handlers] extends [never] ? never : Handlers | Effect.Effect<Handlers, never, RX>) | undefined;
131
+ }
132
+ type NativeLayerOptions<N extends Rpc.Any, ROut, RIn, Handlers, RX> = [N] extends [never] ? [options?: LayerOptions<ROut, RIn>] : [options: LayerOptions<ROut, RIn, Handlers, RX> & {
133
+ readonly rpcs: Handlers | Effect.Effect<Handlers, never, RX>;
134
+ }];
135
+ type Activation = Entity$1.CurrentAddress | Entity$1.CurrentRunnerAddress | Scope.Scope;
136
+ type PerCall<B extends Any$3, Apps extends Served, ROut, A extends Any$1 = B["actions"][number], E extends Any$2 = B["events"][number]> = Exclude<RemoteRequest<Member<Apps>, A> | EventServedRequest<Member<Apps>, E>, Activation | HttpServerRequest.HttpServerRequest | HttpServerRequest.ParsedSearchParams | ROut>;
137
+ type NoPerCall<B extends Any$3, Apps extends Served, ROut> = [PerCall<B, Apps, ROut>] extends [never] ? unknown : {
138
+ readonly "An entity provides no service per call but services' output: yield it in the implementation's builder, where it is a startup service, or build it in layer's services": PerCall<B, Apps, ROut>;
139
+ };
140
+ type EntityLayer<B extends Any$3, Apps extends Served, N extends Rpc.Any, ROut, RIn, Handlers, RX, A extends Any$1 = B["actions"][number], E extends Any$2 = B["events"][number]> = Layer.Layer<never, never, Exclude<ServerBuildServices<Holding<Member<Apps>, A>, A> | EventBuildServices<HoldingEvents<Member<Apps>, E>, E> | ServedProvider<Member<Apps>, A, B extends {
141
+ readonly authentication: infer D;
142
+ } ? D : never, ServingEvents<Member<Apps>, E>> | RX | RpcGroup.HandlersServices<N, Handlers>, Activation | ROut> | Exclude<RIn, Activation> | Rpc.ServicesClient<N> | Rpc.ServicesServer<N> | Rpc.Middleware<N> | Sharding.Sharding>;
143
+ /**
144
+ * Register `entity` with the cluster's `Sharding`, serving its binding's actions and event types
145
+ * from `implementations`, which implement every one. Each entity id builds the implementations
146
+ * itself as it activates, so a builder may read `Entity.CurrentAddress`; each call of a
147
+ * protected one authenticates from the headers its client sent with the binding's descriptor, as
148
+ * `ActionRpc.layer`'s does; then the input decodes, failing `InvalidInput` where it does not, an
149
+ * input whose key names another entity or none is refused with `Forbidden`, and the
150
+ * implementation's `authorize` and the handler run; a declared error is the call's typed failure.
151
+ *
152
+ * **Gotchas**
153
+ *
154
+ * - What the application provides to this layer is shared by every entity of the runner; what an implementation builds, each entity id builds for itself: state held in a builder is that entity's alone.
155
+ * - A handler, an authorizer or an event source reading per call a service other than its caller and `services`' output is a type error naming that service: an entity provides nothing else per call, so yield it in the builder, where it is a startup service, one value for every caller and entity id, or build it in `services`, one per entity id.
156
+ * - `services`' output lies under each call's own context, so a service it outputs that a call provides too, its caller or its request, is the call's.
157
+ * - `Action.layer` above it shares no build with it: each entity id runs its implementations' builders again, beside the run `Action.layer` made for the other surfaces.
158
+ * - A builder that fails or dies is a defect of the entity's activation, never a failure of the layer: Effect's own runners log it and build again, 500 ms later and growing to 10 seconds apart, while its calls wait, and the Cloudflare runtime fails the calls waiting on that build, the next call building again.
159
+ * - A handler's defect or undeclared failure ends that call with an `Error` whose message is `Internal server error`, as on `ActionRpc.layer`, and the call is not run again; Effect's own runners keep the entity's handlers for its next call, and the Cloudflare runtime builds them again, so what its builders and `services` held in memory is gone.
160
+ * - An implementation missing for one of the binding's actions or event types throws as the layer is made: an entity serves its whole binding.
161
+ */
162
+ export declare function layer<const Type extends string, const B extends Any$3, N extends Rpc.Any, const Apps extends Served, ROut = never, RIn = never, Handlers extends Entity$1.HandlersFrom<N> = never, RX = never>(entity: Entity<Type, B, N>, implementations: Apps & NoPerCall<B, Apps, ROut>, ...options: NativeLayerOptions<N, ROut, RIn, Handlers, RX>): EntityLayer<B, Apps, N, ROut, RIn, Handlers, RX>;
163
+ declare const ClusterFailures: Schema.Union<readonly [typeof ClusterError.MailboxFull, typeof ClusterError.PersistenceError, typeof ClusterError.AlreadyProcessingMessage, typeof ClusterError.EntityNotAssignedToRunner]>;
164
+ type ClusterFailure = typeof ClusterFailures.Type;
165
+ /**
166
+ * Whether a failure is one of those Effect's entity client fails with when the entity could not
167
+ * be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
168
+ * `EntityNotAssignedToRunner`, which `client`'s `MethodError` holds and `reaching` makes a
169
+ * defect: a server forwarding calls into an entity, as the Cloudflare package's socket host
170
+ * does, makes them one too.
171
+ */
172
+ export declare const isClusterFailure: <I>(input: I) => input is I & (ClusterError.AlreadyProcessingMessage | ClusterError.EntityNotAssignedToRunner | ClusterError.MailboxFull | ClusterError.PersistenceError);
173
+ /**
174
+ * What one call of an action `A` fails with, beside the binding's errors `E`: its declared and
175
+ * built-in errors, and what Effect's entity client fails with when the entity could not be
176
+ * reached. An answer that does not decode is a defect.
177
+ */
178
+ export type MethodError<A extends Any$1, E extends Errors[number] = never> = A["error"][number]["Type"] | E["Type"] | BuiltIns["Type"] | ClusterFailure;
179
+ type Method<A extends Any$1, E extends Errors[number]> = Call<A, Answer<A["success"], MethodError<A, E>, never>>;
180
+ /**
181
+ * What a watch of `W` over the binding `B` may fail with: a refusal, `InvalidInput`, the
182
+ * binding's errors, an `Event.SubscriptionError` (`NotServed` for an event the entity does not
183
+ * serve), or what Effect's entity client fails with that no retry outlasts.
184
+ */
185
+ export type WatchError<W extends Any$2, B extends Any$3> = SubscriptionError | BuiltIns["Type"] | B["error"][number]["Type"] | VerifierError<W, B["authentication"]>["Type"] | ClusterFailure;
186
+ type Watching<B extends Any$3> = [B["events"][number]] extends [never] ? unknown : {
187
+ readonly watch: <W extends B["events"][number], SE = never>(event: W, ...args: WatchArgs<W, SE, {
188
+ readonly mode?: "poll" | undefined;
189
+ }>) => Stream.Stream<Received<W>, WatchError<W, B> | SE>;
190
+ };
191
+ /**
192
+ * Every action of the binding `B`, as `client.<action>(input)`: a protected one may also fail
193
+ * with what its descriptor's verifier declares. Where `B` lists event types, `watch(event, input,
194
+ * options)` follows one by polling.
195
+ */
196
+ export type Client<B extends Any$3> = { readonly [A in B["actions"][number] as A["name"]]: Method<A, B["error"][number] | VerifierError<A, B["authentication"]>>; } & Watching<B>;
197
+ /**
198
+ * The client of `entity` over Effect's own `Entity.client`: one method per action taking its
199
+ * input, `rooms.postMessage({ room: "lobby", text })`, and `watch(event, input, options)`, which
200
+ * polls the event's rpc, each call and watch sent to the entity its input's key names. Requires
201
+ * `Sharding`, as `Entity.client` does: `TestRunner.layer` in a test. The entity's native rpcs are
202
+ * Effect's own client's methods: `(yield* Room.client)("lobby").expire()`.
203
+ *
204
+ * **Gotchas**
205
+ *
206
+ * - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
207
+ * - Headers set with `RpcClient.withHeaders` around a call go with its envelope, which is how a protected call sends its credential; a call without them fails `Unauthenticated`.
208
+ * - A watch polls, its only `mode` `"poll"`, at the page's `nextPollMs`, its polls holding the subscription hook of the caller's principal in the entity until its source's `lease` lapses after the last, whichever watch sent it.
209
+ * - A watch asks the entity again after `MailboxFull` or `PersistenceError`, from where it reached, a second later and doubling to 30 seconds; a declared error, a refusal included, ends it.
210
+ */
211
+ export declare const client: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(entity: Entity<Type, B, N>) => Effect.Effect<Client<B>, never, Sharding.Sharding>;
212
+ type Nothing<C extends Any$1 | Any$2> = { readonly [K in C["name"]]: never; };
213
+ /**
214
+ * The implementations of `entity`'s actions and event types that any surface serves beside its
215
+ * own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
216
+ * `Entity.client` to the entity its contract's key names for its input, with the caller's
217
+ * headers, and its answer, declared errors and progress passed back; each event followed through
218
+ * the entity's poll rpc.
219
+ *
220
+ * **Gotchas**
221
+ *
222
+ * - The caller's credential is verified by the surface serving these and again by the entity reached, so both are given the verifier: a call the surface refuses reaches no entity.
223
+ * - A refusal by the entity, a credential expired since the surface verified it included, ends a stream after it answered 200, where the surface's own refusal would have answered its 401 or 403.
224
+ * - The caller's request's headers are sent on as `forwardedHeaders` keeps them: its connection's, its body's, what it accepts and an MCP request's routing headers are not.
225
+ * - A credential in the query, an API key the serving surface's HTTP binding reads `in: "query"`, never reaches the entity, whose binding reads headers alone, so it refuses the call with `Unauthenticated`: read the key from a header on the HTTP binding too.
226
+ * - A call with no HTTP request, as through `Action.client` in process or an MCP stdio surface, sends only the headers `RpcClient.withHeaders` sets around it: without them the entity refuses a protected one with `Unauthenticated`.
227
+ * - A call to an entity no runner is assigned waits without an answer, an HTTP request without a response, as Effect's entity client retries `EntityNotAssignedToRunner` every `sendRetryInterval`, 100 milliseconds by default, without limit: bound it with a timeout, such as the host's request timeout.
228
+ * - A stream, HTTP's `text/event-stream`, an RPC subscription or MCP's `events/stream`, polls the entity from the surface, at once while a page has more and otherwise at its `nextPollMs`, a second at least: it holds the caller's request open but no entity, an occurrence arrives up to that interval late, and the entity's object takes a call each `nextPollMs` while the stream is open, so on Cloudflare a stream polling every few seconds keeps it from ever hibernating.
229
+ * - A stream asks the entity again after `MailboxFull` or `PersistenceError`, from where it reached, a second later and doubling to 30 seconds, as `client`'s watch does; any other failure, a declared error or a defect, ends its polling.
230
+ * - HTTP's `text/event-stream` whose polling ended on a failure other than a refusal sends `Failed` and opens it again 5 seconds later, from where it reached; MCP's `events/stream` does what `ActionMcp.layerHttp` says of an upstream's failure, a `-32603` before `active`.
231
+ * - A stream's polls, and a poll, MCP's `events/poll` included, hold the subscriber's subscription hook in the entity until its source's `lease` lapses after the last, as on any surface.
232
+ * - A protected event's webhook subscription is held by the entity its input's key names, the subscribe and unsubscribe sent there with the caller's headers, and delivered by the `Webhook.layer` in that entity's `services`, never the serving surface's: an entity without one fails the subscribe with `Event.SubscriptionError`, reason `Unsupported`, a 409 over HTTP, before any callback is sent.
233
+ * - What `Entity.client` fails with, `MailboxFull`, `AlreadyProcessingMessage`, `PersistenceError` or `EntityNotAssignedToRunner`, is the call's defect, carrying that error alone, since no action declares it: a 500 over HTTP and a defect through `Action.client`, never a typed error.
234
+ * - An error the entity declares beyond the action's own and the built-in ones, its binding's `error` or its verifier's, is undeclared where the serving surface's binding does not declare it too.
235
+ */
236
+ export declare const reaching: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(entity: Entity<Type, B, N>) => ReadonlyArray<Implementation<B["actions"][number], Nothing<B["actions"][number]>, never, Sharding.Sharding> | EventImplementation<B["events"][number], Nothing<B["events"][number]>, never, Sharding.Sharding>>;
237
+ export { forwardedHeaders };
@@ -0,0 +1,211 @@
1
+ import { Forbidden } from "./contract/errors.mjs";
2
+ import { allowAll } from "./Action.mjs";
3
+ import { allowAll as allowAll$1 } from "./Event.mjs";
4
+ import { EventImplementation } from "./contract/feed.mjs";
5
+ import { Implementation, memoized } from "./contract/implementation.mjs";
6
+ import { buildersOf, servingOf } from "./contract/serving.mjs";
7
+ import { Wake } from "./contract/wake.mjs";
8
+ import { polling } from "./contract/watch.mjs";
9
+ import { offersWebhook } from "./contract/webhooks.mjs";
10
+ import { actionMethodOf, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollOf, polledTransport, watchedOf, webhookCallsOf, webhookRpcsOf } from "./rpc/erased.mjs";
11
+ import { forwarded, forwardedHeaders } from "./entity/forwarded.mjs";
12
+ import { WakeRpc, makeWake, wakeTag } from "./entity/wakes.mjs";
13
+ import { Effect, Layer, Predicate, Schema, Stream } from "effect";
14
+ import { ClusterError, Entity } from "effect/cluster";
15
+ import { Rpc, RpcGroup, RpcMessage } from "effect/rpc";
16
+ // src/entity/ActionEntity.ts
17
+ const namedBy = (key) => (input) => {
18
+ const named = key(input);
19
+ return Predicate.isString(named) ? named : void 0;
20
+ };
21
+ /**
22
+ * The cluster entity of type `type` serving the actions and event types of `binding`, an
23
+ * `ActionRpc` binding, each call and subscription in the entity its contract's `key` names for
24
+ * its input. Each event type is a unary rpc named `<event>/poll`, `ActionRpc.pollTag`, taking
25
+ * `{ input, cursor, maxEvents, watch }` and answering a page,
26
+ * `{ events, cursor, truncated, hasMore, nextPollMs, notified }`, an HTTP poll's page and
27
+ * `notified`, `ActionRpc.Page`, as `ActionRpc.layer` serves it too, its subscription hook held
28
+ * for the caller's principal. A protected event type has two more, `<event>/subscribe` and
29
+ * `<event>/unsubscribe`, taking a webhook subscription and its cancellation, and the entity has
30
+ * its wake, `effect-actions/wake`, a persisted tell it sends itself to end a webhook delivery's
31
+ * retry wait. Guide: `docs/ActionEntity.md` in this package.
32
+ *
33
+ * **Gotchas**
34
+ *
35
+ * - The rpcs of its actions, event types and webhook subscriptions are volatile, as `ClusterSchema.Persisted` defaults, and its wake alone is persisted: annotated persisted, each envelope, its caller's headers and credential included, would be stored and replayed with them, on Effect's SQL runners until a `MessageRetention` layer deletes it, and on the Cloudflare runtime, which never prunes `cluster_messages`, for good, its credential headers redacted. `rpcs`' natives are persisted as their own annotations say.
36
+ * - A binding with native rpcs throws: give the entity's own rpcs to `make`'s `rpcs`.
37
+ * - A streaming action, one declaring `progress` or answering `Action.Stream`, is a stream rpc, its frames those `ActionRpc.make` states, `client`'s method handing each progress value to `onProgress` before it answers, and returning a `Stream` of the elements of an `Action.Stream` answer; it holds a slot of the entity's `concurrency`, by default its only one, until its stream ends, but on the Cloudflare runtime, which frees the slot while a frame waits for its client's acknowledgement.
38
+ * - `annotate` and its kin return a plain `Entity`, without `binding` and `key`, which `layer` and `client` do not take.
39
+ */
40
+ const make = (type, binding, options) => {
41
+ const natives = [...nativeOf(binding.rpcs).requests.keys()];
42
+ if (natives.length > 0) throw new Error(`ActionEntity.make: the binding of ${type} holds native rpcs, ${natives.join(", ")} (give them to ActionEntity.make's rpcs, unauthenticated)`);
43
+ const erased = erasedOf(binding.actions, binding.events, "ActionEntity.layer").merge(webhookRpcsOf(binding.events)).add(WakeRpc);
44
+ const rpcs = options.rpcs ?? RpcGroup.make();
45
+ const taken = [...rpcs.requests.keys()].filter((tag) => erased.requests.has(tag) || binding.events.some(({ name }) => name === tag));
46
+ if (taken.length > 0) throw new Error(`ActionEntity.make: the native rpcs of ${type}, ${taken.join(", ")}, are named after an action, an event type, an event's poll, subscribe or unsubscribe, or the entity's wake, ${wakeTag} (rename them)`);
47
+ const protocol = erased.merge(rpcs);
48
+ return Object.assign(Entity.fromRpcGroup(type, protocol), {
49
+ binding,
50
+ key: options.key
51
+ });
52
+ };
53
+ /**
54
+ * The rpcs of `entity`'s binding, as its `protocol` holds them without its native rpcs: one per
55
+ * action, and per event type its poll. What a surface outside the
56
+ * cluster may forward to the entity, as the Cloudflare package's socket host does, which
57
+ * `ActionRpc.client`'s watch polls, finding no stream rpc.
58
+ */
59
+ const bindingRpcs = (entity) => erasedOf(entity.binding.actions, entity.binding.events, "ActionEntity.layer");
60
+ const callOf = (request, rpc) => ({
61
+ client: new Rpc.ServerClient(0),
62
+ requestId: RpcMessage.RequestId(String(request.requestId)),
63
+ headers: request.headers,
64
+ rpc
65
+ });
66
+ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options } = {}) {
67
+ const { binding } = entity;
68
+ const named = namedBy(entity.key);
69
+ const { apps, events, authentication } = servingOf("ActionEntity binding", binding, served, { actions: [...binding.actions, ...binding.events] });
70
+ const [first, ...rest] = buildersOf(apps, events);
71
+ const build = Effect.gen(function* () {
72
+ const address = yield* Entity.CurrentAddress;
73
+ const sharding = yield* Effect.context();
74
+ const { wake, woke } = yield* makeWake((payload) => Effect.flatMap(entity.client, (clientFor) => {
75
+ return clientFor(address.entityId)[wakeTag](payload, { discard: true });
76
+ }).pipe(Effect.provideContext(sharding)));
77
+ const built = yield* Layer.buildWithMemoMap(first === void 0 ? services : Layer.provideMerge(Layer.mergeAll(first, ...rest), services), Layer.makeMemoMapUnsafe(), yield* Effect.scope).pipe(Effect.provideService(Wake, wake));
78
+ const check = (contract, input) => {
79
+ const entityId = named(input);
80
+ return entityId === address.entityId ? Effect.void : Effect.fail(new Forbidden({ message: `This entity is ${address.entityType}/${address.entityId}, and the input of ${contract.name} names ${entityId ?? "none"}` }));
81
+ };
82
+ const { handlers } = yield* Effect.provideContext(handlersOf(binding, {
83
+ apps,
84
+ events,
85
+ authentication,
86
+ server: {
87
+ _tag: "ActionEntity.layer",
88
+ check
89
+ }
90
+ }), built);
91
+ const natives = yield* Effect.provideContext(Effect.isEffect(rpcs) ? rpcs : Effect.succeed(rpcs), built);
92
+ const answering = (handler) => (request) => Rpc.wrapMap(handler(request), (answer) => Effect.isEffect(answer) ? Effect.provideContext(answer, built) : Stream.provideContext(answer, built));
93
+ return Object.fromEntries([...nativeOf(entity.protocol).requests.values()].map((rpc) => {
94
+ if (rpc._tag === "effect-actions/wake") return [rpc._tag, woke];
95
+ const handler = handlers[rpc._tag];
96
+ if (handler !== void 0) return [rpc._tag, (request) => {
97
+ const answer = handler(request.payload, callOf(request, rpc));
98
+ return Effect.provideContext(answer, built);
99
+ }];
100
+ const native = natives[rpc._tag];
101
+ if (native === void 0) throw new Error(`ActionEntity.layer: rpcs holds no handler for the native rpc ${rpc._tag} of ${entity.type} (give layer's rpcs a handler for each of make's rpcs)`);
102
+ return [rpc._tag, answering(native)];
103
+ }));
104
+ }).pipe(Effect.orDie);
105
+ return entity.toLayer(build, {
106
+ ...options,
107
+ disableFatalDefects: true
108
+ });
109
+ }
110
+ const Transients = Schema.Union([ClusterError.MailboxFull, ClusterError.PersistenceError]);
111
+ const ClusterFailures = Schema.Union([
112
+ ...Transients.members,
113
+ ClusterError.AlreadyProcessingMessage,
114
+ ClusterError.EntityNotAssignedToRunner
115
+ ]);
116
+ /**
117
+ * Whether a failure is one of those Effect's entity client fails with when the entity could not
118
+ * be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
119
+ * `EntityNotAssignedToRunner`, which `client`'s `MethodError` holds and `reaching` makes a
120
+ * defect: a server forwarding calls into an entity, as the Cloudflare package's socket host
121
+ * does, makes them one too.
122
+ */
123
+ const isClusterFailure = Schema.is(ClusterFailures);
124
+ const isTransient = Schema.is(Transients);
125
+ function clusterFailuresAsDefects(answer) {
126
+ return Effect.isEffect(answer) ? Effect.catchIf(answer, isClusterFailure, Effect.die) : Stream.catchIf(answer, isClusterFailure, Stream.die);
127
+ }
128
+ const entityCallOf = (rpcs, headers) => erasedCallOf((tag, payload) => {
129
+ const method = rpcs[tag];
130
+ return method === void 0 ? Effect.die(/* @__PURE__ */ new Error(`ActionEntity: no rpc ${tag}`)) : method(payload, headers === void 0 ? void 0 : { headers });
131
+ });
132
+ const reachOf = (entity, headers) => (clientFor) => {
133
+ const named = namedBy(entity.key);
134
+ return (contract, input) => {
135
+ const entityId = named(input);
136
+ return entityId === void 0 ? Effect.fail(new Forbidden({ message: `The input of ${contract.name} names no entity of ${entity.type}` })) : Effect.map(headers, (sent) => entityCallOf(clientFor(entityId), sent));
137
+ };
138
+ };
139
+ /**
140
+ * The client of `entity` over Effect's own `Entity.client`: one method per action taking its
141
+ * input, `rooms.postMessage({ room: "lobby", text })`, and `watch(event, input, options)`, which
142
+ * polls the event's rpc, each call and watch sent to the entity its input's key names. Requires
143
+ * `Sharding`, as `Entity.client` does: `TestRunner.layer` in a test. The entity's native rpcs are
144
+ * Effect's own client's methods: `(yield* Room.client)("lobby").expire()`.
145
+ *
146
+ * **Gotchas**
147
+ *
148
+ * - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
149
+ * - Headers set with `RpcClient.withHeaders` around a call go with its envelope, which is how a protected call sends its credential; a call without them fails `Unauthenticated`.
150
+ * - A watch polls, its only `mode` `"poll"`, at the page's `nextPollMs`, its polls holding the subscription hook of the caller's principal in the entity until its source's `lease` lapses after the last, whichever watch sent it.
151
+ * - A watch asks the entity again after `MailboxFull` or `PersistenceError`, from where it reached, a second later and doubling to 30 seconds; a declared error, a refusal included, ends it.
152
+ */
153
+ const client = (entity) => {
154
+ const methods = methodsOf(entity.binding, polledTransport(isTransient));
155
+ const reach = reachOf(entity, Effect.undefined);
156
+ return Effect.map(entity.client, (clientFor) => methods(reach(clientFor)));
157
+ };
158
+ /**
159
+ * The implementations of `entity`'s actions and event types that any surface serves beside its
160
+ * own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
161
+ * `Entity.client` to the entity its contract's key names for its input, with the caller's
162
+ * headers, and its answer, declared errors and progress passed back; each event followed through
163
+ * the entity's poll rpc.
164
+ *
165
+ * **Gotchas**
166
+ *
167
+ * - The caller's credential is verified by the surface serving these and again by the entity reached, so both are given the verifier: a call the surface refuses reaches no entity.
168
+ * - A refusal by the entity, a credential expired since the surface verified it included, ends a stream after it answered 200, where the surface's own refusal would have answered its 401 or 403.
169
+ * - The caller's request's headers are sent on as `forwardedHeaders` keeps them: its connection's, its body's, what it accepts and an MCP request's routing headers are not.
170
+ * - A credential in the query, an API key the serving surface's HTTP binding reads `in: "query"`, never reaches the entity, whose binding reads headers alone, so it refuses the call with `Unauthenticated`: read the key from a header on the HTTP binding too.
171
+ * - A call with no HTTP request, as through `Action.client` in process or an MCP stdio surface, sends only the headers `RpcClient.withHeaders` sets around it: without them the entity refuses a protected one with `Unauthenticated`.
172
+ * - A call to an entity no runner is assigned waits without an answer, an HTTP request without a response, as Effect's entity client retries `EntityNotAssignedToRunner` every `sendRetryInterval`, 100 milliseconds by default, without limit: bound it with a timeout, such as the host's request timeout.
173
+ * - A stream, HTTP's `text/event-stream`, an RPC subscription or MCP's `events/stream`, polls the entity from the surface, at once while a page has more and otherwise at its `nextPollMs`, a second at least: it holds the caller's request open but no entity, an occurrence arrives up to that interval late, and the entity's object takes a call each `nextPollMs` while the stream is open, so on Cloudflare a stream polling every few seconds keeps it from ever hibernating.
174
+ * - A stream asks the entity again after `MailboxFull` or `PersistenceError`, from where it reached, a second later and doubling to 30 seconds, as `client`'s watch does; any other failure, a declared error or a defect, ends its polling.
175
+ * - HTTP's `text/event-stream` whose polling ended on a failure other than a refusal sends `Failed` and opens it again 5 seconds later, from where it reached; MCP's `events/stream` does what `ActionMcp.layerHttp` says of an upstream's failure, a `-32603` before `active`.
176
+ * - A stream's polls, and a poll, MCP's `events/poll` included, hold the subscriber's subscription hook in the entity until its source's `lease` lapses after the last, as on any surface.
177
+ * - A protected event's webhook subscription is held by the entity its input's key names, the subscribe and unsubscribe sent there with the caller's headers, and delivered by the `Webhook.layer` in that entity's `services`, never the serving surface's: an entity without one fails the subscribe with `Event.SubscriptionError`, reason `Unsupported`, a 409 over HTTP, before any callback is sent.
178
+ * - What `Entity.client` fails with, `MailboxFull`, `AlreadyProcessingMessage`, `PersistenceError` or `EntityNotAssignedToRunner`, is the call's defect, carrying that error alone, since no action declares it: a 500 over HTTP and a defect through `Action.client`, never a typed error.
179
+ * - An error the entity declares beyond the action's own and the built-in ones, its binding's `error` or its verifier's, is undeclared where the serving surface's binding does not declare it too.
180
+ */
181
+ const reaching = (entity) => {
182
+ const { binding } = entity;
183
+ const reaches = Effect.map(entity.client, reachOf(entity, forwarded));
184
+ const handlerOf = (action, reach) => {
185
+ const method = actionMethodOf(action, binding)(reach);
186
+ return (input, reporting) => clusterFailuresAsDefects(method(input, ...reporting === void 0 ? [] : [{ onProgress: reporting.progress }]));
187
+ };
188
+ const runOf = (event, reach) => {
189
+ const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(event.input));
190
+ const poll = pollOf(event, binding);
191
+ const watched = watchedOf(event, binding);
192
+ const webhookCalls = webhookCallsOf(event, binding);
193
+ const reached = (input) => Effect.all([reach(event, input), Effect.orDie(encode(input))]);
194
+ const inEntity = (input, sent) => clusterFailuresAsDefects(Effect.flatMap(reach(event, input), (call) => sent(webhookCalls(call))));
195
+ return {
196
+ polls: true,
197
+ webhook: offersWebhook(event) ? {
198
+ subscribe: (subscribing) => inEntity(subscribing.input, (held) => held.subscribe(subscribing)),
199
+ unsubscribe: (subscription) => inEntity(subscription.input, (held) => held.unsubscribe(subscription))
200
+ } : void 0,
201
+ poll: (input, cursor, { maxEvents }) => clusterFailuresAsDefects(Effect.flatMap(reached(input), ([call, json]) => poll(call)({
202
+ input: json,
203
+ cursor,
204
+ ...maxEvents === void 0 ? {} : { maxEvents }
205
+ }))),
206
+ stream: (input, cursor) => clusterFailuresAsDefects(Stream.unwrap(Effect.map(reached(input), ([call, json]) => polling(watched(call)(json), isTransient)(cursor))))
207
+ };
208
+ };
209
+ return [...binding.actions.length === 0 ? [] : [new Implementation(binding.actions, memoized(Effect.map(reaches, (reach) => binding.actions.map((action) => [action, handlerOf(action, reach)]))), memoized(Effect.succeed(allowAll)))], ...binding.events.length === 0 ? [] : [new EventImplementation(binding.events, binding.events.map((event) => [event, memoized(Effect.map(reaches, (reach) => runOf(event, reach)))]), memoized(Effect.succeed(allowAll$1)))]];
210
+ };
211
+ export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, reaching };