@metacensus/library-research 0.10.0 → 0.12.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.
Files changed (50) hide show
  1. package/README.md +99 -13
  2. package/csp.json +10 -0
  3. package/dist/cli.js +1 -1
  4. package/dist/commands/add.js +2 -1
  5. package/dist/commands/candidate.js +12 -1
  6. package/dist/commands/check.js +22 -13
  7. package/dist/commands/dev.js +92 -9
  8. package/dist/commands/init.d.ts +1 -0
  9. package/dist/commands/init.js +131 -0
  10. package/dist/context.d.ts +4 -0
  11. package/dist/context.js +4 -0
  12. package/dist/data.d.ts +22 -0
  13. package/dist/data.js +76 -0
  14. package/dist/dev/host.d.ts +1 -1
  15. package/dist/dev/host.js +38 -41
  16. package/dist/document-store.d.ts +14 -0
  17. package/dist/document-store.js +78 -0
  18. package/dist/documents.d.ts +10 -0
  19. package/dist/documents.js +22 -0
  20. package/dist/host.d.ts +17 -0
  21. package/dist/host.js +31 -0
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.js +2 -1
  24. package/dist/mount.d.ts +14 -0
  25. package/dist/mount.js +15 -0
  26. package/dist/papers.d.ts +0 -6
  27. package/dist/papers.js +8 -21
  28. package/dist/pdf.d.ts +2 -0
  29. package/dist/pdf.js +2 -0
  30. package/dist/playwright.d.ts +3 -1
  31. package/dist/playwright.js +50 -10
  32. package/dist/react.d.ts +32 -9
  33. package/dist/react.js +170 -36
  34. package/dist/reader.d.ts +2 -0
  35. package/dist/reader.js +2 -0
  36. package/dist/roles.d.ts +7 -5
  37. package/dist/roles.js +103 -36
  38. package/dist/router.d.ts +4 -0
  39. package/dist/router.js +16 -0
  40. package/dist/schema.d.ts +1 -0
  41. package/dist/schema.js +15 -2
  42. package/dist/testing.d.ts +29 -0
  43. package/dist/testing.js +46 -0
  44. package/dist/types.d.ts +22 -12
  45. package/dist/vite-config.js +4 -2
  46. package/dist/vite.js +29 -3
  47. package/package.json +28 -4
  48. package/schema/research.schema.json +11 -0
  49. package/src/virtual.d.ts +2 -2
  50. package/tsconfig.project.json +3 -1
