@u-gotcha/eventbus 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 umeko-gotcha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,58 @@
1
+ /**
2
+ * トピック:データ = 1:1で管理されるアプリメッセージ\
3
+ * イベントの発行者(Message型のデータ生成)と、\
4
+ * イベントの購読者(topicとMessage型のデータを受け取って処理する関数)を\
5
+ * 繋ぐデータ型。任意の型Tを指定のデータで拡張することで静的に型チェックされる。
6
+ * @template M 任意のオブジェクトを拡張した型。トピックとデータのマッピングを定義する。
7
+ * @template T Mのキーの型。トピック名を指定する。
8
+ */
9
+ type Message<M extends object, T extends keyof M> = {
10
+ /** トピック名 */
11
+ topic: T;
12
+ /** トピックと1:1で対応するデータ */
13
+ payload: M[T];
14
+ };
15
+ /**
16
+ * 指定のキーに対応するメッセージを受け取って処理するイベントハンドラー
17
+ * @param message 購読したいトピックに対応したメッセージ型
18
+ */
19
+ type Listener<M extends object, T extends keyof M> = (message: Message<M, T>) => void | Promise<void>;
20
+ /**
21
+ * 実行後にイベントハンドラーを購読解除するための関数
22
+ * @returns イベントハンドラーが削除できたかどうか
23
+ */
24
+ type UnSubscriber = () => boolean;
25
+ /**
26
+ * イベントの発行側がイベント発行時に発生するエラーに対して処理するためのエラーハンドラー
27
+ * @param message エラー発生時に発行していたメッセージオブジェクト
28
+ * @param listener 実行時にエラーを吐いた関数
29
+ * @param error listenerの実行時に発生したエラー
30
+ */
31
+ type OnError<M extends object> = <K extends keyof M>(message: Message<M, K>, listener: Listener<M, K>, error: unknown) => void;
32
+ /**
33
+ * EventBusに対して発行のみを許可するためのインターフェース
34
+ * @example
35
+ * interface YourMessageMap {
36
+ * topic1: { value: string };
37
+ * topic2: { value: number };
38
+ * }
39
+ * const eventbus: Publisher<YourMessageMap> = new EventBus<YourMessageMap>();
40
+ */
41
+ interface Publisher<M extends object> {
42
+ publish<T extends keyof M>(message: Message<M, T>, onError?: OnError<M>): void;
43
+ }
44
+ /**
45
+ * EventBusに対して購読のみを許可するためのインターフェース
46
+ * @example
47
+ * interface YourMessageMap {
48
+ * topic1: { value: string };
49
+ * topic2: { value: number };
50
+ * }
51
+ * const eventbus: Subscriber<YourMessageMap> = new EventBus<YourMessageMap>();
52
+ */
53
+ interface Subscriber<M extends object> {
54
+ /** トピックに対するリスナーを購読する */
55
+ subscribe<T extends keyof M>(topic: T, listener: Listener<M, T>): UnSubscriber;
56
+ }
57
+ export type { Message, Listener, UnSubscriber, OnError, Publisher, Subscriber, };
58
+ //# sourceMappingURL=eventbus-type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventbus-type.d.ts","sourceRoot":"","sources":["../src/eventbus-type.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,KAAK,OAA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27 @@
1
+ import type { Message, Listener, UnSubscriber, OnError } from "./eventbus-type";
2
+ /**
3
+ * メッセージとイベントハンドラーを結ぶためのEventBus
4
+ */
5
+ declare class EventBus<M extends object> {
6
+ #private;
7
+ /**
8
+ * @param onError EventBus共通で処理したい関数。\
9
+ * 指定がない場合はエラーをログに出力するのみ(console.error)となる。
10
+ */
11
+ constructor(onError?: OnError<M>);
12
+ /**
13
+ * 購読したいメッセージを受け取って処理させたい関数を登録するためのsubscriber
14
+ * @param topic 購読したいメッセージのキー
15
+ * @param listener メッセージを受け取って処理させたい関数
16
+ * @returns listenerをEventBusから解除するためのdispose関数
17
+ */
18
+ subscribe<K extends keyof M>(topic: K, listener: Listener<M, K>): UnSubscriber;
19
+ /**
20
+ * イベントを発行しEventBusが管理しているlistenerを実行させる
21
+ * @param message イベントとして飛ばしたいトピックとデータをまとめたメッセージ
22
+ * @param onError listener実行中に例外が発生した際に実行させたエラーハンドラー
23
+ */
24
+ publish<K extends keyof M>(message: Message<M, K>, onError?: OnError<M>): void;
25
+ }
26
+ export { EventBus };
27
+ //# sourceMappingURL=eventbus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventbus.d.ts","sourceRoot":"","sources":["../src/eventbus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,OAAO,EACP,QAAQ,EACR,YAAY,EACZ,OAAO,EACV,MAAM,iBAAiB,CAAC;AASzB;;GAEG;AACH,cAAM,QAAQ,CAAC,CAAC,SAAS,MAAM;;IAO3B;;;OAGG;gBACS,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;IAIhC;;;;;OAKG;IACH,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,YAAY;IAQ9E;;;;OAIG;IACH,OAAO,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI;CAmCjF;AAED,OAAO,EAAE,QAAQ,EAAE,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from "./eventbus";
2
+ export type * from "./eventbus-type";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,mBAAmB,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ // src/eventbus.ts
2
+ var e = class {
3
+ #e = /* @__PURE__ */ new Map();
4
+ #t;
5
+ constructor(e) {
6
+ this.#t = e ?? console.error;
7
+ }
8
+ subscribe(e, t) {
9
+ let n = this.#e.get(e) ?? /* @__PURE__ */ new Set();
10
+ return n.add(t), this.#e.set(e, n), () => n.delete(t);
11
+ }
12
+ publish(e, t) {
13
+ let n = t ?? this.#t, r = Array.from(this.#e.get(e.topic) ?? []), i = (t, r) => {
14
+ try {
15
+ n(e, t, r);
16
+ } catch (t) {
17
+ console.error(`topic「${String(e.topic)}」のエラーハンドラで例外が発生しました。`, t);
18
+ }
19
+ };
20
+ for (let t of r) try {
21
+ let n = t(e);
22
+ n instanceof Promise && n.catch((e) => i(t, e));
23
+ } catch (e) {
24
+ i(t, e);
25
+ }
26
+ }
27
+ };
28
+ export { e as EventBus };
29
+
30
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["EventBus","#onError","onError","listeners","#listenerMap","topic","listener","errorHandler","message","handler","error","err","result"],"sources":["../src/eventbus.ts"],"sourcesContent":["import type {\n Message,\n Listener,\n UnSubscriber,\n OnError\n} from \"./eventbus-type\";\n\n\n/** \n * 内部で使用するサブスクライバーの型\\\n * 内部で持つフィールドに型を持たせられないための対策\n */\ntype AnyListener = (message: never) => void | Promise<void>;\n\n/**\n * メッセージとイベントハンドラーを結ぶためのEventBus\n */\nclass EventBus<M extends object> {\n\n // トピックとトピックを購読したい関数の集合\n #listenerMap: Map<keyof M, Set<AnyListener>> = new Map();\n // EventBus全体で処理する共通のエラーハンドラー\n #onError: OnError<M>;\n\n /**\n * @param onError EventBus共通で処理したい関数。\\\n * 指定がない場合はエラーをログに出力するのみ(console.error)となる。\n */\n constructor(onError?: OnError<M>) {\n this.#onError = onError ?? console.error;\n }\n\n /**\n * 購読したいメッセージを受け取って処理させたい関数を登録するためのsubscriber\n * @param topic 購読したいメッセージのキー\n * @param listener メッセージを受け取って処理させたい関数\n * @returns listenerをEventBusから解除するためのdispose関数\n */\n subscribe<K extends keyof M>(topic: K, listener: Listener<M, K>): UnSubscriber {\n const listeners = this.#listenerMap.get(topic) ?? new Set();\n listeners.add(listener);\n this.#listenerMap.set(topic, listeners);\n // 動的にTopicが増える設計の場合はset自体も削除する必要あり\n return () => listeners.delete(listener);\n }\n\n /**\n * イベントを発行しEventBusが管理しているlistenerを実行させる\n * @param message イベントとして飛ばしたいトピックとデータをまとめたメッセージ\n * @param onError listener実行中に例外が発生した際に実行させたエラーハンドラー\n */\n publish<K extends keyof M>(message: Message<M, K>, onError?: OnError<M>): void {\n\n const errorHandler = onError ?? this.#onError;\n // 元々登録されているlistenerを配列に変換して保持する\n // publish実行時点でのlistenerに対して操作を行うため、\n // subscribe内でのsubscribeやunsubscribeの影響を受けない\n const listeners = Array.from(this.#listenerMap.get(message.topic) ?? []);\n\n // 同期・非同期の両方で使う、例外を外に漏らさないエラー処理\n const handler = (listener: Listener<M, K>, error: unknown) => {\n try {\n errorHandler(message, listener, error);\n } catch (err: unknown) {\n console.error(\n `topic「${String(message.topic)}」のエラーハンドラで例外が発生しました。`,\n err,\n );\n }\n };\n\n // #NOTE: listenerの引数の型であるMessage<M, K>のKをフィールドが持てないため、\n // AnyListener型で保持している。K自体は間違いなくmessage.topicの型であるため、\n // 型アサーションでListener<M, K>[]に変換している。\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n for (const listener of listeners as Listener<M, K>[]) {\n try {\n const result = listener(message);\n if (result instanceof Promise) {\n result.catch(err => handler(listener, err));\n }\n } catch (error: unknown) {\n handler(listener, error);\n }\n }\n }\n}\n\nexport { EventBus };\n"],"mappings":";AAiBA,IAAMA,IAAN,MAAiC;CAG7B,qBAA+C,IAAI,IAAI;CAEvD;CAMA,YAAY,GAAsB;EAC9B,KAAKC,KAAWC,KAAW,QAAQ;CACvC;CAQA,UAA6B,GAAU,GAAwC;EAC3E,IAAMC,IAAY,KAAKC,GAAa,IAAIC,CAAK,qBAAK,IAAI,IAAI;EAI1D,OAHAF,EAAU,IAAIG,CAAQ,GACtB,KAAKF,GAAa,IAAIC,GAAOF,CAAS,SAEzBA,EAAU,OAAOG,CAAQ;CAC1C;CAOA,QAA2B,GAAwB,GAA4B;EAE3E,IAAMC,IAAeL,KAAW,KAAKD,IAI/BE,IAAY,MAAM,KAAK,KAAKC,GAAa,IAAII,EAAQ,KAAK,KAAK,CAAC,CAAC,GAGjEC,KAAW,GAA0B,MAAmB;GAC1D,IAAI;IACA,EAAaD,GAASF,GAAUI,CAAK;GACzC,SAASC,GAAc;IACnB,QAAQ,MACJ,SAAS,OAAOH,EAAQ,KAAK,EAAE,uBAC/BG,CACJ;GACJ;EACJ;EAMA,KAAK,IAAML,KAAYH,GACnB,IAAI;GACA,IAAMS,IAASN,EAASE,CAAO;GAC/B,AAAII,aAAkB,WAClBA,EAAO,OAAM,MAAOH,EAAQH,GAAUK,CAAG,CAAC;EAElD,SAASD,GAAgB;GACrB,EAAQJ,GAAUI,CAAK;EAC3B;CAER;AACJ"}
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@u-gotcha/eventbus",
3
+ "version": "0.1.0",
4
+ "description": "Type-safe event bus",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/umeko-gotcha/common-ts.git",
9
+ "directory": "packages/eventbus"
10
+ },
11
+ "publishConfig": { "access": "public" },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": ["dist"],
19
+ "scripts": {
20
+ "build": "vite build && tsc -p tsconfig.json",
21
+ "prepublishOnly": "npm run build"
22
+ },
23
+ "keywords": [],
24
+ "type": "module"
25
+ }