@txstate-mws/sveltekit-utils 1.0.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) 2024 Texas State ETC
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.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # sveltekit-utils
2
+ Shared library for code that is specifically tied to sveltekit in addition to svelte.
package/dist/api.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { InteractionEvent } from '@txstate-mws/fastify-shared';
2
+ export type APIBaseQueryPayload = string | Record<string, string | number | (string | number)[]>;
3
+ type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
4
+ /**
5
+ * Provided for convenience in case you are not using APIBase but still want to record navigations
6
+ *
7
+ * If you are using or extending APIBase, call `api.recordNavigations` instead.
8
+ *
9
+ * Must be called from a svelte component. Should usually be your root +layout.svelte.
10
+ */
11
+ export declare function recordNavigations(callback: (evt: InteractionEvent) => void): void;
12
+ export declare class APIBase {
13
+ protected apiBase: string;
14
+ protected authRedirect: string;
15
+ protected token?: string;
16
+ fetch: (info: RequestInfo, init?: RequestInit) => Promise<Response>;
17
+ protected ready: () => void;
18
+ protected readyPromise: Promise<void>;
19
+ constructor(apiBase: string, authRedirect: string);
20
+ init(token: string | undefined, fetch?: (info: RequestInfo, init?: RequestInit) => Promise<Response>): Promise<void>;
21
+ stringifyQuery(query: undefined | APIBaseQueryPayload): string;
22
+ protected request<ReturnType = any>(path: string, method: string, payload?: {
23
+ body?: any;
24
+ query?: APIBaseQueryPayload;
25
+ }): Promise<any>;
26
+ get<ReturnType = any>(path: string, query?: APIBaseQueryPayload): Promise<any>;
27
+ post<ReturnType = any>(path: string, body?: any, query?: APIBaseQueryPayload): Promise<any>;
28
+ put<ReturnType = any>(path: string, body?: any, query?: APIBaseQueryPayload): Promise<any>;
29
+ patch<ReturnType = any>(path: string, body?: any, query?: APIBaseQueryPayload): Promise<any>;
30
+ /**
31
+ * Sending a JSON body with an HTTP DELETE is not recommended
32
+ */
33
+ delete<ReturnType = any>(path: string, query?: APIBaseQueryPayload, body?: any): Promise<any>;
34
+ graphql<ReturnType = any>(query: string, variables?: any, querySignature?: string): Promise<ReturnType>;
35
+ protected analyticsQueue: InteractionEvent[];
36
+ recordInteraction(evt: Optional<InteractionEvent, 'screen'>): void;
37
+ /**
38
+ * Due to the mechanics of sveltekit, this function cannot be fully automatic and must
39
+ * be called in your global +layout.svelte
40
+ */
41
+ recordNavigations(): void;
42
+ }
43
+ export {};
package/dist/api.js ADDED
@@ -0,0 +1,137 @@
1
+ import { toasts } from '@txstate-mws/svelte-components';
2
+ import { error } from '@sveltejs/kit';
3
+ import { get } from 'svelte/store';
4
+ import { rescue, toArray } from 'txstate-utils';
5
+ import { page } from '$app/stores';
6
+ import { afterNavigate } from '$app/navigation';
7
+ /**
8
+ * Provided for convenience in case you are not using APIBase but still want to record navigations
9
+ *
10
+ * If you are using or extending APIBase, call `api.recordNavigations` instead.
11
+ *
12
+ * Must be called from a svelte component. Should usually be your root +layout.svelte.
13
+ */
14
+ export function recordNavigations(callback) {
15
+ afterNavigate(navigation => {
16
+ callback({ eventType: 'sveltekit-utils-navigation', screen: (navigation.from ?? navigation.to)?.route.id, target: navigation.to?.url.toString(), action: 'navigation', additionalProperties: { fullPageLoad: String(!navigation.from) } });
17
+ });
18
+ }
19
+ export class APIBase {
20
+ apiBase;
21
+ authRedirect;
22
+ token;
23
+ fetch;
24
+ ready;
25
+ readyPromise;
26
+ constructor(apiBase, authRedirect) {
27
+ this.apiBase = apiBase;
28
+ this.authRedirect = authRedirect;
29
+ this.readyPromise = new Promise(resolve => { this.ready = resolve; });
30
+ }
31
+ async init(token, fetch) {
32
+ this.token = token;
33
+ this.fetch = fetch ?? this.fetch;
34
+ if (this.token) {
35
+ sessionStorage.setItem('token', this.token);
36
+ }
37
+ else {
38
+ this.token = sessionStorage.getItem('token') ?? undefined;
39
+ }
40
+ this.ready();
41
+ }
42
+ stringifyQuery(query) {
43
+ if (query == null)
44
+ return '';
45
+ if (typeof query === 'string')
46
+ return query.startsWith('?') ? query : '?' + query;
47
+ const p = new URLSearchParams();
48
+ for (const [key, val] of Object.entries(query)) {
49
+ for (const v of toArray(val))
50
+ p.append(key, String(v));
51
+ }
52
+ return '?' + p.toString();
53
+ }
54
+ async request(path, method, payload) {
55
+ await this.readyPromise;
56
+ try {
57
+ const resp = await this.fetch(this.apiBase + path + this.stringifyQuery(payload?.query), {
58
+ method,
59
+ headers: {
60
+ Authorization: `Bearer ${this.token ?? ''}`,
61
+ Accept: 'application/json',
62
+ ...(payload?.body ? { 'Content-Type': 'application/json' } : {})
63
+ },
64
+ body: payload?.body ? JSON.stringify(payload.body) : undefined
65
+ });
66
+ if (!resp.ok) {
67
+ if (resp.status === 401) {
68
+ const loginRedirect = new URL(this.authRedirect);
69
+ loginRedirect.searchParams.set('requestedUrl', location.href);
70
+ location.href = loginRedirect.toString();
71
+ throw error(401);
72
+ }
73
+ else {
74
+ const message = ((await rescue(resp.json()))?.message ?? resp.statusText);
75
+ toasts.add(message);
76
+ throw error(resp.status, message);
77
+ }
78
+ }
79
+ const contentType = resp.headers.get("content-type");
80
+ return (contentType && contentType.indexOf("application/json") !== -1) ? await resp.json() : await resp.text();
81
+ }
82
+ catch (e) {
83
+ toasts.add(e.message);
84
+ throw e;
85
+ }
86
+ }
87
+ async get(path, query) {
88
+ return await this.request(path, 'GET', { query });
89
+ }
90
+ async post(path, body, query) {
91
+ return await this.request(path, 'POST', { body, query });
92
+ }
93
+ async put(path, body, query) {
94
+ return await this.request(path, 'PUT', { body, query });
95
+ }
96
+ async patch(path, body, query) {
97
+ return await this.request(path, 'PATCH', { body, query });
98
+ }
99
+ /**
100
+ * Sending a JSON body with an HTTP DELETE is not recommended
101
+ */
102
+ async delete(path, query, body) {
103
+ return await this.request(path, 'DELETE', { body, query });
104
+ }
105
+ async graphql(query, variables, querySignature) {
106
+ const gqlresponse = await this.request('/graphql', 'POST', { body: {
107
+ query,
108
+ variables,
109
+ extensions: {
110
+ querySignature
111
+ }
112
+ } });
113
+ if (gqlresponse.errors?.length) {
114
+ toasts.add(gqlresponse.errors[0].message);
115
+ throw new Error(JSON.stringify(gqlresponse.errors));
116
+ }
117
+ return gqlresponse.data;
118
+ }
119
+ analyticsQueue = [];
120
+ recordInteraction(evt) {
121
+ evt.screen ??= get(page).route.id;
122
+ this.analyticsQueue.push(evt);
123
+ setTimeout(() => {
124
+ const events = [...this.analyticsQueue];
125
+ this.analyticsQueue.length = 0;
126
+ this.post('/analytics', events).catch((e) => console.error(e));
127
+ }, 2000);
128
+ }
129
+ /**
130
+ * Due to the mechanics of sveltekit, this function cannot be fully automatic and must
131
+ * be called in your global +layout.svelte
132
+ */
133
+ recordNavigations() {
134
+ recordNavigations(this.recordInteraction.bind(this));
135
+ }
136
+ }
137
+ //# sourceMappingURL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ED
@@ -0,0 +1,2 @@
1
+ export * from './api.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@txstate-mws/sveltekit-utils",
3
+ "version": "1.0.0",
4
+ "description": "Shared library for code that is specifically tied to sveltekit in addition to svelte.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./dist/index.js"
8
+ },
9
+ "types": "./dist/index.d.ts",
10
+ "dependencies": {
11
+ "@sveltejs/kit": "^2.5.4",
12
+ "@txstate-mws/fastify-shared": "^1.0.4",
13
+ "@txstate-mws/svelte-components": "^1.6.1",
14
+ "txstate-utils": "^1.8.15"
15
+ },
16
+ "devDependencies": {
17
+ "typescript": "^5.4.3"
18
+ },
19
+ "scripts": {
20
+ "prepublishOnly": "npm run build",
21
+ "build": "tsc -b"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/txstate-etc/sveltekit-utils.git"
26
+ },
27
+ "author": "Nick Wing",
28
+ "license": "MIT",
29
+ "bugs": {
30
+ "url": "https://github.com/txstate-etc/sveltekit-utils/issues"
31
+ },
32
+ "homepage": "https://github.com/txstate-etc/sveltekit-utils#readme",
33
+ "files": ["dist"]
34
+ }