@metacensus/library-research 0.11.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.
- 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 +30 -9
- package/dist/react.js +150 -27
- 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 +29 -0
- package/dist/testing.js +46 -0
- package/dist/types.d.ts +20 -12
- package/dist/vite-config.js +1 -0
- package/dist/vite.js +12 -3
- 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
package/README.md
CHANGED
|
@@ -7,26 +7,100 @@ The research-project contract and its tools
|
|
|
7
7
|
A project is this layout, each path fixed, which `npx @metacensus/library-research init` writes into an empty repository:
|
|
8
8
|
|
|
9
9
|
```
|
|
10
|
-
research.json title and
|
|
10
|
+
research.json title, data roles and private roles
|
|
11
11
|
corpus.json sha → paper
|
|
12
12
|
papers/<sha>.<kind> through LFS
|
|
13
|
-
ui/package.json depends on @metacensus/library-research, which brings @playwright/test; scripts dev and
|
|
13
|
+
ui/package.json depends on @metacensus/library-research, which brings @playwright/test; scripts dev, check and test
|
|
14
14
|
ui/tsconfig.json extends @metacensus/library-research/tsconfig.json
|
|
15
|
-
ui/index.tsx default export: the
|
|
16
|
-
ui/local/index.tsx optional;
|
|
15
|
+
ui/index.tsx default export: (parent: Mount) => the project's TanStack routes
|
|
16
|
+
ui/local/index.tsx optional; the same export for the local-only routes, never shipped; declares no Register
|
|
17
|
+
ui/*.test.tsx optional; unit tests on testHost from @metacensus/library-research/testing
|
|
17
18
|
ui/playwright.config.ts with browser/; export { default } from '@metacensus/library-research/playwright'
|
|
18
19
|
ui/browser/*.spec.ts optional; test and expect from @metacensus/library-research/playwright
|
|
19
20
|
```
|
|
20
21
|
|
|
21
22
|
From `ui/`:
|
|
22
23
|
|
|
23
|
-
| Command | Does
|
|
24
|
-
| --------------------------------------------------------------------- |
|
|
25
|
-
| `npm run dev -- [--reader NAME] [--port N]` | serves the
|
|
26
|
-
| `npm run check` | gates the project, one line per failure, as a host's build does
|
|
27
|
-
| `npx playwright test` | runs `browser/` in Chromium on a dev server; a CSP or axe violation fails its spec unless `violations` lists it
|
|
28
|
-
| `npx library-research add <file> [--title T] [--citation C] [--open]` | adds a paper to `papers/` and `corpus.json`
|
|
29
|
-
| `npx library-research candidate` | runs `check`, then tags a clean `HEAD` on `origin/main` as `<id>-YYYY-MM-DD[.N]`, pushes it, and prints the service's `make pin` line
|
|
24
|
+
| Command | Does |
|
|
25
|
+
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
26
|
+
| `npm run dev -- [--reader NAME] [--port N]` | serves the routes at `/project/` and `ui/local/`'s at `/local/`, live from the files, as reader `NAME` (else `local`) to a context that names none, under the host's CSP |
|
|
27
|
+
| `npm run check` | gates the project, one line per failure, as a host's build does |
|
|
28
|
+
| `npx playwright test` | runs `browser/` in Chromium on a dev server; a CSP or axe violation fails its spec unless `violations` lists it |
|
|
29
|
+
| `npx library-research add <file> [--title T] [--citation C] [--open]` | adds a paper to `papers/` and `corpus.json` |
|
|
30
|
+
| `npx library-research candidate` | runs `check`, then tags a clean `HEAD` on `origin/main` as `<id>-YYYY-MM-DD[.N]`, pushes it, and prints the service's `make pin` line |
|
|
31
|
+
|
|
32
|
+
## Rendering
|
|
33
|
+
|
|
34
|
+
A project renders in the browser only: the host is one single-page app and each project is a route of it, with no static build. A project never calls React's `lazy()`, and `check` fails on it; the PDF reader and charting come from `@metacensus/library-ui`.
|
|
35
|
+
|
|
36
|
+
## Data roles
|
|
37
|
+
|
|
38
|
+
Each key of research.json's `data` is a role, and `ui/roles.ts` exports `roles`, one Zod schema per role over the role's whole value; a glob role's is a `z.record` keyed by what its wildcard matched. The UI parses with it and `check` fails, one line per record file, on data that does not. A role with no schema fails, and `corpus.json` is no role: library-research's `Corpus` parses it.
|
|
39
|
+
|
|
40
|
+
## Private data
|
|
41
|
+
|
|
42
|
+
`research.json`'s `private` maps a role to a glob holding exactly one `*`, such as `{ "private": { "ask": "research_notes/coauthors/*/questions.json" } }`. What the `*` matches is the page key, and the build emits each match at `/projects/<id>/private/<page>/<role>.json`, never among the shared `data/` files. A host serves that path only to the people who hold the page. A page key matches `^[a-z0-9][a-z0-9-]*$` and a role is in `data` or `private`, not both; `check` fails otherwise, naming the role.
|
|
43
|
+
|
|
44
|
+
`usePrivate(role, parse)` returns `{ page: parsed }` for the pages the host names for the person the project is viewed as: none, one or several, and a page not yet built is left out. `Object.values(usePrivate('ask', parse))` is that person's questions. The role's schema in `ui/roles.ts` parses one page's file, and `load` returns the role as `{ page: parsed }`. A host's `private(role)` returns the page-to-URL map.
|
|
45
|
+
|
|
46
|
+
In `dev`, a reader's page is the reader's name: `dev --reader hertz` holds `hertz`'s page, another reader's page answers 403, and `testHost`'s `private: { role: { page: json } }` gives the reader the page named as it.
|
|
47
|
+
|
|
48
|
+
Node loads `ui/roles.ts` by stripping its types: no `enum` or namespace, relative imports end in `.ts`, and `ui/package.json` says `"type": "module"`. Dev tooling reads a project's roles through `load` from `@metacensus/library-research/roles`, which takes the folder holding research.json and returns each role parsed, with `corpus`.
|
|
49
|
+
|
|
50
|
+
## Routes
|
|
51
|
+
|
|
52
|
+
A project exports its routes, created against the `Mount` its host hands it, a route at `/$project`; the host owns the router. `Register` types the project's own links. A link names its path in full and passes `from="/$project"`, so a wrong path fails to compile and the current `project` carries over:
|
|
53
|
+
|
|
54
|
+
```tsx
|
|
55
|
+
export default function routes(parent: Mount) {
|
|
56
|
+
const task = createRoute({ getParentRoute: () => parent, path: 'task/$key' })
|
|
57
|
+
return [task]
|
|
58
|
+
}
|
|
59
|
+
declare module '@tanstack/react-router' {
|
|
60
|
+
interface Register {
|
|
61
|
+
router: RouterOf<typeof routes>
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// <Link from="/$project" to="/$project/task/$key" params={{ key }} />
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A host mounts them with `mountRoutes(route, routes)` from `@metacensus/library-research/host`, `route` being its own route at `/$project`.
|
|
68
|
+
|
|
69
|
+
The route also takes `frame(useHost)`, spread into its options: it provides the `Host` that `useHost` returns, shows a resettable error and an announced loading state. A host sets no `defaultPendingComponent` or `defaultErrorComponent` on its router, which would override the frame's for a project's routes. A host serves `@metacensus/library-research/csp.json` as its Content-Security-Policy (directive → sources, adding its own origins and nonces) and `pdfAssets`, `/pdfjs/`, for `configurePdf({ assets })`.
|
|
70
|
+
|
|
71
|
+
`params.project` is `project` or `local` in dev and the project's id in production, so a project never reads it as its id.
|
|
72
|
+
|
|
73
|
+
## Saving
|
|
74
|
+
|
|
75
|
+
A project saves JSON documents through its host, as it reads data.
|
|
76
|
+
|
|
77
|
+
- `useDocument(id, parse)` returns `{ id, writer, revision, body }`, or `null`.
|
|
78
|
+
- `useDocuments(prefix, parse)` lists the documents whose id starts with `prefix`.
|
|
79
|
+
- `useSaveDocument(id)` is a mutation taking `{ body, when }`. `when` is `'absent'` (refuse if the document exists) or a `revision` (refuse unless the document is at it).
|
|
80
|
+
- A refused save, a 412 or a 413, is the mutation's `error`: a `DocumentError` with its `status`.
|
|
81
|
+
- Ids match `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`; a body is at most 256 KiB.
|
|
82
|
+
- The `writer` is the signed-in person, set by the store.
|
|
83
|
+
- A host's `document(id)` and `documents(prefix)` return the URLs of the store's routes.
|
|
84
|
+
- `dev` keeps one in-memory store for every reader; a restart empties it.
|
|
85
|
+
|
|
86
|
+
## Testing
|
|
87
|
+
|
|
88
|
+
`testHost(routes, { data, private, documents, reader, url, sessionLost })` from `@metacensus/library-research/testing` returns `{ element, router, documents }`: a project's routes in the frame and `/$project` mount a real host uses, `data` giving each role's JSON, `reader` the username (default `test`), `documents` the project's saved documents as `{ id: { body, writer? } }`, `url` the path below the project (default `/`). Render `element` with any DOM renderer; `router.state.location` says where the project navigated, and `documents()` what it saved. `init` scaffolds `ui/index.test.tsx` on vitest, jsdom and Testing Library, which a project installs itself.
|
|
89
|
+
|
|
90
|
+
```tsx
|
|
91
|
+
render(
|
|
92
|
+
testHost(routes, { data: { items }, reader: 'ana', url: '/task/7' }).element,
|
|
93
|
+
)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
One dev server serves several readers: a browser context names its reader by the cookie `library-research-reader`, and an empty one is signed out, so data answers 401 and the host reports the session lost. In a browser spec, `as(reader)` opens a page in a new context read as `reader` (`null` signed out), each checked for CSP and axe violations as `page` is. That context takes the project's `contextOptions` and `baseURL`, no other `use` option. A leftover `library-research-reader` cookie in a browser overrides `--reader`:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
test('a leader sees what an author saved', async ({ as }) => {
|
|
100
|
+
const author = await as('author-1')
|
|
101
|
+
const leader = await as('leader')
|
|
102
|
+
})
|
|
103
|
+
```
|
|
30
104
|
|
|
31
105
|
## Release
|
|
32
106
|
|
package/csp.json
ADDED
package/dist/commands/add.js
CHANGED
|
@@ -3,7 +3,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
5
|
import { git, kindOf, paperPath } from '../papers.js';
|
|
6
|
-
import { readCorpus } from '../
|
|
6
|
+
import { readCorpus } from '../data.js';
|
|
7
7
|
import { findRoot } from '../root.js';
|
|
8
8
|
import { Corpus, kinds } from '../schema.js';
|
|
9
9
|
export default function add(args) {
|
package/dist/commands/check.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
|
2
|
+
import { existsSync, globSync, mkdtempSync, readFileSync, rmSync, } from 'node:fs';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
5
|
import { join, sep } from 'node:path';
|
|
6
6
|
import { parseArgs, stripVTControlCharacters } from 'node:util';
|
|
7
7
|
import { build, mergeConfig } from 'vite';
|
|
8
8
|
import { checkPapers } from '../papers.js';
|
|
9
|
-
import {
|
|
9
|
+
import { load } from '../roles.js';
|
|
10
10
|
import { findRoot } from '../root.js';
|
|
11
11
|
import { hostConfig } from '../vite-config.js';
|
|
12
12
|
const tsc = createRequire(import.meta.url).resolve('typescript/bin/tsc');
|
|
13
13
|
export default async function check(args) {
|
|
14
14
|
parseArgs({ args });
|
|
15
15
|
const root = findRoot(process.cwd());
|
|
16
|
-
for (const stage of [data, checkPapers, types, bundle]) {
|
|
16
|
+
for (const stage of [data, checkPapers, noLazy, types, bundle]) {
|
|
17
17
|
let failures;
|
|
18
18
|
try {
|
|
19
19
|
failures = await stage(root);
|
|
@@ -27,16 +27,25 @@ export default async function check(args) {
|
|
|
27
27
|
.join('\n'));
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
|
-
function data(root) {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
30
|
+
async function data(root) {
|
|
31
|
+
try {
|
|
32
|
+
await load(root);
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
return error.message.split('\n');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// Catches `lazy` imported from 'react' and `React.lazy(`. Misses `import * as R`
|
|
40
|
+
// and a `lazy` from another module; flags a comment and `{ x as lazy }`.
|
|
41
|
+
const lazyUse = /\bReact\s*\.\s*lazy\s*\(|\bimport\s*\{[^}]*\blazy\b[^}]*\}\s*from\s*['"]react['"]/;
|
|
42
|
+
function noLazy(root) {
|
|
43
|
+
return globSync('ui/**/*.{ts,tsx,js,jsx}', {
|
|
44
|
+
cwd: root,
|
|
45
|
+
exclude: (name) => name === 'node_modules',
|
|
46
|
+
})
|
|
47
|
+
.filter((file) => lazyUse.test(readFileSync(join(root, file), 'utf8')))
|
|
48
|
+
.map((file) => `${file}: uses React's lazy(), which a project never does`);
|
|
40
49
|
}
|
|
41
50
|
function types(root) {
|
|
42
51
|
const { status, stdout, stderr } = spawnSync(process.execPath, [tsc, '-p', 'ui', '--noEmit', '--pretty', 'false'], { cwd: root, encoding: 'utf8' });
|
package/dist/commands/dev.js
CHANGED
|
@@ -5,16 +5,21 @@ import { extname, join } from 'node:path';
|
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { parseArgs } from 'node:util';
|
|
7
7
|
import { createServer, mergeConfig } from 'vite';
|
|
8
|
+
import { documentStore } from '../document-store.js';
|
|
8
9
|
import { paperPath } from '../papers.js';
|
|
9
|
-
import { readCorpus } from '../
|
|
10
|
+
import { project, read, readCorpus } from '../data.js';
|
|
11
|
+
import { pdfAssets } from '../pdf.js';
|
|
12
|
+
import { readerCookie } from '../reader.js';
|
|
10
13
|
import { findRoot } from '../root.js';
|
|
11
14
|
import { kinds } from '../schema.js';
|
|
12
15
|
import { hostConfig } from '../vite-config.js';
|
|
13
16
|
const entry = 'virtual:research-host';
|
|
14
17
|
const css = `${entry}.css`;
|
|
15
18
|
const host = fileURLToPath(new URL('../dev/host.js', import.meta.url));
|
|
19
|
+
const data = /^\/projects\/project\/data\//;
|
|
20
|
+
const privates = /^\/projects\/project\/private\/([^/]+)\/([^/]+)\.json$/;
|
|
21
|
+
const documents = /^\/projects\/project\/documents(\/[^/]*)?$/;
|
|
16
22
|
const papers = /^\/projects\/project\/papers\/([^/]+)$/;
|
|
17
|
-
const pdfjs = '/pdfjs/';
|
|
18
23
|
const assetTypes = {
|
|
19
24
|
'.js': 'text/javascript',
|
|
20
25
|
'.mjs': 'text/javascript',
|
|
@@ -31,8 +36,17 @@ const page = `<!doctype html>
|
|
|
31
36
|
</html>
|
|
32
37
|
`;
|
|
33
38
|
const nonce = randomBytes(16).toString('base64');
|
|
34
|
-
//
|
|
35
|
-
const
|
|
39
|
+
// csp.json, which a host serves too, plus a nonce on script-src and style-src only, for Vite's inline tags
|
|
40
|
+
const csp = JSON.parse(readFileSync(new URL('../../csp.json', import.meta.url), 'utf8'));
|
|
41
|
+
const policy = Object.entries(csp)
|
|
42
|
+
.map(([name, sources]) => [
|
|
43
|
+
name,
|
|
44
|
+
...sources,
|
|
45
|
+
...(['script-src', 'style-src'].includes(name)
|
|
46
|
+
? [`'nonce-${nonce}'`]
|
|
47
|
+
: []),
|
|
48
|
+
].join(' '))
|
|
49
|
+
.join('; ');
|
|
36
50
|
export default async function dev(args) {
|
|
37
51
|
const { values } = parseArgs({
|
|
38
52
|
args,
|
|
@@ -58,8 +72,11 @@ export default async function dev(args) {
|
|
|
58
72
|
function devHost(root, reader, local) {
|
|
59
73
|
const mount = local ? /^\/(project|local)\// : /^\/project\//;
|
|
60
74
|
const real = realpathSync(root);
|
|
75
|
+
const store = documentStore();
|
|
61
76
|
return {
|
|
62
77
|
name: 'research:dev',
|
|
78
|
+
// Before research:serve, so a signed-out reader's data requests are refused first.
|
|
79
|
+
enforce: 'pre',
|
|
63
80
|
config: () => ({ html: { cspNonce: nonce } }),
|
|
64
81
|
resolveId: (id) => ([entry, css].includes(id) ? '\0' + id : undefined),
|
|
65
82
|
load(id) {
|
|
@@ -73,17 +90,65 @@ function devHost(root, reader, local) {
|
|
|
73
90
|
`import '${css}'`,
|
|
74
91
|
`import { configurePdf } from '@metacensus/library-ui/pdf'`,
|
|
75
92
|
`import { start } from ${JSON.stringify(host)}`,
|
|
76
|
-
`configurePdf({ assets: ${JSON.stringify(
|
|
93
|
+
`configurePdf({ assets: ${JSON.stringify(pdfAssets)} })`,
|
|
77
94
|
`start(${JSON.stringify(reader)})`,
|
|
78
95
|
].join('\n');
|
|
79
96
|
},
|
|
80
97
|
configureServer(server) {
|
|
98
|
+
// The project's documents, shared by every reader, written as the cookie names.
|
|
99
|
+
const document = async (req, res, writer) => {
|
|
100
|
+
const chunks = [];
|
|
101
|
+
for await (const chunk of req)
|
|
102
|
+
chunks.push(chunk);
|
|
103
|
+
const answer = await store.handle(new Request(new URL(req.url, 'http://localhost'), {
|
|
104
|
+
method: req.method,
|
|
105
|
+
headers: req.headers,
|
|
106
|
+
body: ['GET', 'HEAD'].includes(req.method)
|
|
107
|
+
? undefined
|
|
108
|
+
: Buffer.concat(chunks),
|
|
109
|
+
}), writer);
|
|
110
|
+
reply(res, answer.status, Object.fromEntries(answer.headers), Buffer.from(await answer.arrayBuffer()));
|
|
111
|
+
};
|
|
81
112
|
server.middlewares.use((req, res, next) => {
|
|
82
113
|
res.setHeader('Content-Security-Policy', policy);
|
|
83
114
|
const path = req.url?.split('?')[0];
|
|
84
115
|
if (path === '/')
|
|
85
116
|
return res.writeHead(302, { Location: '/project/' }).end();
|
|
86
|
-
|
|
117
|
+
// A cookie with an empty value is a signed-out reader; the raw value is
|
|
118
|
+
// compared, as an encoded name is never empty.
|
|
119
|
+
const named = cookie(req, readerCookie);
|
|
120
|
+
if ([data, documents, privates].some((route) => route.test(path ?? '')) &&
|
|
121
|
+
named === '')
|
|
122
|
+
return reply(res, 401, { 'Content-Type': 'text/plain' }, 'signed out');
|
|
123
|
+
const [, page, role = ''] = path?.match(privates) ?? [];
|
|
124
|
+
if (documents.test(path ?? '') || page) {
|
|
125
|
+
// A cookie that does not decode names no reader.
|
|
126
|
+
let who = reader;
|
|
127
|
+
try {
|
|
128
|
+
if (named !== undefined)
|
|
129
|
+
who = decodeURIComponent(named);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return reply(res, 401, { 'Content-Type': 'text/plain' }, 'signed out');
|
|
133
|
+
}
|
|
134
|
+
if (!page)
|
|
135
|
+
return void document(req, res, who).catch(next);
|
|
136
|
+
// A page is its reader's alone, as the server gates it; view-as is no gate.
|
|
137
|
+
let wanted = page;
|
|
138
|
+
try {
|
|
139
|
+
wanted = decodeURIComponent(page);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return notFound(res, `${page}: not a page`);
|
|
143
|
+
}
|
|
144
|
+
if (who !== wanted)
|
|
145
|
+
return reply(res, 403, { 'Content-Type': 'text/plain' }, 'not yours');
|
|
146
|
+
const file = privateFile(root, wanted, role);
|
|
147
|
+
if (!file)
|
|
148
|
+
return notFound(res, `project has no private role "${role}" page "${page}"`);
|
|
149
|
+
return send(req, res, Buffer.from(JSON.stringify(read(root, file))), 'application/json');
|
|
150
|
+
}
|
|
151
|
+
const asset = path?.startsWith(pdfAssets) && path.slice(pdfAssets.length);
|
|
87
152
|
if (asset) {
|
|
88
153
|
const file = pdfAsset(asset);
|
|
89
154
|
if (!file)
|
|
@@ -119,6 +184,19 @@ function devHost(root, reader, local) {
|
|
|
119
184
|
},
|
|
120
185
|
};
|
|
121
186
|
}
|
|
187
|
+
function privateFile(root, page, role) {
|
|
188
|
+
try {
|
|
189
|
+
return project(root).pages[role]?.()[page];
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (error.message.endsWith(': matches no file'))
|
|
193
|
+
return;
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
function cookie(req, name) {
|
|
198
|
+
return req.headers.cookie?.match(new RegExp(`(?:^|; )${name}=([^;]*)`))?.[1];
|
|
199
|
+
}
|
|
122
200
|
/** A file under library-ui's `pdf-assets/`, as its exports allow. */
|
|
123
201
|
function pdfAsset(asset) {
|
|
124
202
|
// Node warns on resolving a directory.
|
package/dist/commands/init.js
CHANGED
|
@@ -53,24 +53,63 @@ jobs:
|
|
|
53
53
|
- run: npm ci
|
|
54
54
|
- run: npx playwright install --with-deps chromium
|
|
55
55
|
- run: npm run check
|
|
56
|
+
- run: npm test
|
|
56
57
|
- run: npx playwright test
|
|
57
58
|
`,
|
|
58
59
|
'ui/package.json': json({
|
|
59
60
|
private: true,
|
|
60
|
-
|
|
61
|
+
type: 'module',
|
|
62
|
+
scripts: {
|
|
63
|
+
dev: 'library-research dev',
|
|
64
|
+
check: 'library-research check',
|
|
65
|
+
test: 'vitest run --exclude browser/**',
|
|
66
|
+
},
|
|
61
67
|
dependencies: { '@metacensus/library-research': `^${version}` },
|
|
68
|
+
devDependencies: {
|
|
69
|
+
'@testing-library/dom': '^10.4.2',
|
|
70
|
+
'@testing-library/react': '^16.3.3',
|
|
71
|
+
jsdom: '^31.0.1',
|
|
72
|
+
vitest: '^5.1.1',
|
|
73
|
+
},
|
|
62
74
|
devEngines: { runtime: { name: 'node', version: '24' } },
|
|
63
75
|
}),
|
|
64
76
|
'ui/tsconfig.json': json({
|
|
65
77
|
extends: '@metacensus/library-research/tsconfig.json',
|
|
66
78
|
}),
|
|
67
|
-
'ui/index.tsx': `
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
79
|
+
'ui/index.tsx': `import type { Mount, RouterOf } from '@metacensus/library-research'
|
|
80
|
+
import { createRoute } from '@tanstack/react-router'
|
|
81
|
+
|
|
82
|
+
export default function routes(parent: Mount) {
|
|
83
|
+
const index = createRoute({
|
|
84
|
+
getParentRoute: () => parent,
|
|
85
|
+
path: '/',
|
|
86
|
+
component: () => (
|
|
87
|
+
<main>
|
|
88
|
+
<h1>${title}</h1>
|
|
89
|
+
</main>
|
|
90
|
+
),
|
|
91
|
+
})
|
|
92
|
+
return [index]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
declare module '@tanstack/react-router' {
|
|
96
|
+
interface Register {
|
|
97
|
+
router: RouterOf<typeof routes>
|
|
98
|
+
}
|
|
73
99
|
}
|
|
100
|
+
`,
|
|
101
|
+
'ui/index.test.tsx': `// @vitest-environment jsdom
|
|
102
|
+
import { testHost } from '@metacensus/library-research/testing'
|
|
103
|
+
import { cleanup, render, screen } from '@testing-library/react'
|
|
104
|
+
import { afterEach, test } from 'vitest'
|
|
105
|
+
import routes from './index.tsx'
|
|
106
|
+
|
|
107
|
+
afterEach(cleanup)
|
|
108
|
+
|
|
109
|
+
test('the root renders', async () => {
|
|
110
|
+
render(testHost(routes).element)
|
|
111
|
+
await screen.findByRole('heading', { level: 1 })
|
|
112
|
+
})
|
|
74
113
|
`,
|
|
75
114
|
'ui/playwright.config.ts': `export { default } from '@metacensus/library-research/playwright'\n`,
|
|
76
115
|
'ui/browser/page.spec.ts': `import { expect, test } from '@metacensus/library-research/playwright'
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Host } from './types.js';
|
|
2
|
+
export declare const HostContext: import("react").Context<Host | null>;
|
|
3
|
+
/** Where the document hooks fetch from; the test host sets its in-memory store, a host leaves the global. */
|
|
4
|
+
export declare const FetchContext: import("react").Context<typeof fetch | null>;
|
package/dist/context.js
ADDED
package/dist/data.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/** Reads a project's research.json; each role reads its files when called. */
|
|
3
|
+
export declare function project(dir: string): {
|
|
4
|
+
title: string;
|
|
5
|
+
roles: Record<string, () => unknown>;
|
|
6
|
+
pages: Record<string, () => Record<string, string>>;
|
|
7
|
+
};
|
|
8
|
+
/** The files a private role's glob matches, by the page each names; throws on a key a page cannot have. */
|
|
9
|
+
export declare function privatePages(dir: string, role: string, glob: string): Record<string, string>;
|
|
10
|
+
/** The files a role's glob matches; a wildcard keys each by what it matched. */
|
|
11
|
+
export declare function files(dir: string, glob: string): {
|
|
12
|
+
keyed: boolean;
|
|
13
|
+
entries: [file: string, key: string][];
|
|
14
|
+
};
|
|
15
|
+
export declare function match(dir: string, { keyed, entries }: ReturnType<typeof files>): unknown;
|
|
16
|
+
export declare function readCorpus(dir: string): Record<string, {
|
|
17
|
+
kind: "pdf" | "doc" | "docx" | "xls" | "xlsx" | "zip" | "gif" | "jpg" | "tif" | "txt" | "html" | "xml";
|
|
18
|
+
title?: string | undefined;
|
|
19
|
+
citation?: string | undefined;
|
|
20
|
+
open?: true | undefined;
|
|
21
|
+
}>;
|
|
22
|
+
export declare function read<T>(dir: string, file: string, schema?: z.ZodType<T>): T;
|
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
|
+
}
|
package/dist/dev/host.d.ts
CHANGED
|
@@ -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,57 +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
|
|
4
|
-
import {
|
|
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 {
|
|
8
|
+
import { readerCookie } from '../reader.js';
|
|
9
|
+
import { projectRouter } from '../router.js';
|
|
8
10
|
const project = projects.project;
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
function App({ username }) {
|
|
17
|
-
const [location, setLocation] = useState(here);
|
|
18
|
-
const [lost, setLost] = useState(false);
|
|
19
|
-
useEffect(() => {
|
|
20
|
-
const pop = () => setLocation(here());
|
|
21
|
-
window.addEventListener('popstate', pop);
|
|
22
|
-
return () => window.removeEventListener('popstate', pop);
|
|
23
|
-
}, []);
|
|
24
|
-
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(() => ({
|
|
25
18
|
reader: { username },
|
|
26
|
-
base,
|
|
27
|
-
location,
|
|
28
|
-
navigate(to, { replace } = {}) {
|
|
29
|
-
history[replace ? 'replaceState' : 'pushState'](null, '', base + to);
|
|
30
|
-
setLocation(here());
|
|
31
|
-
},
|
|
32
19
|
data: (role) => `/projects/project/data/${role}.json`,
|
|
20
|
+
private: (role) => ({
|
|
21
|
+
[username]: `/projects/project/private/${encodeURIComponent(username)}/${role}.json`,
|
|
22
|
+
}),
|
|
33
23
|
paper: (sha) => `/projects/project/papers/${sha}`,
|
|
34
|
-
|
|
35
|
-
|
|
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]);
|
|
36
32
|
if (lost)
|
|
37
33
|
return (_jsx(Notice, { role: "alert", title: "Your session ended", children: _jsx(Button, { onClick: () => window.location.reload(), children: "Reload" }) }));
|
|
38
|
-
return (_jsx(
|
|
34
|
+
return (_jsx(Reader.Provider, { value: value, children: _jsx(RouterProvider, { router: router }) }));
|
|
39
35
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
this.props.reset();
|
|
49
|
-
this.setState({ error: undefined });
|
|
50
|
-
};
|
|
51
|
-
return (_jsx(Notice, { role: "alert", title: error.message, children: _jsx(Button, { onClick: retry, children: "Try again" }) }));
|
|
52
|
-
}
|
|
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));
|
|
53
44
|
}
|
|
54
|
-
export function start(username) {
|
|
45
|
+
export async function start(username) {
|
|
55
46
|
document.title = project.title;
|
|
56
|
-
|
|
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 }) }));
|
|
57
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
|
+
};
|