@rojaebl/supa-store 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +707 -3
  3. package/dist/derived.d.ts +9 -0
  4. package/dist/derived.js +103 -0
  5. package/dist/index.d.ts +123 -0
  6. package/dist/index.js +271 -0
  7. package/dist/label.d.ts +5 -0
  8. package/dist/label.js +38 -0
  9. package/dist/mutation.d.ts +46 -0
  10. package/dist/mutation.js +131 -0
  11. package/dist/query.d.ts +184 -0
  12. package/dist/query.js +301 -0
  13. package/dist/react.d.ts +29 -0
  14. package/dist/react.js +36 -0
  15. package/dist/refetch.d.ts +25 -0
  16. package/dist/refetch.js +117 -0
  17. package/dist/resourceHook.d.ts +57 -0
  18. package/dist/resourceHook.js +292 -0
  19. package/dist/rpc/client.d.ts +65 -0
  20. package/dist/rpc/client.js +226 -0
  21. package/dist/rpc/error.d.ts +7 -0
  22. package/dist/rpc/error.js +13 -0
  23. package/dist/rpc/framing.d.ts +4 -0
  24. package/dist/rpc/framing.js +64 -0
  25. package/dist/rpc/index.d.ts +4 -0
  26. package/dist/rpc/index.js +4 -0
  27. package/dist/rpc/session.d.ts +18 -0
  28. package/dist/rpc/session.js +120 -0
  29. package/dist/rpc/transport.d.ts +26 -0
  30. package/dist/rpc/transport.js +122 -0
  31. package/dist/server/core.d.ts +72 -0
  32. package/dist/server/core.js +367 -0
  33. package/dist/server/index.d.ts +2 -0
  34. package/dist/server/index.js +2 -0
  35. package/dist/server/node.d.ts +12 -0
  36. package/dist/server/node.js +240 -0
  37. package/dist/server/sse.d.ts +10 -0
  38. package/dist/server/sse.js +25 -0
  39. package/dist/server/web.d.ts +8 -0
  40. package/dist/server/web.js +147 -0
  41. package/dist/stream/client.d.ts +43 -0
  42. package/dist/stream/client.js +397 -0
  43. package/dist/stream/hook.d.ts +9 -0
  44. package/dist/stream/hook.js +70 -0
  45. package/dist/stream/index.d.ts +53 -0
  46. package/dist/stream/index.js +43 -0
  47. package/dist/stream/protocol.d.ts +105 -0
  48. package/dist/stream/protocol.js +32 -0
  49. package/dist/track.d.ts +19 -0
  50. package/dist/track.js +25 -0
  51. package/package.json +104 -3
  52. package/tools/decline-loader.cjs +8 -0
  53. package/tools/definition.cjs +14 -0
  54. package/tools/next.d.mts +2 -0
  55. package/tools/next.mjs +30 -0
  56. package/tools/vite.d.mts +3 -0
  57. package/tools/vite.mjs +43 -0
