@gjermundgaraba/effect-actions 0.29.0 → 0.31.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 (81) hide show
  1. package/README.md +2 -2
  2. package/dist/Action.d.mts +6 -6
  3. package/dist/Action.mjs +17 -18
  4. package/dist/ActionCli.d.mts +23 -23
  5. package/dist/ActionCli.mjs +4 -4
  6. package/dist/ActionHttp.d.mts +17 -16
  7. package/dist/ActionHttp.mjs +18 -22
  8. package/dist/ActionMcp.d.mts +8 -8
  9. package/dist/ActionMcp.mjs +13 -16
  10. package/dist/ActionRpc.d.mts +24 -23
  11. package/dist/ActionRpc.mjs +58 -72
  12. package/dist/ActionToolkit.d.mts +1 -1
  13. package/dist/ActionToolkit.mjs +6 -5
  14. package/dist/Authentication.d.mts +2 -2
  15. package/dist/Authentication.mjs +44 -46
  16. package/dist/Event.d.mts +4 -4
  17. package/dist/Event.mjs +3 -3
  18. package/dist/Webhook.d.mts +2 -0
  19. package/dist/Webhook.mjs +1 -0
  20. package/dist/authentication/provider.d.mts +15 -15
  21. package/dist/authentication/refusal.mjs +12 -5
  22. package/dist/cli/commands.d.mts +2 -2
  23. package/dist/cli/commands.mjs +13 -13
  24. package/dist/contract/authorizer.d.mts +1 -1
  25. package/dist/contract/call.d.mts +2 -2
  26. package/dist/contract/call.mjs +1 -1
  27. package/dist/contract/callback.mjs +6 -1
  28. package/dist/contract/caller.d.mts +1 -1
  29. package/dist/contract/declared.d.mts +1 -1
  30. package/dist/contract/declared.mjs +1 -1
  31. package/dist/contract/digest.mjs +3 -2
  32. package/dist/contract/feed.d.mts +1 -1
  33. package/dist/contract/feed.mjs +12 -10
  34. package/dist/contract/hub.d.mts +1 -1
  35. package/dist/contract/idempotency.d.mts +1 -1
  36. package/dist/contract/idempotency.mjs +4 -4
  37. package/dist/contract/implementation.d.mts +27 -27
  38. package/dist/contract/implementation.mjs +8 -18
  39. package/dist/contract/input-check.d.mts +3 -3
  40. package/dist/contract/listed.d.mts +1 -1
  41. package/dist/contract/listed.mjs +1 -1
  42. package/dist/contract/pages.d.mts +1 -1
  43. package/dist/contract/push.d.mts +2 -2
  44. package/dist/contract/push.mjs +5 -7
  45. package/dist/contract/receiving.d.mts +2 -2
  46. package/dist/contract/receiving.mjs +1 -1
  47. package/dist/contract/recent.mjs +3 -2
  48. package/dist/contract/serving.mjs +18 -18
  49. package/dist/contract/stream.d.mts +1 -1
  50. package/dist/contract/stream.mjs +14 -2
  51. package/dist/contract/subscribe.mjs +7 -2
  52. package/dist/contract/transient.mjs +1 -1
  53. package/dist/contract/watch.d.mts +1 -1
  54. package/dist/contract/watch.mjs +5 -8
  55. package/dist/contract/webhooks.d.mts +1 -1
  56. package/dist/contract/webhooks.mjs +17 -6
  57. package/dist/http/client.d.mts +9 -9
  58. package/dist/http/client.mjs +6 -4
  59. package/dist/http/events.d.mts +6 -6
  60. package/dist/http/events.mjs +7 -5
  61. package/dist/http/placed.d.mts +3 -3
  62. package/dist/http/placed.mjs +5 -5
  63. package/dist/http/streamed.d.mts +3 -2
  64. package/dist/http/streamed.mjs +11 -6
  65. package/dist/http/watch.mjs +1 -1
  66. package/dist/mcp/bridge.mjs +13 -22
  67. package/dist/mcp/client.d.mts +10 -10
  68. package/dist/mcp/client.mjs +5 -14
  69. package/dist/mcp/events.mjs +1 -1
  70. package/dist/mcp/progress.mjs +11 -1
  71. package/dist/mcp/reply.d.mts +1 -1
  72. package/dist/mcp/watch.mjs +4 -4
  73. package/dist/rpc/watch.mjs +3 -5
  74. package/dist/webhook/health.mjs +25 -28
  75. package/dist/webhook/receiver.mjs +4 -7
  76. package/dist/webhook/stored.mjs +1 -1
  77. package/dist/webhook/subscriptions.mjs +19 -17
  78. package/docs/Action.md +1 -1
  79. package/docs/setup-failures.md +1 -1
  80. package/docs/setup.md +4 -4
  81. package/package.json +11 -12
@@ -1,7 +1,7 @@
1
1
  import { Refusal } from "./errors.mjs";
2
- import { reported } from "./reported.mjs";
3
- import { Checked, Gap, OccurrenceOf } from "./occurrence.mjs";
4
2
  import { defaultNextPoll } from "./feed.mjs";
3
+ import { Checked, Gap, OccurrenceOf } from "./occurrence.mjs";
4
+ import { reported } from "./reported.mjs";
5
5
  import { Cause, Duration, Effect, Latch, Match, Queue, Schema, Stream } from "effect";
6
6
  // src/contract/push.ts
7
7
  const Failed = Schema.TaggedStruct("Failed", {});
@@ -11,12 +11,10 @@ const PushedOf = (event) => Schema.Union([
11
11
  Checked,
12
12
  Failed
13
13
  ]);
