@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
@@ -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,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 { eventsOf, feedBuilders, selectEvents } from "./feed.mjs";
3
- import { Implementation, assertHeld, markingOthers, notHeld, provideBuilders, select, servedBy, toList } from "./implementation.mjs";
2
+ import { EventImplementation, eventKind, eventsOf } from "./feed.mjs";
3
+ import { Implementation, actionKind, assertHeld, markingOthers, notHeld, provideBuilders, select, toList } from "./implementation.mjs";
4
4
  import { selection } from "./listed.mjs";
5
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
1
  import { CallbackUrl, WebhookSecret } from "./callback.mjs";
2
- import { CallbackCategory } from "../Event.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 };
@@ -0,0 +1,9 @@
1
+ import { Context } from "effect";
2
+ // src/contract/wake.ts
3
+ /**
4
+ * How an entity's activation waits until a time, which `ActionEntity.layer` provides to its
5
+ * `services`: a wait that builds a stopped activation again when it is due, where a timer is cut
6
+ * by Effect's reaper and keeps a Durable Object awake. Absent outside an entity.
7
+ */
8
+ var Wake = class extends Context.Service()("effect-actions/Wake") {};
9
+ export { Wake };
@@ -1,9 +1,10 @@
1
1
  import { CallbackUrl } from "./callback.mjs";
2
- import { SubscriptionError, Unsupported } from "../Event.mjs";
2
+ import { SubscriptionError } from "../Event.mjs";
3
3
  import { Checked, Gap } from "./occurrence.mjs";
4
4
  import { paged } from "./pages.mjs";
5
5
  import { watchParameter } from "./receiving.mjs";
6
6
  import { makeRecent } from "./recent.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,9 +12,21 @@ 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
+ const reconnecting = (transient, open, cursor, polled) => {
16
+ let at = cursor;
17
+ const once = Stream.suspend(() => open(at)).pipe(Stream.tap((fed) => Effect.sync(() => {
18
+ at = fed.cursor ?? at;
19
+ })));
20
+ const reopened = transient === void 0 ? once : once.pipe(Stream.repeat(Schedule.spaced(reconnectDelay)), Stream.retry(afterFailures(transient)));
21
+ return polled === void 0 ? reopened : reopened.pipe(Stream.catchIf(pushRefused, () => Stream.suspend(() => polled(at))));
22
+ };
23
+ const closeTimeout = Duration.seconds(5);
24
+ const closing = (closed) => closed.pipe(Effect.timeout(closeTimeout), Effect.ignore({ log: "Debug" }));
25
+ const polling = ({ poll }, transient) => (cursor) => Stream.suspend(() => {
26
+ const watch = globalThis.crypto.randomUUID();
27
+ return reconnecting(transient, (at) => paged((from) => poll(from, watch), at), cursor);
28
+ });
15
29
  const capacity = 16;
16
- const unsubscribeTimeout = Duration.seconds(5);
17
30
  const delivered = (webhook, request, received, cursor) => {
18
31
  let at = cursor;
19
32
  const subscribed = Effect.suspend(() => webhook.subscribe({
@@ -30,22 +43,11 @@ const delivered = (webhook, request, received, cursor) => {
30
43
  }));
31
44
  };
32
45
  const watching = (transport, { cursor: given, mode, resume } = {}) => {
33
- const reconnecting = (open, cursor, polled) => {
34
- const { transient } = transport;
35
- let at = cursor;
36
- const once = Stream.suspend(() => open(at)).pipe(Stream.tap((fed) => Effect.sync(() => {
37
- at = fed.cursor ?? at;
38
- })));
39
- const reopened = transient === void 0 ? once : once.pipe(Stream.repeat(Schedule.spaced(reconnectDelay)), Stream.retry(afterFailures(transient)));
40
- return polled === void 0 ? reopened : reopened.pipe(Stream.catchIf(pushRefused, () => Stream.suspend(() => polled(at))));
41
- };
42
- const polled = (cursor) => reconnecting((at) => paged(transport.poll, at), cursor);
46
+ const { transient } = transport;
47
+ const polled = polling(transport, transient);
43
48
  const webhooked = ({ baseUrl, ttl }, cursor) => Stream.unwrap(Effect.gen(function* () {
44
49
  const { webhook } = transport;
45
- if (webhook === void 0) return yield* SubscriptionError.of(transport.name, new Unsupported({
46
- feature: "deliveryMode",
47
- value: "webhook"
48
- }));
50
+ if (webhook === void 0) return yield* deliveryUnsupported(transport.name, "webhook");
49
51
  const base = yield* Schema.decodeEffect(CallbackUrl)(baseUrl);
50
52
  const receiving = yield* webhook.receiver;
51
53
  const received = yield* Queue.unbounded();
@@ -59,11 +61,11 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
59
61
  },
60
62
  ttlMs: ttl === void 0 ? void 0 : Duration.toMillis(Duration.fromInputUnsafe(ttl))
61
63
  };
62
- yield* Effect.addFinalizer(() => webhook.unsubscribe({ delivery: { url } }).pipe(Effect.timeout(unsubscribeTimeout), Effect.ignore));
63
- return reconnecting((at) => delivered(webhook, request, received, at), cursor);
64
+ yield* Effect.addFinalizer(() => closing(webhook.unsubscribe({ delivery: { url } })));
65
+ return reconnecting(transient, (at) => delivered(webhook, request, received, at), cursor);
64
66
  }));
