@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/README.md CHANGED
@@ -1,29 +1,115 @@
1
1
  # library-research
2
2
 
3
- The research-project contract and dev kit
3
+ The research-project contract and its tools
4
4
 
5
5
  ## Run a project
6
6
 
7
- A project is this layout, each path fixed:
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 data roles
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; scripts dev and check
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 root
16
- ui/local/index.tsx optional; default export: the local-only root, never shipped
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 root at `/project/` and `ui/local/` at `/local/`, live from the files, as reader `NAME` (else `local`), under the host's CSP |
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
+ ```
104
+
105
+ ## Release
106
+
107
+ A version reaches npm only from a tag on `origin/main`, as the tarball CI installed; the release workflow refuses any other tag, and the tag sets the version.
108
+
109
+ 1. The Publish issue carries the changelog, drafted before the tag: what changed, how a project upgrades, what breaks. Jacob's `designed` on it is the yes.
110
+ 2. `make release TYPE=patch|minor|major` from a checkout at `origin/main`.
111
+ 3. The approved changelog is the GitHub Release's notes: `gh release create vX.Y.Z --verify-tag --notes-file <file>`.
112
+
113
+ ## Code correctness belongs to tests and PR review
114
+
115
+ Tests and pull-request review settle whether code is correct; nothing else does. Content review is the researcher's process: a person reviews what the research says (claims, passages, citations, narrative) as data and signs off on it. Its checks, receipts, sign-offs and fingerprints never cover source code, styles or build config, in library-research or in a project, so a refactor that changes no content never waits on a content reviewer. A code change that could alter what a reader sees gets a test that pins what the reader sees, not a sign-off.
package/csp.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "default-src": ["'self'"],
3
+ "script-src": ["'self'", "'wasm-unsafe-eval'"],
4
+ "style-src": ["'self'"],
5
+ "worker-src": ["'self'"],
6
+ "connect-src": ["'self'"],
7
+ "frame-ancestors": ["'self'"],
8
+ "base-uri": ["'self'"],
9
+ "form-action": ["'self'"]
10
+ }
package/dist/cli.js CHANGED
@@ -10,7 +10,7 @@ if (name === 'help') {
10
10
  console.log(commands.join('\n'));
11
11
  }
12
12
  else if (commands.includes(name)) {
13
- const command = await import(new URL(`${name}.js`, dir).href);
13
+ const command = (await import(new URL(`${name}.js`, dir).href));
14
14
  try {
15
15
  await command.default(args);
16
16
  }
@@ -2,7 +2,8 @@ import { createHash } from 'node:crypto';
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
- import { git, kindOf, paperPath, readCorpus } from '../papers.js';
5
+ import { git, kindOf, paperPath } from '../papers.js';
6
+ import { readCorpus } from '../data.js';
6
7
  import { findRoot } from '../root.js';
7
8
  import { Corpus, kinds } from '../schema.js';
8
9
  export default function add(args) {
@@ -21,6 +21,17 @@ export default async function candidate(args) {
21
21
  for (let n = 2; taken.has(tag); n++)
22
22
  tag = `${day}.${n}`;
23
23
  git(root, 'tag', '--annotate', '--message', tag, tag);
24
- git(root, 'push', '--quiet', 'origin', `refs/tags/${tag}`);
24
+ try {
25
+ git(root, 'push', '--quiet', 'origin', `refs/tags/${tag}`);
26
+ }
27
+ catch (error) {
28
+ try {
29
+ git(root, 'tag', '--delete', tag);
30
+ }
31
+ catch {
32
+ // the push's error is the one to report
33
+ }
34
+ throw error;
35
+ }
25
36
  console.log(`make pin PROJECT=${id} TAG=${tag}`);
26
37
  }
@@ -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 { project } from '../roles.js';
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
- return Object.values(project(root).roles).flatMap((read) => {
32
- try {
33
- read();
34
- return [];
35
- }
36
- catch (error) {
37
- return [error.message];
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' });
@@ -5,15 +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 { paperPath, readCorpus } from '../papers.js';
8
+ import { documentStore } from '../document-store.js';
9
+ import { paperPath } from '../papers.js';
10
+ import { project, read, readCorpus } from '../data.js';
11
+ import { pdfAssets } from '../pdf.js';
12
+ import { readerCookie } from '../reader.js';
9
13
  import { findRoot } from '../root.js';
10
14
  import { kinds } from '../schema.js';
11
15
  import { hostConfig } from '../vite-config.js';
12
16
  const entry = 'virtual:research-host';
13
17
  const css = `${entry}.css`;
14
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(\/[^/]*)?$/;
15
22
  const papers = /^\/projects\/project\/papers\/([^/]+)$/;
16
- const pdfjs = '/pdfjs/';
17
23
  const assetTypes = {
18
24
  '.js': 'text/javascript',
19
25
  '.mjs': 'text/javascript',
@@ -30,8 +36,17 @@ const page = `<!doctype html>
30
36
  </html>