14
- const subscriptionWith = (input) => Schema.Struct({
15
- input,
14
+ const SubscriptionOf = (event) => Schema.Struct({
15
+ input: event.input,
16
16
  cursor: Schema.NullOr(Schema.String).annotate({ description: "Where to resume: a cursor an occurrence or a page carried; null or omitted, from now." }).pipe(Schema.withDecodingDefaultKey(Effect.succeed(null)))
17
17
  });
18
- const SubscriptionOf = (event) => subscriptionWith(event.input);
19
- const Subscription = subscriptionWith(Schema.Json);
20
18
  const defaultCapacity = 16;
21
19
  const heartbeatEvery = Duration.seconds(30);
22
20
  const isFailed = Schema.is(Failed);
@@ -66,4 +64,4 @@ const queuedPush = (open, cursor, encode, { ending, positions, capacity = defaul
66
64
  }).pipe(ending, Queue.into(queue), Effect.forkScoped({ startImmediately: true }));
67
65
  return queue;
68
66
  });
69
- export { Failed, PushedOf, Subscription, SubscriptionOf, polledOn, pushed, queuedPush, readOn, refusalIn };
67
+ export { Failed, PushedOf, SubscriptionOf, polledOn, pushed, queuedPush, readOn, refusalIn };
@@ -1,7 +1,7 @@
1
+ import { SigningSecret } from "./callback.mjs";
1
2
  import "./errors.mjs";
2
- import "./pages.mjs";
3
3
  import "../Event.mjs";
4
- import { SigningSecret } from "./callback.mjs";
4
+ import "./pages.mjs";
5
5
  import { Context, Effect, Schema, Scope } from "effect";
6
6
  /** A POST a receiver verified, its JSON body: an occurrence, or an envelope. */
