evikit 2.8.0 → 2.8.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/use-api.d.ts CHANGED
@@ -1,12 +1,13 @@
1
- import { type InferOutput, type ObjectSchema } from "valibot";
2
-
3
- export function queryApi<T, U extends ObjectSchema<T, undefined>>(props: {
4
- lang?: string;
5
- origin: string | undefined;
6
- path: string;
7
- schema?: U;
8
- }): { queryFn: () => Promise<InferOutput<U>>; queryKey: string[] };
9
-
10
- export function useApi<T, U extends ObjectSchema<T, undefined>>(routeType: {
11
- outputs: { 200: U };
12
- }): { data?: InferOutput<U>; error?: unknown };
1
+ import { type InferOutput, type ObjectSchema } from "valibot";
2
+
3
+ export function queryApi<T, U extends ObjectSchema<T, undefined>>(props: {
4
+ cookie?: string | undefined;
5
+ lang?: string;
6
+ origin: string | undefined;
7
+ path: string;
8
+ schema?: U;
9
+ }): { queryFn: () => Promise<InferOutput<U>>; queryKey: string[] };
10
+
11
+ export function useApi<T, U extends ObjectSchema<T, undefined>>(routeType: {
12
+ outputs: { 200: U };
13
+ }): { data?: InferOutput<U>; error?: unknown };
package/use-api.js CHANGED
@@ -1,105 +1,119 @@
1
- import { useRoute } from "preact-iso";
2
- import { useEffect, useState } from "preact/hooks";
3
- import { parse } from "valibot";
4
-
5
- import { jsdomCookie } from "./jsdom-cookie.js";
6
- import { SetQueryState, useQuery, useQueryClient } from "./query.js";
7
-
8
- /** @param {{ lang?: string, origin: string | undefined, path: string, schema?: any }} props */
9
- export function queryApi({ lang, origin, path, schema }) {
10
- const queryKey =
11
- path == "/" ? ["home"] : path.split("/").slice(1).map(decodeURIComponent);
12
-
13
- return {
14
- queryFn: async () => {
15
- const response = await fetch(ApiPath({ origin, path }), {
16
- headers: {
17
- ...(lang ? { "Accept-Language": lang } : {}),
18
- Cookie: jsdomCookie.setCookie.join("; "),
19
- },
20
- });
21
- if (response.status >= 400) {
22
- const error = new Error(await response.text());
23
- error.name = response.status.toString();
24
- throw Error;
25
- }
26
- const json = await response.json();
27
- return schema ? parse(schema, json) : json;
28
- },
29
- queryKey,
30
- };
31
- }
32
-
33
- /** @param {{ outputs: { 200: any } }} routeType */
34
- export function useApi(routeType) {
35
- const { origin } = location;
36
- const { path: pathWithoutSearch, query } = useRoute();
37
- const search = new URLSearchParams(query).toString();
38
- const path = pathWithoutSearch + (search ? `?${search}` : "");
39
- const schema = routeType.outputs[200];
40
- const { queryFn, queryKey } = queryApi({ origin, path, schema });
41
- const { data, error } = useQuery({ queryFn, queryKey });
42
- const queryClient = useQueryClient();
43
- const setQueryState = SetQueryState({ queryClient, queryKey });
44
- const [sourceUpdate, setSourceUpdate] = useState(Date.now());
45
- useEffect(() => {
46
- if (typeof EventSource == "undefined") {
47
- return;
48
- }
49
- const source = new EventSource(ApiPath({ origin, path: path }));
50
- source.onerror = () => {
51
- setTimeout(() => {
52
- setSourceUpdate(Date.now());
53
- }, 1e3);
54
- };
55
- source.onmessage = ({ data }) => {
56
- data = JSON.parse(data);
57
- if (!data) {
58
- source.close();
59
- setQueryState((existing) =>
60
- existing ? { ...existing, fromEventSource: false } : undefined,
61
- );
62
- } else if (Number(data.statusCode) >= 400) {
63
- setQueryState((existing) => ({
64
- data: existing?.data ?? null,
65
- dataUpdatedAt: Date.now(),
66
- error,
67
- fromEventSource: true,
68
- isInvalidated: false,
69
- /** @type {"error"} */
70
- status: "error",
71
- }));
72
- } else {
73
- setQueryState(() => ({
74
- data: schema
75
- ? parse(schema, JSON.parse(data.body))
76
- : JSON.parse(data.body),
77
- dataUpdatedAt: Date.now(),
78
- error: null,
79
- fromEventSource: true,
80
- isInvalidated: false,
81
- /** @type {"success"} */
82
- status: "success",
83
- }));
84
- }
85
- };
86
- setQueryState((existing) =>
87
- existing ? { ...existing, fromEventSource: true } : undefined,
88
- );
89
- return () => {
90
- source.close();
91
- setQueryState((existing) =>
92
- existing ? { ...existing, fromEventSource: false } : undefined,
93
- );
94
- };
95
- }, [path, sourceUpdate]);
96
- return { data, error };
97
- }
98
-
99
- /** @param {{ origin: string | undefined, path: string }} props */
100
- function ApiPath({ origin, path }) {
101
- return (
102
- (origin || "") +
103
- path.replace(/^\//, "/api/").replace(/^\/api\/(\?|$)/, "/api$1")
104
- );
105
- }
1
+ import { useRoute } from "preact-iso";
2
+ import { useEffect, useState } from "preact/hooks";
3
+ import { parse } from "valibot";
4
+
5
+ import { jsdomCookie } from "./jsdom-cookie.js";
6
+ import { SetQueryState, useQuery, useQueryClient } from "./query.js";
7
+
8
+ /** @param {{ cookie?: string | undefined, lang?: string, origin: string | undefined, path: string, schema?: any }} props */
9
+ export function queryApi({ cookie, lang, origin, path, schema }) {
10
+ const queryKey =
11
+ path == "/" ? ["home"] : path.split("/").slice(1).map(decodeURIComponent);
12
+
13
+ return {
14
+ queryFn: async () => {
15
+ const response = await fetch(ApiPath({ origin, path }), {
16
+ headers: {
17
+ ...(lang ? { "Accept-Language": lang } : {}),
18
+ Cookie: [...(cookie ? [cookie] : []), ...jsdomCookie.setCookie].join(
19
+ "; ",
20
+ ),
21
+ },
22
+ });
23
+ if (response.status >= 400) {
24
+ const error = new Error(await response.text());
25
+ error.name = response.status.toString();
26
+ throw Error;
27
+ }
28
+ const json = await response.json();
29
+ return schema ? parse(schema, json) : json;
30
+ },
31
+ queryKey,
32
+ };
33
+ }
34
+
35
+ /** @param {{ outputs: { 200: any } }} routeType */
36
+ export function useApi(routeType) {
37
+ const { origin } = location;
38
+ const { path: pathWithoutSearch, query } = useRoute();
39
+ const search = new URLSearchParams(query).toString();
40
+ const path = pathWithoutSearch + (search ? `?${search}` : "");
41
+ const schema = routeType.outputs[200];
42
+ const { queryFn, queryKey } = queryApi({ origin, path, schema });
43
+ const { data, error } = useQuery({ queryFn, queryKey });
44
+ const queryClient = useQueryClient();
45
+ const setQueryState = SetQueryState({ queryClient, queryKey });
46
+ const [sourceUpdatedAt, setSourceUpdatedAt] = useState(Date.now());
47
+ const [cookieChangedAt, setCookieChangedAt] = useState(Date.now());
48
+ useEffect(() => {
49
+ if (typeof cookieStore == "undefined") {
50
+ return;
51
+ }
52
+ function onCookie() {
53
+ queryClient.invalidateQueries({ evenIfEventSource: true, queryKey });
54
+ setCookieChangedAt(Date.now());
55
+ }
56
+ cookieStore.addEventListener("change", onCookie);
57
+ return () => cookieStore.removeEventListener("change", onCookie);
58
+ }, []);
59
+ useEffect(() => {
60
+ if (typeof EventSource == "undefined") {
61
+ return;
62
+ }
63
+ const source = new EventSource(ApiPath({ origin, path: path }));
64
+ source.onerror = () => {
65
+ setTimeout(() => {
66
+ setSourceUpdatedAt(Date.now());
67
+ }, 1e3);
68
+ };
69
+ source.onmessage = ({ data }) => {
70
+ data = JSON.parse(data);
71
+ if (!data) {
72
+ source.close();
73
+ setQueryState((existing) =>
74
+ existing ? { ...existing, fromEventSource: false } : undefined,
75
+ );
76
+ } else if (Number(data.statusCode) >= 400) {
77
+ setQueryState((existing) => ({
78
+ data: existing?.data ?? null,
79
+ dataUpdatedAt: Date.now(),
80
+ error,
81
+ fromEventSource: true,
82
+ isInvalidated: false,
83
+ /** @type {"error"} */
84
+ status: "error",
85
+ }));
86
+ } else {
87
+ setQueryState(() => ({
88
+ data: schema
89
+ ? parse(schema, JSON.parse(data.body))
90
+ : JSON.parse(data.body),
91
+ dataUpdatedAt: Date.now(),
92
+ error: null,
93
+ fromEventSource: true,
94
+ isInvalidated: false,
95
+ /** @type {"success"} */
96
+ status: "success",
97
+ }));
98
+ }
99
+ };
100
+ setQueryState((existing) =>
101
+ existing ? { ...existing, fromEventSource: true } : undefined,
102
+ );
103
+ return () => {
104
+ source.close();
105
+ setQueryState((existing) =>
106
+ existing ? { ...existing, fromEventSource: false } : undefined,
107
+ );
108
+ };
109
+ }, [cookieChangedAt, path, sourceUpdatedAt]);
110
+ return { data, error };
111
+ }
112
+
113
+ /** @param {{ origin: string | undefined, path: string }} props */
114
+ function ApiPath({ origin, path }) {
115
+ return (
116
+ (origin || "") +
117
+ path.replace(/^\//, "/api/").replace(/^\/api\/(\?|$)/, "/api$1")
118
+ );
119
+ }