31
37
  `;
32
38
  const nonce = randomBytes(16).toString('base64');
33
- // service-ui-research's defaultHeaders, plus the nonce
34
- const policy = `default-src 'self'; script-src 'self' 'wasm-unsafe-eval' 'nonce-${nonce}'; style-src 'self' 'nonce-${nonce}'; worker-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self'`;
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('; ');
35
50
  export default async function dev(args) {
36
51
  const { values } = parseArgs({
37
52
  args,
@@ -57,8 +72,11 @@ export default async function dev(args) {
57
72
  function devHost(root, reader, local) {
58
73
  const mount = local ? /^\/(project|local)\// : /^\/project\//;
59
74
  const real = realpathSync(root);
75
+ const store = documentStore();
60
76
  return {
61
77
  name: 'research:dev',
78
+ // Before research:serve, so a signed-out reader's data requests are refused first.
79
+ enforce: 'pre',
62
80
  config: () => ({ html: { cspNonce: nonce } }),
63
81
  resolveId: (id) => ([entry, css].includes(id) ? '\0' + id : undefined),
64
82
  load(id) {
@@ -72,17 +90,65 @@ function devHost(root, reader, local) {
72
90
  `import '${css}'`,
73
91
  `import { configurePdf } from '@metacensus/library-ui/pdf'`,
74
92
  `import { start } from ${JSON.stringify(host)}`,
75
- `configurePdf({ assets: ${JSON.stringify(pdfjs)} })`,
93
+ `configurePdf({ assets: ${JSON.stringify(pdfAssets)} })`,
76
94
  `start(${JSON.stringify(reader)})`,
77
95
  ].join('\n');
78
96
  },
79
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
+ };
80
112
  server.middlewares.use((req, res, next) => {
81
113
  res.setHeader('Content-Security-Policy', policy);
82
114
  const path = req.url?.split('?')[0];
83
115
  if (path === '/')
84
116
  return res.writeHead(302, { Location: '/project/' }).end();
85
- const asset = path?.startsWith(pdfjs) && path.slice(pdfjs.length);
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);
86
152
  if (asset) {
87
153
  const file = pdfAsset(asset);
88
154
  if (!file)
@@ -97,6 +163,8 @@ function devHost(root, reader, local) {
97
163
  if (!kind)
98
164
  return notFound(res, `${sha}: not in corpus.json`);
99
165
  const file = paperPath(sha, kind);
166
+ if (!existsSync(join(root, file)))
167
+ return notFound(res, `${file}: listed in corpus.json but missing`);
100
168
  if (realpathSync(join(root, file)) !== join(real, file))
101
169
  return notFound(res, `${file}: leads outside papers/`);
102
170
  const bytes = readFileSync(join(root, file));
@@ -104,16 +172,31 @@ function devHost(root, reader, local) {
104
172
  return notFound(res, `${file}: an LFS pointer; run git lfs pull`);
105
173
  send(req, res, bytes, kinds[kind]);
106
174
  });
107
- return () => server.middlewares.use(async (req, res, next) => {
175
+ return () => server.middlewares.use((req, res, next) => {
108
176
  const url = req.originalUrl ?? '';
109
177
  if (req.url !== '/index.html' || !mount.test(url))
110
178
  return next();
111
- const html = await server.transformIndexHtml(url, page);
112
- res.writeHead(200, { 'Content-Type': 'text/html' }).end(html);
179
+ server
180
+ .transformIndexHtml(url, page)
181
+ .then((html) => res.writeHead(200, { 'Content-Type': 'text/html' }).end(html))
182
+ .catch(next);
113
183
  });
114
184
  },
115
185
  };
116
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
+ }
117
200
  /** A file under library-ui's `pdf-assets/`, as its exports allow. */
118
201
  function pdfAsset(asset) {
119
202
  // Node warns on resolving a directory.
@@ -0,0 +1 @@
1
+ export default function init(args: string[]): void;
@@ -0,0 +1,131 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ const { version } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
5
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
6
+ export default function init(args) {
7
+ parseArgs({ args });
8
+ const root = process.cwd();
9
+ const title = basename(root);
10
+ if (!/^[\w.-]+$/.test(title))
11
+ throw new Error(`${title}: not a repository name; use letters, digits, ., - or _`);
12
+ const files = {
13
+ 'research.json': json({ title, data: {} }),
14
+ 'corpus.json': '{}\n',
15
+ '.gitattributes': 'papers/** filter=lfs diff=lfs merge=lfs -text\n',
16
+ '.gitignore': 'node_modules/\ntest-results/\n',
17
+ '.nvmrc': '24\n',
18
+ 'README.md': `# ${title}
19
+
20
+ A research project on [\`@metacensus/library-research\`](https://www.npmjs.com/package/@metacensus/library-research), whose README lists every command.
21
+
22
+ From \`ui/\`, run \`npm install\` and commit its lockfile. \`npx library-research candidate\` then names a commit for the service to pin.
23
+ `,
24
+ '.github/workflows/check.yml': `name: Check
25
+
26
+ on:
27
+ pull_request:
28
+ push:
29
+ branches: [main]
30
+
31
+ permissions:
32
+ contents: read
33
+
34
+ concurrency:
35
+ group: \${{ github.workflow }}-\${{ github.ref }}
36
+ cancel-in-progress: true
37
+
38
+ jobs:
39
+ check:
40
+ name: Check
41
+ runs-on: ubuntu-latest
42
+ timeout-minutes: 15
43
+ defaults:
44
+ run:
45
+ working-directory: ui
46
+ steps:
47
+ - uses: actions/checkout@v7
48
+ - uses: actions/setup-node@v7
49
+ with:
50
+ node-version-file: .nvmrc
51
+ cache: npm
52
+ cache-dependency-path: ui/package-lock.json
53
+ - run: npm ci
54
+ - run: npx playwright install --with-deps chromium
55
+ - run: npm run check
56
+ - run: npm test
57
+ - run: npx playwright test
58
+ `,
59
+ 'ui/package.json': json({
60
+ private: true,
61
+ type: 'module',
62
+ scripts: {
63
+ dev: 'library-research dev',
64
+ check: 'library-research check',
65
+ test: 'vitest run --exclude browser/**',
66
+ },
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
+ },
74
+ devEngines: { runtime: { name: 'node', version: '24' } },
75
+ }),
76
+ 'ui/tsconfig.json': json({
77
+ extends: '@metacensus/library-research/tsconfig.json',
78
+ }),
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
+ }
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
+ })
113
+ `,
114
+ 'ui/playwright.config.ts': `export { default } from '@metacensus/library-research/playwright'\n`,
115
+ 'ui/browser/page.spec.ts': `import { expect, test } from '@metacensus/library-research/playwright'
116
+
117
+ test('the root renders', async ({ page }) => {
118
+ await page.goto('')
119
+ await expect(page.getByRole('heading', { level: 1 })).toBeVisible()
120
+ })
121
+ `,
122
+ };
123
+ const taken = Object.keys(files).filter((path) => existsSync(join(root, path)));
124
+ if (taken.length)
125
+ throw new Error(taken.map((path) => `${path}: already exists`).join('\n'));
126
+ for (const [path, text] of Object.entries(files)) {
127
+ mkdirSync(dirname(join(root, path)), { recursive: true });
128
+ writeFileSync(join(root, path), text);
129
+ console.log(path);
130
+ }
131
+ }
@@ -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>;
@@ -0,0 +1,4 @@
1
+ import { createContext } from 'react';
2
+ export const HostContext = createContext(null);
3
+ /** Where the document hooks fetch from; the test host sets its in-memory store, a host leaves the global. */
4
+ export const FetchContext = createContext(null);
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;