7
7
  export interface Delivered {
@@ -1,6 +1,6 @@
1
+ import { reasonOf, refusalOf } from "./codes.mjs";
1
2
  import { Forbidden } from "./errors.mjs";
2
3
  import { Gap, untaggedOccurrenceOf } from "./occurrence.mjs";
3
- import { reasonOf, refusalOf } from "./codes.mjs";
4
4
  import { Context, Effect, Option, Schema, Struct } from "effect";
5
5
  // src/contract/receiving.ts
6
6
  const watchParameter = "watch";
@@ -1,11 +1,12 @@
1
1
  // src/contract/recent.ts
2
- const makeRecent = (size) => {
2
+ const keptIds = 1e3;
3
+ const makeRecent = () => {
3
4
  const ids = /* @__PURE__ */ new Set();
4
5
  return {
5
6
  has: (id) => ids.has(id),
6
7
  add: (id) => {
7
8
  ids.add(id);
8
- if (ids.size > size) ids.delete(ids.values().next().value ?? id);
9
+ if (ids.size > keptIds) ids.delete(ids.values().next().value ?? id);
9
10
  }
10
11
  };
11
12
  };
@@ -1,34 +1,33 @@
1
1
  import { Anyone, assertAuthentication } from "./caller.mjs";
2
- import { assertDistinct, assertOnce, heldOnce } from "./names.mjs";
3
- import { Implementation, assertHeld, markingOthers, notHeld, provideBuilders, select, servedBy, toList } from "./implementation.mjs";
4
- import { eventsOf, feedBuilders, selectEvents } from "./feed.mjs";
2
+ import { EventImplementation, eventKind, eventsOf } from "./feed.mjs";
3
+ import { Implementation, actionKind, assertHeld, markingOthers, notHeld, provideBuilders, select, toList } from "./implementation.mjs";
5
4
  import { selection } from "./listed.mjs";
5
+ import { assertDistinct, assertOnce, heldOnce } from "./names.mjs";
6
6
  // src/contract/serving.ts
7
7
  const selectFrom = (served, actions) => {
8
8
  const listed = selection(actions);
9
9
  return {
10
- apps: select(toList(served), listed.actions),
11
- events: selectEvents(eventsOf(served), listed.events)
10
+ apps: select(actionKind, toList(served), listed.actions),
11
+ events: select(eventKind, eventsOf(served), listed.events)
12
12
  };
13
13
  };
14
- const eventsServedBy = (what, bound, served, listed) => {
15
- const apps = eventsOf(served);
14
+ const servedBy = (kind, what, bound, apps, listed) => {
15
+ const { noun, holds } = kind;
16
16
  if (listed !== void 0) assertHeld(notHeld.byBinding, listed, bound);
17
- const unbound = apps.filter((app) => !app.events.some((event) => bound.includes(event)));
18
- if (listed === void 0 && unbound.length > 0 && unbound.length === apps.length) {
17
+ const held = apps.flatMap(holds);
18
+ if (listed === void 0 && apps.length > 0 && !held.some((contract) => bound.includes(contract))) {
19
19
  const names = new Set(bound.map(({ name }) => name));
20
- throw new Error(`No event of these implementations is in this ${what}: ${markingOthers(unbound.flatMap((app) => app.events), names)} (pass an implementation of a bound event, or bind one of these)`);
20
+ throw new Error(`No ${noun} of these implementations is in this ${what}: ${markingOthers(held, names) || "none"} (pass an implementation of a bound ${noun}, or bind one of these)`);
21
21
  }
22
- const held = new Set(apps.flatMap((app) => app.events));
23
- const selected = selectEvents(apps, listed ?? bound.filter((event) => held.has(event)));
24
- assertOnce("served event", selected.flatMap((app) => app.events), heldOnce);
25
- return selected;
22
+ const served = select(kind, apps, listed ?? bound.filter((contract) => held.includes(contract)));
23
+ assertOnce(`served ${noun}`, served.flatMap(holds), heldOnce);
24
+ return served;
26
25
  };
27
26
  const servingOf = (what, binding, served, options) => {
28
27
  const listed = selection(options.actions);
29
- const apps = servedBy(what, binding.actions, toList(served), listed.actions);
28
+ const apps = servedBy(actionKind, what, binding.actions, toList(served), listed.actions);
30
29
  const actions = apps.flatMap((app) => app.actions);
31
- const events = eventsServedBy(what, binding.events, served, listed.events);
30
+ const events = servedBy(eventKind, what, binding.events, eventsOf(served), listed.events);
32
31
  const eventTypes = events.flatMap((app) => app.events);
33
32
  assertAuthentication(actions, binding.authentication);
34
33
  assertAuthentication(eventTypes, binding.authentication, "event");
@@ -41,5 +40,6 @@ const servingOf = (what, binding, served, options) => {
41
40
  authentication: [...actions, ...eventTypes].some((contract) => contract.caller !== Anyone) ? binding.authentication : void 0
42
41
  };
43
42
  };
44
- const provideServed = (served) => provideBuilders([...served.apps.map((app) => Implementation.layerOf(app)), ...feedBuilders(served.events)]);
45
- export { provideServed, selectFrom, servingOf };
43
+ const buildersOf = (apps, events = []) => [...apps.map((app) => Implementation.layerOf(app)), ...events.map((app) => EventImplementation.layerOf(app))];
44
+ const provideServed = (apps, events = []) => provideBuilders(buildersOf(apps, events));
45
+ export { buildersOf, provideServed, selectFrom, servingOf };
@@ -1,5 +1,5 @@
1
1
  import { Codec, CodecOf, Fields } from "./codec.mjs";
2
- import { Effect, Schema, Stream } from "effect";
2
+ import { Data, Effect, Schema, Stream } from "effect";
3
3
  declare const TypeId = "~effect-actions/Stream";
4
4
  /** The success of an action answering a stream: a schema of `Stream`s, holding its element's. */
5
5
  export interface StreamOf<Element extends Codec> extends Schema.declare<Stream.Stream<Element["Type"]>> {
@@ -1,5 +1,5 @@
1
1
  import { codecOf } from "./codec.mjs";
2
- import { Predicate, Schema, Stream } from "effect";
2
+ import { Data, Predicate, Schema, Stream } from "effect";
3
3
  // src/contract/stream.ts
4
4
  const TypeId = "~effect-actions/Stream";
5
5
  const streams = Schema.declare(Stream.isStream);
@@ -22,8 +22,20 @@ const Stream$1 = (element) => Schema.make(streams.ast, {
22
22
  });
23
23
  const isStreamOf = (success) => Predicate.hasProperty(success, TypeId);
24
24
  const elementOf = (success) => isStreamOf(success) ? success.element : void 0;
25
+ const Answering = Data.taggedEnum();
26
+ const answeringOf = ({ success, progress }) => {
27
+ const element = elementOf(success);
28
+ if (element !== void 0) return Answering.Elements({
29
+ element,
30
+ progress
31
+ });
32
+ return progress === void 0 ? Answering.Value({ success }) : Answering.Progressed({
33
+ success,
34
+ progress
35
+ });
36
+ };
25
37
  const toolSuccessOf = (success) => {
26
38
  const element = elementOf(success);
27
39
  return element === void 0 ? success : Schema.Array(element);
28
40
  };
29
- export { Stream$1 as Stream, elementOf, toolSuccessOf };
41
+ export { Answering, Stream$1 as Stream, answeringOf, elementOf, toolSuccessOf };
@@ -1,8 +1,13 @@
1
- import { CallbackCategory } from "../Event.mjs";
2
1
  import { CallbackUrl, WebhookSecret } from "./callback.mjs";
2
+ import { CallbackCategory, SubscriptionError, Unsupported } from "../Event.mjs";
3
3
  import { SubscriptionOf } from "./push.mjs";
4
4
  import { Schema, Struct } from "effect";
5
5
  // src/contract/subscribe.ts
6
+ /** The error for `event` that is not delivered by `mode` where it is asked for. */
7
+ const deliveryUnsupported = (event, mode) => SubscriptionError.of(event, new Unsupported({
8
+ feature: "deliveryMode",
9
+ value: mode
10
+ }));
6
11
  const WebhookCallback = Schema.Struct({
7
12
  url: CallbackUrl,
8
13
  secret: WebhookSecret
@@ -35,4 +40,4 @@ const Subscribed = Schema.Struct({
35
40
  truncated: Schema.Boolean,
36
41
  deliveryStatus: Schema.optional(DeliveryStatus)
37
42
  });
38
- export { DeliveryStatus, Subscribed, WebhookCallback, WebhookCancellationOf, WebhookSubscriptionOf, WebhookTarget, webhookFields };
43
+ export { DeliveryStatus, Subscribed, WebhookCallback, WebhookCancellationOf, WebhookSubscriptionOf, WebhookTarget, deliveryUnsupported, webhookFields };
@@ -1,5 +1,5 @@
1
- import { isTransientStatus } from "./status.mjs";
2
1
  import { readOn } from "./push.mjs";
2
+ import { isTransientStatus } from "./status.mjs";
3
3
  import { Cause, Duration, Effect, Function, Match, Predicate, Stream } from "effect";
4
4
  import { HttpClientError } from "effect/http";
5
5
  // src/contract/transient.ts
@@ -1,5 +1,5 @@
1
- import "./pages.mjs";
2
1
  import { Any, WatchOptions, WebhookDelivery } from "../Event.mjs";
2
+ import "./pages.mjs";
3
3
  import { Receiving } from "./receiving.mjs";
4
4
  import "./subscribe.mjs";
5
5
  import { Effect, Schema, Stream } from "effect";
@@ -1,9 +1,10 @@
1
+ import { CallbackUrl } from "./callback.mjs";
2
+ import { SubscriptionError } from "../Event.mjs";
1
3
  import { Checked, Gap } from "./occurrence.mjs";
2
4
  import { paged } from "./pages.mjs";
3
- import { SubscriptionError, Unsupported } from "../Event.mjs";
4
5
  import { watchParameter } from "./receiving.mjs";
5
6
  import { makeRecent } from "./recent.mjs";
6
- import { CallbackUrl } from "./callback.mjs";
7
+ import { deliveryUnsupported } from "./subscribe.mjs";
7
8
  import { Cause, Clock, Duration, Effect, Predicate, Queue, Schedule, Schema, Stream } from "effect";
8
9
  // src/contract/watch.ts
9
10
  const reconnectDelay = Duration.seconds(1);
@@ -11,7 +12,6 @@ const maxReconnectDelay = Duration.seconds(30);
11
12
  const afterFailures = (transient) => Schedule.min([Schedule.exponential(reconnectDelay), Schedule.spaced(maxReconnectDelay)]).pipe(Schedule.setInputType(), Schedule.while(({ input }) => transient(input)), Schedule.tap(({ input, duration }) => Effect.logWarning(`A watch reconnects in ${Duration.format(duration)} after a failure`, input)));
12
13
  const isSubscriptionError = Schema.is(SubscriptionError);
13
14
  const pushRefused = Predicate.compose(isSubscriptionError, ({ reason }) => Predicate.isTagged(reason, "Unsupported") && reason.feature === "deliveryMode" && reason.value === "push");
14
- const dedupeWindow = 1e3;
15
15
  const capacity = 16;
16
16
  const unsubscribeTimeout = Duration.seconds(5);
17
17
  const delivered = (webhook, request, received, cursor) => {
@@ -42,10 +42,7 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
42
42
  const polled = (cursor) => reconnecting((at) => paged(transport.poll, at), cursor);
43
43
  const webhooked = ({ baseUrl, ttl }, cursor) => Stream.unwrap(Effect.gen(function* () {
44
44
  const { webhook } = transport;
45
- if (webhook === void 0) return yield* SubscriptionError.of(transport.name, new Unsupported({
46
- feature: "deliveryMode",
47
- value: "webhook"
48
- }));
45
+ if (webhook === void 0) return yield* deliveryUnsupported(transport.name, "webhook");
49
46
  const base = yield* Schema.decodeEffect(CallbackUrl)(baseUrl);
50
47
  const receiving = yield* webhook.receiver;
51
48
  const received = yield* Queue.unbounded();
@@ -63,7 +60,7 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
63
60
  return reconnecting((at) => delivered(webhook, request, received, at), cursor);
64
61
  }));
65
62
  return Stream.suspend(() => {
66
- const seen = makeRecent(dedupeWindow);
63
+ const seen = makeRecent();
67
64
  let keptOnNextPull = null;
68
65
  const keep = (cursor) => cursor === null || resume === void 0 ? Effect.void : resume.store.set(resume.key, cursor);
69
66
  const fresh = (eventId) => {
@@ -1,6 +1,6 @@
1
1
  import { Anyone, Named } from "./caller.mjs";
2
- import { Feed } from "./feed.mjs";
3
2
  import { Any } from "../Event.mjs";
3
+ import { Feed } from "./feed.mjs";
4
4
  import { AnyWebhookCancellation, AnyWebhookSubscription, Subscribed } from "./subscribe.mjs";
5
5
  import { Context, Effect, Option } from "effect";
6
6
  /** An event type a surface may offer by webhook: a protected one, its caller an identity. */
@@ -1,5 +1,6 @@
1
1
  import { Anyone, isNamed } from "./caller.mjs";
2
- import { SubscriptionError, Unsupported } from "../Event.mjs";
2
+ import { acquireFeeds } from "./feed.mjs";
3
+ import { deliveryUnsupported } from "./subscribe.mjs";
3
4
  import { Context, Effect, Option } from "effect";
4
5
  // src/contract/webhooks.ts
5
6
  /**
@@ -24,10 +25,7 @@ const servedWebhooks = (feeds, keyed) => Effect.gen(function* () {
24
25
  });
25
26
  const webhookSubscriber = (feed, keyed, webhooks) => {
26
27
  const { event } = feed;
27
- if (Option.isNone(webhooks) || !isNamed(keyed) || !isProtected(event)) return Effect.fail(SubscriptionError.of(event.name, new Unsupported({
28
- feature: "deliveryMode",
29
- value: "webhook"
30
- })));
28
+ if (Option.isNone(webhooks) || !isNamed(keyed) || !isProtected(event)) return Effect.fail(deliveryUnsupported(event.name, "webhook"));
31
29
  const service = webhooks.value;
32
30
  return Effect.map(Effect.service(event.caller), (identity) => ({
33
31
  webhooks: service,
@@ -39,4 +37,17 @@ const webhookSubscriber = (feed, keyed, webhooks) => {
39
37
  principal: keyed.principal(identity)
40
38
  }));
41
39
  };
42
- export { Webhooks, offersWebhook, servedWebhooks, webhookSubscriber };
40
+ /**
41
+ * The feeds of `events` a surface's layer serves, and the webhooks it offers, served: run as the
42
+ * layer builds, dying where a protected event's subscription hook has no principal to key it by.
43
+ */
44
+ const servingFeeds = Effect.fnUntraced(function* (surface, events, keyed) {
45
+ const feeds = yield* acquireFeeds(events);
46
+ const unkeyed = keyed?.principal === void 0 ? feeds.find(({ event, release }) => release !== void 0 && event.caller !== Anyone) : void 0;
47
+ if (unkeyed !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`${surface} event "${unkeyed.event.name}" is protected and has a subscription hook, so its authentication needs principal to tell poll subscribers apart (give Authentication.make a principal, such as (user) => user.id)`));
48
+ return {
49
+ feeds,
50
+ ...yield* servedWebhooks(feeds, keyed)
51
+ };
52
+ });
53
+ export { Webhooks, offersWebhook, servedWebhooks, servingFeeds, webhookSubscriber };
@@ -1,13 +1,13 @@
1
+ import { Any, VerifierError } from "../authentication/provider.mjs";
2
+ import { Any as Any$1, Errors } from "../Action.mjs";
3
+ import { Call } from "../contract/call.mjs";
1
4
  import { Codec } from "../contract/codec.mjs";
2
5
  import { BuiltIns } from "../contract/errors.mjs";
3
- import { Any, Received, SubscriptionError, WatchOptions } from "../Event.mjs";
6
+ import { Any as Any$2, Received, SubscriptionError, WatchOptions } from "../Event.mjs";
4
7
  import "../contract/implementation.mjs";
5
- import { Call } from "../contract/call.mjs";
6
- import { Answer, StreamOf } from "../contract/stream.mjs";
7
8
  import "../contract/receiving.mjs";
9
+ import { Answer, StreamOf } from "../contract/stream.mjs";
8
10
  import { WatchArgs, WatchRequirement } from "../contract/watch.mjs";
9
- import { Any as Any$1, Errors } from "../Action.mjs";
10
- import { Any as Any$2, VerifierError } from "../authentication/provider.mjs";
11
11
  import { sentOf } from "./events.mjs";
12
12
  import { Effect, Schema, Stream } from "effect";
13
13
  import { HttpClient, HttpClientError } from "effect/http";
@@ -38,7 +38,7 @@ export interface Options<E = HttpClientError.HttpClientError, R = never> {
38
38
  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient.With<E, R>) | undefined;
39
39
  }
40
40
  type BindingError = Errors[number];
41
- type SseFailure = Extract<Stream.Error<HttpApiClient.SuccessType<ReturnType<typeof sentOf<Any>>>>, {
41
+ type SseFailure = Extract<Stream.Error<HttpApiClient.SuccessType<ReturnType<typeof sentOf<Any$2>>>>, {
42
42
  readonly _tag: "SseError" | "Retry";
43
43
  }>;
44
44
  type SseError = Extract<SseFailure, {
@@ -59,9 +59,9 @@ type Method<A extends Any$1, E extends BindingError, CE, CR> = Call<A, Answer<A[
59
59
  * types.
60
60
  */
61
61
  export interface AnyHttp {
62
- readonly authentication?: Any$2 | undefined;
62
+ readonly authentication?: Any | undefined;
63
63
  readonly actions: readonly Any$1[];
64
- readonly events: readonly Any[];
64
+ readonly events: readonly Any$2[];
65
65
  readonly error: readonly BindingError[];
66
66
  readonly prefix: `/${string}`;
67
67
  readonly api: HttpApi.Constraint;
@@ -71,7 +71,7 @@ export interface AnyHttp {
71
71
  * a refusal ending it later, an `Event.SubscriptionError` where it is not served, a native
72
72
  * `HttpClientError` that no reconnect outlasts, or a stream or an occurrence that does not decode.
73
73
  */
74
- export type WatchError<W extends Any, H extends AnyHttp> = SubscriptionError | BuiltIns["Type"] | H["error"][number]["Type"] | VerifierError<W, H["authentication"]>["Type"] | HttpClientError.HttpClientError | Schema.SchemaError | SseError;
74
+ export type WatchError<W extends Any$2, H extends AnyHttp> = SubscriptionError | BuiltIns["Type"] | H["error"][number]["Type"] | VerifierError<W, H["authentication"]>["Type"] | HttpClientError.HttpClientError | Schema.SchemaError | SseError;
75
75
  type Watching<H extends AnyHttp, E, R> = [H["events"][number]] extends [never] ? unknown : {
76
76
  readonly watch: <W extends H["events"][number], SE = never, const O extends WatchOptions<unknown> = {}>(event: W, ...args: WatchArgs<W, SE, O>) => Stream.Stream<Received<W>, WatchError<W, H> | E | SE, R | WatchRequirement<O>>;
77
77
  };
@@ -1,5 +1,5 @@
1
- import { elementOf } from "../contract/stream.mjs";
2
1
  import { checked, checkedStream, sendingValue, watchInput } from "../contract/call.mjs";
2
+ import { Answering, answeringOf } from "../contract/stream.mjs";
3
3
  import { watching } from "../contract/watch.mjs";
4
4
  import { readElements, readWithProgress } from "./streamed.mjs";
5
5
  import { transportOf } from "./watch.mjs";
@@ -19,9 +19,11 @@ const nativeOf = (http, httpClient, baseUrl) => HttpApiClient.makeWith(http.api,
19
19
  });
20
20
  const actionMethodOf = (action, native) => {
21
21
  const method = methodOf(native, action.name, "action");
22
- if (elementOf(action.success) !== void 0) return checkedStream(action, sendingValue, (payload, onProgress) => Stream.unwrap(Effect.map(method({ payload }), (answer) => readElements(answer, onProgress))));
23
- if (action.progress === void 0) return checked(action, sendingValue, (payload) => method({ payload }));
24
- return checked(action, sendingValue, (payload, onProgress) => Effect.flatMap(method({ payload }), (answer) => readWithProgress(answer, onProgress)));
22
+ return Answering.$match(answeringOf(action), {
23
+ Value: () => checked(action, sendingValue, (payload) => method({ payload })),
24
+ Progressed: () => checked(action, sendingValue, (payload, onProgress) => Effect.flatMap(method({ payload }), (answer) => readWithProgress(answer, onProgress))),
25
+ Elements: () => checkedStream(action, sendingValue, (payload, onProgress) => Stream.unwrap(Effect.map(method({ payload }), (answer) => readElements(answer, onProgress))))
26
+ });
25
27
  };
26
28
  const sendersWith = (http, httpClient, baseUrl) => Effect.gen(function* () {
27
29
  const native = yield* nativeOf(http, acceptingStreams(httpClient), baseUrl);
@@ -1,13 +1,13 @@
1
- import "../contract/codec.mjs";
2
- import { Forbidden, Unauthenticated } from "../contract/errors.mjs";
3
1
  import { OccurrenceSchema } from "../contract/occurrence.mjs";
2
+ import { Forbidden, Unauthenticated } from "../contract/errors.mjs";
3
+ import "../contract/codec.mjs";
4
4
  import "../contract/pages.mjs";
5
- import "../contract/feed.mjs";
6
- import { Any } from "../Event.mjs";
7
- import "../contract/subscribe.mjs";
8
- import "../Action.mjs";
9
5
  import "../authentication/provider.mjs";
6
+ import "../Action.mjs";
7
+ import { Any } from "../Event.mjs";
8
+ import "../contract/feed.mjs";
10
9
  import "../contract/push.mjs";
10
+ import "../contract/subscribe.mjs";
11
11
  import "../contract/webhooks.mjs";
12
12
  import { Effect, Option, Schema, Stream } from "effect";
13
13
  import { HttpApiEndpoint, HttpApiSchema } from "effect/http-api";
@@ -1,12 +1,13 @@
1
1
  import { principalOf } from "../contract/caller.mjs";
2
- import { Refusal } from "../contract/errors.mjs";
3
- import { declared } from "../contract/status.mjs";
4
2
  import { assertDistinctTags } from "../contract/declared.mjs";
5
- import { OccurrenceOf } from "../contract/occurrence.mjs";
3
+ import { Refusal } from "../contract/errors.mjs";
6
4
  import { SubscriptionError } from "../Event.mjs";
7
- import { webhookSubscriber } from "../contract/webhooks.mjs";
5
+ import { OccurrenceOf } from "../contract/occurrence.mjs";
8
6
  import { PushedOf, SubscriptionOf, queuedPush } from "../contract/push.mjs";
7
+ import { declared } from "../contract/status.mjs";
9
8
  import { Subscribed, WebhookCancellationOf, WebhookSubscriptionOf } from "../contract/subscribe.mjs";
9
+ import { webhookSubscriber } from "../contract/webhooks.mjs";
10
+ import { acceptsEventStream } from "./streamed.mjs";
10
11
  import { Effect, Function, Schema, Stream } from "effect";
11
12
  import { HttpServerRequest } from "effect/http";
12
13
  import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api";
@@ -62,7 +63,8 @@ const webhookAnswers = (feed, authentication, webhooks) => {
62
63
  const answering = (feed, authentication) => {
63
64
  const encode = Schema.encodeEffect(Schema.toCodecJson(PushedOf(feed.event)));
64
65
  return ({ payload: { input, cursor } }) => Effect.gen(function* () {
65
- if (((yield* HttpServerRequest.HttpServerRequest).headers["accept"] ?? "").includes("text/event-stream")) {
66
+ const request = yield* HttpServerRequest.HttpServerRequest;
67
+ if (acceptsEventStream(request)) {
66
68
  const open = yield* feed.stream(input);
67
69
  return Stream.fromQueue(yield* queuedPush(open, cursor, encode, {
68
70
  ending: Function.identity,
@@ -1,11 +1,11 @@
1
+ import { Any } from "../Action.mjs";
2
+ import { Any as Any$1 } from "../Event.mjs";
1
3
  import { EventImplementation } from "../contract/feed.mjs";
2
- import { Any } from "../Event.mjs";
3
4
  import { Implementation } from "../contract/implementation.mjs";
4
- import { Any as Any$1 } from "../Action.mjs";
5
5
  import { AnyHttp } from "./client.mjs";
6
6
  import { HttpClient } from "effect/http";
7
7
  type Contract<H extends AnyHttp> = H["actions"][number] | H["events"][number];
8
- type Nothing<C extends Any$1 | Any> = { readonly [K in C["name"]]: never; };
8
+ type Nothing<C extends Any | Any$1> = { readonly [K in C["name"]]: never; };
9
9
  /**
10
10
  * What `placed` returns: an implementation of the binding's actions where it has some, and one of
11
11
  * its event types where it has some, which require nothing.
@@ -1,9 +1,9 @@
1
- import { Implementation, memoized } from "../contract/implementation.mjs";
1
+ import { allowAll } from "../Action.mjs";
2
+ import { SubscriptionError, allowAll as allowAll$1 } from "../Event.mjs";
2
3
  import { EventImplementation } from "../contract/feed.mjs";
3
- import { SubscriptionError, allowAll } from "../Event.mjs";
4
- import { isNotFound } from "./watch.mjs";
4
+ import { Implementation, memoized } from "../contract/implementation.mjs";
5
5
  import { sendersWith } from "./client.mjs";
6
- import { allowAll as allowAll$1 } from "../Action.mjs";
6
+ import { isNotFound } from "./watch.mjs";
7
7
  import { Context, Effect, Option, Predicate, Schema, Stream } from "effect";
8
8
  import { Headers, HttpClient, HttpClientRequest, HttpServerRequest } from "effect/http";
9
9
  // src/http/placed.ts
@@ -66,6 +66,6 @@ const placed = (binding, client) => {
66
66
  poll: (input, cursor) => transport(event, input).poll(cursor).pipe(Effect.provideService(Sending, sendingTo(input, event)), Effect.catchIf(isNotServed, () => Effect.die(notServedThere(event.name)))),
67
67
  stream: (input, cursor) => transport(event, input).stream(cursor).pipe(Stream.provideService(Sending, sendingTo(input, event)), Stream.catchIf(isNotServed, () => Stream.die(notServedThere(event.name))))
68
68
  });
69
- return [...binding.actions.length === 0 ? [] : [new Implementation(binding.actions, memoized(Effect.map(senders, (built) => binding.actions.map((action) => [action, handlerOf(built, action)]))), memoized(Effect.succeed(allowAll$1)))], ...binding.events.length === 0 ? [] : [new EventImplementation(binding.events, binding.events.map((event) => [event, memoized(Effect.map(senders, (built) => runOf(built, event)))]), memoized(Effect.succeed(allowAll)))]];
69
+ return [...binding.actions.length === 0 ? [] : [new Implementation(binding.actions, memoized(Effect.map(senders, (built) => binding.actions.map((action) => [action, handlerOf(built, action)]))), memoized(Effect.succeed(allowAll)))], ...binding.events.length === 0 ? [] : [new EventImplementation(binding.events, binding.events.map((event) => [event, memoized(Effect.map(senders, (built) => runOf(built, event)))]), memoized(Effect.succeed(allowAll$1)))]];
70
70
  };
71
71
  export { placed };
@@ -1,9 +1,10 @@
1
+ import { Any } from "../Action.mjs";
1
2
  import { Codec } from "../contract/codec.mjs";
2
- import "../contract/progress.mjs";
3
3
  import { ErasedValue } from "../contract/implementation.mjs";
4
+ import "../contract/progress.mjs";
4
5
  import { StreamOf } from "../contract/stream.mjs";
5
- import { Any } from "../Action.mjs";
6
6
  import { Effect, Schema, Stream } from "effect";
7
+ import { HttpServerRequest } from "effect/http";
7
8
  import { HttpApiSchema } from "effect/http-api";
8
9
  interface Sent {
9
10
  readonly event: "progress" | "element" | "final";
@@ -1,7 +1,7 @@
1
- import { Progressed, answerFrom, elementsFrom } from "../contract/progress.mjs";
2
1
  import { elementsOf } from "../contract/implementation.mjs";
2
+ import { Progressed, answerFrom, elementsFrom } from "../contract/progress.mjs";
3
3
  import { concealed } from "../contract/reported.mjs";
4
- import { Cause, Effect, ErrorReporter, Queue, Schema, Stream } from "effect";
4
+ import { Cause, Duration, Effect, ErrorReporter, Queue, Schema, Stream } from "effect";
5
5
  import { HttpServerRequest } from "effect/http";
6
6
  import { HttpApiSchema } from "effect/http-api";
7
7
  // src/http/streamed.ts
@@ -10,14 +10,17 @@ const eventOf = (event, data) => Schema.Struct({
10
10
  event: Schema.Literal(event),
11
11
  data: Schema.fromJsonString(Schema.toCodecJson(data))
12
12
  });
13
+ const keepAliveEvery = Duration.seconds(15);
13
14
  const answeredWithProgress = (success) => HttpApiSchema.isNoContent(success.ast) ? HttpApiSchema.NoContent : success;
14
15
  const progressStreamOf = (progress, success, errors) => HttpApiSchema.StreamSse({
15
16
  events: Schema.Union([eventOf("progress", progress), eventOf("final", success)]),
16
- error: Schema.Union(errors)
17
+ error: Schema.Union(errors),
18
+ keepAlive: keepAliveEvery
17
19
  });
18
20
  const elementStreamOf = (element, progress, errors) => HttpApiSchema.StreamSse({
19
21
  events: Schema.Union(progress === void 0 ? [eventOf("element", element)] : [eventOf("element", element), eventOf("progress", progress)]),
20
- error: Schema.Union(errors)
22
+ error: Schema.Union(errors),
23
+ keepAlive: keepAliveEvery
21
24
  });
22
25
  const gatedOnFirst = (sent) => Effect.map(Effect.catchIf(Queue.take(sent), Cause.isDone, () => Effect.undefined), (first) => first === void 0 ? Stream.empty : Stream.concat(Stream.make(first), Stream.fromQueue(sent)));
23
26
  const streamed = (answer) => Effect.gen(function* () {
@@ -41,9 +44,11 @@ const checkedBy = (schema) => {
41
44
  const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(schema));
42
45
  return (data) => Effect.orDie(encode(data));
43
46
  };
47
+ /** Whether `request` asks for an SSE stream, `text/event-stream` among whatever else it accepts. */
48
+ const acceptsEventStream = (request) => (request.headers["accept"] ?? "").includes("text/event-stream");
44
49
  const answeringWithProgress = (success, run) => {
45
50
  const check = checkedBy(success);
46
- return (payload) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => (request.headers["accept"] ?? "").includes("text/event-stream") ? streamed((reporting, send) => run(payload, reporting).pipe(Effect.tap(check), Effect.flatMap((data) => send({
51
+ return (payload) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => acceptsEventStream(request) ? streamed((reporting, send) => run(payload, reporting).pipe(Effect.tap(check), Effect.flatMap((data) => send({
47
52
  event: "final",
48
53
  data
49
54
  })))) : run(payload));
@@ -63,4 +68,4 @@ const answeredWithout = /* @__PURE__ */ new Error("A route of an action declarin
63
68
  const sentFrom = (answer) => Stream.isStream(answer) ? Stream.map(answer, progressedOf) : Stream.die(answeredWithout);
64
69
  const readWithProgress = (answer, onProgress) => answerFrom(sentFrom(answer), onProgress);
65
70
  const readElements = (answer, onProgress) => elementsFrom(sentFrom(answer), onProgress);
66
- export { answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf, readElements, readWithProgress };
71
+ export { acceptsEventStream, answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf, readElements, readWithProgress };
@@ -1,5 +1,5 @@
1
- import { fedOf } from "../contract/pages.mjs";
2
1
  import { NotServed, SubscriptionError } from "../Event.mjs";
2
+ import { fedOf } from "../contract/pages.mjs";
3
3
  import { Receiving, webhookFed } from "../contract/receiving.mjs";
4
4
  import { answeredStatus, failingWhenUnanswered, isTransient, receivedFrom } from "../contract/transient.mjs";
5
5
  import { Effect, Predicate, Stream } from "effect";
@@ -1,14 +1,14 @@
1
- import { Anyone, principalOf } from "../contract/caller.mjs";
1
+ import { asCaller } from "../authentication/refusal.mjs";
2
2
  import { inputParseOptions } from "../contract/call.mjs";
3
- import { reported } from "../contract/reported.mjs";
4
- import { encodeUntaggedOf } from "../contract/occurrence.mjs";
5
- import { acquireFeeds, unkeyedHook } from "../contract/feed.mjs";
6
- import { NotServed, SubscriptionError, Unsupported } from "../Event.mjs";
3
+ import { principalOf } from "../contract/caller.mjs";
7
4
  import { sentError } from "../contract/codes.mjs";
8
- import { Webhooks, offersWebhook, servedWebhooks, webhookSubscriber } from "../contract/webhooks.mjs";
5
+ import { NotServed, SubscriptionError } from "../Event.mjs";
6
+ import { acquireFeeds } from "../contract/feed.mjs";
7
+ import { encodeUntaggedOf } from "../contract/occurrence.mjs";
9
8
  import { pushed, refusalIn } from "../contract/push.mjs";
10
- import { promote } from "../authentication/provider.mjs";
11
- import { recordStepUp } from "../authentication/refusal.mjs";
9
+ import { reported } from "../contract/reported.mjs";
10
+ import { deliveryUnsupported } from "../contract/subscribe.mjs";
11
+ import { Webhooks, offersWebhook, webhookSubscriber } from "../contract/webhooks.mjs";
12
12
  import { Active, EventsError, Failed, Heartbeat, Notifications, Occurred, Requests, Terminated, codes, extension, subscriptionIdKey } from "./events.mjs";
13
13
  import { isObjectSchema, toolJsonSchema } from "./protocol.mjs";
14
14
  import { Cause, Context, Duration, Effect, Exit, Match, Option, Predicate, Result, Schema } from "effect";
@@ -70,11 +70,6 @@ const servedOf = (feed, delivery) => {
70
70
  }
71
71
  };
72
72
  };
73
- const refuseUnservable = ({ events, authentication }) => authentication === void 0 ? Effect.void : Effect.flatMap(acquireFeeds(events), (feeds) => {
74
- const refusal = unkeyedHook("MCP", feeds, authentication.principal !== void 0);
75
- return refusal === void 0 ? Effect.void : Effect.die(new Error(refusal));
76
- });
77
- const serveWebhooks = (serving) => Effect.asVoid(Effect.flatMap(acquireFeeds(serving.events), (feeds) => servedWebhooks(feeds, serving.authentication)));
78
73
  const delivered = ({ send, clientId, requestId, wire, _meta: resultMeta }, run) => {
79
74
  const notify = (rpc, payload) => send("2026-07-28", clientId, {
80
75
  tag: rpc._tag,
@@ -135,7 +130,6 @@ const delivered = ({ send, clientId, requestId, wire, _meta: resultMeta }, run)
135
130
  };
136
131
  const withEvents = (base, serving) => {
137
132
  const { authentication } = serving;
138
- const asSubscriber = (event, run) => authentication === void 0 || event.caller === Anyone ? run : recordStepUp(promote(authentication, run));
139
133
  const installHandlers = (core, lifecycle, target) => Effect.gen(function* () {
140
134
  const feeds = yield* acquireFeeds(serving.events);
141
135
  const built = yield* Effect.context();
@@ -153,7 +147,7 @@ const withEvents = (base, serving) => {
153
147
  const found = served.get(name);
154
148
  return found === void 0 ? Effect.fail(new EventsError(sentError(SubscriptionError.of(name, new NotServed())))) : Effect.succeed(found);
155
149
  };
156
- const asWebhook = (feed, run) => Effect.catchCause(asSubscriber(feed.event, Effect.flatMap(webhookSubscriber(feed, authentication, webhooks), run)), (cause) => Effect.flatMap(wireErrorOf(cause), Effect.fail));
150
+ const asWebhook = (feed, run) => Effect.catchCause(asCaller(authentication, feed.event, Effect.flatMap(webhookSubscriber(feed, authentication, webhooks), run)), (cause) => Effect.flatMap(wireErrorOf(cause), Effect.fail));
157
151
  const fromBuilt = (handled) => Effect.updateContext(handled, (request) => Context.merge(built, request));
158
152
  const handlers = Requests.of({
159
153
  "events/list": () => Effect.map(meta, (_meta) => ({
@@ -166,7 +160,7 @@ const withEvents = (base, serving) => {
166
160
  const { feed, decode, wire } = yield* servedNamed(name);
167
161
  const input = yield* decode(args);
168
162
  const { page, events } = yield* Effect.gen(function* () {
169
- const polled = yield* asSubscriber(feed.event, Effect.flatMap(principalOf(feed.event, authentication), (subscriber) => feed.poll(input, cursor ?? null, {
163
+ const polled = yield* asCaller(authentication, feed.event, Effect.flatMap(principalOf(feed.event, authentication), (subscriber) => feed.poll(input, cursor ?? null, {
170
164
  subscriber,
171
165
  maxEvents
172
166
  })));
@@ -189,17 +183,14 @@ const withEvents = (base, serving) => {
189
183
  yield* routedTo(name);
190
184
  const { feed, decode, wire } = yield* servedNamed(name);
191
185
  const input = yield* decode(args);
192
- if (send === void 0) return yield* new EventsError(sentError(SubscriptionError.of(name, new Unsupported({
193
- feature: "deliveryMode",
194
- value: "push"
195
- }))));
186
+ if (send === void 0) return yield* new EventsError(sentError(deliveryUnsupported(name, "push")));
196
187
  return yield* delivered({
197
188
  send,
198
189
  clientId: client.id,
199
190
  requestId,
200
191
  wire,
201
192
  _meta: yield* meta
202
- }, (deliver) => asSubscriber(feed.event, Effect.flatMap(feed.stream(input), (open) => pushed(open, cursor ?? null, deliver, { positions: "heartbeat" }))));
193
+ }, (deliver) => asCaller(authentication, feed.event, Effect.flatMap(feed.stream(input), (open) => pushed(open, cursor ?? null, deliver, { positions: "heartbeat" }))));
203
194
  }).pipe(fromBuilt),
204
195
  "events/subscribe": ({ name, arguments: args, delivery: { url, secret }, cursor, ttlMs }) => Effect.gen(function* () {
205
196
  yield* routedTo(name);
@@ -259,4 +250,4 @@ const withEvents = (base, serving) => {
259
250
  installHandlers
260
251
  };
261
252
  };
262
- export { eventSchemasOf, refuseUnservable, serveWebhooks, withEvents };
253
+ export { eventSchemasOf, withEvents };