65
67
  return Stream.suspend(() => {
66
- const seen = makeRecent(dedupeWindow);
68
+ const seen = makeRecent();
67
69
  let keptOnNextPull = null;
68
70
  const keep = (cursor) => cursor === null || resume === void 0 ? Effect.void : resume.store.set(resume.key, cursor);
69
71
  const fresh = (eventId) => {
@@ -86,8 +88,8 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
86
88
  return Stream.unwrap(Effect.map(start, (cursor) => {
87
89
  if (Predicate.isTagged(mode, "WebhookDelivery")) return webhooked(mode, cursor);
88
90
  if (mode === "poll") return polled(cursor);
89
- return reconnecting(transport.stream, cursor, mode === "stream" ? void 0 : polled);
91
+ return reconnecting(transient, transport.stream, cursor, mode === "stream" ? void 0 : polled);
90
92
  })).pipe(Stream.rechunk(1), Stream.mapEffect(handled), Stream.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.concat(Stream.fromEffectDrain(keep(keptOnNextPull)), Stream.failCause(cause))), Stream.flattenIterable);
91
93
  });
92
94
  };
93
- export { watching };
95
+ export { polling, watching };
@@ -1,4 +1,4 @@
1
- import { Anyone, Named } from "./caller.mjs";
1
+ import { Anyone, Keyed } from "./caller.mjs";
2
2
  import { Any } from "../Event.mjs";
3
3
  import { Feed } from "./feed.mjs";
4
4
  import { AnyWebhookCancellation, AnyWebhookSubscription, Subscribed } from "./subscribe.mjs";
