@metacensus/library-research 0.12.1 → 0.14.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/dist/host.d.ts CHANGED
@@ -1,17 +1,21 @@
1
1
  import { type AnyRoute, type ErrorComponentProps } from '@tanstack/react-router';
2
- import type { Host, Routes } from './types.js';
2
+ import type { AnyProject } from './mount.js';
3
+ import type { Host } from './types.js';
3
4
  export type { Host };
4
5
  export { pdfAssets } from './pdf.js';
5
6
  declare function Failed({ error, reset }: ErrorComponentProps): import("react").JSX.Element;
6
7
  /**
7
- * The route options of a host's route at `/$project`: the project's `Host`
8
- * from `useHost`, a resettable error boundary, and a loading state announced
9
- * to screen readers. Spread into `createRoute`.
8
+ * The route options of a project's mount: the project's `Host` from
9
+ * `useHost`, a resettable error boundary, and a loading state announced to
10
+ * screen readers. Spread into `mount`'s options.
10
11
  */
11
12
  export declare function frame(useHost: () => Host): {
12
13
  component: () => import("react").JSX.Element;
13
14
  errorComponent: typeof Failed;
14
15
  pendingComponent: () => import("react").JSX.Element;
15
16
  };
16
- /** Mounts a project's routes under `parent`, a route at `/$project`; returns `parent`. */
17
- export declare function mountRoutes(parent: AnyRoute, routes: Routes): import("@tanstack/router-core").Route<any, any, any, any, any, any, any, any, any, any, any, any, any, readonly AnyRoute[], any, any, any, any>;
17
+ /**
18
+ * Mounts `project` under `parent` at the path it names, with `options` as the
19
+ * route's options (`frame(useHost)`, and any `loader` or `head`); returns the route.
20
+ */
21
+ export declare function mount(parent: AnyRoute, project: AnyProject, options: Partial<Omit<AnyRoute['options'], 'getParentRoute' | 'path'>>): AnyRoute;
package/dist/host.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { Button, Notice } from '@metacensus/library-ui';
3
3
  import { useQueryErrorResetBoundary } from '@tanstack/react-query';
4
- import { Outlet, } from '@tanstack/react-router';
4
+ import { createRoute, Outlet, } from '@tanstack/react-router';
5
5
  import { HostContext } from './context.js';
6
6
  export { pdfAssets } from './pdf.js';
7
7
  function Failed({ error, reset }) {
@@ -12,9 +12,9 @@ function Failed({ error, reset }) {
12
12
  }, children: "Try again" }) }));
13
13
  }
14
14
  /**
15
- * The route options of a host's route at `/$project`: the project's `Host`
16
- * from `useHost`, a resettable error boundary, and a loading state announced
17
- * to screen readers. Spread into `createRoute`.
15
+ * The route options of a project's mount: the project's `Host` from
16
+ * `useHost`, a resettable error boundary, and a loading state announced to
17
+ * screen readers. Spread into `mount`'s options.
18
18
  */
19
19
  export function frame(useHost) {
20
20
  return {
@@ -25,7 +25,15 @@ export function frame(useHost) {
25
25
  pendingComponent: () => _jsx("p", { role: "status", children: "Loading\u2026" }),
26
26
  };
27
27
  }
28
- /** Mounts a project's routes under `parent`, a route at `/$project`; returns `parent`. */
29
- export function mountRoutes(parent, routes) {
30
- return parent.addChildren(routes(parent));
28
+ /**
29
+ * Mounts `project` under `parent` at the path it names, with `options` as the
30
+ * route's options (`frame(useHost)`, and any `loader` or `head`); returns the route.
31
+ */
32
+ export function mount(parent, project, options) {
33
+ const route = createRoute({
34
+ ...options,
35
+ getParentRoute: () => parent,
36
+ path: project.path,
37
+ });
38
+ return route.addChildren(project.routes(route));
31
39
  }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export type { Corpus, Doc, Host, Kind, Paper, Mount, Reader, RouterOf, Routes, } from './types.js';
2
- export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, usePrivate, useSaveDocument, } from './react.js';
1
+ export type { AnyProject, Corpus, Doc, Host, Kind, Member, Paper, Mount, Project, Reader, RouterOf, } from './types.js';
2
+ export { defineProject } from './mount.js';
3
+ export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, useMembers, usePrivate, useReader, useSaveDocument, } from './react.js';
3
4
  export { DocumentError } from './documents.js';
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
- export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, usePrivate, useSaveDocument, } from './react.js';
1
+ export { defineProject } from './mount.js';
2
+ export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, useMembers, usePrivate, useReader, useSaveDocument, } from './react.js';
2
3
  export { DocumentError } from './documents.js';
