@metacensus/library-research 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -11
- package/csp.json +10 -0
- package/dist/commands/add.js +1 -1
- package/dist/commands/check.js +22 -13
- package/dist/commands/dev.js +84 -6
- package/dist/commands/init.js +46 -7
- package/dist/context.d.ts +4 -0
- package/dist/context.js +4 -0
- package/dist/data.d.ts +22 -0
- package/dist/data.js +76 -0
- package/dist/dev/host.d.ts +1 -1
- package/dist/dev/host.js +36 -43
- package/dist/document-store.d.ts +14 -0
- package/dist/document-store.js +78 -0
- package/dist/documents.d.ts +10 -0
- package/dist/documents.js +22 -0
- package/dist/host.d.ts +17 -0
- package/dist/host.js +31 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/mount.d.ts +14 -0
- package/dist/mount.js +15 -0
- package/dist/papers.js +1 -1
- package/dist/pdf.d.ts +2 -0
- package/dist/pdf.js +2 -0
- package/dist/playwright.d.ts +3 -1
- package/dist/playwright.js +45 -8
- package/dist/react.d.ts +43 -11
- package/dist/react.js +163 -29
- package/dist/reader.d.ts +2 -0
- package/dist/reader.js +2 -0
- package/dist/roles.d.ts +7 -11
- package/dist/roles.js +104 -45
- package/dist/router.d.ts +4 -0
- package/dist/router.js +16 -0
- package/dist/schema.d.ts +1 -0
- package/dist/schema.js +15 -2
- package/dist/testing.d.ts +30 -0
- package/dist/testing.js +46 -0
- package/dist/types.d.ts +33 -12
- package/dist/vite-config.js +1 -0
- package/dist/vite.d.ts +10 -1
- package/dist/vite.js +41 -8
- package/package.json +17 -1
- package/schema/research.schema.json +11 -0
- package/src/virtual.d.ts +2 -2
- package/tsconfig.project.json +2 -0
|
@@ -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,
|
|
2
|
-
export {
|
|
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 {
|
|
1
|
+
export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, usePrivate, useSaveDocument, } from './react.js';
|
|
2
|
+
export { DocumentError } from './documents.js';
|
package/dist/mount.d.ts
ADDED
|
@@ -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.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
2
|
import { extname } from 'node:path';
|
|
3
|
-
import { readCorpus } from './
|
|
3
|
+
import { readCorpus } from './data.js';
|
|
4
4
|
import { kinds } from './schema.js';
|
|
5
5
|
export function git(root, ...args) {
|
|
6
6
|
const { status, stdout, stderr, error } = spawnSync('git', args, {
|
package/dist/pdf.d.ts
ADDED
package/dist/pdf.js
ADDED
package/dist/playwright.d.ts
CHANGED
|
@@ -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 };
|
package/dist/playwright.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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';
|
|
4
5
|
const sent = 'libraryResearchSent';
|
|
5
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']))`;
|
|
@@ -11,17 +12,53 @@ export default defineConfig({
|
|
|
11
12
|
wait: { stdout: /(?<library_research_url>http:\S+\/project\/)/ },
|
|
12
13
|
},
|
|
13
14
|
});
|
|
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} ?? [])`);
|
|
22
|
+
const axe = await new AxeBuilder({ page }).analyze();
|
|
23
|
+
found.push(...axe.violations.map((v) => `axe ${v.id}`));
|
|
24
|
+
expect(found.filter((v) => !listed.includes(v)), 'unlisted violations').toEqual([]);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
14
27
|
export const test = base.extend({
|
|
15
28
|
violations: [[], { option: true }],
|
|
16
29
|
page: async ({ page, violations }, provide) => {
|
|
17
|
-
const
|
|
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)))`);
|
|
30
|
+
const finish = await watch(page);
|
|
20
31
|
await provide(page);
|
|
21
|
-
await
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
+
}
|
|
25
62
|
},
|
|
26
63
|
});
|
|
27
64
|
export { expect };
|
package/dist/react.d.ts
CHANGED
|
@@ -1,19 +1,51 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { Corpus, Host } from './types.js';
|
|
3
|
-
|
|
4
|
-
host: Host;
|
|
5
|
-
}>): import("react").JSX.Element;
|
|
1
|
+
import { DocumentError } from './documents.js';
|
|
2
|
+
import type { Corpus, Doc, Host } from './types.js';
|
|
3
|
+
/** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
|
|
6
4
|
export declare function useHost(): Host;
|
|
7
5
|
type Role<T = unknown> = readonly [role: string, parse: (json: unknown) => T];
|
|
8
|
-
/**
|
|
6
|
+
/**
|
|
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
|
|
9
|
+
* 403 also calls `Host.sessionLost`. `parse` must be pure: it is read once per
|
|
10
|
+
* role list, not on every render.
|
|
11
|
+
*/
|
|
9
12
|
export declare function useData<T>(role: string, parse: (json: unknown) => T): T;
|
|
10
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* `useData` for several roles at once, fetched in parallel: a `[role, parse]`
|
|
15
|
+
* 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.
|
|
17
|
+
*/
|
|
11
18
|
export declare function useDatas<const R extends readonly Role[]>(roles: R): {
|
|
12
19
|
-readonly [K in keyof R]: R[K] extends Role<infer T> ? T : never;
|
|
13
20
|
};
|
|
21
|
+
/**
|
|
22
|
+
* The viewed person's pages of a private role, as `{ page: parsed }`: empty
|
|
23
|
+
* when they hold none, a page the host names but the build did not emit left
|
|
24
|
+
* out. `parse` runs on each page's JSON and must be pure. Its cache entry,
|
|
25
|
+
* `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
|
|
26
|
+
*/
|
|
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`. */
|
|
14
29
|
export declare function useCorpus(): Corpus;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
30
|
+
/**
|
|
31
|
+
* One document of the project, or `null` when none has that id. Suspends while
|
|
32
|
+
* it loads; a failed read throws a `DocumentError` to the frame's error
|
|
33
|
+
* notice. `parse` runs on the body only and must be pure.
|
|
34
|
+
*/
|
|
35
|
+
export declare function useDocument<T>(id: string, parse: (json: unknown) => T): Doc<T> | null;
|
|
36
|
+
/**
|
|
37
|
+
* The project's documents whose id starts with `prefix`, sorted by id; every
|
|
38
|
+
* save of the project refetches them. `parse` runs on each body and must be pure.
|
|
39
|
+
*/
|
|
40
|
+
export declare function useDocuments<T>(prefix: string, parse: (json: unknown) => T): Doc<T>[];
|
|
41
|
+
/**
|
|
42
|
+
* Saves a JSON `body` as the document `id`, written by the signed-in person.
|
|
43
|
+
* `when` makes the save conditional: `'absent'` refuses (412) if the document
|
|
44
|
+
* exists, a revision refuses unless the document is at it; without it the
|
|
45
|
+
* save replaces. A failure is the mutation's `error`, a `DocumentError`.
|
|
46
|
+
*/
|
|
47
|
+
export declare function useSaveDocument(id: string): import("@tanstack/react-query").UseMutationResult<Doc<unknown>, DocumentError, {
|
|
48
|
+
body: unknown;
|
|
49
|
+
when?: "absent" | number;
|
|
50
|
+
}, unknown>;
|
|
19
51
|
export {};
|
package/dist/react.js
CHANGED
|
@@ -1,22 +1,29 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { useMutation, useQueryClient, useSuspenseQueries, useSuspenseQuery, } from '@tanstack/react-query';
|
|
2
|
+
import { useContext, useMemo, useState } from 'react';
|
|
3
|
+
import { FetchContext, HostContext } from './context.js';
|
|
4
|
+
import { DocumentError, documentId, documentPrefix } from './documents.js';
|
|
4
5
|
import * as schema from './schema.js';
|
|
5
|
-
|
|
6
|
-
export function ResearchProvider({ host, children, }) {
|
|
7
|
-
return _jsx(HostContext.Provider, { value: host, children: children });
|
|
8
|
-
}
|
|
6
|
+
/** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
|
|
9
7
|
export function useHost() {
|
|
10
8
|
const host = useContext(HostContext);
|
|
11
9
|
if (!host)
|
|
12
|
-
throw new Error('useHost outside
|
|
10
|
+
throw new Error('useHost outside the frame of ./host');
|
|
13
11
|
return host;
|
|
14
12
|
}
|
|
15
|
-
/**
|
|
13
|
+
/**
|
|
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
|
|
16
|
+
* 403 also calls `Host.sessionLost`. `parse` must be pure: it is read once per
|
|
17
|
+
* role list, not on every render.
|
|
18
|
+
*/
|
|
16
19
|
export function useData(role, parse) {
|
|
17
20
|
return useDatas([[role, parse]])[0];
|
|
18
21
|
}
|
|
19
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* `useData` for several roles at once, fetched in parallel: a `[role, parse]`
|
|
24
|
+
* 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.
|
|
26
|
+
*/
|
|
20
27
|
export function useDatas(roles) {
|
|
21
28
|
const host = useHost();
|
|
22
29
|
// The parsers and select functions are kept until the role list changes, so
|
|
@@ -31,7 +38,7 @@ export function useDatas(roles) {
|
|
|
31
38
|
return parse(json);
|
|
32
39
|
}
|
|
33
40
|
catch (cause) {
|
|
34
|
-
return failed(role
|
|
41
|
+
return failed(`data role "${role}"`, cause);
|
|
35
42
|
}
|
|
36
43
|
}), [held]);
|
|
37
44
|
return useSuspenseQueries({
|
|
@@ -47,7 +54,7 @@ export function useDatas(roles) {
|
|
|
47
54
|
throw new Error(`${response.status} from ${url}`);
|
|
48
55
|
return response.json();
|
|
49
56
|
})
|
|
50
|
-
.catch((cause) => failed(role
|
|
57
|
+
.catch((cause) => failed(`data role "${role}"`, cause)),
|
|
51
58
|
select: selects[i],
|
|
52
59
|
staleTime: Infinity,
|
|
53
60
|
retry: false,
|
|
@@ -58,27 +65,154 @@ export function useDatas(roles) {
|
|
|
58
65
|
}
|
|
59
66
|
// Module-level, so combine reruns only when a result changes.
|
|
60
67
|
const datas = (results) => results.map(({ data }) => data);
|
|
61
|
-
function failed(
|
|
68
|
+
function failed(what, cause) {
|
|
62
69
|
const why = cause instanceof Error ? cause.message : String(cause);
|
|
63
|
-
throw new Error(
|
|
70
|
+
throw new Error(`${what}: ${why}`, { cause });
|
|
64
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* The viewed person's pages of a private role, as `{ page: parsed }`: empty
|
|
74
|
+
* when they hold none, a page the host names but the build did not emit left
|
|
75
|
+
* out. `parse` runs on each page's JSON and must be pure. Its cache entry,
|
|
76
|
+
* `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
|
|
77
|
+
*/
|
|
78
|
+
export function usePrivate(role, parse) {
|
|
79
|
+
const host = useHost();
|
|
80
|
+
const urls = host.private(role);
|
|
81
|
+
const pages = Object.keys(urls);
|
|
82
|
+
const key = pages.join();
|
|
83
|
+
const held = useHeld(role, parse);
|
|
84
|
+
const selects = useMemo(() => pages.map((page) => (found) => {
|
|
85
|
+
if (!found)
|
|
86
|
+
return null;
|
|
87
|
+
try {
|
|
88
|
+
return { value: held(found.json) };
|
|
89
|
+
}
|
|
90
|
+
catch (cause) {
|
|
91
|
+
return failed(`private role "${role}" page "${page}"`, cause);
|
|
92
|
+
}
|
|
93
|
+
}),
|
|
94
|
+
// The pages are named by `key`.
|
|
95
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
96
|
+
[held, key]);
|
|
97
|
+
return useSuspenseQueries({
|
|
98
|
+
queries: pages.map((page, i) => {
|
|
99
|
+
const url = urls[page];
|
|
100
|
+
return {
|
|
101
|
+
queryKey: ['research', url],
|
|
102
|
+
queryFn: () => fetch(url)
|
|
103
|
+
.then((response) => {
|
|
104
|
+
if (response.status === 401 || response.status === 403)
|
|
105
|
+
host.sessionLost();
|
|
106
|
+
if (response.status === 404)
|
|
107
|
+
return null;
|
|
108
|
+
if (!response.ok)
|
|
109
|
+
throw new Error(`${response.status} from ${url}`);
|
|
110
|
+
return response.json().then((json) => ({ json }));
|
|
111
|
+
})
|
|
112
|
+
.catch((cause) => failed(`private role "${role}" page "${page}"`, cause)),
|
|
113
|
+
select: selects[i],
|
|
114
|
+
staleTime: Infinity,
|
|
115
|
+
retry: false,
|
|
116
|
+
};
|
|
117
|
+
}),
|
|
118
|
+
combine: (results) => Object.fromEntries(results.flatMap(({ data }, i) => data ? [[pages[i], data.value]] : [])),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/** The `corpus` role, parsed by the library's own schema, through `useData`. */
|
|
65
122
|
export function useCorpus() {
|
|
66
123
|
return useData('corpus', (json) => schema.Corpus.parse(json));
|
|
67
124
|
}
|
|
68
|
-
|
|
125
|
+
/** A fetch whose 401 and 403 are the host's lost session, and whose other failures are a `DocumentError`. */
|
|
126
|
+
function useSend() {
|
|
69
127
|
const host = useHost();
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
(
|
|
79
|
-
|
|
80
|
-
event.preventDefault();
|
|
81
|
-
host.navigate(to, { replace });
|
|
128
|
+
const get = useContext(FetchContext) ?? fetch;
|
|
129
|
+
return async (url, init, absent = false) => {
|
|
130
|
+
const response = await get(url, init);
|
|
131
|
+
if (response.status === 401 || response.status === 403)
|
|
132
|
+
host.sessionLost();
|
|
133
|
+
if (absent && response.status === 404)
|
|
134
|
+
return null;
|
|
135
|
+
if (!response.ok)
|
|
136
|
+
throw new DocumentError(response.status, `${response.status} from ${url}`);
|
|
137
|
+
return response.json();
|
|
82
138
|
};
|
|
83
|
-
|
|
84
|
-
|
|
139
|
+
}
|
|
140
|
+
/** `parse`, held until `key` changes, so an inline one is not read again on every render. */
|
|
141
|
+
function useHeld(key, parse) {
|
|
142
|
+
const [held, hold] = useState({ key, parse });
|
|
143
|
+
if (held.key !== key)
|
|
144
|
+
hold({ key, parse });
|
|
145
|
+
return held.parse;
|
|
146
|
+
}
|
|
147
|
+
const parsed = (parse) => (doc) => {
|
|
148
|
+
try {
|
|
149
|
+
return { ...doc, body: parse(doc.body) };
|
|
150
|
+
}
|
|
151
|
+
catch (cause) {
|
|
152
|
+
const why = cause instanceof Error ? cause.message : String(cause);
|
|
153
|
+
throw new Error(`document "${doc.id}": ${why}`, { cause });
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* One document of the project, or `null` when none has that id. Suspends while
|
|
158
|
+
* it loads; a failed read throws a `DocumentError` to the frame's error
|
|
159
|
+
* notice. `parse` runs on the body only and must be pure.
|
|
160
|
+
*/
|
|
161
|
+
export function useDocument(id, parse) {
|
|
162
|
+
const url = useHost().document(documentId(id));
|
|
163
|
+
const send = useSend();
|
|
164
|
+
const held = useHeld(url, parse);
|
|
165
|
+
const select = useMemo(() => (doc) => doc && parsed(held)(doc), [held]);
|
|
166
|
+
return useSuspenseQuery({
|
|
167
|
+
queryKey: ['research-document', url],
|
|
168
|
+
queryFn: () => send(url, undefined, true),
|
|
169
|
+
select,
|
|
170
|
+
retry: false,
|
|
171
|
+
}).data;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The project's documents whose id starts with `prefix`, sorted by id; every
|
|
175
|
+
* save of the project refetches them. `parse` runs on each body and must be pure.
|
|
176
|
+
*/
|
|
177
|
+
export function useDocuments(prefix, parse) {
|
|
178
|
+
const url = useHost().documents(documentPrefix(prefix));
|
|
179
|
+
const send = useSend();
|
|
180
|
+
const held = useHeld(url, parse);
|
|
181
|
+
const select = useMemo(() => ({ items }) => items.map(parsed(held)), [held]);
|
|
182
|
+
return useSuspenseQuery({
|
|
183
|
+
queryKey: ['research-documents', url],
|
|
184
|
+
queryFn: () => send(url),
|
|
185
|
+
select,
|
|
186
|
+
retry: false,
|
|
187
|
+
}).data;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Saves a JSON `body` as the document `id`, written by the signed-in person.
|
|
191
|
+
* `when` makes the save conditional: `'absent'` refuses (412) if the document
|
|
192
|
+
* exists, a revision refuses unless the document is at it; without it the
|
|
193
|
+
* save replaces. A failure is the mutation's `error`, a `DocumentError`.
|
|
194
|
+
*/
|
|
195
|
+
export function useSaveDocument(id) {
|
|
196
|
+
const url = useHost().document(documentId(id));
|
|
197
|
+
const send = useSend();
|
|
198
|
+
const client = useQueryClient();
|
|
199
|
+
return useMutation({
|
|
200
|
+
mutationFn: ({ body, when }) => {
|
|
201
|
+
const headers = {
|
|
202
|
+
'Content-Type': 'application/json',
|
|
203
|
+
};
|
|
204
|
+
if (when === 'absent')
|
|
205
|
+
headers['If-None-Match'] = '*';
|
|
206
|
+
else if (when !== undefined)
|
|
207
|
+
headers['If-Match'] = `"${when}"`;
|
|
208
|
+
const text = JSON.stringify(body);
|
|
209
|
+
if (text === undefined)
|
|
210
|
+
throw new Error(`document "${id}": no JSON body`);
|
|
211
|
+
return send(url, { method: 'PUT', headers, body: text });
|
|
212
|
+
},
|
|
213
|
+
onSuccess: (doc) => {
|
|
214
|
+
client.setQueryData(['research-document', url], doc);
|
|
215
|
+
return client.invalidateQueries({ queryKey: ['research-documents'] });
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
}
|
package/dist/reader.d.ts
ADDED
package/dist/reader.js
ADDED
package/dist/roles.d.ts
CHANGED
|
@@ -1,11 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
title?: string | undefined;
|
|
9
|
-
citation?: string | undefined;
|
|
10
|
-
open?: true | undefined;
|
|
11
|
-
}>;
|
|
1
|
+
/**
|
|
2
|
+
* Reads each data role of the project in `dir`, the folder holding
|
|
3
|
+
* research.json, parsed by its schema in ui/roles.ts, and its corpus. A
|
|
4
|
+
* private role is read as `{ page: parsed }`, its schema parsing one page's
|
|
5
|
+
* file. Throws one line per failure.
|
|
6
|
+
*/
|
|
7
|
+
export declare function load(dir: string): Promise<Record<string, unknown>>;
|