package/dist/data.js ADDED
@@ -0,0 +1,76 @@
1
+ import { globSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
2
+ import { join, sep } from 'node:path';
3
+ import { Corpus, Research } from './schema.js';
4
+ /** Reads a project's research.json; each role reads its files when called. */
5
+ export function project(dir) {
6
+ const { title, data, private: held = {}, } = read(dir, 'research.json', Research);
7
+ const roles = {
8
+ corpus: () => readCorpus(dir),
9
+ };
10
+ for (const [role, glob] of Object.entries(data))
11
+ roles[role] = () => match(dir, files(dir, glob));
12
+ const pages = {};
13
+ for (const [role, glob] of Object.entries(held))
14
+ pages[role] = () => privatePages(dir, role, glob);
15
+ return { title, roles, pages };
16
+ }
17
+ /** The files a private role's glob matches, by the page each names; throws on a key a page cannot have. */
18
+ export function privatePages(dir, role, glob) {
19
+ const { entries } = files(dir, glob);
20
+ const bad = entries.filter(([, key]) => !/^[a-z0-9][a-z0-9-]*$/.test(key));
21
+ if (bad.length)
22
+ throw new Error(bad
23
+ .map(([file, key]) => `${join(dir, file)}: private role "${role}": page "${key}" is not [a-z0-9][a-z0-9-]*`)
24
+ .join('\n'));
25
+ const pages = {};
26
+ for (const [file, key] of entries) {
27
+ if (Object.hasOwn(pages, key))
28
+ throw new Error(`private role "${role}": page "${key}" matched by ${pages[key]} and ${file}`);
29
+ pages[key] = file;
30
+ }
31
+ return pages;
32
+ }
33
+ /** The files a role's glob matches; a wildcard keys each by what it matched. */
34
+ export function files(dir, glob) {
35
+ const found = globSync(glob, { cwd: dir }).sort();
36
+ if (!found.length)
37
+ throw new Error(`${join(dir, glob)}: matches no file`);
38
+ const head = glob.indexOf('*');
39
+ const tail = glob.length - glob.lastIndexOf('*') - 1;
40
+ const key = (file) => file.slice(head, file.length - tail).replace(/^[./]+|[./]+$/g, '');
41
+ return {
42
+ keyed: head >= 0,
43
+ entries: head < 0 ? [[found[0], '']] : found.map((file) => [file, key(file)]),
44
+ };
45
+ }
46
+ export function match(dir, { keyed, entries }) {
47
+ return keyed
48
+ ? Object.fromEntries(entries.map(([file, key]) => [key, read(dir, file)]))
49
+ : read(dir, entries[0][0]);
50
+ }
51
+ export function readCorpus(dir) {
52
+ return lstatSync(join(dir, 'corpus.json'), { throwIfNoEntry: false })
53
+ ? read(dir, 'corpus.json', Corpus)
54
+ : {};
55
+ }
56
+ export function read(dir, file, schema) {
57
+ const path = join(dir, file);
58
+ const fail = (why) => new Error(`${path}: ${why}`);
59
+ let json;
60
+ try {
61
+ if (!realpathSync(path).startsWith(realpathSync(dir) + sep))
62
+ throw new Error('leads outside the project');
63
+ json = JSON.parse(readFileSync(path, 'utf8'));
64
+ }
65
+ catch (e) {
66
+ throw fail(e.message);
67
+ }
68
+ if (!schema)
69
+ return json;
70
+ const checked = schema.safeParse(json);
71
+ if (!checked.success)
72
+ throw fail(checked.error.issues
73
+ .map(({ path, message }) => `${path.join('.')}: ${message}`)
74
+ .join('; '));
75
+ return checked.data;
76
+ }
@@ -1 +1 @@
1
- export declare function start(username: string): void;
1
+ export declare function start(username: string): Promise<void>;
package/dist/dev/host.js CHANGED
@@ -1,53 +1,50 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { Button, Notice } from '@metacensus/library-ui';
3
- import { QueryClient, QueryClientProvider, QueryErrorResetBoundary, } from '@tanstack/react-query';
4
- import { Component, lazy, Suspense, useEffect, useState, } from 'react';
3
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
4
+ import { RouterProvider } from '@tanstack/react-router';
5
+ import { createContext, useContext, useMemo, useState } from 'react';
5
6
  import { createRoot } from 'react-dom/client';
6
7
  import projects from 'virtual:research-projects';
7
- import { ResearchProvider } from '../react.js';
8
+ import { readerCookie } from '../reader.js';
9
+ import { projectRouter } from '../router.js';
8
10
  const project = projects.project;
9
- const local = window.location.pathname.startsWith('/local/');
10
- const base = local ? '/local/' : '/project/';
11
- const Root = lazy(local ? project.local : project.root);
12
- function here() {
13
- const { pathname, search, hash } = window.location;
14
- return { path: pathname.slice(base.length), search, hash };
15
- }
16
- function App({ username }) {
17
- const [location, setLocation] = useState(here);
18
- useEffect(() => {
19
- const pop = () => setLocation(here());
20
- window.addEventListener('popstate', pop);
21
- return () => window.removeEventListener('popstate', pop);
22
- }, []);
23
- const host = {
11
+ const load = window.location.pathname.startsWith('/local/')
12
+ ? project.local
13
+ : project.root;
14
+ const Reader = createContext({ username: '', lost: () => { } });
15
+ function useHost() {
16
+ const { username, lost } = useContext(Reader);
17
+ return useMemo(() => ({
24
18
  reader: { username },
25
- base,
26
- location,
27
- navigate(to, { replace } = {}) {
28
- history[replace ? 'replaceState' : 'pushState'](null, '', base + to);
29
- setLocation(here());
30
- },
31
19
  data: (role) => `/projects/project/data/${role}.json`,
20
+ private: (role) => ({
21
+ [username]: `/projects/project/private/${encodeURIComponent(username)}/${role}.json`,
22
+ }),
32
23
  paper: (sha) => `/projects/project/papers/${sha}`,
33
- };
34
- return (_jsx(QueryErrorResetBoundary, { children: ({ reset }) => (_jsx(Boundary, { reset: reset, children: _jsx(Suspense, { fallback: null, children: _jsx(ResearchProvider, { host: host, children: _jsx(Root, {}) }) }) })) }));
24
+ document: (id) => `/projects/project/documents/${id}`,
25
+ documents: (prefix) => `/projects/project/documents?prefix=${prefix}`,
26
+ sessionLost: lost,
27
+ }), [username, lost]);
28
+ }
29
+ function App({ username, router }) {
30
+ const [lost, setLost] = useState(false);
31
+ const value = useMemo(() => ({ username, lost: () => setLost(true) }), [username]);
32
+ if (lost)
33
+ return (_jsx(Notice, { role: "alert", title: "Your session ended", children: _jsx(Button, { onClick: () => window.location.reload(), children: "Reload" }) }));
34
+ return (_jsx(Reader.Provider, { value: value, children: _jsx(RouterProvider, { router: router }) }));
35
35
  }
36
- class Boundary extends Component {
37
- state = {};
38
- static getDerivedStateFromError = (error) => ({ error });
39
- render() {
40
- const { error } = this.state;
41
- if (!error)
42
- return this.props.children;
43
- const retry = () => {
44
- this.props.reset();
45
- this.setState({ error: undefined });
46
- };
47
- return (_jsx(Notice, { role: "alert", title: error.message, children: _jsx(Button, { onClick: retry, children: "Try again" }) }));
48
- }
36
+ /** The reader the browser context names by cookie, else `username`. */
37
+ function readerOf(username) {
38
+ const named = document.cookie
39
+ .split('; ')
40
+ .find((cookie) => cookie.startsWith(`${readerCookie}=`));
41
+ return named === undefined
42
+ ? username
43
+ : decodeURIComponent(named.slice(readerCookie.length + 1));
49
44
  }
50
- export function start(username) {
45
+ export async function start(username) {
51
46
  document.title = project.title;
52
- createRoot(document.getElementById('root')).render(_jsx(QueryClientProvider, { client: new QueryClient(), children: _jsx(App, { username: username }) }));
47
+ const { default: routes } = await load();
48
+ const router = projectRouter(routes, useHost);
49
+ createRoot(document.getElementById('root')).render(_jsx(QueryClientProvider, { client: new QueryClient(), children: _jsx(App, { username: readerOf(username), router: router }) }));
53
50
  }
@@ -0,0 +1,14 @@
1
+ import type { Doc } from './types.js';
2
+ /**
3
+ * The project's document store as service-api-research answers it: the same
4
+ * routes, envelope, id grammar, size limit and conditions, held in memory. The
5
+ * dev host and the test host serve their documents from it.
6
+ */
7
+ export declare function documentStore(seed?: Record<string, {
8
+ body: unknown;
9
+ writer?: string;
10
+ }>, seedWriter?: string): {
11
+ /** Answers a request for `/documents[/id]`; `writer` is the session's person. */
12
+ handle(request: Request, writer: string): Promise<Response>;
13
+ all: () => Doc<unknown>[];
14
+ };
@@ -0,0 +1,78 @@
1
+ import { idPattern, prefixPattern, documentId } from './documents.js';
2
+ const limit = 256 * 1024;
3
+ const json = (status, value, revision) => new Response(JSON.stringify(value), {
4
+ status,
5
+ headers: {
6
+ 'Content-Type': 'application/json',
7
+ 'Cache-Control': 'private, no-cache',
8
+ ...(revision === undefined ? {} : { ETag: `"${revision}"` }),
9
+ },
10
+ });
11
+ const refuse = (status, why) => new Response(why, { status, headers: { 'Content-Type': 'text/plain' } });
12
+ /**
13
+ * The project's document store as service-api-research answers it: the same
14
+ * routes, envelope, id grammar, size limit and conditions, held in memory. The
15
+ * dev host and the test host serve their documents from it.
16
+ */
17
+ export function documentStore(seed = {}, seedWriter = 'test') {
18
+ const docs = new Map();
19
+ let revision = 0;
20
+ for (const [id, { body, writer = seedWriter }] of Object.entries(seed))
21
+ docs.set(documentId(id), { id, writer, revision: ++revision, body });
22
+ /** Every document, sorted by id. */
23
+ const all = () => [...docs.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
24
+ async function put(request, id, writer) {
25
+ if (!idPattern.test(id))
26
+ return refuse(400, `${id}: not a document id`);
27
+ if (!request.headers.get('Content-Type')?.startsWith('application/json'))
28
+ return refuse(415, 'the body is not application/json');
29
+ const match = request.headers.get('If-Match');
30
+ const none = request.headers.get('If-None-Match');
31
+ if ((match !== null && !/^"\d+"$/.test(match)) ||
32
+ (none !== null && none !== '*'))
33
+ return refuse(400, 'a condition header is malformed');
34
+ const text = await request.text();
35
+ if (new TextEncoder().encode(text).length > limit)
36
+ return refuse(413, `the body is over ${limit} bytes`);
37
+ let body;
38
+ try {
39
+ body = JSON.parse(text);
40
+ }
41
+ catch {
42
+ return refuse(400, 'the body is not valid JSON');
43
+ }
44
+ const held = docs.get(id);
45
+ if ((none !== null && held) ||
46
+ (match !== null && held?.revision !== Number(match.slice(1, -1))))
47
+ return refuse(412, 'a condition does not hold');
48
+ const doc = { id, writer, revision: ++revision, body };
49
+ docs.set(id, doc);
50
+ return json(held ? 200 : 201, doc, doc.revision);
51
+ }
52
+ return {
53
+ /** Answers a request for `/documents[/id]`; `writer` is the session's person. */
54
+ async handle(request, writer) {
55
+ const { pathname, searchParams } = new URL(request.url);
56
+ const id = pathname.match(/\/documents(?:\/([^/]*))?$/)?.[1];
57
+ if (request.method === 'PUT' && id !== undefined)
58
+ return put(request, id, writer);
59
+ if (request.method !== 'GET')
60
+ return refuse(405, 'method not allowed');
61
+ if (id === undefined) {
62
+ const prefix = searchParams.get('prefix') ?? '';
63
+ if (!prefixPattern.test(prefix))
64
+ return refuse(400, `${prefix}: not a document prefix`);
65
+ return json(200, {
66
+ items: all().filter((doc) => doc.id.startsWith(prefix)),
67
+ });
68
+ }
69
+ if (!idPattern.test(id))
70
+ return refuse(400, `${id}: not a document id`);
71
+ const doc = docs.get(id);
72
+ return doc
73
+ ? json(200, doc, doc.revision)
74
+ : refuse(404, 'no such document');
75
+ },
76
+ all,
77
+ };
78
+ }
@@ -0,0 +1,10 @@
1
+ /** A document request the host answered with a status the library does not read as data. */
2
+ export declare class DocumentError extends Error {
3
+ /** The HTTP status: 412 when a condition did not hold, 413 over the size limit. */
4
+ status: number;
5
+ constructor(status: number, message: string);
6
+ }
7
+ export declare const idPattern: RegExp;
8
+ export declare const prefixPattern: RegExp;
9
+ export declare function documentId(id: string): string;
10
+ export declare function documentPrefix(prefix: string): string;
@@ -0,0 +1,22 @@
1
+ /** A document request the host answered with a status the library does not read as data. */
2
+ export class DocumentError extends Error {
3
+ /** The HTTP status: 412 when a condition did not hold, 413 over the size limit. */
4
+ status;
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.name = 'DocumentError';
8
+ this.status = status;
9
+ }
10
+ }
11
+ export const idPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
12
+ export const prefixPattern = /^[A-Za-z0-9._-]*$/;
13
+ export function documentId(id) {
14
+ if (!idPattern.test(id))
15
+ throw new Error(`document id "${id}": must match ${idPattern}`);
16
+ return id;
17
+ }
18
+ export function documentPrefix(prefix) {
19
+ if (!prefixPattern.test(prefix))
20
+ throw new Error(`document prefix "${prefix}": must match ${prefixPattern}`);
21
+ return prefix;
22
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { type AnyRoute, type ErrorComponentProps } from '@tanstack/react-router';
2
+ import type { Host, Routes } from './types.js';
3
+ export type { Host };
4
+ export { pdfAssets } from './pdf.js';
5
+ declare function Failed({ error, reset }: ErrorComponentProps): import("react").JSX.Element;
6
+ /**
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`.
10
+ */
11
+ export declare function frame(useHost: () => Host): {
12
+ component: () => import("react").JSX.Element;
13
+ errorComponent: typeof Failed;
14
+ pendingComponent: () => import("react").JSX.Element;
15
+ };
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>;
package/dist/host.js ADDED
@@ -0,0 +1,31 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Button, Notice } from '@metacensus/library-ui';
3
+ import { useQueryErrorResetBoundary } from '@tanstack/react-query';
4
+ import { Outlet, } from '@tanstack/react-router';
5
+ import { HostContext } from './context.js';
6
+ export { pdfAssets } from './pdf.js';
7
+ function Failed({ error, reset }) {
8
+ const queries = useQueryErrorResetBoundary();
9
+ return (_jsx(Notice, { role: "alert", title: error instanceof Error ? error.message : String(error), children: _jsx(Button, { onClick: () => {
10
+ queries.reset();
11
+ reset();
12
+ }, children: "Try again" }) }));
13
+ }
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`.
18
+ */
19
+ export function frame(useHost) {
20
+ return {
21
+ component: function Frame() {
22
+ return (_jsx(HostContext.Provider, { value: useHost(), children: _jsx(Outlet, {}) }));
23
+ },
24
+ errorComponent: Failed,
25
+ pendingComponent: () => _jsx("p", { role: "status", children: "Loading\u2026" }),
26
+ };
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));
31
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export type { Corpus, Host, Kind, Location, Paper, Project, Reader, } from './types.js';
2
- export { Link, ResearchProvider, useCorpus, useData, useDatas, useHost, } from './react.js';
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';
3
+ export { DocumentError } from './documents.js';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- export { Link, ResearchProvider, useCorpus, useData, useDatas, useHost, } from './react.js';
1
+ export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, usePrivate, useSaveDocument, } from './react.js';
2
+ export { DocumentError } from './documents.js';
@@ -0,0 +1,14 @@
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(): {
4
+ 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>;
6
+ };
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>>>;
14
+ export {};
package/dist/mount.js ADDED
@@ -0,0 +1,15 @@
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() {
4
+ const root = createRootRoute();
5
+ const mount = createRoute({ getParentRoute: () => root, path: '$project' });
6
+ return { root, mount };
7
+ }
8
+ // Only `typeof routerOf` is read: it names the router a project's routes make.
9
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
10
+ function routerOf(children) {
11
+ const { root, mount } = createMount();
12
+ return createRouter({
13
+ routeTree: root.addChildren([mount.addChildren(children)]),
14
+ });
15
+ }
package/dist/papers.d.ts CHANGED
@@ -2,10 +2,4 @@ import type { Kind } from './types.js';
2
2
  export declare function git(root: string, ...args: string[]): string;
3
3
  export declare function kindOf(path: string): Kind | undefined;
4
4
  export declare const paperPath: (sha: string, kind: Kind) => string;
5
- export declare function readCorpus(root: string): Record<string, {
6
- kind: "pdf" | "doc" | "docx" | "xls" | "xlsx" | "zip" | "gif" | "jpg" | "tif" | "txt" | "html" | "xml";
7
- title?: string | undefined;
8
- citation?: string | undefined;
9
- open?: true | undefined;
10
- }>;
11
5
  export declare function checkPapers(root: string): string[];
package/dist/papers.js CHANGED
@@ -1,8 +1,7 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync, readFileSync } from 'node:fs';
3
- import { extname, join } from 'node:path';
4
- import { z } from 'zod';
5
- import { Corpus, kinds } from './schema.js';
2
+ import { extname } from 'node:path';
3
+ import { readCorpus } from './data.js';
4
+ import { kinds } from './schema.js';
6
5
  export function git(root, ...args) {
7
6
  const { status, stdout, stderr, error } = spawnSync('git', args, {
8
7
  cwd: root,
@@ -10,29 +9,17 @@ export function git(root, ...args) {
10
9
  });
11
10
  if (status === 0)
12
11
  return stdout;
13
- throw new Error(`git ${args[0]}: ${error?.message ?? stderr.split('\n')[0]}`);
12
+ const why = error?.message ??
13
+ stderr.match(/^ ! \[remote rejected\].*/m)?.[0].trim() ??
14
+ stderr.match(/^(fatal|error): .*/m)?.[0] ??
15
+ stderr.split('\n')[0];
16
+ throw new Error(`git ${args[0]}: ${why}`);
14
17
  }
15
18
  export function kindOf(path) {
16
19
  const extension = extname(path).slice(1).toLowerCase();
17
20
  return Object.hasOwn(kinds, extension) ? extension : undefined;
18
21
  }
19
22
  export const paperPath = (sha, kind) => `papers/${sha}.${kind}`;
20
- export function readCorpus(root) {
21
- const file = join(root, 'corpus.json');
22
- if (!existsSync(file))
23
- return {};
24
- try {
25
- return Corpus.parse(JSON.parse(readFileSync(file, 'utf8')));
26
- }
27
- catch (error) {
28
- const why = error instanceof z.ZodError
29
- ? error.issues
30
- .map(({ path, message }) => `${path.join('.')}: ${message}`)
31
- .join('; ')
32
- : error.message;
33
- throw new Error(`corpus.json: ${why}`);
34
- }
35
- }
36
23
  // git-lfs leaves an empty file as is, so `git lfs ls-files` never lists it.
37
24
  const emptySha = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
38
25
  export function checkPapers(root) {
package/dist/pdf.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Where a host serves library-ui's `pdf-assets/`. */
2
+ export declare const pdfAssets = "/pdfjs/";
package/dist/pdf.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Where a host serves library-ui's `pdf-assets/`. */
2
+ export const pdfAssets = '/pdfjs/';
@@ -1,8 +1,10 @@
1
- import { expect } from '@playwright/test';
1
+ import { expect, type Page } from '@playwright/test';
2
2
  declare const _default: import("@playwright/test").PlaywrightTestConfig<{}, {}>;
3
3
  export default _default;
4
4
  type Violation = `csp ${string} ${string}` | `axe ${string}`;
5
5
  export declare const test: import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & {
6
6
  violations: Violation[];
7
+ /** A page in a new context on the dev server, read as `reader`; `null` is signed out. The context takes the project's `contextOptions` and `baseURL`, no other `use` option. */
8
+ as: (reader: string | null) => Promise<Page>;
7
9
  }, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
8
10
  export { expect };
@@ -1,24 +1,64 @@
1
1
  import AxeBuilder from '@axe-core/playwright';
2
- import { defineConfig, expect, test as base } from '@playwright/test';
2
+ import { defineConfig, expect, test as base, } from '@playwright/test';
3
+ import { readerCookie } from './reader.js';
3
4
  const report = 'libraryResearchViolation';
5
+ const sent = 'libraryResearchSent';
6
+ const server = `const index = require('node:url').pathToFileURL(require.resolve('@metacensus/library-research')); import(new URL('commands/dev.js', index)).then((dev) => dev.default(['--port', '0']))`;
4
7
  export default defineConfig({
5
8
  testDir: 'browser',
6
9
  use: { baseURL: process.env.LIBRARY_RESEARCH_URL },
7
10
  webServer: {
8
- command: 'library-research dev --port 0',
11
+ command: `"${process.execPath}" -e "${server}"`,
9
12
  wait: { stdout: /(?<library_research_url>http:\S+\/project\/)/ },
10
13
  },
11
14
  });
12
- export const test = base.extend({
13
- violations: [[], { option: true }],
14
- page: async ({ page, violations }, use) => {
15
- const found = [];
16
- await page.exposeFunction(report, (v) => found.push(v));
17
- await page.addInitScript(`document.addEventListener('securitypolicyviolation', (e) => ${report}('csp ' + e.effectiveDirective + ' ' + e.blockedURI))`);
18
- await use(page);
15
+ /** Collects a page's CSP and axe violations; the returned function fails on those not listed. */
16
+ async function watch(page) {
17
+ const found = [];
18
+ await page.exposeFunction(report, (v) => found.push(v));
19
+ await page.addInitScript(`window.${sent} = []; document.addEventListener('securitypolicyviolation', (e) => ${sent}.push(${report}('csp ' + e.effectiveDirective + ' ' + e.blockedURI)))`);
20
+ return async (listed) => {
21
+ await page.evaluate(`Promise.all(window.${sent} ?? [])`);
19
22
  const axe = await new AxeBuilder({ page }).analyze();
20
23
  found.push(...axe.violations.map((v) => `axe ${v.id}`));
21
- expect(found.filter((v) => !violations.includes(v)), 'unlisted violations').toEqual([]);
24
+ expect(found.filter((v) => !listed.includes(v)), 'unlisted violations').toEqual([]);
25
+ };
26
+ }
27
+ export const test = base.extend({
28
+ violations: [[], { option: true }],
29
+ page: async ({ page, violations }, provide) => {
30
+ const finish = await watch(page);
31
+ await provide(page);
32
+ await finish(violations);
33
+ },
34
+ as: async ({ browser, baseURL, contextOptions, violations }, provide) => {
35
+ const finishers = [];
36
+ const contexts = [];
37
+ try {
38
+ await provide(async (reader) => {
39
+ const context = await browser.newContext({ ...contextOptions, baseURL });
40
+ contexts.push(context);
41
+ await context.addCookies([
42
+ {
43
+ name: readerCookie,
44
+ value: encodeURIComponent(reader ?? ''),
45
+ domain: new URL(baseURL).hostname,
46
+ path: '/',
47
+ },
48
+ ]);
49
+ const page = await context.newPage();
50
+ finishers.push(await watch(page));
51
+ return page;
52
+ });
53
+ // Every page is checked, and the first failure is the one thrown.
54
+ const results = await Promise.allSettled(finishers.map((finish) => finish(violations)));
55
+ for (const result of results)
56
+ if (result.status === 'rejected')
57
+ throw result.reason;
58
+ }
59
+ finally {
60
+ await Promise.all(contexts.map((context) => context.close()));
61
+ }
22
62
  },
23
63
  });
24
64
  export { expect };
package/dist/react.d.ts CHANGED
@@ -1,17 +1,40 @@
1
- import { type AnchorHTMLAttributes, type PropsWithChildren } from 'react';
2
- import type { Corpus, Host } from './types.js';
3
- export declare function ResearchProvider({ host, children, }: PropsWithChildren<{
4
- host: Host;
5
- }>): import("react").JSX.Element;
1
+ import { DocumentError } from './documents.js';
2
+ import type { Corpus, Doc, Host } from './types.js';
6
3
  export declare function useHost(): Host;
7
4
  type Role<T = unknown> = readonly [role: string, parse: (json: unknown) => T];
5
+ /** `parse` must be pure: it is read once per role list, not on every render. */
8
6
  export declare function useData<T>(role: string, parse: (json: unknown) => T): T;
7
+ /** Each parser must be pure: it is read once per role list, not on every render. */
9
8
  export declare function useDatas<const R extends readonly Role[]>(roles: R): {
10
9
  -readonly [K in keyof R]: R[K] extends Role<infer T> ? T : never;
11
10
  };
11
+ /**
12
+ * The viewed person's pages of a private role, as `{ page: parsed }`: empty
13
+ * when they hold none, a page the host names but the build did not emit left
14
+ * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
15
+ * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
16
+ */
17
+ export declare function usePrivate<T>(role: string, parse: (json: unknown) => T): Record<string, T>;
12
18
  export declare function useCorpus(): Corpus;
13
- export declare function Link({ to, replace, ...a }: {
14
- to: string;
15
- replace?: boolean;
16
- } & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>): import("react").JSX.Element;
19
+ /**
20
+ * One document of the project, or `null` when none has that id. Suspends while
21
+ * it loads; a failed read throws a `DocumentError` to the frame's error
22
+ * notice. `parse` runs on the body only and must be pure.
23
+ */
24
+ export declare function useDocument<T>(id: string, parse: (json: unknown) => T): Doc<T> | null;
25
+ /**
26
+ * The project's documents whose id starts with `prefix`, sorted by id; every
27
+ * save of the project refetches them. `parse` runs on each body and must be pure.
28
+ */
29
+ export declare function useDocuments<T>(prefix: string, parse: (json: unknown) => T): Doc<T>[];
30
+ /**
31
+ * Saves a JSON `body` as the document `id`, written by the signed-in person.
32
+ * `when` makes the save conditional: `'absent'` refuses (412) if the document
33
+ * exists, a revision refuses unless the document is at it; without it the
34
+ * save replaces. A failure is the mutation's `error`, a `DocumentError`.
35
+ */
36
+ export declare function useSaveDocument(id: string): import("@tanstack/react-query").UseMutationResult<Doc<unknown>, DocumentError, {
37
+ body: unknown;
38
+ when?: "absent" | number;
39
+ }, unknown>;
17
40
  export {};