@@ -0,0 +1,226 @@
1
+ // 통로 위의 JSON-RPC 를 값과 요청 함수로 꺼낸다(스펙 §6 · §7 · §8) — 생명주기 · 준비 문 · onConnect · 다시 잇기
2
+ // 서버 전용이라 React 를 들이지 않는다. [USE] · retry() 는 두지 않는다
3
+ import { DISPOSE } from "../index.js";
4
+ import { TIMING } from "../stream/client.js";
5
+ import { DEFAULTS, TEXT } from "../stream/protocol.js";
6
+ import { RpcError } from "./error.js";
7
+ import { openSession } from "./session.js";
8
+ /** setTimeout 은 NaN · 2^31-1 넘는 값을 곧바로 터뜨린다 */
9
+ const timeable = (ms) => Number.isFinite(ms) && ms <= 2_147_483_647;
10
+ export function createJsonRpc(o) {
11
+ const firstGap = o[TIMING] ?? DEFAULTS.backoffStartMs;
12
+ const timeoutOf = (ms) => ms ?? o.timeout ?? DEFAULTS.timeoutMs;
13
+ const listeners = new Set();
14
+ const waiting = new Set();
15
+ let data;
16
+ /** 한 번이라도 준비됐나 — status 가 loading 을 벗어난다 */
17
+ let wasReady = false;
18
+ let session;
19
+ /** onConnect 가 끝났다 — 요청 · 알림이 곧바로 나간다 */
20
+ let ready = false;
21
+ /** 끊긴 뒤 아직 준비되지 않았다 */
22
+ let broken = false;
23
+ /** connect 가 던진 문구 — 다음 통로가 열리면 지운다 */
24
+ let failure;
25
+ let closed = false;
26
+ /** 연결 하나마다 올린다 — 앞 연결의 늦은 알림 · 끝남은 이것과 견줘 버린다 */
27
+ let gen = 0;
28
+ let retry;
29
+ let attempt = 0;
30
+ let shown = { data, status: "loading", isFetching: true, error: null };
31
+ const emit = () => {
32
+ const next = closed
33
+ ? { data, status: "ready", isFetching: false, error: null }
34
+ : {
35
+ data,
36
+ status: wasReady ? "ready" : "loading",
37
+ isFetching: !ready,
38
+ error: failure ?? (broken ? TEXT.reconnecting : null),
39
+ };
40
+ if (next.data === shown.data &&
41
+ next.status === shown.status &&
42
+ next.isFetching === shown.isFetching &&
43
+ next.error === shown.error)
44
+ return;
45
+ shown = next;
46
+ // 구독자가 던져도 나머지를 부른다
47
+ for (const fn of [...listeners])
48
+ try {
49
+ fn();
50
+ }
51
+ catch { }
52
+ };
53
+ /** 1초부터 두 배, 30초에서 멈추고 ±20% 를 흔든다(0.3 client 의 backoff 와 같다) */
54
+ const backoff = () => {
55
+ const ms = Math.min(firstGap * 2 ** attempt++, DEFAULTS.backoffMaxMs);
56
+ return Math.round(ms * (1 + DEFAULTS.jitter * (2 * Math.random() - 1)));
57
+ };
58
+ /** 그 연결을 버리고 다시 잇는다 — 세션을 닫으면 통로도 닫힌다(스스로 닫힌 통로여도 close 를 불러 stdio 가 자식을 거둔다) */
59
+ const lost = (my, s, t) => {
60
+ if (my !== gen || closed)
61
+ return;
62
+ gen++;
63
+ session = undefined;
64
+ ready = false;
65
+ broken = true;
66
+ try {
67
+ s?.close();
68
+ }
69
+ catch { }
70
+ try {
71
+ t?.close();
72
+ }
73
+ catch { }
74
+ retry = setTimeout(open, backoff());
75
+ emit();
76
+ };
77
+ const send = (w, s) => {
78
+ waiting.delete(w);
79
+ clearTimeout(w.timer);
80
+ const left = w.timeout - (Date.now() - w.at);
81
+ if (left <= 0)
82
+ return w.reject(new RpcError(TEXT.timeout, 0)); // 준비를 기다리다 시간이 다 갔다
83
+ s.request(w.method, w.params, left, o.cancel).then(w.resolve, w.reject);
84
+ };
85
+ const becomeReady = (my, s, value, notes) => {
86
+ if (my !== gen || closed)
87
+ return;
88
+ data = value;
89
+ // 던지는 알림 하나는 건너뛴다 — 준비 뒤 길(세션이 삼킨다)과 같게
90
+ if (o.reduce)
91
+ for (const n of notes)
92
+ try {
93
+ data = o.reduce(data, n);
94
+ }
95
+ catch { }
96
+ notes.length = 0;
97
+ ready = wasReady = true;
98
+ broken = false;
99
+ attempt = 0;
100
+ for (const w of [...waiting])
101
+ send(w, s);
102
+ emit();
103
+ };
104
+ const attach = (my, t) => {
105
+ if (my !== gen || closed)
106
+ return t.close(); // 기다리는 동안 닫혔다
107
+ failure = undefined;
108
+ /** onConnect 도중 받은 알림 — 준비되면 돌려준 값 위에 쌓는다 */
109
+ const notes = [];
110
+ const s = openSession(t, {
111
+ handlers: o.handlers,
112
+ onNotification: (n) => {
113
+ if (my !== gen)
114
+ return;
115
+ if (!ready)
116
+ return void notes.push(n);
117
+ if (!o.reduce)
118
+ return;
119
+ data = o.reduce(data, n);
120
+ emit();
121
+ },
122
+ onClose: () => lost(my, undefined, t),
123
+ });
124
+ if (my !== gen)
125
+ return; // 통로가 onClose 를 동기로 불렀다
126
+ session = s;
127
+ if (!o.onConnect)
128
+ return becomeReady(my, s, data, notes);
129
+ const rpc = {
130
+ request: (method, params) => s.request(method, params, timeoutOf(), o.cancel),
131
+ notify: (method, params) => s.notify(method, params),
132
+ };
133
+ new Promise((r) => r(o.onConnect(data, rpc))).then((v) => becomeReady(my, s, v, notes), () => lost(my, s));
134
+ emit();
135
+ };
136
+ const open = () => {
137
+ retry = undefined;
138
+ const my = ++gen;
139
+ const failed = (e) => {
140
+ if (my !== gen || closed)
141
+ return;
142
+ failure = e instanceof Error ? e.message : String(e);
143
+ lost(my);
144
+ };
145
+ /** 앱이 지은 통로의 등록이 던져도 uncaught 가 되지 않게 — 통로를 닫고 실패로 보낸다 */
146
+ const go = (t) => {
147
+ try {
148
+ attach(my, t);
149
+ }
150
+ catch (e) {
151
+ try {
152
+ t.close();
153
+ }
154
+ catch { }
155
+ failed(e);
156
+ }
157
+ };
158
+ let r;
159
+ try {
160
+ r = o.connect();
161
+ }
162
+ catch (e) {
163
+ return failed(e);
164
+ }
165
+ if (typeof r.then === "function")
166
+ r.then(go, failed);
167
+ else
168
+ go(r);
169
+ };
170
+ const request = (method, params, timeout) => {
171
+ if (closed)
172
+ return Promise.reject(new RpcError(TEXT.commandFailed, 0));
173
+ if (ready)
174
+ return session.request(method, params, timeout, o.cancel);
175
+ return new Promise((resolve, reject) => {
176
+ const w = { method, params, timeout, at: Date.now(), resolve, reject };
177
+ waiting.add(w);
178
+ // 보내기 전이라 id 가 없다 — requestId 0
179
+ if (timeable(timeout))
180
+ w.timer = setTimeout(() => {
181
+ waiting.delete(w);
182
+ reject(new RpcError(TEXT.timeout, 0));
183
+ }, timeout);
184
+ });
185
+ };
186
+ const notify = (method, params) => {
187
+ if (!ready || closed)
188
+ return false;
189
+ session.notify(method, params);
190
+ return true;
191
+ };
192
+ const close = () => {
193
+ if (closed)
194
+ return;
195
+ closed = true;
196
+ gen++;
197
+ clearTimeout(retry);
198
+ for (const w of waiting) {
199
+ clearTimeout(w.timer);
200
+ w.reject(new RpcError(TEXT.commandFailed, 0));
201
+ }
202
+ waiting.clear();
203
+ session?.close();
204
+ session = undefined;
205
+ ready = false;
206
+ emit();
207
+ };
208
+ const out = {};
209
+ for (const [name, r] of Object.entries((o.requests ?? {})))
210
+ out[name] = (params) => request(r.method, params, timeoutOf(r.timeout));
211
+ for (const [name, method] of Object.entries((o.notifications ?? {})))
212
+ out[name] = (params) => notify(method, params);
213
+ Object.assign(out, {
214
+ request: (method, params) => request(method, params, timeoutOf()),
215
+ notify,
216
+ view: () => shown,
217
+ subscribe(fn) {
218
+ listeners.add(fn);
219
+ return () => void listeners.delete(fn);
220
+ },
221
+ close,
222
+ [DISPOSE]: close,
223
+ });
224
+ open();
225
+ return out;
226
+ }
@@ -0,0 +1,7 @@
1
+ export declare class RpcError extends Error {
2
+ requestId: number;
3
+ code?: number | undefined;
4
+ data?: unknown | undefined;
5
+ name: string;
6
+ constructor(message: string, requestId: number, code?: number | undefined, data?: unknown | undefined);
7
+ }
@@ -0,0 +1,13 @@
1
+ // 요청 하나의 실패 — 0.3 의 CommandError 처럼 message 가 문구다
2
+ export class RpcError extends Error {
3
+ requestId;
4
+ code;
5
+ data;
6
+ name = "RpcError";
7
+ constructor(message, requestId, code, data) {
8
+ super(message);
9
+ this.requestId = requestId;
10
+ this.code = code;
11
+ this.data = data;
12
+ }
13
+ }
@@ -0,0 +1,4 @@
1
+ export type Framing = "content-length" | "ndjson";
2
+ /** 조각을 쌓아 메시지가 다 차면 글자로 알린다 */
3
+ export declare function createReader(framing: Framing, onMessage: (text: string) => void): (chunk: Buffer) => void;
4
+ export declare function encode(framing: Framing, text: string): Buffer;
@@ -0,0 +1,64 @@
1
+ const SEP = Buffer.from("\r\n\r\n");
2
+ const HEAD_MAX = 8192; // 머리 자리에 이보다 쌓이면 깨진 것으로 본다(본문 · 한 줄에는 상한이 없다)
3
+ /** 조각을 쌓아 메시지가 다 차면 글자로 알린다 */
4
+ export function createReader(framing, onMessage) {
5
+ // 아직 다 차지 않은 것을 조각째 모아 둔다 — 조각마다 전체를 복사하지 않는다
6
+ let parts = [];
7
+ let need = -1; // content-length: 본문을 기다리는 중이면 그 길이, 머리를 찾는 중이면 -1
8
+ let got = 0;
9
+ const ndjson = (chunk) => {
10
+ let from = 0;
11
+ for (;;) {
12
+ const nl = chunk.indexOf(10, from); // 새로 온 조각에서만 찾는다
13
+ if (nl < 0)
14
+ break;
15
+ parts.push(chunk.subarray(from, nl));
16
+ const line = Buffer.concat(parts).toString("utf8").replace(/\r$/, "");
17
+ parts = [];
18
+ if (line)
19
+ onMessage(line);
20
+ from = nl + 1;
21
+ }
22
+ if (from < chunk.length)
23
+ parts.push(chunk.subarray(from));
24
+ };
25
+ const lengthed = (chunk) => {
26
+ while (chunk.length) {
27
+ if (need >= 0) {
28
+ const take = Math.min(chunk.length, need - got);
29
+ parts.push(chunk.subarray(0, take));
30
+ got += take;
31
+ chunk = chunk.subarray(take);
32
+ if (got < need)
33
+ return;
34
+ const body = Buffer.concat(parts).toString("utf8");
35
+ parts = [];
36
+ need = -1;
37
+ got = 0;
38
+ if (body)
39
+ onMessage(body);
40
+ continue;
41
+ }
42
+ // 머리를 찾는 중 — 머리는 작아서 이어 붙여도 싸다
43
+ const head = Buffer.concat([...parts, chunk]);
44
+ const end = head.indexOf(SEP);
45
+ if (end < 0) {
46
+ parts = head.length > HEAD_MAX ? [] : [head];
47
+ return;
48
+ }
49
+ const len = end > HEAD_MAX ? undefined : /^content-length:[ \t]*(\d+)/im.exec(head.subarray(0, end).toString("latin1"))?.[1];
50
+ const n = len === undefined ? NaN : Number(len);
51
+ parts = [];
52
+ chunk = head.subarray(end + 4);
53
+ if (Number.isSafeInteger(n))
54
+ need = n; // 길이 없는 · 깨진 머리는 버린다
55
+ }
56
+ };
57
+ return framing === "ndjson" ? ndjson : lengthed;
58
+ }
59
+ export function encode(framing, text) {
60
+ if (framing === "ndjson")
61
+ return Buffer.from(`${text}\n`, "utf8");
62
+ const body = Buffer.from(text, "utf8");
63
+ return Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, "latin1"), body]);
64
+ }
@@ -0,0 +1,4 @@
1
+ export { createJsonRpc, type JsonRpc, type JsonRpcOptions } from "./client.js";
2
+ export { stdio, websocket, type StdioChild, type Transport } from "./transport.js";
3
+ export type { Framing } from "./framing.js";
4
+ export { RpcError } from "./error.js";
@@ -0,0 +1,4 @@
1
+ // supa-store/rpc — 서버 앱이 띄운 프로세스나 다른 서버에 JSON-RPC 로 붙는다(session 은 내보내지 않는다)
2
+ export { createJsonRpc } from "./client.js";
3
+ export { stdio, websocket } from "./transport.js";
4
+ export { RpcError } from "./error.js";
@@ -0,0 +1,18 @@
1
+ import type { Transport } from "./transport.js";
2
+ export interface Session {
3
+ request(method: string, params: unknown, timeout: number, cancel?: (id: number) => {
4
+ method: string;
5
+ params?: unknown;
6
+ }): Promise<unknown>;
7
+ notify(method: string, params?: unknown): void;
8
+ close(): void;
9
+ }
10
+ export interface SessionOptions {
11
+ handlers?: Record<string, (params: any) => unknown>;
12
+ onNotification(n: {
13
+ method: string;
14
+ params?: unknown;
15
+ }): void;
16
+ onClose(): void;
17
+ }
18
+ export declare function openSession(t: Transport, o: SessionOptions): Session;
@@ -0,0 +1,120 @@
1
+ // 통로 하나 위의 JSON-RPC 2.0 — 요청 · 답 · 알림 · 상대의 요청. 상대가 무엇을 보내도 던지거나 닫지 않는다
2
+ import { TEXT } from "../stream/protocol.js";
3
+ import { RpcError } from "./error.js";
4
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
5
+ const isId = (v) => typeof v === "string" || typeof v === "number";
6
+ export function openSession(t, o) {
7
+ const pending = new Map();
8
+ let next = 1;
9
+ /** 닫힌 까닭의 문구 — 비어 있으면 열려 있다 */
10
+ let ended;
11
+ const send = (m) => t.send(JSON.stringify({ jsonrpc: "2.0", ...m }));
12
+ const fail = (text) => {
13
+ for (const [id, p] of pending) {
14
+ clearTimeout(p.timer);
15
+ p.reject(new RpcError(text, id));
16
+ }
17
+ pending.clear();
18
+ };
19
+ const answer = (id, method, params) => {
20
+ const h = o.handlers && Object.hasOwn(o.handlers, method) ? o.handlers[method] : undefined;
21
+ if (!h)
22
+ return send({ id, error: { code: -32601, message: "Method not found" } });
23
+ const internal = (e) => ({ error: { code: -32603, message: e instanceof Error ? e.message : String(e) } });
24
+ /** 값이 글자로 바뀌지 않으면(BigInt · 순환) 그 문구로 답한다 */
25
+ const reply = (m) => {
26
+ try {
27
+ send({ id, ...m });
28
+ }
29
+ catch (e) {
30
+ send({ id, ...internal(e) });
31
+ }
32
+ };
33
+ new Promise((r) => r(h(params))).then((result) => reply({ result: result ?? null }), (e) => reply(internal(e)));
34
+ };
35
+ const handle = (m) => {
36
+ if (!isObject(m))
37
+ return;
38
+ if (typeof m.method === "string") {
39
+ if (m.id === undefined) {
40
+ try {
41
+ o.onNotification("params" in m ? { method: m.method, params: m.params } : { method: m.method });
42
+ }
43
+ catch { }
44
+ }
45
+ else if (isId(m.id))
46
+ answer(m.id, m.method, m.params);
47
+ return;
48
+ }
49
+ const p = typeof m.id === "number" ? pending.get(m.id) : undefined;
50
+ if (!p || !("result" in m || isObject(m.error)))
51
+ return; // 늦은 답 · 모르는 id · 답이 아닌 꼴
52
+ const id = m.id;
53
+ pending.delete(id);
54
+ clearTimeout(p.timer);
55
+ if (isObject(m.error)) {
56
+ const { message, code, data } = m.error;
57
+ const c = typeof code === "number" ? code : undefined;
58
+ const text = typeof message === "string" ? message : c === undefined ? "상대 오류" : `상대 오류 ${c}`;
59
+ p.reject(new RpcError(text, id, c, data));
60
+ }
61
+ else
62
+ p.resolve(m.result);
63
+ };
64
+ t.onMessage((text) => {
65
+ let m;
66
+ try {
67
+ m = JSON.parse(text);
68
+ }
69
+ catch {
70
+ return;
71
+ }
72
+ for (const one of Array.isArray(m) ? m : [m])
73
+ handle(one);
74
+ });
75
+ t.onClose(() => {
76
+ if (ended === undefined)
77
+ ended = TEXT.unknown;
78
+ fail(ended);
79
+ o.onClose();
80
+ });
81
+ return {
82
+ request(method, params, timeout, cancel) {
83
+ const id = next++;
84
+ if (ended !== undefined)
85
+ return Promise.reject(new RpcError(ended, id));
86
+ return new Promise((resolve, reject) => {
87
+ const p = { resolve, reject };
88
+ pending.set(id, p);
89
+ try {
90
+ send({ id, method, params });
91
+ }
92
+ catch (e) {
93
+ pending.delete(id); // params 가 글자로 바뀌지 않으면 남기지 않고 그 오류로 거절한다
94
+ throw e;
95
+ }
96
+ if (!pending.has(id))
97
+ return; // send 도중 답 · 닫힘으로 이미 끝났다
98
+ // setTimeout 은 NaN · 2^31-1 넘는 값을 곧바로 터뜨린다
99
+ if (Number.isFinite(timeout) && timeout <= 2_147_483_647)
100
+ p.timer = setTimeout(() => {
101
+ pending.delete(id);
102
+ reject(new RpcError(TEXT.timeout, id));
103
+ try {
104
+ if (cancel)
105
+ send(cancel(id));
106
+ }
107
+ catch { }
108
+ }, timeout);
109
+ });
110
+ },
111
+ notify: (method, params) => send(params === undefined ? { method } : { method, params }),
112
+ close() {
113
+ if (ended !== undefined)
114
+ return;
115
+ ended = TEXT.commandFailed;
116
+ fail(ended);
117
+ t.close();
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,26 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { type Framing } from "./framing.js";
3
+ export interface Transport {
4
+ send(message: string): void;
5
+ onMessage(fn: (message: string) => void): void;
6
+ /** 한 번만 알린다 — close() 로 닫아도 */
7
+ onClose(fn: (reason?: Error) => void): void;
8
+ close(): void;
9
+ }
10
+ export interface StdioChild {
11
+ stdin: Writable;
12
+ stdout: Readable;
13
+ kill?(): unknown;
14
+ /** ChildProcess 면 'close'(표준 입출력이 다 닫힌 뒤)를 끝남으로, 'error'(실행 파일이 없다 따위)를 그 까닭으로 본다 */
15
+ on?(event: "close" | "error", fn: (e?: Error) => void): unknown;
16
+ }
17
+ /** close() 는 표준 입력을 닫고, kill 이 있으면 killAfter 안에 끝나지 않을 때 kill 한다 */
18
+ export declare function stdio(child: StdioChild, options: {
19
+ framing: Framing;
20
+ killAfter?: number;
21
+ }): Transport;
22
+ /** 프레임 하나가 메시지 하나. 열리기 전에 보낸 것은 열린 뒤 보낸다. url 이 틀리면 동기로 던진다(ws 의 생성자) */
23
+ export declare function websocket(url: string, options?: {
24
+ headers?: Record<string, string>;
25
+ maxPayload?: number;
26
+ }): Transport;
@@ -0,0 +1,122 @@
1
+ import { createRequire } from "node:module";
2
+ import { DEFAULTS } from "../stream/protocol.js";
3
+ import { TIMING } from "../stream/client.js";
4
+ import { createReader, encode } from "./framing.js";
5
+ /** 듣는 이를 모아 알린다 — 쓰는 쪽이 던져도 읽기를 끊지 않는다
6
+ * close() 뒤의 send 는 버리고, 우리가 닫았으면 reason 을 비운다. onClose 뒤에는 메시지를 알리지 않는다 */
7
+ function base(send, close) {
8
+ const onMessage = new Set();
9
+ const onClose = new Set();
10
+ let ended = false;
11
+ let closing = false;
12
+ const transport = {
13
+ send: (m) => {
14
+ if (!ended && !closing)
15
+ send(m);
16
+ },
17
+ onMessage: (fn) => void onMessage.add(fn),
18
+ onClose: (fn) => void onClose.add(fn),
19
+ close: () => {
20
+ if (closing)
21
+ return;
22
+ closing = true;
23
+ close();
24
+ },
25
+ };
26
+ const message = (m) => {
27
+ if (ended)
28
+ return;
29
+ for (const fn of onMessage) {
30
+ try {
31
+ fn(m);
32
+ }
33
+ catch { }
34
+ }
35
+ };
36
+ const end = (reason) => {
37
+ if (ended)
38
+ return;
39
+ ended = true;
40
+ for (const fn of onClose) {
41
+ try {
42
+ fn(closing ? undefined : reason);
43
+ }
44
+ catch { }
45
+ }
46
+ };
47
+ return { transport, message, end, ended: () => ended };
48
+ }
49
+ /** close() 는 표준 입력을 닫고, kill 이 있으면 killAfter 안에 끝나지 않을 때 kill 한다 */
50
+ export function stdio(child, options) {
51
+ const { framing, killAfter = 2_000 } = options;
52
+ let timer;
53
+ /** 프로세스가 끝났나 — 통로가 끝난 것(출력 end)과는 따로 든다. 출력만 닫고 사는 프로세스도 거둬야 한다 */
54
+ let exited = false;
55
+ const b = base((m) => void child.stdin.write(encode(framing, m)), () => {
56
+ child.stdin.end();
57
+ if (!child.kill || exited)
58
+ return;
59
+ timer = setTimeout(() => child.kill(), killAfter);
60
+ timer.unref?.();
61
+ });
62
+ const exit = (e) => {
63
+ exited = true;
64
+ clearTimeout(timer);
65
+ b.end(e);
66
+ };
67
+ child.stdout.on("data", createReader(framing, b.message));
68
+ child.stdout.on("end", () => b.end());
69
+ child.stdout.on("error", (e) => b.end(e));
70
+ child.stdin.on("error", (e) => b.end(e)); // 죽은 프로세스에 쓰면 EPIPE
71
+ child.on?.("close", () => exit());
72
+ child.on?.("error", exit); // 듣지 않으면 spawn 의 ENOENT 가 앱을 죽인다
73
+ return b.transport;
74
+ }
75
+ /** 프레임 하나가 메시지 하나. 열리기 전에 보낸 것은 열린 뒤 보낸다. url 이 틀리면 동기로 던진다(ws 의 생성자) */
76
+ export function websocket(url, options = {}) {
77
+ const { pingMs, idleMs } = options[TIMING] ?? DEFAULTS;
78
+ let WebSocket;
79
+ try {
80
+ ({ WebSocket } = createRequire(import.meta.url)("ws"));
81
+ }
82
+ catch (cause) {
83
+ throw new Error("supa-store/rpc 의 websocket() 은 ws 가 필요하다 — pnpm add ws", { cause });
84
+ }
85
+ const ws = new WebSocket(url, { headers: options.headers, maxPayload: options.maxPayload ?? 1024 * 1024 });
86
+ const queue = [];
87
+ let ping;
88
+ let idle;
89
+ let error;
90
+ const b = base((m) => {
91
+ if (ws.readyState === WebSocket.OPEN)
92
+ ws.send(m);
93
+ else if (ws.readyState === WebSocket.CONNECTING)
94
+ queue.push(m);
95
+ }, () => ws.close());
96
+ /** 살아 있음을 볼 때마다 다시 센다 — 마지막으로 본 뒤 idleMs 면 끊는다(0.3 client 의 watch 와 같은 꼴) */
97
+ const watch = () => {
98
+ clearTimeout(idle);
99
+ idle = setTimeout(() => {
100
+ error = new Error(`${idleMs}ms 동안 pong 이 없다`);
101
+ ws.terminate();
102
+ }, idleMs);
103
+ };
104
+ ws.on("open", () => {
105
+ for (const m of queue.splice(0))
106
+ ws.send(m);
107
+ watch();
108
+ ping = setInterval(() => ws.ping(), pingMs); // 표준 ping 프레임
109
+ });
110
+ ws.on("pong", watch);
111
+ ws.on("message", (data) => {
112
+ watch();
113
+ b.message(data.toString());
114
+ });
115
+ ws.on("error", (e) => (error ??= e)); // 늘 close 가 뒤따른다
116
+ ws.on("close", () => {
117
+ clearInterval(ping);
118
+ clearTimeout(idle);
119
+ b.end(error);
120
+ });
121
+ return b.transport;
122
+ }