@tonightpass/react 0.0.243 → 0.0.245

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/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { SWRConfiguration, SWRResponse } from 'swr';
2
2
  import { Client, PathsFor, Endpoints, TonightPassAPIError, APIRequestOptions, Query, WebSocketPaths, WebSocketEndpoints } from 'tonightpass';
3
3
  import { SWRInfiniteConfiguration, SWRInfiniteResponse } from 'swr/infinite';
4
+ import { SWRSubscriptionOptions } from 'swr/subscription';
4
5
 
5
6
  declare const client: Client;
6
7
  type AnyEndpoint = Endpoints extends infer T ? T : never;
@@ -20,6 +21,13 @@ interface UseAPIInfiniteConfig<Path extends PathsFor<"GET">> extends SWRInfinite
20
21
  }
21
22
  declare function useAPIInfinite<Path extends PathsFor<"GET">>(getKey: (pageIndex: number, previousPageData: ResponseType<Path> | null) => [Path, Query<Path> | undefined] | null, config?: UseAPIInfiniteConfig<Path>): SWRInfiniteResponse<ResponseType<Path>, ErrorType<Path>>;
22
23
 
24
+ type StreamInner<T> = T extends ReadableStream<infer U> ? U : T;
25
+ type SubscriptionMessageType<Path extends PathsFor<"GET">> = StreamInner<ResponseType<Path>>;
26
+ declare function useAPISubscription<Path extends PathsFor<"GET">, TState = SubscriptionMessageType<Path>>(path: Path | null | undefined, query: Query<Path> | undefined, onMessage: (data: SubscriptionMessageType<Path>, next: SWRSubscriptionOptions<TState>["next"]) => void): {
27
+ data: TState | undefined;
28
+ error: any;
29
+ };
30
+
23
31
  type AnyWebSocketEndpoint = WebSocketEndpoints extends infer T ? T : never;
24
32
  type ForceAccept<T> = T extends never ? unknown : T;
25
33
  type WebSocketOptionsType<Path extends WebSocketPaths> = ForceAccept<Extract<AnyWebSocketEndpoint, {
@@ -37,4 +45,4 @@ declare function useWebSocket<Path extends WebSocketPaths>(path: Path | null | u
37
45
  message: any;
38
46
  };
39
47
 
40
- export { type ErrorType, type ResponseType, type UseAPIConfig, type UseAPIInfiniteConfig, type UseWebSocketOptions, type WebSocketOptionsType, client, useAPI, useAPIInfinite, useWebSocket };
48
+ export { type ErrorType, type ResponseType, type SubscriptionMessageType, type UseAPIConfig, type UseAPIInfiniteConfig, type UseWebSocketOptions, type WebSocketOptionsType, client, useAPI, useAPIInfinite, useAPISubscription, useWebSocket };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { SWRConfiguration, SWRResponse } from 'swr';
2
2
  import { Client, PathsFor, Endpoints, TonightPassAPIError, APIRequestOptions, Query, WebSocketPaths, WebSocketEndpoints } from 'tonightpass';
3
3
  import { SWRInfiniteConfiguration, SWRInfiniteResponse } from 'swr/infinite';
4
+ import { SWRSubscriptionOptions } from 'swr/subscription';
4
5
 
5
6
  declare const client: Client;
6
7
  type AnyEndpoint = Endpoints extends infer T ? T : never;
@@ -20,6 +21,13 @@ interface UseAPIInfiniteConfig<Path extends PathsFor<"GET">> extends SWRInfinite
20
21
  }
21
22
  declare function useAPIInfinite<Path extends PathsFor<"GET">>(getKey: (pageIndex: number, previousPageData: ResponseType<Path> | null) => [Path, Query<Path> | undefined] | null, config?: UseAPIInfiniteConfig<Path>): SWRInfiniteResponse<ResponseType<Path>, ErrorType<Path>>;
22
23
 
24
+ type StreamInner<T> = T extends ReadableStream<infer U> ? U : T;
25
+ type SubscriptionMessageType<Path extends PathsFor<"GET">> = StreamInner<ResponseType<Path>>;
26
+ declare function useAPISubscription<Path extends PathsFor<"GET">, TState = SubscriptionMessageType<Path>>(path: Path | null | undefined, query: Query<Path> | undefined, onMessage: (data: SubscriptionMessageType<Path>, next: SWRSubscriptionOptions<TState>["next"]) => void): {
27
+ data: TState | undefined;
28
+ error: any;
29
+ };
30
+
23
31
  type AnyWebSocketEndpoint = WebSocketEndpoints extends infer T ? T : never;
24
32
  type ForceAccept<T> = T extends never ? unknown : T;
