foldkit-primitives 0.9.0 → 0.10.1
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.
- package/README.md +31 -1
- package/dist/device/index.d.mts +69 -36
- package/dist/device/index.d.mts.map +1 -1
- package/dist/device/index.mjs +34 -34
- package/dist/device/index.mjs.map +1 -1
- package/dist/dom/index.d.mts +68 -19
- package/dist/dom/index.d.mts.map +1 -1
- package/dist/dom/index.mjs +32 -25
- package/dist/dom/index.mjs.map +1 -1
- package/dist/{editable-text-BbsPOATY.d.mts → editable-text-Dvm-Fuqs.d.mts} +65 -3
- package/dist/editable-text-Dvm-Fuqs.d.mts.map +1 -0
- package/dist/events/index.d.mts +52 -31
- package/dist/events/index.d.mts.map +1 -1
- package/dist/events/index.mjs +40 -28
- package/dist/events/index.mjs.map +1 -1
- package/dist/{follow-tab-stop-BDxyoUPQ.mjs → follow-tab-stop-Ci1tqAIW.mjs} +63 -61
- package/dist/follow-tab-stop-Ci1tqAIW.mjs.map +1 -0
- package/dist/{index-Cppf-lBx.d.mts → index-CmmxqSEi.d.mts} +34 -15
- package/dist/index-CmmxqSEi.d.mts.map +1 -0
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +3 -3
- package/dist/{input-modality-m6v7__Xs.mjs → input-modality-BXD383jg.mjs} +9 -9
- package/dist/input-modality-BXD383jg.mjs.map +1 -0
- package/dist/{input-modality-DGOhAknO.d.mts → input-modality-BY-bSrEc.d.mts} +9 -2
- package/dist/input-modality-BY-bSrEc.d.mts.map +1 -0
- package/dist/interaction/index.d.mts +118 -118
- package/dist/interaction/index.d.mts.map +1 -1
- package/dist/interaction/index.mjs +3 -3
- package/dist/interaction/index.mjs.map +1 -1
- package/dist/media/index.d.mts +24 -3
- package/dist/media/index.d.mts.map +1 -1
- package/dist/media/index.mjs +23 -13
- package/dist/media/index.mjs.map +1 -1
- package/dist/motion/index.d.mts +1 -1
- package/dist/motion/index.mjs +1 -2
- package/dist/{motion-DGGBZ0wt.mjs → motion-DmFDppRn.mjs} +20 -20
- package/dist/{motion-DGGBZ0wt.mjs.map → motion-DmFDppRn.mjs.map} +1 -1
- package/dist/net/index.d.mts +63 -25
- package/dist/net/index.d.mts.map +1 -1
- package/dist/net/index.mjs +31 -31
- package/dist/net/index.mjs.map +1 -1
- package/dist/observers/index.d.mts +25 -0
- package/dist/observers/index.d.mts.map +1 -1
- package/dist/observers/index.mjs +22 -22
- package/dist/observers/index.mjs.map +1 -1
- package/dist/state/index.d.mts +98 -44
- package/dist/state/index.d.mts.map +1 -1
- package/dist/state/index.mjs +39 -39
- package/dist/state/index.mjs.map +1 -1
- package/dist/time/index.d.mts +35 -5
- package/dist/time/index.d.mts.map +1 -1
- package/dist/time/index.mjs +20 -20
- package/dist/time/index.mjs.map +1 -1
- package/package.json +14 -14
- package/dist/editable-text-BbsPOATY.d.mts.map +0 -1
- package/dist/follow-tab-stop-BDxyoUPQ.mjs.map +0 -1
- package/dist/index-Cppf-lBx.d.mts.map +0 -1
- package/dist/input-modality-DGOhAknO.d.mts.map +0 -1
- package/dist/input-modality-m6v7__Xs.mjs.map +0 -1
package/dist/net/index.mjs
CHANGED
|
@@ -73,38 +73,27 @@ const postBroadcast = (name, data, create) => ({
|
|
|
73
73
|
});
|
|
74
74
|
//#endregion
|
|
75
75
|
//#region src/net/online.ts
|
|
76
|
-
/**
|
|
77
|
-
* Online presence as a bundle: `online` in the Model, kept current by the
|
|
78
|
-
* window's online/offline events. The browser reports facts; the Model owns
|
|
79
|
-
* the state, so presence replays like any other transition.
|
|
80
|
-
*/
|
|
81
76
|
const OnlineModel = Schema.Struct({ online: Schema.Boolean });
|
|
82
77
|
const OnlineMessage = defineMessageUnion({ Changed: { online: Schema.Boolean } });
|
|
83
78
|
const presenceStream = () => {
|
|
84
79
|
if (typeof window === "undefined") return Stream.empty;
|
|
85
80
|
return Stream.mergeAll([Stream.fromEventListener(window, "online").pipe(Stream.map(() => OnlineMessage.Changed({ online: true }))), Stream.fromEventListener(window, "offline").pipe(Stream.map(() => OnlineMessage.Changed({ online: false })))], { concurrency: "unbounded" });
|
|
86
81
|
};
|
|
82
|
+
/**
|
|
83
|
+
* Online presence as a bundle: `online` in the Model, kept current by the
|
|
84
|
+
* window's online/offline events. The browser reports facts; the Model owns
|
|
85
|
+
* the state, so presence replays like any other transition.
|
|
86
|
+
*/
|
|
87
87
|
const Online = Bundle.make("Online", {
|
|
88
88
|
Model: OnlineModel,
|
|
89
89
|
Message: OnlineMessage,
|
|
90
90
|
init: () => ({ model: { online: typeof navigator !== "undefined" && typeof navigator.onLine === "boolean" ? navigator.onLine : true } }),
|
|
91
91
|
update: (model, message) => message.online === model.online ? { model } : { model: { online: message.online } },
|
|
92
|
-
subscriptions: () => Subscription.make()(() => ({ changes: Subscription.
|
|
92
|
+
subscriptions: () => Subscription.make()(() => ({ changes: Subscription.persistentEntry(presenceStream()) }))
|
|
93
93
|
});
|
|
94
94
|
//#endregion
|
|
95
95
|
//#region src/net/sharedHost.ts
|
|
96
96
|
/**
|
|
97
|
-
* One server in the browser for many documents: every tab and frame of an
|
|
98
|
-
* application meets the same host. A page opens conversations, each a
|
|
99
|
-
* `MessagePort` with a decoded opening that says what it is for; the host, in
|
|
100
|
-
* a SharedWorker shared by every tab, or in the top document where there is no
|
|
101
|
-
* SharedWorker, is handed each one with a signal that aborts when the page
|
|
102
|
-
* that opened it is gone.
|
|
103
|
-
*
|
|
104
|
-
* It owns the host's lifetime and the routing of conversations, nothing
|
|
105
|
-
* spoken over them: Sync's `portSocket` and Remote's `port` do that.
|
|
106
|
-
*/
|
|
107
|
-
/**
|
|
108
97
|
* A shared host: its `name`, which keeps two on one origin apart, and
|
|
109
98
|
* the schema of what opens a conversation, which the host decodes before
|
|
110
99
|
* anything else, ignoring a message that does not decode.
|
|
@@ -211,15 +200,20 @@ const hold = (lock) => Option.match(locks(), {
|
|
|
211
200
|
});
|
|
212
201
|
/** Web Locks, which a page outside a secure context, or an older browser, lacks. */
|
|
213
202
|
const locks = () => Option.fromUndefinedOr(navigator.locks);
|
|
203
|
+
/**
|
|
204
|
+
* One server in the browser for many documents: every tab and frame of an
|
|
205
|
+
* application meets the same host. A page opens conversations, each a
|
|
206
|
+
* `MessagePort` with a decoded opening that says what it is for; the host, in
|
|
207
|
+
* a SharedWorker shared by every tab, or in the top document where there is no
|
|
208
|
+
* SharedWorker, is handed each one with a signal that aborts when the page
|
|
209
|
+
* that opened it is gone.
|
|
210
|
+
*
|
|
211
|
+
* It owns the host's lifetime and the routing of conversations, nothing
|
|
212
|
+
* spoken over them: Sync's `portSocket` and Remote's `port` do that.
|
|
213
|
+
*/
|
|
214
214
|
const SharedHost = { define };
|
|
215
215
|
//#endregion
|
|
216
216
|
//#region src/net/sse.ts
|
|
217
|
-
/**
|
|
218
|
-
* Server-sent events as a bundle: connection lifecycle in the Model, the
|
|
219
|
-
* event stream through one Managed Resource. One-directional, so there is no
|
|
220
|
-
* send: the server speaks, the Model listens. The browser reconnects dropped
|
|
221
|
-
* streams itself; a Failed only records the error.
|
|
222
|
-
*/
|
|
223
217
|
const SseModel = Schema.Struct({
|
|
224
218
|
url: Schema.String,
|
|
225
219
|
status: Schema.Literals([
|
|
@@ -268,6 +262,12 @@ const viewOfSse = (model, wanted) => {
|
|
|
268
262
|
/** The live stream, for the incoming subscription. One assembly holds one. */
|
|
269
263
|
const Source = ManagedResource.tag()("sse");
|
|
270
264
|
const failMessage$1 = (error) => error instanceof Error ? error.message : String(error);
|
|
265
|
+
/**
|
|
266
|
+
* Server-sent events as a bundle: connection lifecycle in the Model, the
|
|
267
|
+
* event stream through one Managed Resource. One-directional, so there is no
|
|
268
|
+
* send: the server speaks, the Model listens. The browser reconnects dropped
|
|
269
|
+
* streams itself; a Failed only records the error.
|
|
270
|
+
*/
|
|
271
271
|
const sse = (config) => {
|
|
272
272
|
const createSource = config.createSource ?? ((url) => new EventSource(url));
|
|
273
273
|
return Bundle.make(config.name, {
|
|
@@ -341,14 +341,6 @@ const sse = (config) => {
|
|
|
341
341
|
};
|
|
342
342
|
//#endregion
|
|
343
343
|
//#region src/net/websocket.ts
|
|
344
|
-
/**
|
|
345
|
-
* A WebSocket as a bundle: connection lifecycle in the Model, full duplex
|
|
346
|
-
* through one Managed Resource. The resource owns the socket; a `send`
|
|
347
|
-
* helper writes through its tag service (lifted to the parent like every
|
|
348
|
-
* helper); a subscription stream reads incoming messages through the same
|
|
349
|
-
* tag. No hidden hub: everything the bundle touches is the Model, the
|
|
350
|
-
* resource registry, or a Message.
|
|
351
|
-
*/
|
|
352
344
|
const WebSocketModel = Schema.Struct({
|
|
353
345
|
url: Schema.String,
|
|
354
346
|
status: Schema.Literals([
|
|
@@ -414,6 +406,14 @@ const closeSilently = (socket) => {
|
|
|
414
406
|
socket.close();
|
|
415
407
|
};
|
|
416
408
|
const failMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
409
|
+
/**
|
|
410
|
+
* A WebSocket as a bundle: connection lifecycle in the Model, full duplex
|
|
411
|
+
* through one Managed Resource. The resource owns the socket; a `send`
|
|
412
|
+
* helper writes through its tag service (lifted to the parent like every
|
|
413
|
+
* helper); a subscription stream reads incoming messages through the same
|
|
414
|
+
* tag. No hidden hub: everything the bundle touches is the Model, the
|
|
415
|
+
* resource registry, or a Message.
|
|
416
|
+
*/
|
|
417
417
|
const websocket = (config) => {
|
|
418
418
|
const createSocket = config.createSocket ?? ((url) => new WebSocket(url));
|
|
419
419
|
return Bundle.make(config.name, {
|
package/dist/net/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["failMessage","failMessage"],"sources":["../../src/net/broadcast.ts","../../src/net/online.ts","../../src/net/sharedHost.ts","../../src/net/sse.ts","../../src/net/websocket.ts"],"sourcesContent":["/**\n * Cross-tab messaging as an entry plus a Command — not a bundle, because the\n * channel owns no state: the parent maps `Received` into its own Message and\n * stores whatever it keeps. One assembly may open the same name twice (two\n * listeners); share the entry instead. By spec a post never echoes to its\n * own channel, so a tab never hears itself.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport type { Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\n\nexport const BroadcastMessage = defineMessageUnion({\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.Unknown },\n Posted: {},\n BroadcastFailed: { message: Schema.String },\n})\nexport type BroadcastMessage = typeof BroadcastMessage.Type\n\n/** The slice of a BroadcastChannel this module needs; satisfied by the platform class. */\nexport interface BroadcastChannelHandle {\n postMessage(data: unknown): void\n close(): void\n onmessage: ((event: { readonly data: unknown }) => void) | null\n}\n\ntype ChannelFactory = (name: string) => BroadcastChannelHandle\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst createChannel = (\n factory: ChannelFactory | undefined,\n name: string,\n): BroadcastChannelHandle | null => {\n if (factory !== undefined) return factory(name)\n if (typeof BroadcastChannel === 'undefined') return null\n return new BroadcastChannel(name) as unknown as BroadcastChannelHandle\n}\n\n/**\n * Every post to `name` from another channel, as Messages. Without a\n * BroadcastChannel API the stream is empty instead of throwing; closing the\n * stream closes the channel.\n */\nexport const broadcastMessages = (\n name: string,\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n create?: ChannelFactory | undefined,\n): Stream.Stream<BroadcastMessage> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const channel = createChannel(create, name)\n if (channel === null) return Stream.empty\n const queue = yield* Queue.unbounded<BroadcastMessage>()\n channel.onmessage = event => {\n Effect.runFork(Queue.offer(queue, BroadcastMessage.Received({ data: event.data })))\n }\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n channel.onmessage = null\n channel.close()\n }),\n )\n return Stream.fromQueue(queue)\n }),\n )\n\n/**\n * Posts one message to `name`. Opens a channel, posts, and closes it: the\n * send is one-shot, so it is a Command, not a resource. Without a\n * BroadcastChannel API — or when the post throws — it yields\n * `BroadcastFailed` instead of throwing.\n */\nexport const postBroadcast = (\n name: string,\n data: unknown,\n create?: ChannelFactory | undefined,\n): Command<BroadcastMessage, never, never> => ({\n name: 'Broadcast.post',\n args: { name, data },\n // One path for every failure: no factory and no platform API, or a post\n // that throws (a closed channel) all become BroadcastFailed.\n effect: Effect.matchEffect(\n Effect.try({\n try: () => {\n const channel = createChannel(create, name)\n if (channel === null) throw new Error('broadcast is unavailable')\n try {\n channel.postMessage(data)\n } finally {\n channel.close()\n }\n },\n catch: failMessage,\n }),\n {\n onFailure: message => Effect.succeed(BroadcastMessage.BroadcastFailed({ message })),\n onSuccess: () => Effect.succeed(BroadcastMessage.Posted()),\n },\n ),\n})\n","/**\n * Online presence as a bundle: `online` in the Model, kept current by the\n * window's online/offline events. The browser reports facts; the Model owns\n * the state, so presence replays like any other transition.\n */\nimport { Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Subscription from 'foldkit/subscription'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const OnlineModel = Schema.Struct({ online: Schema.Boolean })\nexport type OnlineModel = typeof OnlineModel.Type\n\nexport const OnlineMessage = defineMessageUnion({ Changed: { online: Schema.Boolean } })\nexport type OnlineMessage = typeof OnlineMessage.Type\n\nconst presenceStream = (): Stream.Stream<OnlineMessage> => {\n // No window (SSR): nothing to listen to, so the slice keeps its default.\n if (typeof window === 'undefined') return Stream.empty\n return Stream.mergeAll(\n [\n Stream.fromEventListener(window, 'online').pipe(\n Stream.map(() => OnlineMessage.Changed({ online: true })),\n ),\n Stream.fromEventListener(window, 'offline').pipe(\n Stream.map(() => OnlineMessage.Changed({ online: false })),\n ),\n ],\n { concurrency: 'unbounded' },\n )\n}\n\nexport const Online = Bundle.make('Online', {\n Model: OnlineModel,\n Message: OnlineMessage,\n init: () => ({\n // navigator.onLine is the browser's current answer; true elsewhere (SSR).\n model: {\n online:\n typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'\n ? navigator.onLine\n : true,\n },\n }),\n update: (model, message) =>\n message.online === model.online ? { model } : { model: { online: message.online } },\n subscriptions: (): Subscription.Subscriptions<OnlineModel, OnlineMessage> =>\n Subscription.make<OnlineModel, OnlineMessage>()(() => ({\n changes: Subscription.persistent(presenceStream()),\n })),\n})\n","/**\n * One server in the browser for many documents: every tab and frame of an\n * application meets the same host. A page opens conversations, each a\n * `MessagePort` with a decoded opening that says what it is for; the host, in\n * a SharedWorker shared by every tab, or in the top document where there is no\n * SharedWorker, is handed each one with a signal that aborts when the page\n * that opened it is gone.\n *\n * It owns the host's lifetime and the routing of conversations, nothing\n * spoken over them: Sync's `portSocket` and Remote's `port` do that.\n */\nimport { Option, Schema } from 'effect'\n\n/** One conversation a page opened: its port, and a signal that aborts once the page is gone. */\nexport interface Conversation {\n readonly port: MessagePort\n readonly signal: AbortSignal\n}\n\n/** What the host does with each conversation, told what the page opened it for. */\nexport type ConversationHandler<Opening> = (opening: Opening, conversation: Conversation) => void\n\n/** Starts the host, once, the first time a conversation needs it. */\nexport type StartHost<Opening> = () =>\n ConversationHandler<Opening> | Promise<ConversationHandler<Opening>>\n\nexport interface SharedHostOptions<Opening> {\n /**\n * The SharedWorker whose entry calls `serve`. Constructed by the\n * application, since a bundler finds a worker only in a literal\n * `new SharedWorker(new URL('./worker.ts', import.meta.url), …)`.\n */\n readonly worker: () => { readonly port: MessagePort }\n /** The host, for a browser without SharedWorker: started in the top document. */\n readonly inPage: StartHost<Opening>\n}\n\n/** A page's way to the host. */\nexport interface SharedHostConnection<Opening> {\n /** Opens a conversation for `opening`, returning the page's end of it. */\n readonly open: (opening: Opening) => MessagePort\n}\n\nexport interface SharedHost<Opening> {\n readonly name: string\n /** A SharedWorker's entry: hands the host every conversation a page opens. */\n readonly serve: (start: StartHost<Opening>) => void\n /**\n * A page's connection: through the SharedWorker, or, without one, to the\n * host in the top document. Call it in the top document too when that\n * document frames the pages, so that it is the one the frames meet.\n */\n readonly connect: (options: SharedHostOptions<Opening>) => SharedHostConnection<Opening>\n}\n\n/**\n * A shared host: its `name`, which keeps two on one origin apart, and\n * the schema of what opens a conversation, which the host decodes before\n * anything else, ignoring a message that does not decode.\n */\nconst define = <Opening, Encoded>(options: {\n readonly name: string\n readonly opening: Schema.Codec<Opening, Encoded, never, never>\n}): SharedHost<Opening> => {\n const { name } = options\n const Envelope = Schema.Struct({\n host: Schema.Literal(name),\n conversation: Schema.String,\n opening: options.opening,\n })\n const encode = Schema.encodeSync(Envelope)\n const decode = Schema.decodeUnknownOption(Envelope)\n const lockOf = (conversation: string) => `foldkit-shared-host:${name}:${conversation}`\n const marker = `foldkit-shared-host:${name}`\n\n const receive = (\n host: () => Promise<ConversationHandler<Opening>>,\n data: unknown,\n port: MessagePort | undefined,\n ) =>\n Option.match(\n Option.zipWith(decode(data), Option.fromUndefinedOr(port), (envelope, given) => ({\n envelope,\n given,\n })),\n {\n // Not a page's opening, or one without its port: nothing to answer.\n onNone: () => {},\n onSome: ({ envelope, given }) => {\n const ended = new AbortController()\n // The page holds this lock while it lives, so the host is granted it\n // when the page's document unloads or crashes.\n Option.match(locks(), {\n onNone: () => {},\n onSome: held => {\n void held.request(lockOf(envelope.conversation), () => ended.abort())\n },\n })\n void host()\n .then(started => started(envelope.opening, { port: given, signal: ended.signal }))\n .catch(reportError)\n },\n },\n )\n\n const once = (start: StartHost<Opening>): (() => Promise<ConversationHandler<Opening>>) => {\n let started: Promise<ConversationHandler<Opening>> | undefined\n return () => (started ??= Promise.resolve().then(start))\n }\n\n const serve = (start: StartHost<Opening>): void => {\n const host = once(start)\n self.addEventListener('connect', event => {\n if (!(event instanceof MessageEvent)) return\n const [connection] = event.ports\n connection?.addEventListener('message', message =>\n receive(host, message.data, message.ports[0]),\n )\n connection?.start()\n })\n }\n\n const connect = ({\n worker,\n inPage,\n }: SharedHostOptions<Opening>): SharedHostConnection<Opening> => {\n const send = routeOf(worker, inPage)\n return {\n open: opening => {\n const { port1, port2 } = new MessageChannel()\n const conversation = crypto.randomUUID()\n const envelope = encode({ host: name, conversation, opening })\n // The opening goes once the lock is held, so the host cannot be\n // granted it first and end the conversation before it began.\n void hold(lockOf(conversation)).then(() => send(envelope, port2))\n return port1\n },\n }\n }\n\n const routeOf = (\n worker: SharedHostOptions<Opening>['worker'],\n inPage: StartHost<Opening>,\n ): ((envelope: unknown, port: MessagePort) => void) => {\n if (typeof SharedWorker !== 'undefined') {\n const { port } = worker()\n return (envelope, given) => port.postMessage(envelope, [given])\n }\n return Option.match(acceptingTop(marker), {\n onSome: top => (envelope, given) => top.postMessage(envelope, location.origin, [given]),\n onNone: () => {\n const host = once(inPage)\n Reflect.set(window, marker, true)\n window.addEventListener('message', event => {\n if (event.origin === location.origin) receive(host, event.data, event.ports[0])\n })\n return (envelope, given) => receive(host, envelope, given)\n },\n })\n }\n\n return { name, serve, connect }\n}\n\n/** The top document, when it is another of this origin's and runs this host. */\nconst acceptingTop = (marker: string): Option.Option<Window> => {\n const top = window.top\n if (top === null || top === window) return Option.none()\n try {\n return Reflect.get(top, marker) === true ? Option.some(top) : Option.none()\n } catch {\n // Another origin's top document: reading it throws.\n return Option.none()\n }\n}\n\n/** Resolves once this document holds `lock`, which it then holds while it lives. */\nconst hold = (lock: string): Promise<void> =>\n Option.match(locks(), {\n onNone: () => Promise.resolve(),\n onSome: held =>\n new Promise(granted => {\n void held.request(lock, () => {\n granted()\n return new Promise(() => {})\n })\n }),\n })\n\n/** Web Locks, which a page outside a secure context, or an older browser, lacks. */\nconst locks = (): Option.Option<LockManager> => Option.fromUndefinedOr(navigator.locks)\n\nexport const SharedHost = { define }\n","/**\n * Server-sent events as a bundle: connection lifecycle in the Model, the\n * event stream through one Managed Resource. One-directional, so there is no\n * send: the server speaks, the Model listens. The browser reconnects dropped\n * streams itself; a Failed only records the error.\n */\nimport { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { defineTaggedUnion } from 'foldkit/schema'\nimport * as ManagedResource from 'foldkit/managedResource'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\n/** The slice of an EventSource the bundle needs; satisfied by the platform class. */\nexport interface SourceHandle {\n readonly readyState: number\n close(): void\n onopen: ((event: any) => void) | null\n onmessage: ((event: any) => void) | null\n onerror: ((event: any) => void) | null\n}\n\nexport const SseModel = Schema.Struct({\n url: Schema.String,\n status: Schema.Literals(['closed', 'connecting', 'open']),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type SseModel = typeof SseModel.Type\n\nexport const SseMessage = defineMessageUnion({\n Connecting: {},\n Opened: {},\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.String },\n Closed: {},\n Failed: { message: Schema.String },\n})\nexport type SseMessage = typeof SseMessage.Type\n\n/**\n * What the reader sees: the stream's state, or its error. A page derives\n * this instead of keeping its own connection state machine. `lastError`\n * carries the stored failure text: the runtime error sentence (`event stream\n * error for …`) or the acquire error's own message.\n */\nexport const SseView = defineTaggedUnion({\n Disconnected: {},\n Connecting: {},\n Connected: {},\n Error: { error: Schema.String },\n})\nexport type SseView = typeof SseView.Type\n\n/**\n * Whether the stream is live: open with no error outstanding. The browser\n * reconnects a dropped stream itself; a `Failed` only records the error.\n */\nexport const isLive = (model: SseModel): boolean =>\n model.status === 'open' && model.lastError === null\n\n/**\n * The view of a stream, and whether its page still wants it. An error stands\n * until the page stops wanting the stream; a retry still waiting for its\n * stream reads as connecting, so it answers at once.\n */\nexport const viewOfSse = (model: SseModel, wanted: boolean): SseView => {\n if (model.lastError !== null)\n return model.status === 'open' || !wanted\n ? SseView.Error({ error: model.lastError })\n : SseView.Connecting()\n if (model.status === 'open') return SseView.Connected()\n if (model.status === 'connecting' || wanted) return SseView.Connecting()\n return SseView.Disconnected()\n}\n\n/** The registry value behind the source tag: the live source and its incoming queue. */\nexport interface AcquiredSource {\n readonly source: SourceHandle\n readonly events: Queue.Queue<SseMessage>\n}\n\n/** The live stream, for the incoming subscription. One assembly holds one. */\nexport const Source = ManagedResource.tag<AcquiredSource>()('sse')\n\n/** The source service a placed SSE stream requires. */\nexport type SourceService = ManagedResource.ServiceOf<typeof Source>\n\ntype SourceResources = Readonly<{\n source: ManagedResource.Entry<\n SseModel,\n SseMessage,\n Option.Option<string>,\n AcquiredSource,\n SourceService,\n () => SseMessage\n >\n}>\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nexport const sse = <const Name extends string>(config: {\n readonly name: Name\n /** Defaults to the platform EventSource, read lazily so tests can substitute a double. */\n readonly createSource?: ((url: string) => SourceHandle) | undefined\n}) => {\n const createSource: (url: string) => SourceHandle =\n config.createSource ?? (url => new EventSource(url) as unknown as SourceHandle)\n return Bundle.make<\n Name,\n SseModel,\n SseMessage,\n { readonly url: string },\n never,\n SourceService,\n SourceService,\n void,\n SourceResources,\n {}\n >(config.name, {\n Model: SseModel,\n Message: SseMessage,\n args: Schema.Struct({ url: Schema.String }),\n init: (args): Update.Return<SseModel, SseMessage, SourceService> => ({\n model: { url: args.url, status: 'closed', lastError: null },\n }),\n update: (\n model,\n message,\n ): Update.ReturnWithOutMessage<SseModel, SseMessage, never, SourceService> =>\n SseMessage.match(message, {\n Connecting: () => ({ model: unlessSame(model, { ...model, status: 'connecting' }) }),\n Opened: () => ({\n model: unlessSame(model, { ...model, status: 'open', lastError: null }),\n }),\n Received: () => ({ model }),\n Closed: () => ({ model: unlessSame(model, { ...model, status: 'closed' }) }),\n // EventSource retries on its own, erroring the same way on every attempt.\n Failed: ({ message }) => ({\n model: unlessSame(model, { ...model, status: 'connecting', lastError: message }),\n }),\n }),\n resources: () =>\n ManagedResource.make<SseModel, SseMessage>()(entry => ({\n source: entry(Schema.Option(Schema.String), {\n resource: Source,\n modelToMaybeRequirements: model => Option.some(model.url),\n acquire: (url: string) =>\n Effect.gen(function* () {\n const events = yield* Queue.unbounded<SseMessage>()\n const source = createSource(url)\n // Offers run in arrival order; see the WebSocket bundle.\n let tail: Promise<void> = Promise.resolve()\n const enqueue = (effect: Effect.Effect<unknown>): void => {\n const run = () =>\n Effect.runPromise(effect).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n const offer = (message: SseMessage) => enqueue(Queue.offer(events, message))\n source.onopen = () => offer(SseMessage.Opened())\n // Event data is always text per the SSE spec.\n source.onmessage = event => offer(SseMessage.Received({ data: String(event.data) }))\n source.onerror = () =>\n offer(SseMessage.Failed({ message: `event stream error for ${url}` }))\n return { source, events }\n }),\n onAcquired: () => SseMessage.Connecting(),\n onReleased: () => SseMessage.Closed(),\n onAcquireError: error => SseMessage.Failed({ message: failMessage(error) }),\n // Daemon teardown: close the stream and drain the queue.\n release: ({ source, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => {\n source.onopen = null\n source.onmessage = null\n source.onerror = null\n source.close()\n }),\n Queue.shutdown(events),\n ),\n ),\n }),\n })),\n subscriptions: (): Subscription.Subscriptions<SseModel, SseMessage, SourceService> =>\n Subscription.make<SseModel, SseMessage, SourceService>()(entry => ({\n incoming: entry(\n // Connecting to open is no reason to restart: the stream reads the\n // same queue, and replays an open it attached too late to see.\n { live: Schema.Boolean },\n {\n modelToDependencies: model => ({ live: model.status !== 'closed' }),\n dependenciesToStream: ({ live }) =>\n !live\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Source.get, {\n // Released between the dependency read and attach: end\n // quietly; onReleased reports Closed through update.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ source, events }) =>\n Effect.succeed(\n Stream.concat(\n // A fast server opens before the stream attaches.\n // 1 is OPEN for EventSource everywhere.\n source.readyState === 1\n ? Stream.make(SseMessage.Opened())\n : Stream.empty,\n Stream.fromQueue(events),\n ),\n ),\n }),\n ),\n },\n ),\n })),\n })\n}\n","/**\n * A WebSocket as a bundle: connection lifecycle in the Model, full duplex\n * through one Managed Resource. The resource owns the socket; a `send`\n * helper writes through its tag service (lifted to the parent like every\n * helper); a subscription stream reads incoming messages through the same\n * tag. No hidden hub: everything the bundle touches is the Model, the\n * resource registry, or a Message.\n */\nimport { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { defineTaggedUnion } from 'foldkit/schema'\nimport * as ManagedResource from 'foldkit/managedResource'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\n/** The slice of a WebSocket the bundle needs; satisfied by the platform socket and test doubles. Handler events are `any`: the DOM and `ws` type them differently, and only `data` is read. */\nexport interface SocketHandle {\n readonly readyState: number\n send(data: string): void\n close(): void\n onopen: ((event: any) => void) | null\n onmessage: ((event: any) => void) | null\n onclose: ((event: any) => void) | null\n onerror: ((event: any) => void) | null\n}\n\nexport const WebSocketModel = Schema.Struct({\n url: Schema.String,\n status: Schema.Literals(['closed', 'connecting', 'open']),\n lastError: Schema.NullOr(Schema.String),\n /** Whether this connection attempt ever reached open; reset on Connecting. */\n opened: Schema.Boolean,\n})\nexport type WebSocketModel = typeof WebSocketModel.Type\n\nexport const WebSocketMessage = defineMessageUnion({\n Connecting: {},\n Opened: {},\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.String },\n Closed: {},\n Failed: { message: Schema.String },\n SendFailed: { message: Schema.String },\n /** Acknowledges dispatch of `data`, not its delivery; update ignores it. */\n Sent: { data: Schema.String },\n /** The socket was still connecting when `connectTimeoutMs` ran out, and was closed. */\n TimedOut: {},\n})\nexport type WebSocketMessage = typeof WebSocketMessage.Type\n\n/** The registry value behind the socket tag: the live socket and its incoming queue. */\nexport interface Acquired {\n readonly socket: SocketHandle\n readonly events: Queue.Queue<WebSocketMessage>\n}\n\n/**\n * What the reader sees: the socket's state, or its error. A page derives\n * this instead of keeping its own connection state machine. `lastError` is\n * already worded for the reader (`Failed to connect to WebSocket`, never the\n * socket's own text, which error handling drops in favor of the sentence).\n */\nexport const SocketView = defineTaggedUnion({\n Disconnected: {},\n Connecting: {},\n Connected: {},\n Error: { error: Schema.String },\n})\nexport type SocketView = typeof SocketView.Type\n\n/**\n * Whether the socket is usable: open with no error outstanding. Gates sends\n * and received frames.\n */\nexport const isOpen = (model: WebSocketModel): boolean =>\n model.status === 'open' && model.lastError === null\n\n/**\n * The view of a socket, and whether its page still wants it. An error stands\n * until the page stops wanting the socket; a retry still waiting for its\n * socket reads as connecting, so it answers at once. An error on an open\n * socket always reads as an error.\n */\nexport const viewOf = (model: WebSocketModel, wanted: boolean): SocketView => {\n if (model.lastError !== null)\n return model.status === 'open' || !wanted\n ? SocketView.Error({ error: model.lastError })\n : SocketView.Connecting()\n if (model.status === 'open') return SocketView.Connected()\n if (model.status === 'connecting' || wanted) return SocketView.Connecting()\n return SocketView.Disconnected()\n}\n\n/** The live connection, for `send` and the incoming stream. One assembly holds one. */\nexport const Socket = ManagedResource.tag<Acquired>()('websocket')\n\n/** The socket service a placed WebSocket's streams and send commands require. */\nexport type SocketService = ManagedResource.ServiceOf<typeof Socket>\n\ntype SocketResources = Readonly<{\n socket: ManagedResource.Entry<\n WebSocketModel,\n WebSocketMessage,\n Option.Option<string>,\n Acquired,\n SocketService,\n () => WebSocketMessage\n >\n}>\n\ntype SendHelpers = Readonly<{\n send: (\n model: WebSocketModel,\n data: string,\n ) => Update.ReturnWithOutMessage<WebSocketModel, WebSocketMessage, never, SocketService>\n}>\n\nconst textOf = (data: unknown): Effect.Effect<string> =>\n typeof data === 'string'\n ? Effect.succeed(data)\n : data instanceof Blob\n ? Effect.promise(() => data.text())\n : data instanceof ArrayBuffer || ArrayBuffer.isView(data)\n ? Effect.succeed(new TextDecoder().decode(data))\n : Effect.succeed(String(data))\n\n/** Closes the socket with its handlers detached first, so the close reports nothing. */\nconst closeSilently = (socket: SocketHandle): void => {\n socket.onopen = null\n socket.onmessage = null\n socket.onclose = null\n socket.onerror = null\n socket.close()\n}\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nexport const websocket = <const Name extends string>(config: {\n readonly name: Name\n /** Defaults to the platform WebSocket, read lazily so tests can substitute a double. */\n readonly createSocket?: ((url: string) => SocketHandle) | undefined\n}) => {\n const createSocket: (url: string) => SocketHandle =\n config.createSocket ?? (url => new WebSocket(url) as unknown as SocketHandle)\n return Bundle.make<\n Name,\n WebSocketModel,\n WebSocketMessage,\n { readonly url: string; readonly connectTimeoutMs?: number | undefined },\n never,\n SocketService,\n SocketService,\n void,\n SocketResources,\n SendHelpers\n >(config.name, {\n Model: WebSocketModel,\n Message: WebSocketMessage,\n args: Schema.Struct({\n url: Schema.String,\n /** How long a socket may stay connecting before it is closed as `TimedOut`; unbounded when absent. */\n connectTimeoutMs: Schema.optional(\n Schema.Number.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.check(Schema.isFinite())),\n ),\n }),\n init: (args): Update.Return<WebSocketModel, WebSocketMessage, SocketService> => ({\n model: { url: args.url, status: 'closed', lastError: null, opened: false },\n }),\n update: (\n model,\n message,\n ): Update.ReturnWithOutMessage<WebSocketModel, WebSocketMessage, never, SocketService> =>\n WebSocketMessage.match(message, {\n Connecting: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'connecting',\n lastError: null,\n opened: false,\n }),\n }),\n Opened: () => ({\n model: unlessSame(model, { ...model, status: 'open', lastError: null, opened: true }),\n }),\n Received: () => ({ model }),\n // The close that follows an error, and the release after it, find it closed.\n Closed: () => ({ model: unlessSame(model, { ...model, status: 'closed' }) }),\n // Worded by whether the socket had opened: the socket's own text is\n // dropped in favor of the sentence, as a page would word it.\n Failed: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'closed',\n lastError:\n model.status === 'open' ? 'Connection error' : 'Failed to connect to WebSocket',\n }),\n }),\n SendFailed: () => ({\n model: unlessSame(model, { ...model, lastError: 'Socket unavailable' }),\n }),\n Sent: () => ({ model }),\n TimedOut: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'closed',\n lastError: 'Connection timeout',\n }),\n }),\n }),\n resources: () =>\n ManagedResource.make<WebSocketModel, WebSocketMessage>()(entry => ({\n socket: entry(Schema.Option(Schema.String), {\n resource: Socket,\n modelToMaybeRequirements: model => Option.some(model.url),\n acquire: (url: string) =>\n Effect.gen(function* () {\n const events = yield* Queue.unbounded<WebSocketMessage>()\n const socket = createSocket(url)\n // Offers run in arrival order: an async decode (Blob text) must\n // not overtake a later message. Rejections settle the chain\n // without breaking it; shutdown races are expected at teardown.\n let tail: Promise<void> = Promise.resolve()\n const enqueue = (effect: Effect.Effect<unknown>): void => {\n const run = () =>\n Effect.runPromise(effect).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n const offer = (message: WebSocketMessage) => enqueue(Queue.offer(events, message))\n socket.onopen = () => offer(WebSocketMessage.Opened())\n socket.onmessage = event => {\n enqueue(\n Effect.flatMap(textOf(event.data), text =>\n Queue.offer(events, WebSocketMessage.Received({ data: text })),\n ),\n )\n }\n socket.onclose = () => offer(WebSocketMessage.Closed())\n socket.onerror = () =>\n offer(WebSocketMessage.Failed({ message: `websocket error for ${url}` }))\n return { socket, events }\n }),\n onAcquired: () => WebSocketMessage.Connecting(),\n onReleased: () => WebSocketMessage.Closed(),\n onAcquireError: error => WebSocketMessage.Failed({ message: failMessage(error) }),\n // Daemon teardown: close the socket and drain the queue.\n release: ({ socket, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => closeSilently(socket)),\n Queue.shutdown(events),\n ),\n ),\n }),\n })),\n subscriptions: ({\n connectTimeoutMs,\n }): Subscription.Subscriptions<WebSocketModel, WebSocketMessage, SocketService> =>\n Subscription.make<WebSocketModel, WebSocketMessage, SocketService>()(entry => ({\n connectTimeout: entry(\n { connecting: Schema.Boolean },\n {\n modelToDependencies: model => ({ connecting: model.status === 'connecting' }),\n dependenciesToStream: ({ connecting }) =>\n !connecting || connectTimeoutMs === undefined\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Effect.andThen(Effect.sleep(connectTimeoutMs), Socket.get), {\n // Released while waiting: onReleased reports Closed.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ socket }) =>\n Effect.sync((): Stream.Stream<WebSocketMessage> => {\n // 0 is WebSocket.CONNECTING. An open that beat the\n // timer wins; the handlers go before the close, so\n // the error and close it causes report nothing.\n if (socket.readyState !== 0) return Stream.empty\n closeSilently(socket)\n return Stream.make(WebSocketMessage.TimedOut())\n }),\n }),\n ),\n },\n ),\n incoming: entry(\n // Connecting to open is no reason to restart: the stream reads the\n // same queue, and replays an open it attached too late to see.\n { live: Schema.Boolean },\n {\n modelToDependencies: model => ({ live: model.status !== 'closed' }),\n dependenciesToStream: ({ live }) =>\n !live\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Socket.get, {\n // Released between the dependency read and attach: end\n // quietly; onReleased reports Closed through update.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ socket, events }) =>\n Effect.succeed(\n Stream.concat(\n // A fast server opens before the stream attaches; without\n // this the status would stick at connecting while\n // messages flow. 1 is WebSocket.OPEN everywhere.\n socket.readyState === 1\n ? Stream.make(WebSocketMessage.Opened())\n : Stream.empty,\n Stream.fromQueue(events),\n ),\n ),\n }),\n ),\n },\n ),\n })),\n helpers: {\n send: (model, data) => ({\n model,\n commands: [\n {\n name: 'WebSocket.send',\n args: { data },\n effect: Effect.matchEffect(\n Effect.flatMap(Socket.get, ({ socket }) =>\n // A closed socket's send is a silent no-op per spec (only a\n // connecting socket throws), so check first: SendFailed either way.\n socket.readyState === 1\n ? Effect.map(\n Effect.sync(() => {\n socket.send(data)\n }),\n () => WebSocketMessage.Sent({ data }),\n )\n : Effect.fail(\n new Error(\n `cannot send: socket is not open (readyState ${socket.readyState})`,\n ),\n ),\n ),\n {\n onFailure: error =>\n Effect.succeed(WebSocketMessage.SendFailed({ message: failMessage(error) })),\n onSuccess: message => Effect.succeed(message),\n },\n ),\n },\n ],\n }),\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAa,mBAAmB,mBAAmB;;CAEjD,UAAU,EAAE,M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,MAAM,MAAM,WAAW,SAAS;IACjE,uBAAuB,EAAE,WACvB,CAAC,OACG,OAAO,QACP,OAAO,OACL,OAAO,YAAY,OAAO,KAAK;KAG7B,iBAAiB,OAAO,QAAQ,OAAO,KAAK;KAC5C,YAAY,EAAE,QAAQ,aACpB,OAAO,QACL,OAAO,OAIL,OAAO,eAAe,IAClB,OAAO,KAAK,iBAAiB,OAAO,CAAC,IACrC,OAAO,OACX,OAAO,UAAU,MAAM,CACzB,CACF;IACJ,CAAC,CACH;GACR,CACF;EACF,EAAE;EACJ,SAAS,EACP,OAAO,OAAO,UAAU;GACtB;GACA,UAAU,CACR;IACE,MAAM;IACN,MAAM,EAAE,KAAK;IACb,QAAQ,OAAO,YACb,OAAO,QAAQ,OAAO,MAAM,EAAE,aAG5B,OAAO,eAAe,IAClB,OAAO,IACL,OAAO,WAAW;KAChB,OAAO,KAAK,IAAI;IAClB,CAAC,SACK,iBAAiB,KAAK,EAAE,KAAK,CAAC,CACtC,IACA,OAAO,qBACL,IAAI,MACF,+CAA+C,OAAO,WAAW,EACnE,CACF,CACN,GACA;KACE,YAAW,UACT,OAAO,QAAQ,iBAAiB,WAAW,EAAE,SAAS,YAAY,KAAK,EAAE,CAAC,CAAC;KAC7E,YAAW,YAAW,OAAO,QAAQ,OAAO;IAC9C,CACF;GACF,CACF;EACF,GACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["failMessage","failMessage"],"sources":["../../src/net/broadcast.ts","../../src/net/online.ts","../../src/net/sharedHost.ts","../../src/net/sse.ts","../../src/net/websocket.ts"],"sourcesContent":["/**\n * Cross-tab messaging as an entry plus a Command — not a bundle, because the\n * channel owns no state: the parent maps `Received` into its own Message and\n * stores whatever it keeps. One assembly may open the same name twice (two\n * listeners); share the entry instead. By spec a post never echoes to its\n * own channel, so a tab never hears itself.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport type { Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\n\nexport const BroadcastMessage = defineMessageUnion({\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.Unknown },\n Posted: {},\n BroadcastFailed: { message: Schema.String },\n})\nexport type BroadcastMessage = typeof BroadcastMessage.Type\n\n/** The slice of a BroadcastChannel this module needs; satisfied by the platform class. */\nexport interface BroadcastChannelHandle {\n postMessage(data: unknown): void\n close(): void\n onmessage: ((event: { readonly data: unknown }) => void) | null\n}\n\ntype ChannelFactory = (name: string) => BroadcastChannelHandle\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst createChannel = (\n factory: ChannelFactory | undefined,\n name: string,\n): BroadcastChannelHandle | null => {\n if (factory !== undefined) return factory(name)\n if (typeof BroadcastChannel === 'undefined') return null\n return new BroadcastChannel(name) as unknown as BroadcastChannelHandle\n}\n\n/**\n * Every post to `name` from another channel, as Messages. Without a\n * BroadcastChannel API the stream is empty instead of throwing; closing the\n * stream closes the channel.\n */\nexport const broadcastMessages = (\n name: string,\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n create?: ChannelFactory | undefined,\n): Stream.Stream<BroadcastMessage> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const channel = createChannel(create, name)\n if (channel === null) return Stream.empty\n const queue = yield* Queue.unbounded<BroadcastMessage>()\n channel.onmessage = event => {\n Effect.runFork(Queue.offer(queue, BroadcastMessage.Received({ data: event.data })))\n }\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n channel.onmessage = null\n channel.close()\n }),\n )\n return Stream.fromQueue(queue)\n }),\n )\n\n/**\n * Posts one message to `name`. Opens a channel, posts, and closes it: the\n * send is one-shot, so it is a Command, not a resource. Without a\n * BroadcastChannel API — or when the post throws — it yields\n * `BroadcastFailed` instead of throwing.\n */\nexport const postBroadcast = (\n name: string,\n data: unknown,\n create?: ChannelFactory | undefined,\n): Command<BroadcastMessage, never, never> => ({\n name: 'Broadcast.post',\n args: { name, data },\n // One path for every failure: no factory and no platform API, or a post\n // that throws (a closed channel) all become BroadcastFailed.\n effect: Effect.matchEffect(\n Effect.try({\n try: () => {\n const channel = createChannel(create, name)\n if (channel === null) throw new Error('broadcast is unavailable')\n try {\n channel.postMessage(data)\n } finally {\n channel.close()\n }\n },\n catch: failMessage,\n }),\n {\n onFailure: message => Effect.succeed(BroadcastMessage.BroadcastFailed({ message })),\n onSuccess: () => Effect.succeed(BroadcastMessage.Posted()),\n },\n ),\n})\n","import { Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Subscription from 'foldkit/subscription'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const OnlineModel = Schema.Struct({ online: Schema.Boolean })\nexport type OnlineModel = typeof OnlineModel.Type\n\nexport const OnlineMessage = defineMessageUnion({ Changed: { online: Schema.Boolean } })\nexport type OnlineMessage = typeof OnlineMessage.Type\n\nconst presenceStream = (): Stream.Stream<OnlineMessage> => {\n // No window (SSR): nothing to listen to, so the slice keeps its default.\n if (typeof window === 'undefined') return Stream.empty\n return Stream.mergeAll(\n [\n Stream.fromEventListener(window, 'online').pipe(\n Stream.map(() => OnlineMessage.Changed({ online: true })),\n ),\n Stream.fromEventListener(window, 'offline').pipe(\n Stream.map(() => OnlineMessage.Changed({ online: false })),\n ),\n ],\n { concurrency: 'unbounded' },\n )\n}\n\n/**\n * Online presence as a bundle: `online` in the Model, kept current by the\n * window's online/offline events. The browser reports facts; the Model owns\n * the state, so presence replays like any other transition.\n */\nexport const Online = Bundle.make('Online', {\n Model: OnlineModel,\n Message: OnlineMessage,\n init: () => ({\n // navigator.onLine is the browser's current answer; true elsewhere (SSR).\n model: {\n online:\n typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'\n ? navigator.onLine\n : true,\n },\n }),\n update: (model, message) =>\n message.online === model.online ? { model } : { model: { online: message.online } },\n subscriptions: (): Subscription.Subscriptions<OnlineModel, OnlineMessage> =>\n Subscription.make<OnlineModel, OnlineMessage>()(() => ({\n changes: Subscription.persistentEntry(presenceStream()),\n })),\n})\n","import { Option, Schema } from 'effect'\n\n/** One conversation a page opened: its port, and a signal that aborts once the page is gone. */\nexport interface Conversation {\n readonly port: MessagePort\n readonly signal: AbortSignal\n}\n\n/** What the host does with each conversation, told what the page opened it for. */\nexport type ConversationHandler<Opening> = (opening: Opening, conversation: Conversation) => void\n\n/** Starts the host, once, the first time a conversation needs it. */\nexport type StartHost<Opening> = () =>\n ConversationHandler<Opening> | Promise<ConversationHandler<Opening>>\n\n/** Where `SharedHost` runs the host: in a SharedWorker, or in the page when there is none. */\nexport interface SharedHostOptions<Opening> {\n /**\n * The SharedWorker whose entry calls `serve`. Constructed by the\n * application, since a bundler finds a worker only in a literal\n * `new SharedWorker(new URL('./worker.ts', import.meta.url), …)`.\n */\n readonly worker: () => { readonly port: MessagePort }\n /** The host, for a browser without SharedWorker: started in the top document. */\n readonly inPage: StartHost<Opening>\n}\n\n/** A page's way to the host. */\nexport interface SharedHostConnection<Opening> {\n /** Opens a conversation for `opening`, returning the page's end of it. */\n readonly open: (opening: Opening) => MessagePort\n}\n\nexport interface SharedHost<Opening> {\n readonly name: string\n /** A SharedWorker's entry: hands the host every conversation a page opens. */\n readonly serve: (start: StartHost<Opening>) => void\n /**\n * A page's connection: through the SharedWorker, or, without one, to the\n * host in the top document. Call it in the top document too when that\n * document frames the pages, so that it is the one the frames meet.\n */\n readonly connect: (options: SharedHostOptions<Opening>) => SharedHostConnection<Opening>\n}\n\n/**\n * A shared host: its `name`, which keeps two on one origin apart, and\n * the schema of what opens a conversation, which the host decodes before\n * anything else, ignoring a message that does not decode.\n */\nconst define = <Opening, Encoded>(options: {\n readonly name: string\n readonly opening: Schema.Codec<Opening, Encoded, never, never>\n}): SharedHost<Opening> => {\n const { name } = options\n const Envelope = Schema.Struct({\n host: Schema.Literal(name),\n conversation: Schema.String,\n opening: options.opening,\n })\n const encode = Schema.encodeSync(Envelope)\n const decode = Schema.decodeUnknownOption(Envelope)\n const lockOf = (conversation: string) => `foldkit-shared-host:${name}:${conversation}`\n const marker = `foldkit-shared-host:${name}`\n\n const receive = (\n host: () => Promise<ConversationHandler<Opening>>,\n data: unknown,\n port: MessagePort | undefined,\n ) =>\n Option.match(\n Option.zipWith(decode(data), Option.fromUndefinedOr(port), (envelope, given) => ({\n envelope,\n given,\n })),\n {\n // Not a page's opening, or one without its port: nothing to answer.\n onNone: () => {},\n onSome: ({ envelope, given }) => {\n const ended = new AbortController()\n // The page holds this lock while it lives, so the host is granted it\n // when the page's document unloads or crashes.\n Option.match(locks(), {\n onNone: () => {},\n onSome: held => {\n void held.request(lockOf(envelope.conversation), () => ended.abort())\n },\n })\n void host()\n .then(started => started(envelope.opening, { port: given, signal: ended.signal }))\n .catch(reportError)\n },\n },\n )\n\n const once = (start: StartHost<Opening>): (() => Promise<ConversationHandler<Opening>>) => {\n let started: Promise<ConversationHandler<Opening>> | undefined\n return () => (started ??= Promise.resolve().then(start))\n }\n\n const serve = (start: StartHost<Opening>): void => {\n const host = once(start)\n self.addEventListener('connect', event => {\n if (!(event instanceof MessageEvent)) return\n const [connection] = event.ports\n connection?.addEventListener('message', message =>\n receive(host, message.data, message.ports[0]),\n )\n connection?.start()\n })\n }\n\n const connect = ({\n worker,\n inPage,\n }: SharedHostOptions<Opening>): SharedHostConnection<Opening> => {\n const send = routeOf(worker, inPage)\n return {\n open: opening => {\n const { port1, port2 } = new MessageChannel()\n const conversation = crypto.randomUUID()\n const envelope = encode({ host: name, conversation, opening })\n // The opening goes once the lock is held, so the host cannot be\n // granted it first and end the conversation before it began.\n void hold(lockOf(conversation)).then(() => send(envelope, port2))\n return port1\n },\n }\n }\n\n const routeOf = (\n worker: SharedHostOptions<Opening>['worker'],\n inPage: StartHost<Opening>,\n ): ((envelope: unknown, port: MessagePort) => void) => {\n if (typeof SharedWorker !== 'undefined') {\n const { port } = worker()\n return (envelope, given) => port.postMessage(envelope, [given])\n }\n return Option.match(acceptingTop(marker), {\n onSome: top => (envelope, given) => top.postMessage(envelope, location.origin, [given]),\n onNone: () => {\n const host = once(inPage)\n Reflect.set(window, marker, true)\n window.addEventListener('message', event => {\n if (event.origin === location.origin) receive(host, event.data, event.ports[0])\n })\n return (envelope, given) => receive(host, envelope, given)\n },\n })\n }\n\n return { name, serve, connect }\n}\n\n/** The top document, when it is another of this origin's and runs this host. */\nconst acceptingTop = (marker: string): Option.Option<Window> => {\n const top = window.top\n if (top === null || top === window) return Option.none()\n try {\n return Reflect.get(top, marker) === true ? Option.some(top) : Option.none()\n } catch {\n // Another origin's top document: reading it throws.\n return Option.none()\n }\n}\n\n/** Resolves once this document holds `lock`, which it then holds while it lives. */\nconst hold = (lock: string): Promise<void> =>\n Option.match(locks(), {\n onNone: () => Promise.resolve(),\n onSome: held =>\n new Promise(granted => {\n void held.request(lock, () => {\n granted()\n return new Promise(() => {})\n })\n }),\n })\n\n/** Web Locks, which a page outside a secure context, or an older browser, lacks. */\nconst locks = (): Option.Option<LockManager> => Option.fromUndefinedOr(navigator.locks)\n\n/**\n * One server in the browser for many documents: every tab and frame of an\n * application meets the same host. A page opens conversations, each a\n * `MessagePort` with a decoded opening that says what it is for; the host, in\n * a SharedWorker shared by every tab, or in the top document where there is no\n * SharedWorker, is handed each one with a signal that aborts when the page\n * that opened it is gone.\n *\n * It owns the host's lifetime and the routing of conversations, nothing\n * spoken over them: Sync's `portSocket` and Remote's `port` do that.\n */\nexport const SharedHost = { define }\n","import { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { defineTaggedUnion } from 'foldkit/schema'\nimport * as ManagedResource from 'foldkit/managedResource'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\n/** The slice of an EventSource the bundle needs; satisfied by the platform class. */\nexport interface SourceHandle {\n readonly readyState: number\n close(): void\n onopen: ((event: any) => void) | null\n onmessage: ((event: any) => void) | null\n onerror: ((event: any) => void) | null\n}\n\nexport const SseModel = Schema.Struct({\n url: Schema.String,\n status: Schema.Literals(['closed', 'connecting', 'open']),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type SseModel = typeof SseModel.Type\n\nexport const SseMessage = defineMessageUnion({\n Connecting: {},\n Opened: {},\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.String },\n Closed: {},\n Failed: { message: Schema.String },\n})\nexport type SseMessage = typeof SseMessage.Type\n\n/**\n * What the reader sees: the stream's state, or its error. A page derives\n * this instead of keeping its own connection state machine. `lastError`\n * carries the stored failure text: the runtime error sentence (`event stream\n * error for …`) or the acquire error's own message.\n */\nexport const SseView = defineTaggedUnion({\n Disconnected: {},\n Connecting: {},\n Connected: {},\n Error: { error: Schema.String },\n})\nexport type SseView = typeof SseView.Type\n\n/**\n * Whether the stream is live: open with no error outstanding. The browser\n * reconnects a dropped stream itself; a `Failed` only records the error.\n */\nexport const isLive = (model: SseModel): boolean =>\n model.status === 'open' && model.lastError === null\n\n/**\n * The view of a stream, and whether its page still wants it. An error stands\n * until the page stops wanting the stream; a retry still waiting for its\n * stream reads as connecting, so it answers at once.\n */\nexport const viewOfSse = (model: SseModel, wanted: boolean): SseView => {\n if (model.lastError !== null)\n return model.status === 'open' || !wanted\n ? SseView.Error({ error: model.lastError })\n : SseView.Connecting()\n if (model.status === 'open') return SseView.Connected()\n if (model.status === 'connecting' || wanted) return SseView.Connecting()\n return SseView.Disconnected()\n}\n\n/** The registry value behind the source tag: the live source and its incoming queue. */\nexport interface AcquiredSource {\n readonly source: SourceHandle\n readonly events: Queue.Queue<SseMessage>\n}\n\n/** The live stream, for the incoming subscription. One assembly holds one. */\nexport const Source = ManagedResource.tag<AcquiredSource>()('sse')\n\n/** The source service a placed SSE stream requires. */\nexport type SourceService = ManagedResource.ServiceOf<typeof Source>\n\ntype SourceResources = Readonly<{\n source: ManagedResource.Entry<\n SseModel,\n SseMessage,\n Option.Option<string>,\n AcquiredSource,\n SourceService,\n () => SseMessage\n >\n}>\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\n/**\n * Server-sent events as a bundle: connection lifecycle in the Model, the\n * event stream through one Managed Resource. One-directional, so there is no\n * send: the server speaks, the Model listens. The browser reconnects dropped\n * streams itself; a Failed only records the error.\n */\nexport const sse = <const Name extends string>(config: {\n readonly name: Name\n /** Defaults to the platform EventSource, read lazily so tests can substitute a double. */\n readonly createSource?: ((url: string) => SourceHandle) | undefined\n}) => {\n const createSource: (url: string) => SourceHandle =\n config.createSource ?? (url => new EventSource(url) as unknown as SourceHandle)\n return Bundle.make<\n Name,\n SseModel,\n SseMessage,\n { readonly url: string },\n never,\n SourceService,\n SourceService,\n void,\n SourceResources,\n {}\n >(config.name, {\n Model: SseModel,\n Message: SseMessage,\n args: Schema.Struct({ url: Schema.String }),\n init: (args): Update.Return<SseModel, SseMessage, SourceService> => ({\n model: { url: args.url, status: 'closed', lastError: null },\n }),\n update: (\n model,\n message,\n ): Update.ReturnWithOutMessage<SseModel, SseMessage, never, SourceService> =>\n SseMessage.match(message, {\n Connecting: () => ({ model: unlessSame(model, { ...model, status: 'connecting' }) }),\n Opened: () => ({\n model: unlessSame(model, { ...model, status: 'open', lastError: null }),\n }),\n Received: () => ({ model }),\n Closed: () => ({ model: unlessSame(model, { ...model, status: 'closed' }) }),\n // EventSource retries on its own, erroring the same way on every attempt.\n Failed: ({ message }) => ({\n model: unlessSame(model, { ...model, status: 'connecting', lastError: message }),\n }),\n }),\n resources: () =>\n ManagedResource.make<SseModel, SseMessage>()(entry => ({\n source: entry(Schema.Option(Schema.String), {\n resource: Source,\n modelToMaybeRequirements: model => Option.some(model.url),\n acquire: (url: string) =>\n Effect.gen(function* () {\n const events = yield* Queue.unbounded<SseMessage>()\n const source = createSource(url)\n // Offers run in arrival order; see the WebSocket bundle.\n let tail: Promise<void> = Promise.resolve()\n const enqueue = (effect: Effect.Effect<unknown>): void => {\n const run = () =>\n Effect.runPromise(effect).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n const offer = (message: SseMessage) => enqueue(Queue.offer(events, message))\n source.onopen = () => offer(SseMessage.Opened())\n // Event data is always text per the SSE spec.\n source.onmessage = event => offer(SseMessage.Received({ data: String(event.data) }))\n source.onerror = () =>\n offer(SseMessage.Failed({ message: `event stream error for ${url}` }))\n return { source, events }\n }),\n onAcquired: () => SseMessage.Connecting(),\n onReleased: () => SseMessage.Closed(),\n onAcquireError: error => SseMessage.Failed({ message: failMessage(error) }),\n // Daemon teardown: close the stream and drain the queue.\n release: ({ source, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => {\n source.onopen = null\n source.onmessage = null\n source.onerror = null\n source.close()\n }),\n Queue.shutdown(events),\n ),\n ),\n }),\n })),\n subscriptions: (): Subscription.Subscriptions<SseModel, SseMessage, SourceService> =>\n Subscription.make<SseModel, SseMessage, SourceService>()(entry => ({\n incoming: entry(\n // Connecting to open is no reason to restart: the stream reads the\n // same queue, and replays an open it attached too late to see.\n { live: Schema.Boolean },\n {\n modelToDependencies: model => ({ live: model.status !== 'closed' }),\n dependenciesToStream: ({ live }) =>\n !live\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Source.get, {\n // Released between the dependency read and attach: end\n // quietly; onReleased reports Closed through update.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ source, events }) =>\n Effect.succeed(\n Stream.concat(\n // A fast server opens before the stream attaches.\n // 1 is OPEN for EventSource everywhere.\n source.readyState === 1\n ? Stream.make(SseMessage.Opened())\n : Stream.empty,\n Stream.fromQueue(events),\n ),\n ),\n }),\n ),\n },\n ),\n })),\n })\n}\n","import { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { defineTaggedUnion } from 'foldkit/schema'\nimport * as ManagedResource from 'foldkit/managedResource'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\n/** The slice of a WebSocket the bundle needs; satisfied by the platform socket and test doubles. Handler events are `any`: the DOM and `ws` type them differently, and only `data` is read. */\nexport interface SocketHandle {\n readonly readyState: number\n send(data: string): void\n close(): void\n onopen: ((event: any) => void) | null\n onmessage: ((event: any) => void) | null\n onclose: ((event: any) => void) | null\n onerror: ((event: any) => void) | null\n}\n\nexport const WebSocketModel = Schema.Struct({\n url: Schema.String,\n status: Schema.Literals(['closed', 'connecting', 'open']),\n lastError: Schema.NullOr(Schema.String),\n /** Whether this connection attempt ever reached open; reset on Connecting. */\n opened: Schema.Boolean,\n})\nexport type WebSocketModel = typeof WebSocketModel.Type\n\nexport const WebSocketMessage = defineMessageUnion({\n Connecting: {},\n Opened: {},\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.String },\n Closed: {},\n Failed: { message: Schema.String },\n SendFailed: { message: Schema.String },\n /** Acknowledges dispatch of `data`, not its delivery; update ignores it. */\n Sent: { data: Schema.String },\n /** The socket was still connecting when `connectTimeoutMs` ran out, and was closed. */\n TimedOut: {},\n})\nexport type WebSocketMessage = typeof WebSocketMessage.Type\n\n/** The registry value behind the socket tag: the live socket and its incoming queue. */\nexport interface Acquired {\n readonly socket: SocketHandle\n readonly events: Queue.Queue<WebSocketMessage>\n}\n\n/**\n * What the reader sees: the socket's state, or its error. A page derives\n * this instead of keeping its own connection state machine. `lastError` is\n * already worded for the reader (`Failed to connect to WebSocket`, never the\n * socket's own text, which error handling drops in favor of the sentence).\n */\nexport const SocketView = defineTaggedUnion({\n Disconnected: {},\n Connecting: {},\n Connected: {},\n Error: { error: Schema.String },\n})\nexport type SocketView = typeof SocketView.Type\n\n/**\n * Whether the socket is usable: open with no error outstanding. Gates sends\n * and received frames.\n */\nexport const isOpen = (model: WebSocketModel): boolean =>\n model.status === 'open' && model.lastError === null\n\n/**\n * The view of a socket, and whether its page still wants it. An error stands\n * until the page stops wanting the socket; a retry still waiting for its\n * socket reads as connecting, so it answers at once. An error on an open\n * socket always reads as an error.\n */\nexport const viewOf = (model: WebSocketModel, wanted: boolean): SocketView => {\n if (model.lastError !== null)\n return model.status === 'open' || !wanted\n ? SocketView.Error({ error: model.lastError })\n : SocketView.Connecting()\n if (model.status === 'open') return SocketView.Connected()\n if (model.status === 'connecting' || wanted) return SocketView.Connecting()\n return SocketView.Disconnected()\n}\n\n/** The live connection, for `send` and the incoming stream. One assembly holds one. */\nexport const Socket = ManagedResource.tag<Acquired>()('websocket')\n\n/** The socket service a placed WebSocket's streams and send commands require. */\nexport type SocketService = ManagedResource.ServiceOf<typeof Socket>\n\ntype SocketResources = Readonly<{\n socket: ManagedResource.Entry<\n WebSocketModel,\n WebSocketMessage,\n Option.Option<string>,\n Acquired,\n SocketService,\n () => WebSocketMessage\n >\n}>\n\ntype SendHelpers = Readonly<{\n send: (\n model: WebSocketModel,\n data: string,\n ) => Update.ReturnWithOutMessage<WebSocketModel, WebSocketMessage, never, SocketService>\n}>\n\nconst textOf = (data: unknown): Effect.Effect<string> =>\n typeof data === 'string'\n ? Effect.succeed(data)\n : data instanceof Blob\n ? Effect.promise(() => data.text())\n : data instanceof ArrayBuffer || ArrayBuffer.isView(data)\n ? Effect.succeed(new TextDecoder().decode(data))\n : Effect.succeed(String(data))\n\n/** Closes the socket with its handlers detached first, so the close reports nothing. */\nconst closeSilently = (socket: SocketHandle): void => {\n socket.onopen = null\n socket.onmessage = null\n socket.onclose = null\n socket.onerror = null\n socket.close()\n}\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\n/**\n * A WebSocket as a bundle: connection lifecycle in the Model, full duplex\n * through one Managed Resource. The resource owns the socket; a `send`\n * helper writes through its tag service (lifted to the parent like every\n * helper); a subscription stream reads incoming messages through the same\n * tag. No hidden hub: everything the bundle touches is the Model, the\n * resource registry, or a Message.\n */\nexport const websocket = <const Name extends string>(config: {\n readonly name: Name\n /** Defaults to the platform WebSocket, read lazily so tests can substitute a double. */\n readonly createSocket?: ((url: string) => SocketHandle) | undefined\n}) => {\n const createSocket: (url: string) => SocketHandle =\n config.createSocket ?? (url => new WebSocket(url) as unknown as SocketHandle)\n return Bundle.make<\n Name,\n WebSocketModel,\n WebSocketMessage,\n { readonly url: string; readonly connectTimeoutMs?: number | undefined },\n never,\n SocketService,\n SocketService,\n void,\n SocketResources,\n SendHelpers\n >(config.name, {\n Model: WebSocketModel,\n Message: WebSocketMessage,\n args: Schema.Struct({\n url: Schema.String,\n /** How long a socket may stay connecting before it is closed as `TimedOut`; unbounded when absent. */\n connectTimeoutMs: Schema.optional(\n Schema.Number.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.check(Schema.isFinite())),\n ),\n }),\n init: (args): Update.Return<WebSocketModel, WebSocketMessage, SocketService> => ({\n model: { url: args.url, status: 'closed', lastError: null, opened: false },\n }),\n update: (\n model,\n message,\n ): Update.ReturnWithOutMessage<WebSocketModel, WebSocketMessage, never, SocketService> =>\n WebSocketMessage.match(message, {\n Connecting: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'connecting',\n lastError: null,\n opened: false,\n }),\n }),\n Opened: () => ({\n model: unlessSame(model, { ...model, status: 'open', lastError: null, opened: true }),\n }),\n Received: () => ({ model }),\n // The close that follows an error, and the release after it, find it closed.\n Closed: () => ({ model: unlessSame(model, { ...model, status: 'closed' }) }),\n // Worded by whether the socket had opened: the socket's own text is\n // dropped in favor of the sentence, as a page would word it.\n Failed: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'closed',\n lastError:\n model.status === 'open' ? 'Connection error' : 'Failed to connect to WebSocket',\n }),\n }),\n SendFailed: () => ({\n model: unlessSame(model, { ...model, lastError: 'Socket unavailable' }),\n }),\n Sent: () => ({ model }),\n TimedOut: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'closed',\n lastError: 'Connection timeout',\n }),\n }),\n }),\n resources: () =>\n ManagedResource.make<WebSocketModel, WebSocketMessage>()(entry => ({\n socket: entry(Schema.Option(Schema.String), {\n resource: Socket,\n modelToMaybeRequirements: model => Option.some(model.url),\n acquire: (url: string) =>\n Effect.gen(function* () {\n const events = yield* Queue.unbounded<WebSocketMessage>()\n const socket = createSocket(url)\n // Offers run in arrival order: an async decode (Blob text) must\n // not overtake a later message. Rejections settle the chain\n // without breaking it; shutdown races are expected at teardown.\n let tail: Promise<void> = Promise.resolve()\n const enqueue = (effect: Effect.Effect<unknown>): void => {\n const run = () =>\n Effect.runPromise(effect).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n const offer = (message: WebSocketMessage) => enqueue(Queue.offer(events, message))\n socket.onopen = () => offer(WebSocketMessage.Opened())\n socket.onmessage = event => {\n enqueue(\n Effect.flatMap(textOf(event.data), text =>\n Queue.offer(events, WebSocketMessage.Received({ data: text })),\n ),\n )\n }\n socket.onclose = () => offer(WebSocketMessage.Closed())\n socket.onerror = () =>\n offer(WebSocketMessage.Failed({ message: `websocket error for ${url}` }))\n return { socket, events }\n }),\n onAcquired: () => WebSocketMessage.Connecting(),\n onReleased: () => WebSocketMessage.Closed(),\n onAcquireError: error => WebSocketMessage.Failed({ message: failMessage(error) }),\n // Daemon teardown: close the socket and drain the queue.\n release: ({ socket, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => closeSilently(socket)),\n Queue.shutdown(events),\n ),\n ),\n }),\n })),\n subscriptions: ({\n connectTimeoutMs,\n }): Subscription.Subscriptions<WebSocketModel, WebSocketMessage, SocketService> =>\n Subscription.make<WebSocketModel, WebSocketMessage, SocketService>()(entry => ({\n connectTimeout: entry(\n { connecting: Schema.Boolean },\n {\n modelToDependencies: model => ({ connecting: model.status === 'connecting' }),\n dependenciesToStream: ({ connecting }) =>\n !connecting || connectTimeoutMs === undefined\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Effect.andThen(Effect.sleep(connectTimeoutMs), Socket.get), {\n // Released while waiting: onReleased reports Closed.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ socket }) =>\n Effect.sync((): Stream.Stream<WebSocketMessage> => {\n // 0 is WebSocket.CONNECTING. An open that beat the\n // timer wins; the handlers go before the close, so\n // the error and close it causes report nothing.\n if (socket.readyState !== 0) return Stream.empty\n closeSilently(socket)\n return Stream.make(WebSocketMessage.TimedOut())\n }),\n }),\n ),\n },\n ),\n incoming: entry(\n // Connecting to open is no reason to restart: the stream reads the\n // same queue, and replays an open it attached too late to see.\n { live: Schema.Boolean },\n {\n modelToDependencies: model => ({ live: model.status !== 'closed' }),\n dependenciesToStream: ({ live }) =>\n !live\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Socket.get, {\n // Released between the dependency read and attach: end\n // quietly; onReleased reports Closed through update.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ socket, events }) =>\n Effect.succeed(\n Stream.concat(\n // A fast server opens before the stream attaches; without\n // this the status would stick at connecting while\n // messages flow. 1 is WebSocket.OPEN everywhere.\n socket.readyState === 1\n ? Stream.make(WebSocketMessage.Opened())\n : Stream.empty,\n Stream.fromQueue(events),\n ),\n ),\n }),\n ),\n },\n ),\n })),\n helpers: {\n send: (model, data) => ({\n model,\n commands: [\n {\n name: 'WebSocket.send',\n args: { data },\n effect: Effect.matchEffect(\n Effect.flatMap(Socket.get, ({ socket }) =>\n // A closed socket's send is a silent no-op per spec (only a\n // connecting socket throws), so check first: SendFailed either way.\n socket.readyState === 1\n ? Effect.map(\n Effect.sync(() => {\n socket.send(data)\n }),\n () => WebSocketMessage.Sent({ data }),\n )\n : Effect.fail(\n new Error(\n `cannot send: socket is not open (readyState ${socket.readyState})`,\n ),\n ),\n ),\n {\n onFailure: error =>\n Effect.succeed(WebSocketMessage.SendFailed({ message: failMessage(error) })),\n onSuccess: message => Effect.succeed(message),\n },\n ),\n },\n ],\n }),\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAa,mBAAmB,mBAAmB;;CAEjD,UAAU,EAAE,MAAM,OAAO,QAAQ;CACjC,QAAQ,CAAC;CACT,iBAAiB,EAAE,S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,OACG,OAAO,QACP,OAAO,OACL,OAAO,YAAY,OAAO,KAAK;KAG7B,iBAAiB,OAAO,QAAQ,OAAO,KAAK;KAC5C,YAAY,EAAE,QAAQ,aACpB,OAAO,QACL,OAAO,OAIL,OAAO,eAAe,IAClB,OAAO,KAAK,iBAAiB,OAAO,CAAC,IACrC,OAAO,OACX,OAAO,UAAU,MAAM,CACzB,CACF;IACJ,CAAC,CACH;GACR,CACF;EACF,EAAE;EACJ,SAAS,EACP,OAAO,OAAO,UAAU;GACtB;GACA,UAAU,CACR;IACE,MAAM;IACN,MAAM,EAAE,KAAK;IACb,QAAQ,OAAO,YACb,OAAO,QAAQ,OAAO,MAAM,EAAE,aAG5B,OAAO,eAAe,IAClB,OAAO,IACL,OAAO,WAAW;KAChB,OAAO,KAAK,IAAI;IAClB,CAAC,SACK,iBAAiB,KAAK,EAAE,KAAK,CAAC,CACtC,IACA,OAAO,qBACL,IAAI,MACF,+CAA+C,OAAO,WAAW,EACnE,CACF,CACN,GACA;KACE,YAAW,UACT,OAAO,QAAQ,iBAAiB,WAAW,EAAE,SAAS,YAAY,KAAK,EAAE,CAAC,CAAC;KAC7E,YAAW,YAAW,OAAO,QAAQ,OAAO;IAC9C,CACF;GACF,CACF;EACF,GACF;CACF,CAAC;AACH"}
|
|
@@ -8,6 +8,13 @@ export declare const Measured: Schema.TaggedStruct<"Measured", {
|
|
|
8
8
|
readonly height: Schema.Number;
|
|
9
9
|
}>;
|
|
10
10
|
export type Measured = typeof Measured.Type;
|
|
11
|
+
/**
|
|
12
|
+
* Element bounds as a Mount: the bounding rect re-measured on
|
|
13
|
+
* ResizeObserver, window scroll, and window resize, starting with the
|
|
14
|
+
* current rect. Without a ResizeObserver the window events still measure —
|
|
15
|
+
* position changes never needed the observer. No window (SSR) emits nothing
|
|
16
|
+
* instead of throwing.
|
|
17
|
+
*/
|
|
11
18
|
export declare const Bounds: Mount.MountDefinitionNoArgs<"Bounds", {
|
|
12
19
|
readonly _tag: "Measured";
|
|
13
20
|
readonly x: number;
|
|
@@ -22,6 +29,11 @@ export declare const IntersectionChanged: Schema.TaggedStruct<"IntersectionChang
|
|
|
22
29
|
readonly ratio: Schema.Number;
|
|
23
30
|
}>;
|
|
24
31
|
export type IntersectionChanged = typeof IntersectionChanged.Type;
|
|
32
|
+
/**
|
|
33
|
+
* Element visibility as a Mount: IntersectionObserver reports viewport
|
|
34
|
+
* crossings as Messages for the element carrying this Mount. No observer
|
|
35
|
+
* (SSR, old browser) emits nothing instead of throwing.
|
|
36
|
+
*/
|
|
25
37
|
export declare const Intersection: Mount.MountDefinitionNoArgs<"Intersection", {
|
|
26
38
|
readonly _tag: "IntersectionChanged";
|
|
27
39
|
readonly isIntersecting: boolean;
|
|
@@ -36,6 +48,14 @@ export declare const Mutated: Schema.TaggedStruct<"Mutated", {
|
|
|
36
48
|
readonly attribute: Schema.NullOr<Schema.String>;
|
|
37
49
|
}>;
|
|
38
50
|
export type Mutated = typeof Mutated.Type;
|
|
51
|
+
/**
|
|
52
|
+
* DOM mutations as a Mount: MutationObserver reports child, attribute, and
|
|
53
|
+
* text changes as Messages for the element carrying this Mount. Nodes cross
|
|
54
|
+
* as their names (serializable); the live nodes stay in the DOM, never in
|
|
55
|
+
* the Model. No observer (SSR, old browser) emits nothing instead of
|
|
56
|
+
* throwing. Observes the whole subtree — narrow by placing on a smaller
|
|
57
|
+
* element, not by options.
|
|
58
|
+
*/
|
|
39
59
|
export declare const Mutation: Mount.MountDefinitionNoArgs<"Mutation", {
|
|
40
60
|
readonly _tag: "Mutated";
|
|
41
61
|
readonly type: "attributes" | "characterData" | "childList";
|
|
@@ -50,6 +70,11 @@ export declare const Resized: Schema.TaggedStruct<"Resized", {
|
|
|
50
70
|
readonly height: Schema.Number;
|
|
51
71
|
}>;
|
|
52
72
|
export type Resized = typeof Resized.Type;
|
|
73
|
+
/**
|
|
74
|
+
* Element size as a Mount: ResizeObserver reports content-box changes as
|
|
75
|
+
* Messages for the element carrying this Mount. No observer (SSR, old
|
|
76
|
+
* browser) emits nothing instead of throwing.
|
|
77
|
+
*/
|
|
53
78
|
export declare const Resize: Mount.MountDefinitionNoArgs<"Resize", {
|
|
54
79
|
readonly _tag: "Resized";
|
|
55
80
|
readonly width: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/observers/bounds.ts","../../src/observers/intersection.ts","../../src/observers/mutation.ts","../../src/observers/resize.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/observers/bounds.ts","../../src/observers/intersection.ts","../../src/observers/mutation.ts","../../src/observers/resize.ts"],"mappings":";;;qBAGa,UAAQ,OAAA;;;;;;YAMT,kBAAkB,SAAS;;;;;;;;qBAc1B,QAAM,MAAA;;;;;;;;;qBCpBN,qBAAmB,OAAA;;;;YAIpB,6BAA6B,oBAAoB;;;;;;qBAShD,cAAY,MAAA;;;;;;;qBCbZ,SAAO,OAAA;;;;;;YAMR,iBAAiB,QAAQ;;;;;;;;;qBAexB,UAAQ,MAAA;;;;;;;;;qBCrBR,SAAO,OAAA;;;;YAIR,iBAAiB,QAAQ;;;;;;qBASxB,QAAM,MAAA"}
|
package/dist/observers/index.mjs
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { Effect, Queue, Schema, Stream } from "effect";
|
|
2
2
|
import * as Mount from "foldkit/mount";
|
|
3
3
|
//#region src/observers/bounds.ts
|
|
4
|
+
const Measured = Schema.TaggedStruct("Measured", {
|
|
5
|
+
x: Schema.Number,
|
|
6
|
+
y: Schema.Number,
|
|
7
|
+
width: Schema.Number,
|
|
8
|
+
height: Schema.Number
|
|
9
|
+
});
|
|
4
10
|
/**
|
|
5
11
|
* Element bounds as a Mount: the bounding rect re-measured on
|
|
6
12
|
* ResizeObserver, window scroll, and window resize, starting with the
|
|
@@ -8,12 +14,6 @@ import * as Mount from "foldkit/mount";
|
|
|
8
14
|
* position changes never needed the observer. No window (SSR) emits nothing
|
|
9
15
|
* instead of throwing.
|
|
10
16
|
*/
|
|
11
|
-
const Measured = Schema.TaggedStruct("Measured", {
|
|
12
|
-
x: Schema.Number,
|
|
13
|
-
y: Schema.Number,
|
|
14
|
-
width: Schema.Number,
|
|
15
|
-
height: Schema.Number
|
|
16
|
-
});
|
|
17
17
|
const Bounds = Mount.defineStream("Bounds", {
|
|
18
18
|
messages: [Measured],
|
|
19
19
|
execute: ({ element }) => Stream.callback((queue) => Effect.gen(function* () {
|
|
@@ -48,15 +48,15 @@ const Bounds = Mount.defineStream("Bounds", {
|
|
|
48
48
|
});
|
|
49
49
|
//#endregion
|
|
50
50
|
//#region src/observers/intersection.ts
|
|
51
|
+
const IntersectionChanged = Schema.TaggedStruct("IntersectionChanged", {
|
|
52
|
+
isIntersecting: Schema.Boolean,
|
|
53
|
+
ratio: Schema.Number
|
|
54
|
+
});
|
|
51
55
|
/**
|
|
52
56
|
* Element visibility as a Mount: IntersectionObserver reports viewport
|
|
53
57
|
* crossings as Messages for the element carrying this Mount. No observer
|
|
54
58
|
* (SSR, old browser) emits nothing instead of throwing.
|
|
55
59
|
*/
|
|
56
|
-
const IntersectionChanged = Schema.TaggedStruct("IntersectionChanged", {
|
|
57
|
-
isIntersecting: Schema.Boolean,
|
|
58
|
-
ratio: Schema.Number
|
|
59
|
-
});
|
|
60
60
|
const Intersection = Mount.defineStream("Intersection", {
|
|
61
61
|
messages: [IntersectionChanged],
|
|
62
62
|
execute: ({ element }) => Stream.callback((queue) => Effect.gen(function* () {
|
|
@@ -77,14 +77,6 @@ const Intersection = Mount.defineStream("Intersection", {
|
|
|
77
77
|
});
|
|
78
78
|
//#endregion
|
|
79
79
|
//#region src/observers/mutation.ts
|
|
80
|
-
/**
|
|
81
|
-
* DOM mutations as a Mount: MutationObserver reports child, attribute, and
|
|
82
|
-
* text changes as Messages for the element carrying this Mount. Nodes cross
|
|
83
|
-
* as their names (serializable); the live nodes stay in the DOM, never in
|
|
84
|
-
* the Model. No observer (SSR, old browser) emits nothing instead of
|
|
85
|
-
* throwing. Observes the whole subtree — narrow by placing on a smaller
|
|
86
|
-
* element, not by options.
|
|
87
|
-
*/
|
|
88
80
|
const Mutated = Schema.TaggedStruct("Mutated", {
|
|
89
81
|
type: Schema.Literals([
|
|
90
82
|
"childList",
|
|
@@ -96,6 +88,14 @@ const Mutated = Schema.TaggedStruct("Mutated", {
|
|
|
96
88
|
attribute: Schema.NullOr(Schema.String)
|
|
97
89
|
});
|
|
98
90
|
const recordType = (type) => type === "childList" || type === "attributes" || type === "characterData" ? type : null;
|
|
91
|
+
/**
|
|
92
|
+
* DOM mutations as a Mount: MutationObserver reports child, attribute, and
|
|
93
|
+
* text changes as Messages for the element carrying this Mount. Nodes cross
|
|
94
|
+
* as their names (serializable); the live nodes stay in the DOM, never in
|
|
95
|
+
* the Model. No observer (SSR, old browser) emits nothing instead of
|
|
96
|
+
* throwing. Observes the whole subtree — narrow by placing on a smaller
|
|
97
|
+
* element, not by options.
|
|
98
|
+
*/
|
|
99
99
|
const Mutation = Mount.defineStream("Mutation", {
|
|
100
100
|
messages: [Mutated],
|
|
101
101
|
execute: ({ element }) => Stream.callback((queue) => Effect.gen(function* () {
|
|
@@ -126,15 +126,15 @@ const Mutation = Mount.defineStream("Mutation", {
|
|
|
126
126
|
});
|
|
127
127
|
//#endregion
|
|
128
128
|
//#region src/observers/resize.ts
|
|
129
|
+
const Resized = Schema.TaggedStruct("Resized", {
|
|
130
|
+
width: Schema.Number,
|
|
131
|
+
height: Schema.Number
|
|
132
|
+
});
|
|
129
133
|
/**
|
|
130
134
|
* Element size as a Mount: ResizeObserver reports content-box changes as
|
|
131
135
|
* Messages for the element carrying this Mount. No observer (SSR, old
|
|
132
136
|
* browser) emits nothing instead of throwing.
|
|
133
137
|
*/
|
|
134
|
-
const Resized = Schema.TaggedStruct("Resized", {
|
|
135
|
-
width: Schema.Number,
|
|
136
|
-
height: Schema.Number
|
|
137
|
-
});
|
|
138
138
|
const Resize = Mount.defineStream("Resize", {
|
|
139
139
|
messages: [Resized],
|
|
140
140
|
execute: ({ element }) => Stream.callback((queue) => Effect.gen(function* () {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/observers/bounds.ts","../../src/observers/intersection.ts","../../src/observers/mutation.ts","../../src/observers/resize.ts"],"sourcesContent":["/**\n * Element bounds as a Mount: the bounding rect re-measured on\n * ResizeObserver, window scroll, and window resize, starting with the\n * current rect. Without a ResizeObserver the window events still measure —\n * position changes never needed the observer. No window (SSR) emits nothing\n * instead of throwing.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const Measured = Schema.TaggedStruct('Measured', {\n x: Schema.Number,\n y: Schema.Number,\n width: Schema.Number,\n height: Schema.Number,\n})\nexport type Measured = typeof Measured.Type\n\ntype ObserverCtor = new (callback: () => void) => {\n observe(element: Element): void\n disconnect(): void\n}\n\nexport const Bounds = Mount.defineStream('Bounds', {\n messages: [Measured],\n execute: ({ element }) =>\n Stream.callback<typeof Measured.Type>(queue =>\n Effect.gen(function* () {\n if (typeof window === 'undefined') return\n // Every scroll anywhere measures, and mounting measures twice (the\n // observer's first report and the call below): report only a change.\n let last: DOMRectReadOnly | null = null\n const measure = () => {\n const rect = element.getBoundingClientRect()\n if (\n last !== null &&\n last.x === rect.x &&\n last.y === rect.y &&\n last.width === rect.width &&\n last.height === rect.height\n ) {\n return\n }\n last = rect\n Queue.offerUnsafe(\n queue,\n Measured.make({ x: rect.x, y: rect.y, width: rect.width, height: rect.height }),\n )\n }\n // Capture phase: container scrolls do not bubble, but every scroll\n // descends past the window first.\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n window.addEventListener('scroll', measure, true)\n window.addEventListener('resize', measure)\n const Observed = (globalThis as { ResizeObserver?: ObserverCtor }).ResizeObserver\n if (Observed === undefined) return null\n const observer = new Observed(measure)\n observer.observe(element)\n return observer\n }),\n observer =>\n Effect.sync(() => {\n window.removeEventListener('scroll', measure, true)\n window.removeEventListener('resize', measure)\n observer?.disconnect()\n }),\n )\n measure()\n }),\n ),\n})\n","/**\n * Element visibility as a Mount: IntersectionObserver reports viewport\n * crossings as Messages for the element carrying this Mount. No observer\n * (SSR, old browser) emits nothing instead of throwing.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const IntersectionChanged = Schema.TaggedStruct('IntersectionChanged', {\n isIntersecting: Schema.Boolean,\n ratio: Schema.Number,\n})\nexport type IntersectionChanged = typeof IntersectionChanged.Type\n\ntype ObserverCtor = new (callback: IntersectionObserverCallback) => IntersectionObserver\n\nexport const Intersection = Mount.defineStream('Intersection', {\n messages: [IntersectionChanged],\n execute: ({ element }) =>\n Stream.callback<typeof IntersectionChanged.Type>(queue =>\n Effect.gen(function* () {\n const Observed = (globalThis as { IntersectionObserver?: ObserverCtor })\n .IntersectionObserver\n if (Observed === undefined) return\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n const observer = new Observed(entries => {\n const first = entries[0]\n if (first !== undefined) {\n Queue.offerUnsafe(\n queue,\n IntersectionChanged.make({\n isIntersecting: first.isIntersecting,\n ratio: first.intersectionRatio,\n }),\n )\n }\n })\n observer.observe(element)\n return observer\n }),\n observer => Effect.sync(() => observer.disconnect()),\n )\n }),\n ),\n})\n","/**\n * DOM mutations as a Mount: MutationObserver reports child, attribute, and\n * text changes as Messages for the element carrying this Mount. Nodes cross\n * as their names (serializable); the live nodes stay in the DOM, never in\n * the Model. No observer (SSR, old browser) emits nothing instead of\n * throwing. Observes the whole subtree — narrow by placing on a smaller\n * element, not by options.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const Mutated = Schema.TaggedStruct('Mutated', {\n type: Schema.Literals(['childList', 'attributes', 'characterData']),\n added: Schema.Array(Schema.String),\n removed: Schema.Array(Schema.String),\n attribute: Schema.NullOr(Schema.String),\n})\nexport type Mutated = typeof Mutated.Type\n\ntype ObserverCtor = new (callback: MutationCallback) => MutationObserver\n\nconst recordType = (type: string): Mutated['type'] | null =>\n type === 'childList' || type === 'attributes' || type === 'characterData' ? type : null\n\nexport const Mutation = Mount.defineStream('Mutation', {\n messages: [Mutated],\n execute: ({ element }) =>\n Stream.callback<typeof Mutated.Type>(queue =>\n Effect.gen(function* () {\n const Observed = (globalThis as { MutationObserver?: ObserverCtor }).MutationObserver\n if (Observed === undefined) return\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n const observer = new Observed(records => {\n for (const record of records) {\n const type = recordType(record.type)\n if (type === null) continue\n Queue.offerUnsafe(\n queue,\n Mutated.make({\n type,\n added:\n type === 'childList'\n ? Array.from(record.addedNodes, node => node.nodeName)\n : [],\n removed:\n type === 'childList'\n ? Array.from(record.removedNodes, node => node.nodeName)\n : [],\n attribute: type === 'attributes' ? (record.attributeName ?? null) : null,\n }),\n )\n }\n })\n observer.observe(element, {\n childList: true,\n attributes: true,\n characterData: true,\n subtree: true,\n })\n return observer\n }),\n observer => Effect.sync(() => observer.disconnect()),\n )\n }),\n ),\n})\n","/**\n * Element size as a Mount: ResizeObserver reports content-box changes as\n * Messages for the element carrying this Mount. No observer (SSR, old\n * browser) emits nothing instead of throwing.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const Resized = Schema.TaggedStruct('Resized', {\n width: Schema.Number,\n height: Schema.Number,\n})\nexport type Resized = typeof Resized.Type\n\ntype ObserverCtor = new (callback: ResizeObserverCallback) => ResizeObserver\n\nexport const Resize = Mount.defineStream('Resize', {\n messages: [Resized],\n execute: ({ element }) =>\n Stream.callback<typeof Resized.Type>(queue =>\n Effect.gen(function* () {\n const Observed = (globalThis as { ResizeObserver?: ObserverCtor }).ResizeObserver\n if (Observed === undefined) return\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n const observer = new Observed(entries => {\n const rect = entries[0]?.contentRect\n if (rect !== undefined) {\n Queue.offerUnsafe(queue, Resized.make({ width: rect.width, height: rect.height }))\n }\n })\n observer.observe(element)\n return observer\n }),\n observer => Effect.sync(() => observer.disconnect()),\n )\n }),\n ),\n})\n"],"mappings":";;;;;;;;;;AAUA,MAAa,WAAW,OAAO,aAAa,YAAY;CACtD,GAAG,OAAO;CACV,GAAG,OAAO;CACV,OAAO,OAAO;CACd,QAAQ,OAAO;AACjB,CAAC;AAQD,MAAa,SAAS,MAAM,aAAa,UAAU;CACjD,UAAU,CAAC,QAAQ;CACnB,UAAU,EAAE,cACV,OAAO,UAA+B,UACpC,OAAO,IAAI,aAAa;EACtB,IAAI,OAAO,WAAW,aAAa;EAGnC,IAAI,OAA+B;EACnC,MAAM,gBAAgB;GACpB,MAAM,OAAO,QAAQ,sBAAsB;GAC3C,IACE,SAAS,QACT,KAAK,MAAM,KAAK,KAChB,KAAK,MAAM,KAAK,KAChB,KAAK,UAAU,KAAK,SACpB,KAAK,WAAW,KAAK,QAErB;GAEF,OAAO;GACP,MAAM,YACJ,OACA,SAAS,KAAK;IAAE,GAAG,KAAK;IAAG,GAAG,KAAK;IAAG,OAAO,KAAK;IAAO,QAAQ,KAAK;GAAO,CAAC,CAChF;EACF;EAGA,OAAO,OAAO,eACZ,OAAO,WAAW;GAChB,OAAO,iBAAiB,UAAU,SAAS,IAAI;GAC/C,OAAO,iBAAiB,UAAU,OAAO;GACzC,MAAM,WAAY,WAAiD;GACnE,IAAI,aAAa,KAAA,GAAW,OAAO;GACnC,MAAM,WAAW,IAAI,SAAS,OAAO;GACrC,SAAS,QAAQ,OAAO;GACxB,OAAO;EACT,CAAC,IACD,aACE,OAAO,WAAW;GAChB,OAAO,oBAAoB,UAAU,SAAS,IAAI;GAClD,OAAO,oBAAoB,UAAU,OAAO;GAC5C,UAAU,WAAW;EACvB,CAAC,CACL;EACA,QAAQ;CACV,CAAC,CACH;AACJ,CAAC;;;;;;;;AC/DD,MAAa,sBAAsB,OAAO,aAAa,uBAAuB;CAC5E,gBAAgB,OAAO;CACvB,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A,OACE,SAAS,cACL,MAAM,KAAK,OAAO,aAAY,SAAQ,KAAK,QAAQ,IACnD,CAAC;MACP,SACE,SAAS,cACL,MAAM,KAAK,OAAO,eAAc,SAAQ,KAAK,QAAQ,IACrD,CAAC;MACP,WAAW,SAAS,eAAgB,OAAO,iBAAiB,OAAQ;KACtE,CAAC,CACH;IACF;GACF,CAAC;GACD,SAAS,QAAQ,SAAS;IACxB,WAAW;IACX,YAAY;IACZ,eAAe;IACf,SAAS;GACX,CAAC;GACD,OAAO;EACT,CAAC,IACD,aAAY,OAAO,WAAW,SAAS,WAAW,CAAC,CACrD;CACF,CAAC,CACH;AACJ,CAAC;;;;;;;;AC1DD,MAAa,UAAU,OAAO,aAAa,WAAW;CACpD,OAAO,OAAO;CACd,QAAQ,OAAO;AACjB,CAAC;AAKD,MAAa,SAAS,MAAM,aAAa,UAAU;CACjD,UAAU,CAAC,OAAO;CAClB,UAAU,EAAE,cACV,OAAO,UAA8B,UACnC,OAAO,IAAI,aAAa;EACtB,MAAM,WAAY,WAAiD;EACnE,IAAI,aAAa,KAAA,GAAW;EAC5B,OAAO,OAAO,eACZ,OAAO,WAAW;GAChB,MAAM,WAAW,IAAI,UAAS,YAAW;IACvC,MAAM,OAAO,QAAQ,EAAE,EAAE;IACzB,IAAI,SAAS,KAAA,GACX,MAAM,YAAY,OAAO,QAAQ,KAAK;KAAE,OAAO,KAAK;KAAO,QAAQ,KAAK;IAAO,CAAC,CAAC;GAErF,CAAC;GACD,SAAS,QAAQ,OAAO;GACxB,OAAO;EACT,CAAC,IACD,aAAY,OAAO,WAAW,SAAS,WAAW,CAAC,CACrD;CACF,CAAC,CACH;AACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/observers/bounds.ts","../../src/observers/intersection.ts","../../src/observers/mutation.ts","../../src/observers/resize.ts"],"sourcesContent":["import { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const Measured = Schema.TaggedStruct('Measured', {\n x: Schema.Number,\n y: Schema.Number,\n width: Schema.Number,\n height: Schema.Number,\n})\nexport type Measured = typeof Measured.Type\n\ntype ObserverCtor = new (callback: () => void) => {\n observe(element: Element): void\n disconnect(): void\n}\n\n/**\n * Element bounds as a Mount: the bounding rect re-measured on\n * ResizeObserver, window scroll, and window resize, starting with the\n * current rect. Without a ResizeObserver the window events still measure —\n * position changes never needed the observer. No window (SSR) emits nothing\n * instead of throwing.\n */\nexport const Bounds = Mount.defineStream('Bounds', {\n messages: [Measured],\n execute: ({ element }) =>\n Stream.callback<typeof Measured.Type>(queue =>\n Effect.gen(function* () {\n if (typeof window === 'undefined') return\n // Every scroll anywhere measures, and mounting measures twice (the\n // observer's first report and the call below): report only a change.\n let last: DOMRectReadOnly | null = null\n const measure = () => {\n const rect = element.getBoundingClientRect()\n if (\n last !== null &&\n last.x === rect.x &&\n last.y === rect.y &&\n last.width === rect.width &&\n last.height === rect.height\n ) {\n return\n }\n last = rect\n Queue.offerUnsafe(\n queue,\n Measured.make({ x: rect.x, y: rect.y, width: rect.width, height: rect.height }),\n )\n }\n // Capture phase: container scrolls do not bubble, but every scroll\n // descends past the window first.\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n window.addEventListener('scroll', measure, true)\n window.addEventListener('resize', measure)\n const Observed = (globalThis as { ResizeObserver?: ObserverCtor }).ResizeObserver\n if (Observed === undefined) return null\n const observer = new Observed(measure)\n observer.observe(element)\n return observer\n }),\n observer =>\n Effect.sync(() => {\n window.removeEventListener('scroll', measure, true)\n window.removeEventListener('resize', measure)\n observer?.disconnect()\n }),\n )\n measure()\n }),\n ),\n})\n","import { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const IntersectionChanged = Schema.TaggedStruct('IntersectionChanged', {\n isIntersecting: Schema.Boolean,\n ratio: Schema.Number,\n})\nexport type IntersectionChanged = typeof IntersectionChanged.Type\n\ntype ObserverCtor = new (callback: IntersectionObserverCallback) => IntersectionObserver\n\n/**\n * Element visibility as a Mount: IntersectionObserver reports viewport\n * crossings as Messages for the element carrying this Mount. No observer\n * (SSR, old browser) emits nothing instead of throwing.\n */\nexport const Intersection = Mount.defineStream('Intersection', {\n messages: [IntersectionChanged],\n execute: ({ element }) =>\n Stream.callback<typeof IntersectionChanged.Type>(queue =>\n Effect.gen(function* () {\n const Observed = (globalThis as { IntersectionObserver?: ObserverCtor })\n .IntersectionObserver\n if (Observed === undefined) return\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n const observer = new Observed(entries => {\n const first = entries[0]\n if (first !== undefined) {\n Queue.offerUnsafe(\n queue,\n IntersectionChanged.make({\n isIntersecting: first.isIntersecting,\n ratio: first.intersectionRatio,\n }),\n )\n }\n })\n observer.observe(element)\n return observer\n }),\n observer => Effect.sync(() => observer.disconnect()),\n )\n }),\n ),\n})\n","import { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const Mutated = Schema.TaggedStruct('Mutated', {\n type: Schema.Literals(['childList', 'attributes', 'characterData']),\n added: Schema.Array(Schema.String),\n removed: Schema.Array(Schema.String),\n attribute: Schema.NullOr(Schema.String),\n})\nexport type Mutated = typeof Mutated.Type\n\ntype ObserverCtor = new (callback: MutationCallback) => MutationObserver\n\nconst recordType = (type: string): Mutated['type'] | null =>\n type === 'childList' || type === 'attributes' || type === 'characterData' ? type : null\n\n/**\n * DOM mutations as a Mount: MutationObserver reports child, attribute, and\n * text changes as Messages for the element carrying this Mount. Nodes cross\n * as their names (serializable); the live nodes stay in the DOM, never in\n * the Model. No observer (SSR, old browser) emits nothing instead of\n * throwing. Observes the whole subtree — narrow by placing on a smaller\n * element, not by options.\n */\nexport const Mutation = Mount.defineStream('Mutation', {\n messages: [Mutated],\n execute: ({ element }) =>\n Stream.callback<typeof Mutated.Type>(queue =>\n Effect.gen(function* () {\n const Observed = (globalThis as { MutationObserver?: ObserverCtor }).MutationObserver\n if (Observed === undefined) return\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n const observer = new Observed(records => {\n for (const record of records) {\n const type = recordType(record.type)\n if (type === null) continue\n Queue.offerUnsafe(\n queue,\n Mutated.make({\n type,\n added:\n type === 'childList'\n ? Array.from(record.addedNodes, node => node.nodeName)\n : [],\n removed:\n type === 'childList'\n ? Array.from(record.removedNodes, node => node.nodeName)\n : [],\n attribute: type === 'attributes' ? (record.attributeName ?? null) : null,\n }),\n )\n }\n })\n observer.observe(element, {\n childList: true,\n attributes: true,\n characterData: true,\n subtree: true,\n })\n return observer\n }),\n observer => Effect.sync(() => observer.disconnect()),\n )\n }),\n ),\n})\n","import { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const Resized = Schema.TaggedStruct('Resized', {\n width: Schema.Number,\n height: Schema.Number,\n})\nexport type Resized = typeof Resized.Type\n\ntype ObserverCtor = new (callback: ResizeObserverCallback) => ResizeObserver\n\n/**\n * Element size as a Mount: ResizeObserver reports content-box changes as\n * Messages for the element carrying this Mount. No observer (SSR, old\n * browser) emits nothing instead of throwing.\n */\nexport const Resize = Mount.defineStream('Resize', {\n messages: [Resized],\n execute: ({ element }) =>\n Stream.callback<typeof Resized.Type>(queue =>\n Effect.gen(function* () {\n const Observed = (globalThis as { ResizeObserver?: ObserverCtor }).ResizeObserver\n if (Observed === undefined) return\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n const observer = new Observed(entries => {\n const rect = entries[0]?.contentRect\n if (rect !== undefined) {\n Queue.offerUnsafe(queue, Resized.make({ width: rect.width, height: rect.height }))\n }\n })\n observer.observe(element)\n return observer\n }),\n observer => Effect.sync(() => observer.disconnect()),\n )\n }),\n ),\n})\n"],"mappings":";;;AAGA,MAAa,WAAW,OAAO,aAAa,YAAY;CACtD,GAAG,OAAO;CACV,GAAG,OAAO;CACV,OAAO,OAAO;CACd,QAAQ,OAAO;AACjB,CAAC;;;;;;;;AAeD,MAAa,SAAS,MAAM,aAAa,UAAU;CACjD,UAAU,CAAC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