@@ -23,20 +23,24 @@ export interface Subscription extends AnyWebhookCancellation {
23
23
  export interface Subscribing extends AnyWebhookSubscription {
24
24
  readonly feed: WebhookFeed;
25
25
  readonly principal: string;
26
- readonly keyed: Named;
26
+ readonly keyed: Keyed;
27
27
  }
28
28
  declare const Webhooks_base: Context.ServiceClass<Webhooks, "effect-actions/Webhooks", {
29
- readonly serve: (feeds: readonly WebhookFeed[], keyed: Named) => Effect.Effect<void, never, unknown>;
29
+ readonly serve: (feeds: readonly WebhookFeed[], keyed: Keyed) => Effect.Effect<void, never, unknown>;
30
30
  readonly subscribe: (subscribing: Subscribing) => Effect.Effect<Subscribed, unknown, unknown>;
31
31
  readonly unsubscribe: (subscription: Subscription) => Effect.Effect<void, unknown, unknown>;
32
32
  }>;
33
33
  /**
34
34
  * Where a surface's webhook subscriptions are held and delivered from: `Webhook.layer` provides
35
- * it, and a surface offers webhook delivery only where it is. A surface `serve`s the feeds it
35
+ * it, and a surface offers webhook delivery of its own events only where it is, and of a
36
+ * protected event `ActionEntity.reaching` serves, held by the entity reached, which refuses
37
+ * a subscription as `Unsupported` where it holds no `Webhook.layer`. A surface `serve`s the feeds it
36
38
  * offers by webhook as it builds, with its authentication, which restores their kept
37
39
  * subscriptions, and dies where they cannot be kept. `subscribe` runs as the subscriber, whose
38
40
  * context each delivery runs in; it fails as the feed's admission does, or with
39
41
  * `Event.SubscriptionError`.
40
42
  */
41
43
  export declare class Webhooks extends Webhooks_base {}
44
+ /** Subscribes and unsubscribes a feed's webhooks where they are held. */
45
+ export type WebhookHolder = Pick<Webhooks["Service"], "subscribe" | "unsubscribe">;
42
46
  export {};
@@ -1,42 +1,64 @@
1
- import { Anyone, isNamed } from "./caller.mjs";
2
- import { SubscriptionError, Unsupported } from "../Event.mjs";
1
+ import { Anyone } from "./caller.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
  /**
6
7
  * Where a surface's webhook subscriptions are held and delivered from: `Webhook.layer` provides
7
- * it, and a surface offers webhook delivery only where it is. A surface `serve`s the feeds it
8
+ * it, and a surface offers webhook delivery of its own events only where it is, and of a
9
+ * protected event `ActionEntity.reaching` serves, held by the entity reached, which refuses
10
+ * a subscription as `Unsupported` where it holds no `Webhook.layer`. A surface `serve`s the feeds it
8
11
  * offers by webhook as it builds, with its authentication, which restores their kept
9
12
  * subscriptions, and dies where they cannot be kept. `subscribe` runs as the subscriber, whose
10
13
  * context each delivery runs in; it fails as the feed's admission does, or with
11
14
  * `Event.SubscriptionError`.
12
15
  */
13
16
  var Webhooks = class extends Context.Service()("effect-actions/Webhooks") {};
14
- const isProtected = (event) => event.caller !== Anyone;
15
- const offersWebhook = (event, keyed) => isProtected(event) && isNamed(keyed);
16
- const servedWebhooks = (feeds, keyed) => Effect.gen(function* () {
17
+ /** Whether a surface offers `event` by webhook: a protected one, its caller an identity. */
18
+ const offersWebhook = (event) => event.caller !== Anyone;
19
+ const offeredByWebhook = (feed) => offersWebhook(feed.event);
20
+ const deliversByWebhook = (feed) => feed.webhook === void 0 && offeredByWebhook(feed);
21
+ /**
22
+ * Who subscribes to `feed`'s webhooks, and where they are held: the holder the feed names, a
23
+ * reached entity, or else the surface's own `Webhooks`; none where the event is not offered by
24
+ * webhook. Its principal is read from the caller each time it runs.
25
+ */
26
+ const webhookSubscriber = (feed, keyed, webhooks) => keyed !== void 0 && offeredByWebhook(feed) ? Option.map(feed.webhook === void 0 ? webhooks : Option.some(feed.webhook), (holder) => Effect.map(Effect.service(feed.event.caller), (identity) => ({
27
+ webhooks: holder,
28
+ feed,
29
+ keyed,
30
+ principal: keyed.principal(identity)
31
+ }))) : Option.none();
32
+ /** As `webhookSubscriber`, failing as `Unsupported` where the event is not offered by webhook. */
33
+ const subscriberOf = (feed, keyed, webhooks) => Option.getOrElse(webhookSubscriber(feed, keyed, webhooks), () => Effect.fail(deliveryUnsupported(feed.event.name, "webhook")));
34
+ /** A surface's answers to a webhook subscribe and unsubscribe of `feed`, run as its subscriber. */
35
+ const webhookAnswers = (feed, keyed, webhooks) => {
36
+ const served = subscriberOf(feed, keyed, webhooks);
37
+ return {
38
+ subscribe: (payload) => Effect.flatMap(served, ({ webhooks: holder, ...subscriber }) => holder.subscribe({
39
+ ...payload,
40
+ ...subscriber
41
+ })),
42
+ unsubscribe: (payload) => Effect.flatMap(served, ({ webhooks: holder, feed: subscribed, principal }) => holder.unsubscribe({
43
+ ...payload,
44
+ feed: subscribed,
45
+ principal
46
+ }))
47
+ };
48
+ };
49
+ /**
50
+ * The feeds of `events` a surface's layer serves, and the `Webhooks` it offers them by: run as
51
+ * the layer builds, which serves the webhooks it delivers itself, those of the feeds `holds`
52
+ * admits, and restores their kept subscriptions.
53
+ */
54
+ const servingFeeds = Effect.fnUntraced(function* (events, keyed, holds = () => true) {
55
+ const feeds = yield* acquireFeeds(events);
17
56
  const webhooks = yield* Effect.serviceOption(Webhooks);
18
- const offered = feeds.filter((feed) => offersWebhook(feed.event, keyed));
19
- if (Option.isSome(webhooks) && isNamed(keyed)) yield* webhooks.value.serve(offered, keyed);
57
+ const delivered = feeds.filter(deliversByWebhook).filter(holds);
58
+ if (Option.isSome(webhooks) && keyed !== void 0) yield* webhooks.value.serve(delivered, keyed);
20
59
  return {
21
- webhooks,
22
- offered
60
+ feeds,
61
+ webhooks
23
62
  };
24
63
  });
25
- const webhookSubscriber = (feed, keyed, webhooks) => {
26
- 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
- })));
31
- const service = webhooks.value;
32
- return Effect.map(Effect.service(event.caller), (identity) => ({
33
- webhooks: service,
34
- feed: {
35
- ...feed,
36
- event
37
- },
38
- keyed,
39
- principal: keyed.principal(identity)
40
- }));
41
- };
42
- export { Webhooks, offersWebhook, servedWebhooks, webhookSubscriber };
64
+ export { Webhooks, offersWebhook, servingFeeds, subscriberOf, webhookAnswers, webhookSubscriber };
@@ -0,0 +1,11 @@
1
+ import { Effect } from "effect";
2
+ import { Headers } from "effect/http";
3
+ /**
4
+ * The headers of a request that a call into an entity carries, their names lowercased: every
5
+ * one but its connection's (`host`, `connection`, `keep-alive`, `te`, `trailer`,
6
+ * `transfer-encoding`, `upgrade`), its body's (`content-*`), what it accepts (`accept*`), a
7
+ * proxy's (`proxy-*`), a WebSocket upgrade's (`sec-websocket-*`) and an MCP request's routing
8
+ * headers (`mcp-*`). `reaching` sends these of the caller's request, and the Cloudflare
9
+ * package's socket host keeps these of a page's upgrade.
10
+ */
11
+ export declare const forwardedHeaders: (headers: Headers.Input) => Headers.Headers;
@@ -0,0 +1,32 @@
1
+ import { Effect, Option } from "effect";
2
+ import { Headers, HttpServerRequest } from "effect/http";
3
+ // src/entity/forwarded.ts
4
+ const ownedByTheRequest = (name) => [
5
+ "host",
6
+ "connection",
7
+ "keep-alive",
8
+ "te",
9
+ "trailer",
10
+ "transfer-encoding",
11
+ "upgrade"
12
+ ].includes(name) || [
13
+ "content-",
14
+ "accept",
15
+ "proxy-",
16
+ "sec-websocket-",
17
+ "mcp-"
18
+ ].some((family) => name.startsWith(family));
19
+ /**
20
+ * The headers of a request that a call into an entity carries, their names lowercased: every
21
+ * one but its connection's (`host`, `connection`, `keep-alive`, `te`, `trailer`,
22
+ * `transfer-encoding`, `upgrade`), its body's (`content-*`), what it accepts (`accept*`), a
23
+ * proxy's (`proxy-*`), a WebSocket upgrade's (`sec-websocket-*`) and an MCP request's routing
24
+ * headers (`mcp-*`). `reaching` sends these of the caller's request, and the Cloudflare
25
+ * package's socket host keeps these of a page's upgrade.
26
+ */
27
+ const forwardedHeaders = (headers) => Headers.fromInput(Object.entries(Headers.fromInput(headers)).filter(([name]) => !ownedByTheRequest(name)));
28
+ const forwarded = Effect.map(Effect.serviceOption(HttpServerRequest.HttpServerRequest), Option.match({
29
+ onNone: () => Headers.empty,
30
+ onSome: ({ headers }) => forwardedHeaders(headers)
31
+ }));
32
+ export { forwarded, forwardedHeaders };
@@ -0,0 +1,39 @@
1
+ import { reported } from "../contract/reported.mjs";
2
+ import { Wake } from "../contract/wake.mjs";
3
+ import { Clock, DateTime, Duration, Effect, Exit, Latch, Schema } from "effect";
4
+ import { ClusterSchema, DeliverAt } from "effect/cluster";
5
+ import { Rpc } from "effect/rpc";
6
+ // src/entity/wakes.ts
7
+ const wakeTag = "effect-actions/wake";
8
+ var WakeAt = class extends Schema.Class("effect-actions/ActionEntity/WakeAt")({ at: Schema.Int }) {
9
+ [DeliverAt.symbol]() {
10
+ return DateTime.makeUnsafe(this.at);
11
+ }
12
+ };
13
+ const WakeRpc = Rpc.make(wakeTag, { payload: WakeAt }).annotate(ClusterSchema.Persisted, true);
14
+ const makeWake = (send) => Effect.map(Clock.Clock, (clock) => {
15
+ const waiting = /* @__PURE__ */ new Set();
16
+ const sent = /* @__PURE__ */ new Set();
17
+ const slept = (at) => clock.sleep(Duration.millis(Math.max(at - clock.currentTimeMillisUnsafe(), 0)));
18
+ const until = (at) => Effect.suspend(() => {
19
+ const waiter = {
20
+ at,
21
+ woken: Latch.makeUnsafe()
22
+ };
23
+ waiting.add(waiter);
24
+ return Effect.raceFirst(waiter.woken.await, sent.has(at) ? Effect.never : Effect.uninterruptible(Effect.exit(Effect.tap(send(new WakeAt({ at })), () => Effect.sync(() => sent.add(at))))).pipe(Effect.flatMap(Exit.match({
25
+ onSuccess: () => Effect.never,
26
+ onFailure: (cause) => Effect.andThen(reported(cause), slept(at))
27
+ })))).pipe(Effect.ensuring(Effect.sync(() => {
28
+ waiting.delete(waiter);
29
+ })));
30
+ });
31
+ return {
32
+ wake: Wake.of({ until }),
33
+ woke: ({ payload }) => Rpc.fork(Effect.sync(() => {
34
+ for (const each of sent) if (each <= payload.at) sent.delete(each);
35
+ for (const waiter of waiting) if (waiter.at <= payload.at) waiter.woken.openUnsafe();
36
+ }))
37
+ };
38
+ });
39
+ export { WakeRpc, makeWake, wakeTag };
@@ -1,5 +1,5 @@
1
- import { checked, checkedStream, sendingValue, watchInput } from "../contract/call.mjs";
2
- import { elementOf } from "../contract/stream.mjs";
1
+ import { checked, checkedStream, sendingValue, sentInput } 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);
@@ -46,7 +48,7 @@ const sendersWith = (http, httpClient, baseUrl) => Effect.gen(function* () {
46
48
  const methodsWith = (http, httpClient, baseUrl) => Effect.map(sendersWith(http, httpClient, baseUrl), ({ method, transport }) => {
47
49
  const actions = Object.fromEntries(http.actions.map((action) => [action.name, method(action)]));
48
50
  if (http.events.length === 0) return actions;
49
- const watch = (event, input, options) => Stream.unwrap(Effect.map(watchInput(event, input), ({ value }) => watching(transport(event, value), options)));
51
+ const watch = (event, input, options) => Stream.unwrap(Effect.map(sentInput(event, input), ({ value }) => watching(transport(event, value), options)));
50
52
  return {
51
53
  ...actions,
52
54
  watch
@@ -7,19 +7,8 @@ import "../Action.mjs";
7
7
  import { Any } from "../Event.mjs";
8
8
  import "../contract/feed.mjs";
9
9
  import "../contract/push.mjs";
10
- import "../contract/subscribe.mjs";
11
- import "../contract/webhooks.mjs";
12
- import { Effect, Option, Schema, Stream } from "effect";
10
+ import { Effect, Schema, Stream } from "effect";
13
11
  import { HttpApiEndpoint, HttpApiSchema } from "effect/http-api";
14
- export declare const pageOf: <E extends Any>(event: E) => Schema.encodeKeys<Schema.Struct<{
15
- readonly events: Schema.$Array<OccurrenceSchema<E>>;
16
- readonly cursor: Schema.NullOr<Schema.String>;
17
- readonly truncated: Schema.Boolean;
18
- readonly hasMore: Schema.Boolean;
19
- readonly nextPoll: Schema.DurationFromMillis;
20
- }>, {
21
- readonly nextPoll: "nextPollMs";
22
- }>;
23
12
  export declare const sentOf: <E extends Any>(event: E) => HttpApiSchema.StreamSse<HttpApiSchema.SseEventFromData<Schema.Union<readonly [OccurrenceSchema<E>, Schema.TaggedStruct<"Gap", {
24
13
  readonly cursor: Schema.NullOr<Schema.String>;
25
14
  }>, Schema.TaggedStruct<"Checked", {
@@ -2,22 +2,15 @@ import { principalOf } from "../contract/caller.mjs";
2
2
  import { assertDistinctTags } from "../contract/declared.mjs";
3
3
  import { Refusal } from "../contract/errors.mjs";
4
4
  import { SubscriptionError } from "../Event.mjs";
5
- import { OccurrenceOf } from "../contract/occurrence.mjs";
5
+ import { pageOf } from "../contract/pages.mjs";
6
6
  import { PushedOf, SubscriptionOf, queuedPush } from "../contract/push.mjs";
7
7
  import { declared } from "../contract/status.mjs";
8
8
  import { Subscribed, WebhookCancellationOf, WebhookSubscriptionOf } from "../contract/subscribe.mjs";
9
- import { webhookSubscriber } from "../contract/webhooks.mjs";
9
+ import { acceptsEventStream } from "./streamed.mjs";
10
10
  import { Effect, Function, Schema, Stream } from "effect";
11
11
  import { HttpServerRequest } from "effect/http";
12
12
  import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api";
13
13
  // src/http/events.ts
14
- const pageOf = (event) => Schema.Struct({
15
- events: Schema.Array(OccurrenceOf(event)),
16
- cursor: Schema.NullOr(Schema.String),
17
- truncated: Schema.Boolean,
18
- hasMore: Schema.Boolean,
19
- nextPoll: Schema.DurationFromMillis
20
- }).pipe(Schema.encodeKeys({ nextPoll: "nextPollMs" }));
21
14
  const sentOf = (event) => HttpApiSchema.StreamSse({
22
15
  data: PushedOf(event),
23
16
  error: Refusal
@@ -45,24 +38,11 @@ const webhookEndpointsOf = (event, path, errors) => {
45
38
  error
46
39
  }).annotate(OpenApi.Description, `Stop delivering ${event.name} to a webhook.`)];
47
40
  };
48
- const webhookAnswers = (feed, authentication, webhooks) => {
49
- const served = webhookSubscriber(feed, authentication, webhooks);
50
- return {
51
- subscribe: ({ payload }) => Effect.flatMap(served, ({ webhooks: service, ...subscriber }) => service.subscribe({
52
- ...payload,
53
- ...subscriber
54
- })),
55
- unsubscribe: ({ payload }) => Effect.flatMap(served, ({ webhooks: service, feed: subscribed, principal }) => service.unsubscribe({
56
- ...payload,
57
- feed: subscribed,
58
- principal
59
- }))
60
- };
61
- };
62
41
  const answering = (feed, authentication) => {
63
42
  const encode = Schema.encodeEffect(Schema.toCodecJson(PushedOf(feed.event)));
64
43
  return ({ payload: { input, cursor } }) => Effect.gen(function* () {
65
- if (((yield* HttpServerRequest.HttpServerRequest).headers["accept"] ?? "").includes("text/event-stream")) {
44
+ const request = yield* HttpServerRequest.HttpServerRequest;
45
+ if (acceptsEventStream(request)) {
66
46
  const open = yield* feed.stream(input);
67
47
  return Stream.fromQueue(yield* queuedPush(open, cursor, encode, {
68
48
  ending: Function.identity,
@@ -73,4 +53,4 @@ const answering = (feed, authentication) => {
73
53
  return yield* feed.poll(input, cursor, { subscriber });
74
54
  });
75
55
  };
76
- export { answering, eventEndpointOf, pageOf, sentOf, servedSent, webhookAnswers, webhookEndpointsOf };
56
+ export { answering, eventEndpointOf, sentOf, servedSent, webhookEndpointsOf };
@@ -0,0 +1,9 @@
1
+ import { Function, Match } from "effect";
2
+ // src/http/redacted.ts
3
+ /**
4
+ * Where an API key scheme sends its credential, for `HttpApi.RedactedNames`: a span records a
5
+ * request's query, and a header that the host's `TracerHeaderFilter` admits, as sent unless it
6
+ * is named there or by Effect's defaults, which already cover `Authorization` and `Cookie`.
7
+ */
8
+ const credentialNames = (authentication) => authentication === void 0 ? {} : Match.value(authentication.security).pipe(Match.tag("ApiKey", ({ in: placement, key }) => Match.value(placement).pipe(Match.when("query", () => ({ query: [key] })), Match.when("header", () => ({ headers: [key] })), Match.when("cookie", Function.constant({})), Match.exhaustive)), Match.tag("Http", "Basic", Function.constant({})), Match.exhaustive);
9
+ export { credentialNames };
@@ -4,6 +4,7 @@ import { ErasedValue } from "../contract/implementation.mjs";
4
4
  import "../contract/progress.mjs";
5
5
  import { StreamOf } from "../contract/stream.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";