25
33
  type WebSocketOptionsType<Path extends WebSocketPaths> = ForceAccept<Extract<AnyWebSocketEndpoint, {
@@ -37,4 +45,4 @@ declare function useWebSocket<Path extends WebSocketPaths>(path: Path | null | u
37
45
  message: any;
38
46
  };
39
47
 
40
- export { type ErrorType, type ResponseType, type UseAPIConfig, type UseAPIInfiniteConfig, type UseWebSocketOptions, type WebSocketOptionsType, client, useAPI, useAPIInfinite, useWebSocket };
48
+ export { type ErrorType, type ResponseType, type SubscriptionMessageType, type UseAPIConfig, type UseAPIInfiniteConfig, type UseWebSocketOptions, type WebSocketOptionsType, client, useAPI, useAPIInfinite, useAPISubscription, useWebSocket };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var d=require('swr'),tonightpass=require('tonightpass'),l=require('swr/infinite'),R=require('swr/subscription');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var d__default=/*#__PURE__*/_interopDefault(d);var l__default=/*#__PURE__*/_interopDefault(l);var R__default=/*#__PURE__*/_interopDefault(R);var y=new tonightpass.Client({baseURL:tonightpass.DEFAULT_API_URL});function W(t,p,s){let{requestOptions:e,...i}=s||{};return d__default.default(t?[t,p]:null,async([a,n])=>await y.get(a,n,e),i)}function C(t,p){let{requestOptions:s,...e}=p||{};return l__default.default(t,async([P,a])=>await y.get(P,a,s),e)}var x=/^http/;function U(t,p,s){let{data:e,error:i}=R__default.default(t?[t,p]:null,([P,a],{next:n})=>{let c=new tonightpass.WebSocketClient({baseURL:tonightpass.DEFAULT_API_URL.replace(x,"ws"),maxReconnectAttempts:s?.maxReconnectAttempts??3,reconnectInterval:s?.reconnectInterval??1e3}),r=false,u=async()=>{try{await c.connect(P,a??{}),r=!0;}catch(o){n(o instanceof Error?o:new Error("Connection failed"));}};c.on("*",o=>{n(null,{type:"message",data:o});});let h=setInterval(()=>{let o=c.connected;o&&!r?(r=true,n(null,{type:"connected"})):!o&&r&&(r=false,n(null,{type:"disconnected"}));},100);return u(),()=>{clearInterval(h),r&&c.disconnect();}});return {data:e,error:i,isConnected:e?.type==="connected",isDisconnected:e?.type==="disconnected",message:e?.type==="message"?e.data:null}}exports.client=y;exports.useAPI=W;exports.useAPIInfinite=C;exports.useWebSocket=U;//# sourceMappingURL=index.js.map
1
+ 'use strict';var d=require('swr'),tonightpass=require('tonightpass'),l=require('swr/infinite'),S=require('swr/subscription');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var d__default=/*#__PURE__*/_interopDefault(d);var l__default=/*#__PURE__*/_interopDefault(l);var S__default=/*#__PURE__*/_interopDefault(S);var y=new tonightpass.Client({baseURL:tonightpass.DEFAULT_API_URL});function A(n,p,r){let{requestOptions:e,...c}=r||{};return d__default.default(n?[n,p]:null,async([a,t])=>await y.get(a,t,e),c)}function C(n,p){let{requestOptions:r,...e}=p||{};return l__default.default(n,async([u,a])=>await y.get(u,a,r),e)}function U(n,p,r){let e=n?y.url(n,p??{}):null,{data:c,error:u}=S__default.default(e,(a,{next:t})=>{let o=new EventSource(a);return o.onmessage=s=>{try{let P=JSON.parse(s.data);r(P,t);}catch{t(new Error("Failed to parse subscription message"));}},o.onerror=()=>{t(new Error("Subscription connection error"));},()=>o.close()});return {data:c,error:u}}var E=/^http/;function L(n,p,r){let{data:e,error:c}=S__default.default(n?[n,p]:null,([u,a],{next:t})=>{let o=new tonightpass.WebSocketClient({baseURL:tonightpass.DEFAULT_API_URL.replace(E,"ws"),maxReconnectAttempts:r?.maxReconnectAttempts??3,reconnectInterval:r?.reconnectInterval??1e3}),s=false,P=async()=>{try{await o.connect(u,a??{}),s=!0;}catch(i){t(i instanceof Error?i:new Error("Connection failed"));}};o.on("*",i=>{t(null,{type:"message",data:i});});let h=setInterval(()=>{let i=o.connected;i&&!s?(s=true,t(null,{type:"connected"})):!i&&s&&(s=false,t(null,{type:"disconnected"}));},100);return P(),()=>{clearInterval(h),s&&o.disconnect();}});return {data:e,error:c,isConnected:e?.type==="connected",isDisconnected:e?.type==="disconnected",message:e?.type==="message"?e.data:null}}exports.client=y;exports.useAPI=A;exports.useAPIInfinite=C;exports.useAPISubscription=U;exports.useWebSocket=L;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-api.ts","../src/hooks/use-api-infinite.ts","../src/hooks/use-web-socket.ts"],"names":["client","Client","DEFAULT_API_URL","useAPI","path","query","config","requestOptions","swrConfig","useSWR","fetchPath","fetchQuery","useAPIInfinite","getKey","useSWRInfinite","WS_PROTOCOL_REGEX","useWebSocket","options","data","error","useSWRSubscription","wsPath","wsOptions","next","WebSocketClient","isConnected","connect","err","event","connectionInterval","connected"],"mappings":"2UAWaA,IAAAA,CAAAA,CAAS,IAAIC,kBAAAA,CAAO,CAAE,OAASC,CAAAA,2BAAgB,CAAC,EAmBtD,SAASC,CAAAA,CACdC,CACAC,CAAAA,CAAAA,CACAC,CACkD,CAAA,CAClD,GAAM,CAAE,cAAAC,CAAAA,CAAAA,CAAgB,GAAGC,CAAU,EAAIF,CAAU,EAAA,EAUnD,CAAA,OAAOG,kBAILL,CAAAA,CAAAA,CAAO,CAACA,CAAAA,CAAMC,CAAK,CAAA,CAAI,IAZT,CAAA,MAAO,CAACK,CAAAA,CAAWC,CAAU,CAAA,GAI1B,MAAMX,CAAO,CAAA,GAAA,CAAIU,CAAWC,CAAAA,CAAAA,CAAYJ,CAAc,CAAA,CAQjCC,CAAS,CACnD,CCrCO,SAASI,CACdC,CAAAA,CAAAA,CAIAP,CAC0D,CAAA,CAC1D,GAAM,CAAE,cAAA,CAAAC,CAAgB,CAAA,GAAGC,CAAU,CAAA,CAAIF,CAAU,EAAA,EAUnD,CAAA,OAAOQ,kBAAeD,CAAAA,CAAAA,CARN,MAAO,CAACH,CAAWC,CAAAA,CAAU,IAI1B,MAAMX,CAAAA,CAAO,GAAIU,CAAAA,CAAAA,CAAWC,CAAYJ,CAAAA,CAAc,CAIlCC,CAAAA,CAAS,CAClD,CCvBA,IAAMO,CAAoB,CAAA,OAAA,CAenB,SAASC,CAAAA,CACdZ,CACAa,CAAAA,CA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GAAAA,CAAAA,CAAc,KACdF,CAAAA,CAAAA,CAAK,KAAM,CAAE,IAAA,CAAM,cAAe,CAAC,CAEvC,EAAA,CAAA,CAEwD,GAAG,CAAA,CAE3D,OAAAG,CAAQ,EAAA,CAED,IAAM,CACX,aAAcG,CAAAA,CAAkB,CAC5BJ,CAAAA,CAAAA,EACFzB,CAAO,CAAA,UAAA,GAEX,CACF,CACF,CAAA,CAEA,OAAO,CACL,KAAAkB,CACA,CAAA,KAAA,CAAAC,CACA,CAAA,WAAA,CAAaD,CAAM,EAAA,IAAA,GAAS,WAC5B,CAAA,cAAA,CAAgBA,GAAM,IAAS,GAAA,cAAA,CAC/B,OAASA,CAAAA,CAAAA,EAAM,IAAS,GAAA,SAAA,CAAYA,CAAK,CAAA,IAAA,CAAO,IAClD,CACF","file":"index.js","sourcesContent":["import useSWR, { type SWRConfiguration, type SWRResponse } from \"swr\";\nimport {\n type APIRequestOptions,\n Client,\n DEFAULT_API_URL,\n type Endpoints,\n type PathsFor,\n type Query,\n type TonightPassAPIError,\n} from \"tonightpass\";\n\nexport const client = new Client({ baseURL: DEFAULT_API_URL });\n\ntype AnyEndpoint = Endpoints extends infer T ? T : never;\n\ntype ForceAccept<T> = T extends never ? any : T;\n\nexport type ResponseType<Path extends PathsFor<\"GET\">> = ForceAccept<\n Extract<AnyEndpoint, { path: Path; method: \"GET\" }>[\"res\"]\n>;\n\nexport type ErrorType<Path extends PathsFor<\"GET\">> = TonightPassAPIError<\n ResponseType<Path>\n>;\n\nexport interface UseAPIConfig<Path extends PathsFor<\"GET\">>\n extends SWRConfiguration<ResponseType<Path>, ErrorType<Path>> {\n requestOptions?: APIRequestOptions;\n}\n\nexport function useAPI<Path extends PathsFor<\"GET\">>(\n path: Path | null | undefined,\n query?: Query<Path>,\n config?: UseAPIConfig<Path>\n): SWRResponse<ResponseType<Path>, ErrorType<Path>> {\n const { requestOptions, ...swrConfig } = config || {};\n\n const fetcher = async ([fetchPath, fetchQuery]: [\n Path,\n Query<Path> | undefined,\n ]) => {\n const response = await client.get(fetchPath, fetchQuery, requestOptions);\n return response as unknown as ResponseType<Path>;\n };\n\n return useSWR<\n ResponseType<Path>,\n ErrorType<Path>,\n [Path, Query<Path> | undefined] | null\n >(path ? [path, query] : null, fetcher, swrConfig);\n}\n","import useSWRInfinite, {\n type SWRInfiniteConfiguration,\n type SWRInfiniteResponse,\n} from \"swr/infinite\";\nimport type { APIRequestOptions, PathsFor, Query } from \"tonightpass\";\n\nimport { client, type ErrorType, type ResponseType } from \"./use-api\";\n\nexport interface UseAPIInfiniteConfig<Path extends PathsFor<\"GET\">>\n extends SWRInfiniteConfiguration<ResponseType<Path>, ErrorType<Path>> {\n requestOptions?: APIRequestOptions;\n}\n\nexport function useAPIInfinite<Path extends PathsFor<\"GET\">>(\n getKey: (\n pageIndex: number,\n previousPageData: ResponseType<Path> | null\n ) => [Path, Query<Path> | undefined] | null,\n config?: UseAPIInfiniteConfig<Path>\n): SWRInfiniteResponse<ResponseType<Path>, ErrorType<Path>> {\n const { requestOptions, ...swrConfig } = config || {};\n\n const fetcher = async ([fetchPath, fetchQuery]: [\n Path,\n Query<Path> | undefined,\n ]) => {\n const response = await client.get(fetchPath, fetchQuery, requestOptions);\n return response as unknown as ResponseType<Path>;\n };\n\n return useSWRInfinite(getKey, fetcher, swrConfig);\n}\n","import useSWRSubscription from \"swr/subscription\";\nimport {\n DEFAULT_API_URL,\n WebSocketClient,\n type WebSocketEndpoints,\n type WebSocketPaths,\n} from \"tonightpass\";\n\nconst WS_PROTOCOL_REGEX = /^http/;\n\ntype AnyWebSocketEndpoint = WebSocketEndpoints extends infer T ? T : never;\n\ntype ForceAccept<T> = T extends never ? unknown : T;\n\nexport type WebSocketOptionsType<Path extends WebSocketPaths> = ForceAccept<\n Extract<AnyWebSocketEndpoint, { path: Path }>[\"options\"]\n>;\n\nexport type UseWebSocketOptions = {\n maxReconnectAttempts?: number;\n reconnectInterval?: number;\n};\n\nexport function useWebSocket<Path extends WebSocketPaths>(\n path: Path | null | undefined,\n options?: WebSocketOptionsType<Path>,\n config?: UseWebSocketOptions\n) {\n const { data, error } = useSWRSubscription(\n path ? [path, options] : null,\n ([wsPath, wsOptions], { next }) => {\n const client = new WebSocketClient({\n baseURL: DEFAULT_API_URL.replace(WS_PROTOCOL_REGEX, \"ws\"),\n maxReconnectAttempts: config?.maxReconnectAttempts ?? 3,\n reconnectInterval: config?.reconnectInterval ?? 1000,\n });\n\n let isConnected = false;\n\n const connect = async () => {\n try {\n await client.connect(wsPath, wsOptions ?? ({} as any));\n isConnected = true;\n } catch (err) {\n next(err instanceof Error ? err : new Error(\"Connection failed\"));\n }\n };\n\n client.on(\"*\", (event: unknown) => {\n next(null, { type: \"message\", data: event });\n });\n\n // Monitor connection state changes\n const checkConnection = () => {\n const connected = client.connected;\n if (connected && !isConnected) {\n isConnected = true;\n next(null, { type: \"connected\" });\n } else if (!connected && isConnected) {\n isConnected = false;\n next(null, { type: \"disconnected\" });\n }\n };\n\n const connectionInterval = setInterval(checkConnection, 100);\n\n connect();\n\n return () => {\n clearInterval(connectionInterval);\n if (isConnected) {\n client.disconnect();\n }\n };\n }\n );\n\n return {\n data,\n error,\n isConnected: data?.type === \"connected\",\n isDisconnected: data?.type === \"disconnected\",\n message: data?.type === \"message\" ? data.data : null,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/use-api.ts","../src/hooks/use-api-infinite.ts","../src/hooks/use-api-subscription.ts","../src/hooks/use-web-socket.ts"],"names":["client","Client","DEFAULT_API_URL","useAPI","path","query","config","requestOptions","swrConfig","useSWR","fetchPath","fetchQuery","useAPIInfinite","getKey","useSWRInfinite","useAPISubscription","onMessage","url","data","error","useSWRSubscription","sseUrl","next","eventSource","event","parsed","WS_PROTOCOL_REGEX","useWebSocket","options","wsPath","wsOptions","WebSocketClient","isConnected","connect","err","connectionInterval","connected"],"mappings":"2UAWO,IAAMA,EAAS,IAAIC,kBAAAA,CAAO,CAAE,OAASC,CAAAA,2BAAgB,C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AAYpC,CAAO,CAAA,SAAA,CACrBoC,GAAa,CAACJ,CAAAA,EAChBA,EAAc,IACdV,CAAAA,CAAAA,CAAK,KAAM,CAAE,IAAA,CAAM,WAAY,CAAC,CAAA,EACvB,CAACc,CAAaJ,EAAAA,CAAAA,GACvBA,EAAc,KACdV,CAAAA,CAAAA,CAAK,IAAM,CAAA,CAAE,KAAM,cAAe,CAAC,GAEvC,CAEwD,CAAA,GAAG,EAE3D,OAAAW,CAAAA,GAEO,IAAM,CACX,cAAcE,CAAkB,CAAA,CAC5BH,GACFhC,CAAO,CAAA,UAAA,GAEX,CACF,CACF,EAEA,OAAO,CACL,KAAAkB,CACA,CAAA,KAAA,CAAAC,EACA,WAAaD,CAAAA,CAAAA,EAAM,OAAS,WAC5B,CAAA,cAAA,CAAgBA,GAAM,IAAS,GAAA,cAAA,CAC/B,QAASA,CAAM,EAAA,IAAA,GAAS,UAAYA,CAAK,CAAA,IAAA,CAAO,IAClD,CACF","file":"index.js","sourcesContent":["import useSWR, { type SWRConfiguration, type SWRResponse } from \"swr\";\nimport {\n type APIRequestOptions,\n Client,\n DEFAULT_API_URL,\n type Endpoints,\n type PathsFor,\n type Query,\n type TonightPassAPIError,\n} from \"tonightpass\";\n\nexport const client = new Client({ baseURL: DEFAULT_API_URL });\n\ntype AnyEndpoint = Endpoints extends infer T ? T : never;\n\ntype ForceAccept<T> = T extends never ? any : T;\n\nexport type ResponseType<Path extends PathsFor<\"GET\">> = ForceAccept<\n Extract<AnyEndpoint, { path: Path; method: \"GET\" }>[\"res\"]\n>;\n\nexport type ErrorType<Path extends PathsFor<\"GET\">> = TonightPassAPIError<\n ResponseType<Path>\n>;\n\nexport interface UseAPIConfig<Path extends PathsFor<\"GET\">>\n extends SWRConfiguration<ResponseType<Path>, ErrorType<Path>> {\n requestOptions?: APIRequestOptions;\n}\n\nexport function useAPI<Path extends PathsFor<\"GET\">>(\n path: Path | null | undefined,\n query?: Query<Path>,\n config?: UseAPIConfig<Path>\n): SWRResponse<ResponseType<Path>, ErrorType<Path>> {\n const { requestOptions, ...swrConfig } = config || {};\n\n const fetcher = async ([fetchPath, fetchQuery]: [\n Path,\n Query<Path> | undefined,\n ]) => {\n const response = await client.get(fetchPath, fetchQuery, requestOptions);\n return response as unknown as ResponseType<Path>;\n };\n\n return useSWR<\n ResponseType<Path>,\n ErrorType<Path>,\n [Path, Query<Path> | undefined] | null\n >(path ? [path, query] : null, fetcher, swrConfig);\n}\n","import useSWRInfinite, {\n type SWRInfiniteConfiguration,\n type SWRInfiniteResponse,\n} from \"swr/infinite\";\nimport type { APIRequestOptions, PathsFor, Query } from \"tonightpass\";\n\nimport { client, type ErrorType, type ResponseType } from \"./use-api\";\n\nexport interface UseAPIInfiniteConfig<Path extends PathsFor<\"GET\">>\n extends SWRInfiniteConfiguration<ResponseType<Path>, ErrorType<Path>> {\n requestOptions?: APIRequestOptions;\n}\n\nexport function useAPIInfinite<Path extends PathsFor<\"GET\">>(\n getKey: (\n pageIndex: number,\n previousPageData: ResponseType<Path> | null\n ) => [Path, Query<Path> | undefined] | null,\n config?: UseAPIInfiniteConfig<Path>\n): SWRInfiniteResponse<ResponseType<Path>, ErrorType<Path>> {\n const { requestOptions, ...swrConfig } = config || {};\n\n const fetcher = async ([fetchPath, fetchQuery]: [\n Path,\n Query<Path> | undefined,\n ]) => {\n const response = await client.get(fetchPath, fetchQuery, requestOptions);\n return response as unknown as ResponseType<Path>;\n };\n\n return useSWRInfinite(getKey, fetcher, swrConfig);\n}\n","import type { SWRSubscriptionOptions } from \"swr/subscription\";\nimport useSWRSubscription from \"swr/subscription\";\nimport type { PathsFor, Query } from \"tonightpass\";\n\nimport { client, type ResponseType } from \"./use-api\";\n\ntype StreamInner<T> = T extends ReadableStream<infer U> ? U : T;\n\nexport type SubscriptionMessageType<Path extends PathsFor<\"GET\">> = StreamInner<\n ResponseType<Path>\n>;\n\nexport function useAPISubscription<\n Path extends PathsFor<\"GET\">,\n TState = SubscriptionMessageType<Path>,\n>(\n path: Path | null | undefined,\n query: Query<Path> | undefined,\n onMessage: (\n data: SubscriptionMessageType<Path>,\n next: SWRSubscriptionOptions<TState>[\"next\"]\n ) => void\n) {\n const url = path ? client.url(path, query ?? {}) : null;\n\n const { data, error } = useSWRSubscription(\n url,\n (sseUrl: string, { next }: SWRSubscriptionOptions<TState>) => {\n const eventSource = new EventSource(sseUrl);\n\n eventSource.onmessage = (event) => {\n try {\n const parsed: SubscriptionMessageType<Path> = JSON.parse(event.data);\n onMessage(parsed, next);\n } catch {\n next(new Error(\"Failed to parse subscription message\"));\n }\n };\n\n eventSource.onerror = () => {\n next(new Error(\"Subscription connection error\"));\n };\n\n return () => eventSource.close();\n }\n );\n\n return { data, error };\n}\n","import useSWRSubscription from \"swr/subscription\";\nimport {\n DEFAULT_API_URL,\n WebSocketClient,\n type WebSocketEndpoints,\n type WebSocketPaths,\n} from \"tonightpass\";\n\nconst WS_PROTOCOL_REGEX = /^http/;\n\ntype AnyWebSocketEndpoint = WebSocketEndpoints extends infer T ? T : never;\n\ntype ForceAccept<T> = T extends never ? unknown : T;\n\nexport type WebSocketOptionsType<Path extends WebSocketPaths> = ForceAccept<\n Extract<AnyWebSocketEndpoint, { path: Path }>[\"options\"]\n>;\n\nexport type UseWebSocketOptions = {\n maxReconnectAttempts?: number;\n reconnectInterval?: number;\n};\n\nexport function useWebSocket<Path extends WebSocketPaths>(\n path: Path | null | undefined,\n options?: WebSocketOptionsType<Path>,\n config?: UseWebSocketOptions\n) {\n const { data, error } = useSWRSubscription(\n path ? [path, options] : null,\n ([wsPath, wsOptions], { next }) => {\n const client = new WebSocketClient({\n baseURL: DEFAULT_API_URL.replace(WS_PROTOCOL_REGEX, \"ws\"),\n maxReconnectAttempts: config?.maxReconnectAttempts ?? 3,\n reconnectInterval: config?.reconnectInterval ?? 1000,\n });\n\n let isConnected = false;\n\n const connect = async () => {\n try {\n await client.connect(wsPath, wsOptions ?? ({} as any));\n isConnected = true;\n } catch (err) {\n next(err instanceof Error ? err : new Error(\"Connection failed\"));\n }\n };\n\n client.on(\"*\", (event: unknown) => {\n next(null, { type: \"message\", data: event });\n });\n\n // Monitor connection state changes\n const checkConnection = () => {\n const connected = client.connected;\n if (connected && !isConnected) {\n isConnected = true;\n next(null, { type: \"connected\" });\n } else if (!connected && isConnected) {\n isConnected = false;\n next(null, { type: \"disconnected\" });\n }\n };\n\n const connectionInterval = setInterval(checkConnection, 100);\n\n connect();\n\n return () => {\n clearInterval(connectionInterval);\n if (isConnected) {\n client.disconnect();\n }\n };\n }\n );\n\n return {\n data,\n error,\n isConnected: data?.type === \"connected\",\n isDisconnected: data?.type === \"disconnected\",\n message: data?.type === \"message\" ? data.data : null,\n };\n}\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import d from'swr';import {Client,DEFAULT_API_URL,WebSocketClient}from'tonightpass';import l from'swr/infinite';import R from'swr/subscription';var y=new Client({baseURL:DEFAULT_API_URL});function W(t,p,s){let{requestOptions:e,...i}=s||{};return d(t?[t,p]:null,async([a,n])=>await y.get(a,n,e),i)}function C(t,p){let{requestOptions:s,...e}=p||{};return l(t,async([P,a])=>await y.get(P,a,s),e)}var x=/^http/;function U(t,p,s){let{data:e,error:i}=R(t?[t,p]:null,([P,a],{next:n})=>{let c=new WebSocketClient({baseURL:DEFAULT_API_URL.replace(x,"ws"),maxReconnectAttempts:s?.maxReconnectAttempts??3,reconnectInterval:s?.reconnectInterval??1e3}),r=false,u=async()=>{try{await c.connect(P,a??{}),r=!0;}catch(o){n(o instanceof Error?o:new Error("Connection failed"));}};c.on("*",o=>{n(null,{type:"message",data:o});});let h=setInterval(()=>{let o=c.connected;o&&!r?(r=true,n(null,{type:"connected"})):!o&&r&&(r=false,n(null,{type:"disconnected"}));},100);return u(),()=>{clearInterval(h),r&&c.disconnect();}});return {data:e,error:i,isConnected:e?.type==="connected",isDisconnected:e?.type==="disconnected",message:e?.type==="message"?e.data:null}}export{y as client,W as useAPI,C as useAPIInfinite,U as useWebSocket};//# sourceMappingURL=index.mjs.map
1
+ import d from'swr';import {Client,DEFAULT_API_URL,WebSocketClient}from'tonightpass';import l from'swr/infinite';import S from'swr/subscription';var y=new Client({baseURL:DEFAULT_API_URL});function A(n,p,r){let{requestOptions:e,...c}=r||{};return d(n?[n,p]:null,async([a,t])=>await y.get(a,t,e),c)}function C(n,p){let{requestOptions:r,...e}=p||{};return l(n,async([u,a])=>await y.get(u,a,r),e)}function U(n,p,r){let e=n?y.url(n,p??{}):null,{data:c,error:u}=S(e,(a,{next:t})=>{let o=new EventSource(a);return o.onmessage=s=>{try{let P=JSON.parse(s.data);r(P,t);}catch{t(new Error("Failed to parse subscription message"));}},o.onerror=()=>{t(new Error("Subscription connection error"));},()=>o.close()});return {data:c,error:u}}var E=/^http/;function L(n,p,r){let{data:e,error:c}=S(n?[n,p]:null,([u,a],{next:t})=>{let o=new WebSocketClient({baseURL:DEFAULT_API_URL.replace(E,"ws"),maxReconnectAttempts:r?.maxReconnectAttempts??3,reconnectInterval:r?.reconnectInterval??1e3}),s=false,P=async()=>{try{await o.connect(u,a??{}),s=!0;}catch(i){t(i instanceof Error?i:new Error("Connection failed"));}};o.on("*",i=>{t(null,{type:"message",data:i});});let h=setInterval(()=>{let i=o.connected;i&&!s?(s=true,t(null,{type:"connected"})):!i&&s&&(s=false,t(null,{type:"disconnected"}));},100);return P(),()=>{clearInterval(h),s&&o.disconnect();}});return {data:e,error:c,isConnected:e?.type==="connected",isDisconnected:e?.type==="disconnected",message:e?.type==="message"?e.data:null}}export{y as client,A as useAPI,C as useAPIInfinite,U as useAPISubscription,L as useWebSocket};//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-api.ts","../src/hooks/use-api-infinite.ts","../src/hooks/use-web-socket.ts"],"names":["client","Client","DEFAULT_API_URL","useAPI","path","query","config","requestOptions","swrConfig","useSWR","fetchPath","fetchQuery","useAPIInfinite","getKey","useSWRInfinite","WS_PROTOCOL_REGEX","useWebSocket","options","data","error","useSWRSubscription","wsPath","wsOptions","next","WebSocketClient","isConnected","connect","err","event","connectionInterval","connected"],"mappings":"gJAWaA,IAAAA,CAAAA,CAAS,IAAIC,MAAAA,CAAO,CAAE,OAASC,CAAAA,eAAgB,CAAC,EAmBtD,SAASC,CAAAA,CACdC,CACAC,CAAAA,CAAAA,CACAC,CACkD,CAAA,CAClD,GAAM,CAAE,cAAAC,CAAAA,CAAAA,CAAgB,GAAGC,CAAU,EAAIF,CAAU,EAAA,EAUnD,CAAA,OAAOG,CAILL,CAAAA,CAAAA,CAAO,CAACA,CAAAA,CAAMC,CAAK,CAAA,CAAI,IAZT,CAAA,MAAO,CAACK,CAAAA,CAAWC,CAAU,CAAA,GAI1B,MAAMX,CAAO,CAAA,GAAA,CAAIU,CAAWC,CAAAA,CAAAA,CAAYJ,CAAc,CAAA,CAQjCC,CAAS,CACnD,CCrCO,SAASI,CACdC,CAAAA,CAAAA,CAIAP,CAC0D,CAAA,CAC1D,GAAM,CAAE,cAAA,CAAAC,CAAgB,CAAA,GAAGC,CAAU,CAAA,CAAIF,CAAU,EAAA,EAUnD,CAAA,OAAOQ,CAAeD,CAAAA,CAAAA,CARN,MAAO,CAACH,CAAWC,CAAAA,CAAU,IAI1B,MAAMX,CAAAA,CAAO,GAAIU,CAAAA,CAAAA,CAAWC,CAAYJ,CAAAA,CAAc,CAIlCC,CAAAA,CAAS,CAClD,CCvBA,IAAMO,CAAoB,CAAA,OAAA,CAenB,SAASC,CAAAA,CACdZ,CACAa,CAAAA,CAAAA,CACAX,CACA,CAAA,CACA,GAAM,CAAE,IAAAY,CAAAA,CAAAA,CAAM,KAAAC,CAAAA,CAAM,EAAIC,CACtBhB,CAAAA,CAAAA,CAAO,CAACA,CAAAA,CAAMa,CAAO,CAAA,CAAI,IACzB,CAAA,CAAC,CAACI,CAAQC,CAAAA,CAAS,CAAG,CAAA,CAAE,IAAAC,CAAAA,CAAK,CAAM,GAAA,CAC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,OAAO,CACL,KAAAkB,CACA,CAAA,KAAA,CAAAC,CACA,CAAA,WAAA,CAAaD,CAAM,EAAA,IAAA,GAAS,WAC5B,CAAA,cAAA,CAAgBA,GAAM,IAAS,GAAA,cAAA,CAC/B,OAASA,CAAAA,CAAAA,EAAM,IAAS,GAAA,SAAA,CAAYA,CAAK,CAAA,IAAA,CAAO,IAClD,CACF","file":"index.mjs","sourcesContent":["import useSWR, { type SWRConfiguration, type SWRResponse } from \"swr\";\nimport {\n type APIRequestOptions,\n Client,\n DEFAULT_API_URL,\n type Endpoints,\n type PathsFor,\n type Query,\n type TonightPassAPIError,\n} from \"tonightpass\";\n\nexport const client = new Client({ baseURL: DEFAULT_API_URL });\n\ntype AnyEndpoint = Endpoints extends infer T ? T : never;\n\ntype ForceAccept<T> = T extends never ? any : T;\n\nexport type ResponseType<Path extends PathsFor<\"GET\">> = ForceAccept<\n Extract<AnyEndpoint, { path: Path; method: \"GET\" }>[\"res\"]\n>;\n\nexport type ErrorType<Path extends PathsFor<\"GET\">> = TonightPassAPIError<\n ResponseType<Path>\n>;\n\nexport interface UseAPIConfig<Path extends PathsFor<\"GET\">>\n extends SWRConfiguration<ResponseType<Path>, ErrorType<Path>> {\n requestOptions?: APIRequestOptions;\n}\n\nexport function useAPI<Path extends PathsFor<\"GET\">>(\n path: Path | null | undefined,\n query?: Query<Path>,\n config?: UseAPIConfig<Path>\n): SWRResponse<ResponseType<Path>, ErrorType<Path>> {\n const { requestOptions, ...swrConfig } = config || {};\n\n const fetcher = async ([fetchPath, fetchQuery]: [\n Path,\n Query<Path> | undefined,\n ]) => {\n const response = await client.get(fetchPath, fetchQuery, requestOptions);\n return response as unknown as ResponseType<Path>;\n };\n\n return useSWR<\n ResponseType<Path>,\n ErrorType<Path>,\n [Path, Query<Path> | undefined] | null\n >(path ? [path, query] : null, fetcher, swrConfig);\n}\n","import useSWRInfinite, {\n type SWRInfiniteConfiguration,\n type SWRInfiniteResponse,\n} from \"swr/infinite\";\nimport type { APIRequestOptions, PathsFor, Query } from \"tonightpass\";\n\nimport { client, type ErrorType, type ResponseType } from \"./use-api\";\n\nexport interface UseAPIInfiniteConfig<Path extends PathsFor<\"GET\">>\n extends SWRInfiniteConfiguration<ResponseType<Path>, ErrorType<Path>> {\n requestOptions?: APIRequestOptions;\n}\n\nexport function useAPIInfinite<Path extends PathsFor<\"GET\">>(\n getKey: (\n pageIndex: number,\n previousPageData: ResponseType<Path> | null\n ) => [Path, Query<Path> | undefined] | null,\n config?: UseAPIInfiniteConfig<Path>\n): SWRInfiniteResponse<ResponseType<Path>, ErrorType<Path>> {\n const { requestOptions, ...swrConfig } = config || {};\n\n const fetcher = async ([fetchPath, fetchQuery]: [\n Path,\n Query<Path> | undefined,\n ]) => {\n const response = await client.get(fetchPath, fetchQuery, requestOptions);\n return response as unknown as ResponseType<Path>;\n };\n\n return useSWRInfinite(getKey, fetcher, swrConfig);\n}\n","import useSWRSubscription from \"swr/subscription\";\nimport {\n DEFAULT_API_URL,\n WebSocketClient,\n type WebSocketEndpoints,\n type WebSocketPaths,\n} from \"tonightpass\";\n\nconst WS_PROTOCOL_REGEX = /^http/;\n\ntype AnyWebSocketEndpoint = WebSocketEndpoints extends infer T ? T : never;\n\ntype ForceAccept<T> = T extends never ? unknown : T;\n\nexport type WebSocketOptionsType<Path extends WebSocketPaths> = ForceAccept<\n Extract<AnyWebSocketEndpoint, { path: Path }>[\"options\"]\n>;\n\nexport type UseWebSocketOptions = {\n maxReconnectAttempts?: number;\n reconnectInterval?: number;\n};\n\nexport function useWebSocket<Path extends WebSocketPaths>(\n path: Path | null | undefined,\n options?: WebSocketOptionsType<Path>,\n config?: UseWebSocketOptions\n) {\n const { data, error } = useSWRSubscription(\n path ? [path, options] : null,\n ([wsPath, wsOptions], { next }) => {\n const client = new WebSocketClient({\n baseURL: DEFAULT_API_URL.replace(WS_PROTOCOL_REGEX, \"ws\"),\n maxReconnectAttempts: config?.maxReconnectAttempts ?? 3,\n reconnectInterval: config?.reconnectInterval ?? 1000,\n });\n\n let isConnected = false;\n\n const connect = async () => {\n try {\n await client.connect(wsPath, wsOptions ?? ({} as any));\n isConnected = true;\n } catch (err) {\n next(err instanceof Error ? err : new Error(\"Connection failed\"));\n }\n };\n\n client.on(\"*\", (event: unknown) => {\n next(null, { type: \"message\", data: event });\n });\n\n // Monitor connection state changes\n const checkConnection = () => {\n const connected = client.connected;\n if (connected && !isConnected) {\n isConnected = true;\n next(null, { type: \"connected\" });\n } else if (!connected && isConnected) {\n isConnected = false;\n next(null, { type: \"disconnected\" });\n }\n };\n\n const connectionInterval = setInterval(checkConnection, 100);\n\n connect();\n\n return () => {\n clearInterval(connectionInterval);\n if (isConnected) {\n client.disconnect();\n }\n };\n }\n );\n\n return {\n data,\n error,\n isConnected: data?.type === \"connected\",\n isDisconnected: data?.type === \"disconnected\",\n message: data?.type === \"message\" ? data.data : null,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/use-api.ts","../src/hooks/use-api-infinite.ts","../src/hooks/use-api-subscription.ts","../src/hooks/use-web-socket.ts"],"names":["client","Client","DEFAULT_API_URL","useAPI","path","query","config","requestOptions","swrConfig","useSWR","fetchPath","fetchQuery","useAPIInfinite","getKey","useSWRInfinite","useAPISubscription","onMessage","url","data","error","useSWRSubscription","sseUrl","next","eventSource","event","parsed","WS_PROTOCOL_REGEX","useWebSocket","options","wsPath","wsOptions","WebSocketClient","isConnected","connect","err","connectionInterval","connected"],"mappings":"gJAWO,IAAMA,EAAS,IAAIC,MAAAA,CAAO,CAAE,OAASC,CAAAA,eAAgB,CAAC,EAmBtD,SAASC,EACdC,CACAC,CAAAA,CAAAA,CACAC,CACkD,CAAA,CAClD,GAAM,CAAE,cAAA,CAAAC,EAAgB,GAAGC,CAAU,EAAIF,CAAU,EAAA,GAUnD,OAAOG,CAAAA,CAILL,EAAO,CAACA,CAAAA,CAAMC,CAAK,CAAI,CAAA,IAAA,CAZT,MAAO,CAACK,CAAAA,CAAWC,CAAU,CAAA,GAI1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AG,EAE3D,OAAAW,CAAAA,GAEO,IAAM,CACX,cAAcE,CAAkB,CAAA,CAC5BH,GACFhC,CAAO,CAAA,UAAA,GAEX,CACF,CACF,EAEA,OAAO,CACL,KAAAkB,CACA,CAAA,KAAA,CAAAC,EACA,WAAaD,CAAAA,CAAAA,EAAM,OAAS,WAC5B,CAAA,cAAA,CAAgBA,GAAM,IAAS,GAAA,cAAA,CAC/B,QAASA,CAAM,EAAA,IAAA,GAAS,UAAYA,CAAK,CAAA,IAAA,CAAO,IAClD,CACF","file":"index.mjs","sourcesContent":["import useSWR, { type SWRConfiguration, type SWRResponse } from \"swr\";\nimport {\n type APIRequestOptions,\n Client,\n DEFAULT_API_URL,\n type Endpoints,\n type PathsFor,\n type Query,\n type TonightPassAPIError,\n} from \"tonightpass\";\n\nexport const client = new Client({ baseURL: DEFAULT_API_URL });\n\ntype AnyEndpoint = Endpoints extends infer T ? T : never;\n\ntype ForceAccept<T> = T extends never ? any : T;\n\nexport type ResponseType<Path extends PathsFor<\"GET\">> = ForceAccept<\n Extract<AnyEndpoint, { path: Path; method: \"GET\" }>[\"res\"]\n>;\n\nexport type ErrorType<Path extends PathsFor<\"GET\">> = TonightPassAPIError<\n ResponseType<Path>\n>;\n\nexport interface UseAPIConfig<Path extends PathsFor<\"GET\">>\n extends SWRConfiguration<ResponseType<Path>, ErrorType<Path>> {\n requestOptions?: APIRequestOptions;\n}\n\nexport function useAPI<Path extends PathsFor<\"GET\">>(\n path: Path | null | undefined,\n query?: Query<Path>,\n config?: UseAPIConfig<Path>\n): SWRResponse<ResponseType<Path>, ErrorType<Path>> {\n const { requestOptions, ...swrConfig } = config || {};\n\n const fetcher = async ([fetchPath, fetchQuery]: [\n Path,\n Query<Path> | undefined,\n ]) => {\n const response = await client.get(fetchPath, fetchQuery, requestOptions);\n return response as unknown as ResponseType<Path>;\n };\n\n return useSWR<\n ResponseType<Path>,\n ErrorType<Path>,\n [Path, Query<Path> | undefined] | null\n >(path ? [path, query] : null, fetcher, swrConfig);\n}\n","import useSWRInfinite, {\n type SWRInfiniteConfiguration,\n type SWRInfiniteResponse,\n} from \"swr/infinite\";\nimport type { APIRequestOptions, PathsFor, Query } from \"tonightpass\";\n\nimport { client, type ErrorType, type ResponseType } from \"./use-api\";\n\nexport interface UseAPIInfiniteConfig<Path extends PathsFor<\"GET\">>\n extends SWRInfiniteConfiguration<ResponseType<Path>, ErrorType<Path>> {\n requestOptions?: APIRequestOptions;\n}\n\nexport function useAPIInfinite<Path extends PathsFor<\"GET\">>(\n getKey: (\n pageIndex: number,\n previousPageData: ResponseType<Path> | null\n ) => [Path, Query<Path> | undefined] | null,\n config?: UseAPIInfiniteConfig<Path>\n): SWRInfiniteResponse<ResponseType<Path>, ErrorType<Path>> {\n const { requestOptions, ...swrConfig } = config || {};\n\n const fetcher = async ([fetchPath, fetchQuery]: [\n Path,\n Query<Path> | undefined,\n ]) => {\n const response = await client.get(fetchPath, fetchQuery, requestOptions);\n return response as unknown as ResponseType<Path>;\n };\n\n return useSWRInfinite(getKey, fetcher, swrConfig);\n}\n","import type { SWRSubscriptionOptions } from \"swr/subscription\";\nimport useSWRSubscription from \"swr/subscription\";\nimport type { PathsFor, Query } from \"tonightpass\";\n\nimport { client, type ResponseType } from \"./use-api\";\n\ntype StreamInner<T> = T extends ReadableStream<infer U> ? U : T;\n\nexport type SubscriptionMessageType<Path extends PathsFor<\"GET\">> = StreamInner<\n ResponseType<Path>\n>;\n\nexport function useAPISubscription<\n Path extends PathsFor<\"GET\">,\n TState = SubscriptionMessageType<Path>,\n>(\n path: Path | null | undefined,\n query: Query<Path> | undefined,\n onMessage: (\n data: SubscriptionMessageType<Path>,\n next: SWRSubscriptionOptions<TState>[\"next\"]\n ) => void\n) {\n const url = path ? client.url(path, query ?? {}) : null;\n\n const { data, error } = useSWRSubscription(\n url,\n (sseUrl: string, { next }: SWRSubscriptionOptions<TState>) => {\n const eventSource = new EventSource(sseUrl);\n\n eventSource.onmessage = (event) => {\n try {\n const parsed: SubscriptionMessageType<Path> = JSON.parse(event.data);\n onMessage(parsed, next);\n } catch {\n next(new Error(\"Failed to parse subscription message\"));\n }\n };\n\n eventSource.onerror = () => {\n next(new Error(\"Subscription connection error\"));\n };\n\n return () => eventSource.close();\n }\n );\n\n return { data, error };\n}\n","import useSWRSubscription from \"swr/subscription\";\nimport {\n DEFAULT_API_URL,\n WebSocketClient,\n type WebSocketEndpoints,\n type WebSocketPaths,\n} from \"tonightpass\";\n\nconst WS_PROTOCOL_REGEX = /^http/;\n\ntype AnyWebSocketEndpoint = WebSocketEndpoints extends infer T ? T : never;\n\ntype ForceAccept<T> = T extends never ? unknown : T;\n\nexport type WebSocketOptionsType<Path extends WebSocketPaths> = ForceAccept<\n Extract<AnyWebSocketEndpoint, { path: Path }>[\"options\"]\n>;\n\nexport type UseWebSocketOptions = {\n maxReconnectAttempts?: number;\n reconnectInterval?: number;\n};\n\nexport function useWebSocket<Path extends WebSocketPaths>(\n path: Path | null | undefined,\n options?: WebSocketOptionsType<Path>,\n config?: UseWebSocketOptions\n) {\n const { data, error } = useSWRSubscription(\n path ? [path, options] : null,\n ([wsPath, wsOptions], { next }) => {\n const client = new WebSocketClient({\n baseURL: DEFAULT_API_URL.replace(WS_PROTOCOL_REGEX, \"ws\"),\n maxReconnectAttempts: config?.maxReconnectAttempts ?? 3,\n reconnectInterval: config?.reconnectInterval ?? 1000,\n });\n\n let isConnected = false;\n\n const connect = async () => {\n try {\n await client.connect(wsPath, wsOptions ?? ({} as any));\n isConnected = true;\n } catch (err) {\n next(err instanceof Error ? err : new Error(\"Connection failed\"));\n }\n };\n\n client.on(\"*\", (event: unknown) => {\n next(null, { type: \"message\", data: event });\n });\n\n // Monitor connection state changes\n const checkConnection = () => {\n const connected = client.connected;\n if (connected && !isConnected) {\n isConnected = true;\n next(null, { type: \"connected\" });\n } else if (!connected && isConnected) {\n isConnected = false;\n next(null, { type: \"disconnected\" });\n }\n };\n\n const connectionInterval = setInterval(checkConnection, 100);\n\n connect();\n\n return () => {\n clearInterval(connectionInterval);\n if (isConnected) {\n client.disconnect();\n }\n };\n }\n );\n\n return {\n data,\n error,\n isConnected: data?.type === \"connected\",\n isDisconnected: data?.type === \"disconnected\",\n message: data?.type === \"message\" ? data.data : null,\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonightpass/react",
3
- "version": "0.0.243",
3
+ "version": "0.0.245",
4
4
  "description": "@tonightpass react sdk.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -28,7 +28,7 @@
28
28
  "types": "dist/index.d.ts",
29
29
  "dependencies": {
30
30
  "swr": "^2.2.5",
31
- "tonightpass": "^0.0.239"
31
+ "tonightpass": "^0.0.241"
32
32
  },
33
33
  "peerDependencies": {
34
34
  "react": "*"