@ismou-workspace/web-kit 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,16 @@
1
- # Temporary Holding Version
1
+ # @ismou-workspace/web-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Browser plumbing for Ismou's web clients: typed fetch, query client.
4
+
5
+ Part of the [Ismou SDK](https://github.com/ismou-workspace/sdk): the packages the core and every app of [Ismou](https://github.com/ismou-workspace) are built with, released together under one version.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @ismou-workspace/web-kit
11
+ ```
12
+
13
+ ## Documentation
14
+
15
+ - [The platform's documentation](https://github.com/ismou-workspace/sdk/tree/main/docs): architecture, conventions, design system.
16
+ - [Source](https://github.com/ismou-workspace/sdk/tree/main/packages/web-kit)
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The base path the app is served under (`/apps/drive`), `''` at the root of its origin. The
3
+ * server names it in the `<base>` element of `index.html`; the Vite dev server serves at the root.
4
+ */
5
+ export declare function appBasePath(): string;
6
+ /**
7
+ * A path from the app's root (`/api/files`), on the page's origin: under the base path, if any.
8
+ * A path already under it, or a URL, is returned as is: app paths never start with the base
9
+ * path's segments (`/api`, `/.well-known`, `/assets`...).
10
+ */
11
+ export declare function appPath(path: string): string;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The base path the app is served under (`/apps/drive`), `''` at the root of its origin. The
3
+ * server names it in the `<base>` element of `index.html`; the Vite dev server serves at the root.
4
+ */
5
+ export function appBasePath() {
6
+ const href = typeof document === 'undefined' ? null : document.querySelector('base')?.getAttribute('href');
7
+ return href ? href.replace(/\/+$/, '') : '';
8
+ }
9
+ /**
10
+ * A path from the app's root (`/api/files`), on the page's origin: under the base path, if any.
11
+ * A path already under it, or a URL, is returned as is: app paths never start with the base
12
+ * path's segments (`/api`, `/.well-known`, `/assets`...).
13
+ */
14
+ export function appPath(path) {
15
+ const base = appBasePath();
16
+ if (!path.startsWith('/') || path.startsWith('//'))
17
+ return path;
18
+ if (base && (path === base || path.startsWith(`${base}/`)))
19
+ return path;
20
+ return `${base}${path}`;
21
+ }
@@ -0,0 +1,29 @@
1
+ import type { z } from 'zod';
2
+ /** A non-2xx response of a platform API, carrying the message of its `ApiErrorBody`. */
3
+ export declare class ApiError extends Error {
4
+ readonly name = "ApiError";
5
+ readonly status: number;
6
+ constructor(status: number, message: string);
7
+ }
8
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
9
+ export interface RequestOptions {
10
+ method?: HttpMethod;
11
+ /** Serialized as JSON; `FormData` is sent as is (multipart, the browser sets the boundary). */
12
+ body?: unknown;
13
+ signal?: AbortSignal;
14
+ }
15
+ /**
16
+ * The failure a non-2xx response carries: its `ApiErrorBody` message, or a plain one when it
17
+ * has none. For calls made with `fetch` directly (a file's bytes, an upload's progress).
18
+ */
19
+ export declare function readApiError(response: Response): Promise<ApiError>;
20
+ /** Calls a JSON endpoint and validates its response with a contract schema. */
21
+ export declare function fetchJson<Schema extends z.ZodType>(path: string, schema: Schema, options?: RequestOptions): Promise<z.output<Schema>>;
22
+ /** A 2xx response whose body does not match the contract the client was built with. */
23
+ export declare class UnexpectedResponseError extends Error {
24
+ readonly name = "UnexpectedResponseError";
25
+ readonly path: string;
26
+ constructor(path: string);
27
+ }
28
+ /** Calls an endpoint that answers `204 No Content`; any response body is ignored. */
29
+ export declare function fetchNoContent(path: string, options?: RequestOptions): Promise<void>;
@@ -0,0 +1,67 @@
1
+ import { ApiErrorBodySchema } from '@ismou-workspace/contracts';
2
+ import { appPath } from './app-path.js';
3
+ /** A non-2xx response of a platform API, carrying the message of its `ApiErrorBody`. */
4
+ export class ApiError extends Error {
5
+ name = 'ApiError';
6
+ status;
7
+ constructor(status, message) {
8
+ super(message);
9
+ this.status = status;
10
+ }
11
+ }
12
+ function encodeBody(body, headers) {
13
+ if (body === undefined)
14
+ return undefined;
15
+ if (body instanceof FormData)
16
+ return body;
17
+ headers.set('Content-Type', 'application/json');
18
+ return JSON.stringify(body);
19
+ }
20
+ async function send(path, { method = 'GET', body, signal }) {
21
+ const headers = new Headers({ Accept: 'application/json' });
22
+ const response = await fetch(appPath(path), {
23
+ method,
24
+ headers,
25
+ body: encodeBody(body, headers),
26
+ credentials: 'same-origin',
27
+ signal,
28
+ });
29
+ if (!response.ok)
30
+ throw await readApiError(response);
31
+ return response;
32
+ }
33
+ /**
34
+ * The failure a non-2xx response carries: its `ApiErrorBody` message, or a plain one when it
35
+ * has none. For calls made with `fetch` directly (a file's bytes, an upload's progress).
36
+ */
37
+ export async function readApiError(response) {
38
+ const parsed = ApiErrorBodySchema.safeParse(await response.json().catch(() => null));
39
+ const message = parsed.success
40
+ ? parsed.data.error.message
41
+ : `Request failed with status ${response.status}.`;
42
+ return new ApiError(response.status, message);
43
+ }
44
+ /** Calls a JSON endpoint and validates its response with a contract schema. */
45
+ export async function fetchJson(path, schema, options = {}) {
46
+ const response = await send(path, options);
47
+ const parsed = schema.safeParse(await response.json());
48
+ if (parsed.success)
49
+ return parsed.data;
50
+ // The server and this client disagree on the contract (usually a deploy skew): a bug, not
51
+ // something the person can act on. Details go to the console, the screen gets a plain message.
52
+ console.error(`Unexpected response from ${path}`, parsed.error.issues);
53
+ throw new UnexpectedResponseError(path);
54
+ }
55
+ /** A 2xx response whose body does not match the contract the client was built with. */
56
+ export class UnexpectedResponseError extends Error {
57
+ name = 'UnexpectedResponseError';
58
+ path;
59
+ constructor(path) {
60
+ super('The server sent an unexpected response. Reload the page and try again.');
61
+ this.path = path;
62
+ }
63
+ }
64
+ /** Calls an endpoint that answers `204 No Content`; any response body is ignored. */
65
+ export async function fetchNoContent(path, options = {}) {
66
+ await send(path, options);
67
+ }
@@ -0,0 +1,7 @@
1
+ export { appBasePath, appPath } from './app-path.ts';
2
+ export { ApiError, fetchJson, fetchNoContent, type HttpMethod, type RequestOptions, readApiError, UnexpectedResponseError, } from './fetch-json.ts';
3
+ export { navigateToUrl } from './navigate-to-url.ts';
4
+ export { type FieldErrors, type ParseFormResult, parseForm } from './parse-form.ts';
5
+ export { createQueryClient } from './query-client.ts';
6
+ export { type UploadOptions, uploadForm } from './upload-form.ts';
7
+ export { useTranslator } from './use-translator.ts';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { appBasePath, appPath } from './app-path.js';
2
+ export { ApiError, fetchJson, fetchNoContent, readApiError, UnexpectedResponseError, } from './fetch-json.js';
3
+ export { navigateToUrl } from './navigate-to-url.js';
4
+ export { parseForm } from './parse-form.js';
5
+ export { createQueryClient } from './query-client.js';
6
+ export { uploadForm } from './upload-form.js';
7
+ export { useTranslator } from './use-translator.js';
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Full page navigation, for destinations the client-side router doesn't own:
3
+ * server routes (OIDC interactions, platform sign-in) and other apps.
4
+ */
5
+ export declare function navigateToUrl(url: string): void;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Full page navigation, for destinations the client-side router doesn't own:
3
+ * server routes (OIDC interactions, platform sign-in) and other apps.
4
+ */
5
+ export function navigateToUrl(url) {
6
+ window.location.assign(url);
7
+ }
@@ -0,0 +1,14 @@
1
+ import type { z } from 'zod';
2
+ export type FieldErrors<Schema extends z.ZodObject> = Partial<Record<keyof z.input<Schema> & string, string>>;
3
+ export type ParseFormResult<Schema extends z.ZodObject> = {
4
+ success: true;
5
+ data: z.output<Schema>;
6
+ } | {
7
+ success: false;
8
+ fieldErrors: FieldErrors<Schema>;
9
+ };
10
+ /**
11
+ * Validates form values with a contract schema and keeps one message per field.
12
+ * `messages` replaces the schema's technical messages with sentences fit for a form.
13
+ */
14
+ export declare function parseForm<Schema extends z.ZodObject>(schema: Schema, values: unknown, messages?: FieldErrors<Schema>): ParseFormResult<Schema>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Validates form values with a contract schema and keeps one message per field.
3
+ * `messages` replaces the schema's technical messages with sentences fit for a form.
4
+ */
5
+ export function parseForm(schema, values, messages = {}) {
6
+ const result = schema.safeParse(values);
7
+ if (result.success)
8
+ return { success: true, data: result.data };
9
+ const fieldErrors = {};
10
+ for (const issue of result.error.issues) {
11
+ const field = String(issue.path[0] ?? '');
12
+ fieldErrors[field] ??= messages[field] ?? issue.message;
13
+ }
14
+ return { success: false, fieldErrors: fieldErrors };
15
+ }
@@ -0,0 +1,2 @@
1
+ import { QueryClient } from '@tanstack/react-query';
2
+ export declare function createQueryClient(): QueryClient;
@@ -0,0 +1,24 @@
1
+ import { QueryClient } from '@tanstack/react-query';
2
+ import { ApiError } from './fetch-json.js';
3
+ const MAX_QUERY_RETRIES = 2;
4
+ const STALE_TIME_MS = 30_000;
5
+ /** Client errors (4xx) won't succeed on retry; network and server errors might. */
6
+ function shouldRetry(failureCount, error) {
7
+ if (error instanceof ApiError && error.status < 500)
8
+ return false;
9
+ return failureCount < MAX_QUERY_RETRIES;
10
+ }
11
+ export function createQueryClient() {
12
+ return new QueryClient({
13
+ defaultOptions: {
14
+ queries: {
15
+ staleTime: STALE_TIME_MS,
16
+ retry: shouldRetry,
17
+ refetchOnWindowFocus: false,
18
+ },
19
+ mutations: {
20
+ retry: false,
21
+ },
22
+ },
23
+ });
24
+ }
@@ -0,0 +1 @@
1
+ export { type StubbedRequest, type StubbedRoute, type StubbedRoutes, stubFetch, } from './stub-fetch.ts';
@@ -0,0 +1,2 @@
1
+ /* Test helpers for web clients, built on vitest. */
2
+ export { stubFetch, } from './stub-fetch.js';
@@ -0,0 +1,12 @@
1
+ export interface StubbedRequest {
2
+ url: URL;
3
+ init: RequestInit | undefined;
4
+ }
5
+ export type StubbedRoute = (request: StubbedRequest) => Response | Promise<Response>;
6
+ /** Handlers keyed by `"<METHOD> <pathname>"` (for example `GET /api/apps`), without the query. */
7
+ export type StubbedRoutes = Record<string, StubbedRoute>;
8
+ /**
9
+ * Replaces the global `fetch` with one handler per route; any other request fails the test.
10
+ * Restore it with `vi.unstubAllGlobals()`.
11
+ */
12
+ export declare function stubFetch(routes: StubbedRoutes): import("vitest").Mock<typeof fetch>;
@@ -0,0 +1,19 @@
1
+ import { vi } from 'vitest';
2
+ /** Resolves the relative paths web clients fetch; only the pathname is matched. */
3
+ const BASE_URL = 'http://web.test';
4
+ /**
5
+ * Replaces the global `fetch` with one handler per route; any other request fails the test.
6
+ * Restore it with `vi.unstubAllGlobals()`.
7
+ */
8
+ export function stubFetch(routes) {
9
+ const fetchMock = vi.fn(async (input, init) => {
10
+ const url = new URL(String(input), BASE_URL);
11
+ const key = `${init?.method ?? 'GET'} ${url.pathname}`;
12
+ const route = routes[key];
13
+ if (!route)
14
+ throw new Error(`Unexpected request: ${key}`);
15
+ return route({ url, init });
16
+ });
17
+ vi.stubGlobal('fetch', fetchMock);
18
+ return fetchMock;
19
+ }
@@ -0,0 +1,11 @@
1
+ import type { z } from 'zod';
2
+ export interface UploadOptions {
3
+ /** Called as the body goes out, with the share sent so far (0 to 1). */
4
+ onProgress?: (sent: number) => void;
5
+ signal?: AbortSignal;
6
+ }
7
+ /**
8
+ * POSTs a multipart form and validates the JSON answer with a contract schema, like `fetchJson`,
9
+ * reporting how much of the body was sent: `fetch` can't tell, `XMLHttpRequest` can.
10
+ */
11
+ export declare function uploadForm<Schema extends z.ZodType>(path: string, schema: Schema, form: FormData, { onProgress, signal }?: UploadOptions): Promise<z.output<Schema>>;
@@ -0,0 +1,52 @@
1
+ import { ApiErrorBodySchema } from '@ismou-workspace/contracts';
2
+ import { appPath } from './app-path.js';
3
+ import { ApiError, UnexpectedResponseError } from './fetch-json.js';
4
+ function parseJson(text) {
5
+ try {
6
+ return JSON.parse(text);
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ }
12
+ /**
13
+ * POSTs a multipart form and validates the JSON answer with a contract schema, like `fetchJson`,
14
+ * reporting how much of the body was sent: `fetch` can't tell, `XMLHttpRequest` can.
15
+ */
16
+ export function uploadForm(path, schema, form, { onProgress, signal } = {}) {
17
+ return new Promise((resolve, reject) => {
18
+ const request = new XMLHttpRequest();
19
+ request.open('POST', appPath(path));
20
+ request.withCredentials = true;
21
+ request.setRequestHeader('Accept', 'application/json');
22
+ request.upload.addEventListener('progress', (event) => {
23
+ if (event.lengthComputable)
24
+ onProgress?.(event.loaded / event.total);
25
+ });
26
+ request.addEventListener('load', () => {
27
+ const body = parseJson(request.responseText);
28
+ if (request.status < 200 || request.status >= 300) {
29
+ const error = ApiErrorBodySchema.safeParse(body);
30
+ reject(new ApiError(request.status, error.success
31
+ ? error.data.error.message
32
+ : `Request failed with status ${request.status}.`));
33
+ return;
34
+ }
35
+ const parsed = schema.safeParse(body);
36
+ if (parsed.success) {
37
+ resolve(parsed.data);
38
+ return;
39
+ }
40
+ console.error(`Unexpected response from ${path}`, parsed.error.issues);
41
+ reject(new UnexpectedResponseError(path));
42
+ });
43
+ request.addEventListener('error', () => reject(new ApiError(0, 'The upload failed: check your connection and try again.')));
44
+ request.addEventListener('abort', () => reject(signal?.reason ?? new DOMException('The upload was cancelled.', 'AbortError')));
45
+ if (signal?.aborted) {
46
+ reject(signal.reason);
47
+ return;
48
+ }
49
+ signal?.addEventListener('abort', () => request.abort(), { once: true });
50
+ request.send(form);
51
+ });
52
+ }
@@ -0,0 +1,3 @@
1
+ import { type Translator } from '@ismou-workspace/translations';
2
+ /** Translator of the platform's names (permissions, entities…) in the language spoken here. */
3
+ export declare function useTranslator(): Translator;
@@ -0,0 +1,8 @@
1
+ import { createTranslator } from '@ismou-workspace/translations';
2
+ import { useLocale } from '@ismou-workspace/translations/react';
3
+ import { useMemo } from 'react';
4
+ /** Translator of the platform's names (permissions, entities…) in the language spoken here. */
5
+ export function useTranslator() {
6
+ const locale = useLocale();
7
+ return useMemo(() => createTranslator(locale), [locale]);
8
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@ismou-workspace/web-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.2",
4
+ "description": "Browser plumbing for Ismou's web clients: typed fetch, query client.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./testing": {
13
+ "types": "./dist/testing/index.d.ts",
14
+ "default": "./dist/testing/index.js"
15
+ }
16
+ },
17
+ "dependencies": {
18
+ "zod": "4.6.7",
19
+ "@ismou-workspace/contracts": "^0.1.2",
20
+ "@ismou-workspace/translations": "^0.1.2"
21
+ },
22
+ "peerDependencies": {
23
+ "@tanstack/react-query": "5.108.4",
24
+ "react": "19.3.1",
25
+ "vitest": "5.1.2"
26
+ },
27
+ "peerDependenciesMeta": {
28
+ "vitest": {
29
+ "optional": true
30
+ }
31
+ },
32
+ "devDependencies": {
33
+ "@tanstack/react-query": "5.108.4",
34
+ "@testing-library/react": "16.3.3",
35
+ "@types/react": "19.3.3",
36
+ "@types/react-dom": "19.3.0",
37
+ "jsdom": "31.0.1",
38
+ "react": "19.3.1",
39
+ "react-dom": "19.3.1",
40
+ "typescript": "7.0.2",
41
+ "vitest": "5.1.2",
42
+ "@ismou-workspace/tsconfig": "^0.1.2"
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/ismou-workspace/sdk.git",
47
+ "directory": "packages/web-kit"
48
+ },
49
+ "files": [
50
+ "dist"
51
+ ],
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "scripts": {
56
+ "build": "tsc --project tsconfig.build.json",
57
+ "typecheck": "tsc --project tsconfig.json",
58
+ "test": "vitest run"
59
+ }
6
60
  }