package/dist/mount.d.ts CHANGED
@@ -1,14 +1,28 @@
1
1
  import { type AnyRoute } from '@tanstack/react-router';
2
- /** A host's route at `/$project`, under which a project's routes mount. */
3
- export declare function createMount(): {
2
+ declare function mountRoute<P extends string>(path: P): {
4
3
  root: import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>;
5
- mount: import("@tanstack/react-router").Route<unknown, import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, "$project", "/$project", string, "/$project", undefined, import("@tanstack/react-router").ResolveParams<"$project">, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>;
4
+ route: import("@tanstack/react-router").Route<unknown, import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, P, import("@tanstack/react-router").ResolveFullPath<import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, P, import("@tanstack/router-core").RoutePrefix<"/", P>>, string, import("@tanstack/router-core").RoutePrefix<"__root__", P>, undefined, import("@tanstack/react-router").ResolveParams<P>, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>;
6
5
  };
7
- declare function routerOf<C extends readonly AnyRoute[]>(children: C): import("@tanstack/router-core").RouterCore<import("@tanstack/router-core").Route<import("@tanstack/react-router").Register, any, "/", "/", string, "__root__", undefined, {}, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, readonly [import("@tanstack/router-core").Route<unknown, import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, "$project", "/$project", string, "/$project", undefined, import("@tanstack/react-router").ResolveParams<"$project">, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, C, unknown, unknown, unknown, undefined>], unknown, unknown, unknown, undefined>, "never", false, import("@tanstack/history").RouterHistory, Record<string, any>>;
8
- /** The parent a project's routes are created against; they type as `/$project/…`. */
9
- export type Mount = ReturnType<typeof createMount>['mount'];
10
- /** What `ui/index.tsx` and `ui/local/index.tsx` default-export. */
11
- export type Routes = (parent: Mount) => readonly AnyRoute[];
12
- /** A project's `Register`: `router: RouterOf<typeof routes>`. */
13
- export type RouterOf<R extends Routes> = ReturnType<typeof routerOf<ReturnType<R>>>;
6
+ declare function routerOf<P extends string, C extends readonly AnyRoute[]>(path: P, children: C): import("@tanstack/router-core").RouterCore<import("@tanstack/router-core").Route<import("@tanstack/react-router").Register, any, "/", "/", string, "__root__", undefined, {}, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, readonly [import("@tanstack/router-core").Route<unknown, import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, P, import("@tanstack/react-router").ResolveFullPath<import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, P, import("@tanstack/router-core").RoutePrefix<"/", P>>, string, import("@tanstack/router-core").RoutePrefix<"__root__", P>, undefined, import("@tanstack/react-router").ResolveParams<P>, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, C, unknown, unknown, unknown, undefined>], unknown, unknown, unknown, undefined>, "never", false, import("@tanstack/history").RouterHistory, Record<string, any>>;
7
+ /** The parent a project's routes are created against; they type as `/<path>/…`. */
8
+ export type Mount<P extends string> = ReturnType<typeof mountRoute<P>>['route'];
9
+ /** A project's routes under the first path segment it names. */
10
+ export interface Project<P extends string = string, C = readonly AnyRoute[]> {
11
+ readonly path: P;
12
+ routes(parent: Mount<P>): C;
13
+ }
14
+ /** Any project, for a list or a constraint: a `Project<'a'>` is not a `Project<string>`. */
15
+ export interface AnyProject {
16
+ readonly path: string;
17
+ routes(parent: never): readonly AnyRoute[];
18
+ }
19
+ /**
20
+ * What `ui/index.tsx` and `ui/local/index.tsx` default-export. `path` is the
21
+ * project's first URL segment, matching `^[a-z0-9][a-z0-9-]*$` and not
22
+ * `projects`, `local` or `pdfjs`, which dev and the host reserve; `routes`
23
+ * creates its routes against `parent`.
24
+ */
25
+ export declare function defineProject<P extends string, const C>(path: P, routes: (parent: Mount<P>) => C): Project<P, C>;
26
+ /** A project's `Register`: `router: RouterOf<typeof project>`. */
27
+ export type RouterOf<R extends AnyProject> = ReturnType<R['routes']> extends infer C extends readonly AnyRoute[] ? ReturnType<typeof routerOf<R['path'], C>> : never;
14
28
  export {};
package/dist/mount.js CHANGED
@@ -1,15 +1,29 @@
1
1
  import { createRootRoute, createRoute, createRouter, } from '@tanstack/react-router';
2
- /** A host's route at `/$project`, under which a project's routes mount. */
3
- export function createMount() {
2
+ const format = /^[a-z0-9][a-z0-9-]*$/;
3
+ // First segments that dev and the host serve themselves.
4
+ const reserved = ['projects', 'local', 'pdfjs'];
5
+ function mountRoute(path) {
4
6
  const root = createRootRoute();
5
- const mount = createRoute({ getParentRoute: () => root, path: '$project' });
6
- return { root, mount };
7
+ return { root, route: createRoute({ getParentRoute: () => root, path }) };
7
8
  }
8
9
  // Only `typeof routerOf` is read: it names the router a project's routes make.
9
10
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
10
- function routerOf(children) {
11
- const { root, mount } = createMount();
11
+ function routerOf(path, children) {
12
+ const { root, route } = mountRoute(path);
12
13
  return createRouter({
13
- routeTree: root.addChildren([mount.addChildren(children)]),
14
+ routeTree: root.addChildren([route.addChildren(children)]),
14
15
  });
15
16
  }
17
+ /**
18
+ * What `ui/index.tsx` and `ui/local/index.tsx` default-export. `path` is the
19
+ * project's first URL segment, matching `^[a-z0-9][a-z0-9-]*$` and not
20
+ * `projects`, `local` or `pdfjs`, which dev and the host reserve; `routes`
21
+ * creates its routes against `parent`.
22
+ */
23
+ export function defineProject(path, routes) {
24
+ if (!format.test(path))
25
+ throw new Error(`project path "${path}" does not match ${format}`);
26
+ if (reserved.includes(path))
27
+ throw new Error(`project path "${path}" is reserved by dev and the host`);
28
+ return { path, routes };
29
+ }
@@ -9,7 +9,7 @@ export default defineConfig({
9
9
  use: { baseURL: process.env.LIBRARY_RESEARCH_URL },
10
10
  webServer: {
11
11
  command: `"${process.execPath}" -e "${server}"`,
12
- wait: { stdout: /(?<library_research_url>http:\S+\/project\/)/ },
12
+ wait: { stdout: /(?<library_research_url>http:\S+\/)/ },
13
13
  },
14
14
  });
15
15
  /** Collects a page's CSP and axe violations; the returned function fails on those not listed. */
package/dist/react.d.ts CHANGED
@@ -1,31 +1,38 @@
1
1
  import { DocumentError } from './documents.js';
2
- import type { Corpus, Doc, Host } from './types.js';
2
+ import type { Corpus, Doc, Host, Member, Reader } from './types.js';
3
3
  /** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
4
4
  export declare function useHost(): Host;
5
- type Role<T = unknown> = readonly [role: string, parse: (json: unknown) => T];
5
+ /** The person the project is viewed as; `self` is false while the host views it as another. */
6
+ export declare function useReader(): Reader;
7
+ /** Every person of the project, each with their role. */
8
+ export declare function useMembers(): Member[];
9
+ type Dataset<T = unknown> = readonly [
10
+ dataset: string,
11
+ parse: (json: unknown) => T
12
+ ];
6
13
  /**
7
- * One data role's JSON, parsed by `parse`. Suspends while it loads; a failed
8
- * fetch or parse throws to the frame's error notice, naming the role. A 401 or
14
+ * One dataset's JSON, parsed by `parse`. Suspends while it loads; a failed
15
+ * fetch or parse throws to the frame's error notice, naming the dataset. A 401 or
9
16
  * 403 also calls `Host.sessionLost`. `parse` must be pure: it is read once per
10
- * role list, not on every render.
17
+ * dataset list, not on every render.
11
18
  */
12
- export declare function useData<T>(role: string, parse: (json: unknown) => T): T;
19
+ export declare function useData<T>(dataset: string, parse: (json: unknown) => T): T;
13
20
  /**
14
- * `useData` for several roles at once, fetched in parallel: a `[role, parse]`
21
+ * `useData` for several datasets at once, fetched in parallel: a `[dataset, parse]`
15
22
  * tuple each, the values returned in the same order and typed by their parsers.
16
- * Each parser must be pure: it is read once per role list, not on every render.
23
+ * Each parser must be pure: it is read once per dataset list, not on every render.
17
24
  */
18
- export declare function useDatas<const R extends readonly Role[]>(roles: R): {
19
- -readonly [K in keyof R]: R[K] extends Role<infer T> ? T : never;
25
+ export declare function useDatas<const R extends readonly Dataset[]>(datasets: R): {
26
+ -readonly [K in keyof R]: R[K] extends Dataset<infer T> ? T : never;
20
27
  };
21
28
  /**
22
- * The viewed person's pages of a private role, as `{ page: parsed }`: empty
29
+ * The viewed person's pages of a private dataset, as `{ page: parsed }`: empty
23
30
  * when they hold none, a page the host names but the build did not emit left
24
31
  * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
25
32
  * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
26
33
  */
27
- export declare function usePrivate<T>(role: string, parse: (json: unknown) => T): Record<string, T>;
28
- /** The `corpus` role, parsed by the library's own schema, through `useData`. */
34
+ export declare function usePrivate<T>(dataset: string, parse: (json: unknown) => T): Record<string, T>;
35
+ /** The `corpus` dataset, parsed by the library's own schema, through `useData`. */
29
36
  export declare function useCorpus(): Corpus;
30
37
  /**
31
38
  * One document of the project, or `null` when none has that id. Suspends while
package/dist/react.js CHANGED
@@ -10,40 +10,48 @@ export function useHost() {
10
10
  throw new Error('useHost outside the frame of ./host');
11
11
  return host;
12
12
  }
13
+ /** The person the project is viewed as; `self` is false while the host views it as another. */
14
+ export function useReader() {
15
+ return useHost().reader;
16
+ }
17
+ /** Every person of the project, each with their role. */
18
+ export function useMembers() {
19
+ return useHost().members;
20
+ }
13
21
  /**
14
- * One data role's JSON, parsed by `parse`. Suspends while it loads; a failed
15
- * fetch or parse throws to the frame's error notice, naming the role. A 401 or
22
+ * One dataset's JSON, parsed by `parse`. Suspends while it loads; a failed
23
+ * fetch or parse throws to the frame's error notice, naming the dataset. A 401 or
16
24
  * 403 also calls `Host.sessionLost`. `parse` must be pure: it is read once per
17
- * role list, not on every render.
25
+ * dataset list, not on every render.
18
26
  */
19
- export function useData(role, parse) {
20
- return useDatas([[role, parse]])[0];
27
+ export function useData(dataset, parse) {
28
+ return useDatas([[dataset, parse]])[0];
21
29
  }
22
30
  /**
23
- * `useData` for several roles at once, fetched in parallel: a `[role, parse]`
31
+ * `useData` for several datasets at once, fetched in parallel: a `[dataset, parse]`
24
32
  * tuple each, the values returned in the same order and typed by their parsers.
25
- * Each parser must be pure: it is read once per role list, not on every render.
33
+ * Each parser must be pure: it is read once per dataset list, not on every render.
26
34
  */
27
- export function useDatas(roles) {
35
+ export function useDatas(datasets) {
28
36
  const host = useHost();
29
- // The parsers and select functions are kept until the role list changes, so
37
+ // The parsers and select functions are kept until the dataset list changes, so
30
38
  // an inline parse does not rerun on every render.
31
- const key = JSON.stringify(roles.map(([role]) => role));
32
- const [held, hold] = useState({ key, roles });
39
+ const key = JSON.stringify(datasets.map(([dataset]) => dataset));
40
+ const [held, hold] = useState({ key, datasets });
33
41
  if (held.key !== key)
34
- hold({ key, roles });
35
- const names = held.roles.map(([role]) => role);
36
- const selects = useMemo(() => held.roles.map(([role, parse]) => (json) => {
42
+ hold({ key, datasets });
43
+ const names = held.datasets.map(([dataset]) => dataset);
44
+ const selects = useMemo(() => held.datasets.map(([dataset, parse]) => (json) => {
37
45
  try {
38
46
  return parse(json);
39
47
  }
40
48
  catch (cause) {
41
- return failed(`data role "${role}"`, cause);
49
+ return failed(`dataset "${dataset}"`, cause);
42
50
  }
43
51
  }), [held]);
44
52
  return useSuspenseQueries({
45
- queries: names.map((role, i) => {
46
- const url = host.data(role);
53
+ queries: names.map((dataset, i) => {
54
+ const url = host.data(dataset);
47
55
  return {
48
56
  queryKey: ['research', url],
49
57
  queryFn: () => fetch(url)
@@ -54,7 +62,7 @@ export function useDatas(roles) {
54
62
  throw new Error(`${response.status} from ${url}`);
55
63
  return response.json();
56
64
  })
57
- .catch((cause) => failed(`data role "${role}"`, cause)),
65
+ .catch((cause) => failed(`dataset "${dataset}"`, cause)),
58
66
  select: selects[i],
59
67
  staleTime: Infinity,
60
68
  retry: false,
@@ -70,17 +78,17 @@ function failed(what, cause) {
70
78
  throw new Error(`${what}: ${why}`, { cause });
71
79
  }
72
80
  /**
73
- * The viewed person's pages of a private role, as `{ page: parsed }`: empty
81
+ * The viewed person's pages of a private dataset, as `{ page: parsed }`: empty
74
82
  * when they hold none, a page the host names but the build did not emit left
75
83
  * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
76
84
  * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
77
85
  */
78
- export function usePrivate(role, parse) {
86
+ export function usePrivate(dataset, parse) {
79
87
  const host = useHost();
80
- const urls = host.private(role);
88
+ const urls = host.private(dataset);
81
89
  const pages = Object.keys(urls);
82
90
  const key = pages.join();
83
- const held = useHeld(role, parse);
91
+ const held = useHeld(dataset, parse);
84
92
  const selects = useMemo(() => pages.map((page) => (found) => {
85
93
  if (!found)
86
94
  return null;
@@ -88,7 +96,7 @@ export function usePrivate(role, parse) {
88
96
  return { value: held(found.json) };
89
97
  }
90
98
  catch (cause) {
91
- return failed(`private role "${role}" page "${page}"`, cause);
99
+ return failed(`private dataset "${dataset}" page "${page}"`, cause);
92
100
  }
93
101
  }),
94
102
  // The pages are named by `key`.
@@ -109,7 +117,7 @@ export function usePrivate(role, parse) {
109
117
  throw new Error(`${response.status} from ${url}`);
110
118
  return response.json().then((json) => ({ json }));
111
119
  })
112
- .catch((cause) => failed(`private role "${role}" page "${page}"`, cause)),
120
+ .catch((cause) => failed(`private dataset "${dataset}" page "${page}"`, cause)),
113
121
  select: selects[i],
114
122
  staleTime: Infinity,
115
123
  retry: false,
@@ -118,7 +126,7 @@ export function usePrivate(role, parse) {
118
126
  combine: (results) => Object.fromEntries(results.flatMap(({ data }, i) => data ? [[pages[i], data.value]] : [])),
119
127
  });
120
128
  }
121
- /** The `corpus` role, parsed by the library's own schema, through `useData`. */
129
+ /** The `corpus` dataset, parsed by the library's own schema, through `useData`. */
122
130
  export function useCorpus() {
123
131
  return useData('corpus', (json) => schema.Corpus.parse(json));
124
132
  }
package/dist/reader.d.ts CHANGED
@@ -1,2 +1,20 @@
1
+ import type { z } from 'zod';
2
+ import type { Research } from './schema.js';
3
+ import type { Member, Reader } from './types.js';
1
4
  /** The cookie that names the reader of a browser context on a dev server. */
2
5
  export declare const readerCookie = "library-research-reader";
6
+ /** research.json's `people`: each person `dev` and `testHost` serve, by username. */
7
+ export type People = NonNullable<z.infer<typeof Research>['people']>;
8
+ /**
9
+ * `username` as `dev` and `testHost` serve them. In a project that declares
10
+ * `roles`, one `people` omits is refused, naming them; elsewhere they are named
11
+ * by their username and hold no role.
12
+ */
13
+ export declare function readerOf({ people, roles }: {
14
+ people?: People;
15
+ roles?: string[];
16
+ }, username: string, self: boolean): Reader;
17
+ /** Every person of `people`, in its order. */
18
+ export declare const membersOf: (people?: People) => Member[];
19
+ /** The pages `username` holds in `dev` and `testHost`: their `pages` in `people`, else none. */
20
+ export declare const pagesOf: (people: People | undefined, username: string) => string[];
package/dist/reader.js CHANGED
@@ -1,2 +1,27 @@
1
1
  /** The cookie that names the reader of a browser context on a dev server. */
2
2
  export const readerCookie = 'library-research-reader';
3
+ const personOf = (people, username) => people && Object.hasOwn(people, username) ? people[username] : undefined;
4
+ /**
5
+ * `username` as `dev` and `testHost` serve them. In a project that declares
6
+ * `roles`, one `people` omits is refused, naming them; elsewhere they are named
7
+ * by their username and hold no role.
8
+ */
9
+ export function readerOf({ people, roles }, username, self) {
10
+ const person = personOf(people, username);
11
+ if (!person && roles)
12
+ throw new Error(`reader "${username}" is not in research.json's people, which lists every reader of a project that declares roles`);
13
+ return {
14
+ username,
15
+ name: person?.name ?? username,
16
+ role: person?.role ?? null,
17
+ self,
18
+ };
19
+ }
20
+ /** Every person of `people`, in its order. */
21
+ export const membersOf = (people = {}) => Object.entries(people).map(([username, { name, role = null }]) => ({
22
+ username,
23
+ name,
24
+ role,
25
+ }));
26
+ /** The pages `username` holds in `dev` and `testHost`: their `pages` in `people`, else none. */
27
+ export const pagesOf = (people, username) => personOf(people, username)?.pages ?? [];
package/dist/router.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type RouterHistory } from '@tanstack/react-router';
2
- import type { Host, Routes } from './types.js';
3
- /** A project's routes under `/$project`, in the frame a real host uses; shared by the dev host and the test host. */
4
- export declare function projectRouter(routes: Routes, useHost: () => Host, history?: RouterHistory): import("@tanstack/router-core").RouterCore<import("@tanstack/router-core").Route<import("@tanstack/react-router").Register, any, "/", "/", string, "__root__", undefined, {}, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, readonly [import("@tanstack/router-core").Route<any, any, any, any, any, any, any, any, any, any, any, any, any, readonly import("@tanstack/react-router").AnyRoute[], any, any, any, any>], unknown, unknown, unknown, undefined>, "preserve", false, RouterHistory, Record<string, any>>;
2
+ import type { AnyProject } from './mount.js';
3
+ import type { Host } from './types.js';
4
+ /** A project mounted in the frame a real host uses, under `basepath` if given; shared by the dev host and the test host. */
5
+ export declare function projectRouter(project: AnyProject, useHost: () => Host, history?: RouterHistory, basepath?: string): import("@tanstack/router-core").RouterCore<import("@tanstack/router-core").Route<import("@tanstack/react-router").Register, any, "/", "/", string, "__root__", undefined, {}, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, readonly [import("@tanstack/react-router").AnyRoute], unknown, unknown, unknown, undefined>, "preserve", false, RouterHistory, Record<string, any>>;
package/dist/router.js CHANGED
@@ -1,15 +1,14 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { Notice } from '@metacensus/library-ui';
3
- import { createRouter } from '@tanstack/react-router';
4
- import { frame, mountRoutes } from './host.js';
5
- import { createMount } from './mount.js';
6
- /** A project's routes under `/$project`, in the frame a real host uses; shared by the dev host and the test host. */
7
- export function projectRouter(routes, useHost, history) {
8
- const { root, mount } = createMount();
9
- mount.update(frame(useHost));
3
+ import { createRootRoute, createRouter, } from '@tanstack/react-router';
4
+ import { frame, mount } from './host.js';
5
+ /** A project mounted in the frame a real host uses, under `basepath` if given; shared by the dev host and the test host. */
6
+ export function projectRouter(project, useHost, history, basepath) {
7
+ const root = createRootRoute();
10
8
  return createRouter({
11
- routeTree: root.addChildren([mountRoutes(mount, routes)]),
9
+ routeTree: root.addChildren([mount(root, project, frame(useHost))]),
12
10
  history,
11
+ basepath,
13
12
  trailingSlash: 'preserve',
14
13
  defaultNotFoundComponent: () => _jsx(Notice, { role: "alert", title: "Not found" }),
15
14
  });
package/dist/schema.d.ts CHANGED
@@ -17,6 +17,12 @@ export declare const Research: z.ZodObject<{
17
17
  title: z.ZodString;
18
18
  data: z.ZodRecord<z.ZodString, z.ZodString>;
19
19
  private: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
20
+ roles: z.ZodOptional<z.ZodArray<z.ZodString>>;
21
+ people: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
22
+ name: z.ZodString;
23
+ role: z.ZodOptional<z.ZodString>;
24
+ pages: z.ZodOptional<z.ZodArray<z.ZodString>>;
25
+ }, z.core.$strict>>>;
20
26
  }, z.core.$strict>;
21
27
  export declare const Corpus: z.ZodRecord<z.ZodString, z.ZodObject<{
22
28
  kind: z.ZodEnum<{
package/dist/schema.js CHANGED
@@ -14,21 +14,52 @@ export const kinds = {
14
14
  html: 'text/plain',
15
15
  xml: 'text/plain',
16
16
  };
17
- const role = z.string().regex(/^(?!corpus$)[a-z][A-Za-z0-9]*$/);
17
+ const dataset = z.string().regex(/^(?!corpus$)[a-z][A-Za-z0-9]*$/);
18
18
  const glob = z.string().regex(/^(?!\/)(?!.*\.\.).+$/);
19
+ const role = z.string().regex(/^[a-z][a-z0-9-]*$/);
20
+ const page = z.string().regex(/^[a-z0-9][a-z0-9-]*$/);
19
21
  export const Research = z
20
22
  .strictObject({
21
23
  title: z.string().min(1),
22
- data: z.record(role, glob),
23
- private: z.record(role, glob).optional(),
24
+ data: z.record(dataset, glob),
25
+ private: z.record(dataset, glob).optional(),
26
+ /** The roles a person of the project holds one of. */
27
+ roles: z
28
+ .array(role)
29
+ .refine((roles) => new Set(roles).size === roles.length, 'roles repeat')
30
+ .meta({ uniqueItems: true })
31
+ .optional(),
32
+ /** The people `dev` and `testHost` serve, by username; production's people.json holds the real ones. */
33
+ people: z
34
+ .record(z.string(), z.strictObject({
35
+ name: z.string().min(1),
36
+ role: z.string().optional(),
37
+ pages: z.array(page).optional(),
38
+ }))
39
+ .optional(),
24
40
  })
25
- .superRefine(({ data, private: held = {} }, ctx) => {
41
+ .superRefine(({ data, private: held = {}, roles, people = {} }, ctx) => {
42
+ for (const [username, person] of Object.entries(people)) {
43
+ const issue = (message) => ctx.addIssue({
44
+ code: 'custom',
45
+ path: ['people', username, 'role'],
46
+ message: `${username} ${message}`,
47
+ });
48
+ if (!roles) {
49
+ if (person.role !== undefined)
50
+ issue('has a role, and the project declares no roles');
51
+ }
52
+ else if (person.role === undefined)
53
+ issue('has no role, and the project declares roles');
54
+ else if (!roles.includes(person.role))
55
+ issue(`has role "${person.role}", which is not in roles`);
56
+ }
26
57
  for (const [name, pattern] of Object.entries(held)) {
27
58
  const issue = (message) => ctx.addIssue({ code: 'custom', path: ['private', name], message });
28
59
  if (Object.hasOwn(data, name))
29
- issue(`role "${name}" is in data and private`);
60
+ issue(`dataset "${name}" is in data and private`);
30
61
  if (pattern.split('*').length !== 2 || /[?[\]{}()!]/.test(pattern))
31
- issue(`role "${name}": glob "${pattern}" must hold exactly one * and no other glob character`);
62
+ issue(`dataset "${name}": glob "${pattern}" must hold exactly one * and no other glob character`);
32
63
  }
33
64
  });
34
65
  export const Corpus = z.record(z.string().regex(/^[0-9a-f]{64}$/), z.strictObject({
package/dist/testing.d.ts CHANGED
@@ -1,30 +1,38 @@
1
1
  import type { ReactElement } from 'react';
2
- import type { Routes } from './types.js';
3
- /** What `testHost` is given besides the routes; every field is optional. */
2
+ import { type People } from './reader.js';
3
+ import type { AnyProject } from './mount.js';
4
+ export { membersOf, readerOf, type People } from './reader.js';
5
+ /** What `testHost` is given besides the project; every field is optional. */
4
6
  export interface TestHostOptions {
5
- /** Each data role's JSON value, parsed by the project's own schema. */
7
+ /** Each dataset's JSON value, parsed by the project's own schema. */
6
8
  data?: Record<string, unknown>;
7
- /** Each private role's pages, `{ role: { page: JSON } }`; the reader's page is the one named as the reader. */
9
+ /** Each private dataset's pages, `{ dataset: { page: JSON } }`; the reader sees those `people` gives them. */
8
10
  private?: Record<string, Record<string, unknown>>;
9
11
  /** Each document the project starts with, by id; `writer` defaults to the reader. */
10
12
  documents?: Record<string, {
11
13
  body: unknown;
12
14
  writer?: string;
13
15
  }>;
14
- /** The reader's username. */
16
+ /** The project's people, as research.json's `people`: each is a member, and `reader` holds their `pages`. */
17
+ people?: People;
18
+ /** The project's roles, as research.json's `roles`; with them, `reader` must be in `people`. */
19
+ roles?: string[];
20
+ /** The reader's username, and the writer of every save: `testHost` holds this one identity. */
15
21
  reader?: string;
22
+ /** False to view the project as `reader` while signed in as another; saves are still written as `reader`. */
23
+ self?: boolean;
16
24
  /** The path below the project, with search and hash. */
17
25
  url?: string;
18
26
  /** Called as `Host.sessionLost` is. */
19
27
  sessionLost?: () => void;
20
28
  }
21
29
  /**
22
- * A project's routes rendered through the frame and the `/$project` mount a
23
- * real host uses. Render `element` with any DOM renderer; `router` says where
30
+ * A project rendered through the frame and the mount a real host uses, at the
31
+ * path it names. Render `element` with any DOM renderer; `router` says where
24
32
  * the project navigated, and `documents()` what it saved, sorted by id.
25
33
  */
26
- export declare function testHost(routes: Routes, { data, documents, private: held, reader, url, sessionLost, }?: TestHostOptions): {
34
+ export declare function testHost(project: AnyProject, { data, documents, private: held, people, roles, reader, self, url, sessionLost, }?: TestHostOptions): {
27
35
  element: ReactElement<any, string | import("react").JSXElementConstructor<any>>;
28
- router: import("@tanstack/router-core").RouterCore<import("@tanstack/router-core").Route<import("@tanstack/react-router").Register, any, "/", "/", string, "__root__", undefined, {}, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, readonly [import("@tanstack/router-core").Route<any, any, any, any, any, any, any, any, any, any, any, any, any, readonly import("@tanstack/react-router").AnyRoute[], any, any, any, any>], unknown, unknown, unknown, undefined>, "preserve", false, import("@tanstack/history").RouterHistory, Record<string, any>>;
36
+ router: import("@tanstack/router-core").RouterCore<import("@tanstack/router-core").Route<import("@tanstack/react-router").Register, any, "/", "/", string, "__root__", undefined, {}, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, readonly [import("@tanstack/react-router").AnyRoute], unknown, unknown, unknown, undefined>, "preserve", false, import("@tanstack/history").RouterHistory, Record<string, any>>;
29
37
  documents: () => import("./types.js").Doc<unknown>[];
30
38
  };