@metacensus/library-research 0.0.0-stage → 0.9.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/LICENSE +661 -0
- package/README.md +24 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +25 -0
- package/dist/commands/add.d.ts +1 -0
- package/dist/commands/add.js +46 -0
- package/dist/commands/check.d.ts +1 -0
- package/dist/commands/check.js +73 -0
- package/dist/commands/dev.d.ts +1 -0
- package/dist/commands/dev.js +140 -0
- package/dist/dev/host.d.ts +1 -0
- package/dist/dev/host.js +53 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/papers.d.ts +11 -0
- package/dist/papers.js +80 -0
- package/dist/react.d.ts +17 -0
- package/dist/react.js +73 -0
- package/dist/roles.d.ts +5 -0
- package/dist/roles.js +42 -0
- package/dist/root.d.ts +1 -0
- package/dist/root.js +9 -0
- package/dist/schema.d.ts +38 -0
- package/dist/schema.js +25 -0
- package/dist/types.d.ts +25 -0
- package/dist/types.js +1 -0
- package/dist/vite-config.d.ts +2 -0
- package/dist/vite-config.js +33 -0
- package/dist/vite.d.ts +6 -0
- package/dist/vite.js +232 -0
- package/package.json +64 -4
- package/schema/corpus.schema.json +44 -0
- package/schema/kinds.json +14 -0
- package/schema/research.schema.json +26 -0
- package/src/virtual.d.ts +8 -0
- package/tsconfig.project.json +15 -0
package/README.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# library-research
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The research-project contract and dev kit
|
|
4
|
+
|
|
5
|
+
## Run a project
|
|
6
|
+
|
|
7
|
+
A project is this layout, each path fixed:
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
research.json title and data roles
|
|
11
|
+
corpus.json sha → paper
|
|
12
|
+
papers/<sha>.<kind> through LFS
|
|
13
|
+
ui/package.json depends on @metacensus/library-research; scripts dev and check
|
|
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
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
From `ui/`:
|
|
20
|
+
|
|
21
|
+
| Command | Does |
|
|
22
|
+
| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
23
|
+
| `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`) |
|
|
24
|
+
| `npm run check` | gates the project, one line per failure, as a host's build does |
|
|
25
|
+
| `npx library-research add <file> [--title T] [--citation C] [--open]` | adds a paper to `papers/` and `corpus.json` |
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { globSync } from 'node:fs';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
const dir = new URL('./commands/', import.meta.url);
|
|
5
|
+
const commands = globSync('*.js', { cwd: fileURLToPath(dir) })
|
|
6
|
+
.map((file) => file.slice(0, -'.js'.length))
|
|
7
|
+
.sort();
|
|
8
|
+
const [name = 'help', ...args] = process.argv.slice(2);
|
|
9
|
+
if (name === 'help') {
|
|
10
|
+
console.log(commands.join('\n'));
|
|
11
|
+
}
|
|
12
|
+
else if (commands.includes(name)) {
|
|
13
|
+
const command = await import(new URL(`${name}.js`, dir).href);
|
|
14
|
+
try {
|
|
15
|
+
await command.default(args);
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
console.error(error.message);
|
|
19
|
+
process.exit(1);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
console.error(`unknown command "${name}"; one of:\n${commands.join('\n')}`);
|
|
24
|
+
process.exit(2);
|
|
25
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default function add(args: string[]): void;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { git, kindOf, paperPath, readCorpus } from '../papers.js';
|
|
6
|
+
import { findRoot } from '../root.js';
|
|
7
|
+
import { Corpus, kinds } from '../schema.js';
|
|
8
|
+
export default function add(args) {
|
|
9
|
+
const { positionals, values } = parseArgs({
|
|
10
|
+
args,
|
|
11
|
+
allowPositionals: true,
|
|
12
|
+
options: {
|
|
13
|
+
title: { type: 'string' },
|
|
14
|
+
citation: { type: 'string' },
|
|
15
|
+
open: { type: 'boolean' },
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
const [file, ...extra] = positionals;
|
|
19
|
+
if (!file || extra.length)
|
|
20
|
+
throw new Error('usage: add <file> [--title T] [--citation C] [--open]');
|
|
21
|
+
const kind = kindOf(file);
|
|
22
|
+
if (!kind)
|
|
23
|
+
throw new Error(`${file}: not a kind; rename it to end in .${Object.keys(kinds).join(', .')}`);
|
|
24
|
+
const root = findRoot(process.cwd());
|
|
25
|
+
const bytes = readFileSync(file);
|
|
26
|
+
const sha = createHash('sha256').update(bytes).digest('hex');
|
|
27
|
+
const path = paperPath(sha, kind);
|
|
28
|
+
if (git(root, 'check-attr', 'filter', '--', path) !== `${path}: filter: lfs\n`)
|
|
29
|
+
throw new Error(`.gitattributes: papers/** doesn't go through LFS; run git lfs track 'papers/**'`);
|
|
30
|
+
const corpus = readCorpus(root);
|
|
31
|
+
const listed = corpus[sha]?.kind;
|
|
32
|
+
if (listed && listed !== kind)
|
|
33
|
+
throw new Error(`${file}: already listed as ${paperPath(sha, listed)}`);
|
|
34
|
+
mkdirSync(join(root, 'papers'), { recursive: true });
|
|
35
|
+
if (!existsSync(join(root, path)))
|
|
36
|
+
writeFileSync(join(root, path), bytes);
|
|
37
|
+
writeCorpus(root, { ...corpus, [sha]: { ...corpus[sha], kind, ...values } });
|
|
38
|
+
git(root, 'add', '--', path, 'corpus.json');
|
|
39
|
+
console.log(path);
|
|
40
|
+
}
|
|
41
|
+
function writeCorpus(root, corpus) {
|
|
42
|
+
const lines = Object.entries(Corpus.parse(corpus))
|
|
43
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
44
|
+
.map(([sha, paper]) => ` "${sha}": ${JSON.stringify(paper)}`);
|
|
45
|
+
writeFileSync(join(root, 'corpus.json'), `{\n${lines.join(',\n')}\n}\n`);
|
|
46
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default function check(args: string[]): Promise<void>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join, sep } from 'node:path';
|
|
6
|
+
import { parseArgs, stripVTControlCharacters } from 'node:util';
|
|
7
|
+
import { build, mergeConfig } from 'vite';
|
|
8
|
+
import { checkPapers } from '../papers.js';
|
|
9
|
+
import { project } from '../roles.js';
|
|
10
|
+
import { findRoot } from '../root.js';
|
|
11
|
+
import { hostConfig } from '../vite-config.js';
|
|
12
|
+
const tsc = createRequire(import.meta.url).resolve('typescript/bin/tsc');
|
|
13
|
+
export default async function check(args) {
|
|
14
|
+
parseArgs({ args });
|
|
15
|
+
const root = findRoot(process.cwd());
|
|
16
|
+
for (const stage of [data, checkPapers, types, bundle]) {
|
|
17
|
+
let failures;
|
|
18
|
+
try {
|
|
19
|
+
failures = await stage(root);
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
failures = [String(error?.message || error)];
|
|
23
|
+
}
|
|
24
|
+
if (failures.length)
|
|
25
|
+
throw new Error(failures
|
|
26
|
+
.map((why) => why.replaceAll(root + sep, '').replace(/\s*\n\s*/g, ' '))
|
|
27
|
+
.join('\n'));
|
|
28
|
+
}
|
|
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
|
+
});
|
|
40
|
+
}
|
|
41
|
+
function types(root) {
|
|
42
|
+
const { status, stdout, stderr } = spawnSync(process.execPath, [tsc, '-p', 'ui', '--noEmit', '--pretty', 'false'], { cwd: root, encoding: 'utf8' });
|
|
43
|
+
return status === 0 ? [] : (stdout + stderr).trim().split(/\n(?=\S)/);
|
|
44
|
+
}
|
|
45
|
+
async function bundle(root) {
|
|
46
|
+
if (!existsSync(join(root, 'ui/index.tsx')))
|
|
47
|
+
return ['ui/index.tsx: missing'];
|
|
48
|
+
const outDir = mkdtempSync(join(tmpdir(), 'check-'));
|
|
49
|
+
try {
|
|
50
|
+
await build(mergeConfig(hostConfig(root), {
|
|
51
|
+
publicDir: false,
|
|
52
|
+
logLevel: 'silent',
|
|
53
|
+
build: {
|
|
54
|
+
outDir,
|
|
55
|
+
rolldownOptions: { input: 'virtual:research-projects' },
|
|
56
|
+
},
|
|
57
|
+
}));
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
const thrown = error;
|
|
62
|
+
// A Rolldown message goes on to draw a code frame below its first line.
|
|
63
|
+
return (thrown.errors ?? [thrown]).map(({ id, message }) => {
|
|
64
|
+
const [line = ''] = stripVTControlCharacters(String(message)).split('\n');
|
|
65
|
+
const why = line.replace(/^\[vite\]: /, '') || 'the build failed';
|
|
66
|
+
const path = id?.replace('\0', '') ?? why.match(/ from "([^"]+)"/)?.[1];
|
|
67
|
+
return path ? `${path}: ${why}` : why;
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
rmSync(outDir, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default function dev(args: string[]): Promise<void>;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { extname, join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { createServer, mergeConfig } from 'vite';
|
|
7
|
+
import { paperPath, readCorpus } from '../papers.js';
|
|
8
|
+
import { findRoot } from '../root.js';
|
|
9
|
+
import { kinds } from '../schema.js';
|
|
10
|
+
import { hostConfig } from '../vite-config.js';
|
|
11
|
+
const entry = 'virtual:research-host';
|
|
12
|
+
const css = `${entry}.css`;
|
|
13
|
+
const host = fileURLToPath(new URL('../dev/host.js', import.meta.url));
|
|
14
|
+
const papers = /^\/projects\/project\/papers\/([^/]+)$/;
|
|
15
|
+
const pdfjs = '/pdfjs/';
|
|
16
|
+
const assetTypes = {
|
|
17
|
+
'.js': 'text/javascript',
|
|
18
|
+
'.mjs': 'text/javascript',
|
|
19
|
+
'.wasm': 'application/wasm',
|
|
20
|
+
};
|
|
21
|
+
const require = createRequire(import.meta.url);
|
|
22
|
+
const lfsPointer = 'version https://git-lfs.github.com/spec/';
|
|
23
|
+
const page = `<!doctype html>
|
|
24
|
+
<html lang="en">
|
|
25
|
+
<meta charset="utf-8" />
|
|
26
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
27
|
+
<div id="root"></div>
|
|
28
|
+
<script type="module" src="/@id/${entry}"></script>
|
|
29
|
+
</html>
|
|
30
|
+
`;
|
|
31
|
+
export default async function dev(args) {
|
|
32
|
+
const { values } = parseArgs({
|
|
33
|
+
args,
|
|
34
|
+
options: {
|
|
35
|
+
reader: { type: 'string', default: 'local' },
|
|
36
|
+
port: { type: 'string' },
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
const root = findRoot(process.cwd());
|
|
40
|
+
const local = existsSync(join(root, 'ui/local/index.tsx'));
|
|
41
|
+
const server = await createServer(mergeConfig(hostConfig(root), {
|
|
42
|
+
plugins: [devHost(root, values.reader, local)],
|
|
43
|
+
server: {
|
|
44
|
+
port: values.port === undefined ? undefined : Number(values.port),
|
|
45
|
+
},
|
|
46
|
+
}));
|
|
47
|
+
await server.listen();
|
|
48
|
+
const [url] = server.resolvedUrls.local;
|
|
49
|
+
console.log(`${url}project/`);
|
|
50
|
+
if (local)
|
|
51
|
+
console.log(`${url}local/`);
|
|
52
|
+
}
|
|
53
|
+
function devHost(root, reader, local) {
|
|
54
|
+
const mount = local ? /^\/(project|local)\// : /^\/project\//;
|
|
55
|
+
const real = realpathSync(root);
|
|
56
|
+
return {
|
|
57
|
+
name: 'research:dev',
|
|
58
|
+
resolveId: (id) => ([entry, css].includes(id) ? '\0' + id : undefined),
|
|
59
|
+
load(id) {
|
|
60
|
+
if (id === '\0' + css)
|
|
61
|
+
return '@tailwind base;\n@tailwind components;\n@tailwind utilities;\n';
|
|
62
|
+
if (id === '\0' + entry)
|
|
63
|
+
return [
|
|
64
|
+
`import '@metacensus/library-ui/fonts.css'`,
|
|
65
|
+
`import '@metacensus/library-ui/tokens.css'`,
|
|
66
|
+
`import '@metacensus/library-ui/styles.css'`,
|
|
67
|
+
`import '${css}'`,
|
|
68
|
+
`import { configurePdf } from '@metacensus/library-ui/pdf'`,
|
|
69
|
+
`import { start } from ${JSON.stringify(host)}`,
|
|
70
|
+
`configurePdf({ assets: ${JSON.stringify(pdfjs)} })`,
|
|
71
|
+
`start(${JSON.stringify(reader)})`,
|
|
72
|
+
].join('\n');
|
|
73
|
+
},
|
|
74
|
+
configureServer(server) {
|
|
75
|
+
server.middlewares.use((req, res, next) => {
|
|
76
|
+
const path = req.url?.split('?')[0];
|
|
77
|
+
if (path === '/')
|
|
78
|
+
return res.writeHead(302, { Location: '/project/' }).end();
|
|
79
|
+
const asset = path?.startsWith(pdfjs) && path.slice(pdfjs.length);
|
|
80
|
+
if (asset) {
|
|
81
|
+
const file = pdfAsset(asset);
|
|
82
|
+
if (!file)
|
|
83
|
+
return notFound(res, `${asset}: not in pdf-assets/`);
|
|
84
|
+
const type = assetTypes[extname(file)] ?? 'application/octet-stream';
|
|
85
|
+
return send(req, res, readFileSync(file), type);
|
|
86
|
+
}
|
|
87
|
+
const sha = path?.match(papers)?.[1];
|
|
88
|
+
if (!sha)
|
|
89
|
+
return next();
|
|
90
|
+
const kind = readCorpus(root)[sha]?.kind;
|
|
91
|
+
if (!kind)
|
|
92
|
+
return notFound(res, `${sha}: not in corpus.json`);
|
|
93
|
+
const file = paperPath(sha, kind);
|
|
94
|
+
if (realpathSync(join(root, file)) !== join(real, file))
|
|
95
|
+
return notFound(res, `${file}: leads outside papers/`);
|
|
96
|
+
const bytes = readFileSync(join(root, file));
|
|
97
|
+
if (bytes.toString('latin1', 0, lfsPointer.length) === lfsPointer)
|
|
98
|
+
return notFound(res, `${file}: an LFS pointer; run git lfs pull`);
|
|
99
|
+
send(req, res, bytes, kinds[kind]);
|
|
100
|
+
});
|
|
101
|
+
return () => server.middlewares.use(async (req, res, next) => {
|
|
102
|
+
const url = req.originalUrl ?? '';
|
|
103
|
+
if (req.url !== '/index.html' || !mount.test(url))
|
|
104
|
+
return next();
|
|
105
|
+
const html = await server.transformIndexHtml(url, page);
|
|
106
|
+
res.writeHead(200, { 'Content-Type': 'text/html' }).end(html);
|
|
107
|
+
});
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** A file under library-ui's `pdf-assets/`, as its exports allow. */
|
|
112
|
+
function pdfAsset(asset) {
|
|
113
|
+
// Node warns on resolving a directory.
|
|
114
|
+
if (asset.endsWith('/'))
|
|
115
|
+
return;
|
|
116
|
+
try {
|
|
117
|
+
return require.resolve(`@metacensus/library-ui/pdf-assets/${asset}`);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function send(req, res, bytes, type) {
|
|
124
|
+
const headers = { 'Content-Type': type, 'Accept-Ranges': 'bytes' };
|
|
125
|
+
const range = req.headers.range?.match(/^bytes=(\d*)-(\d*)$/);
|
|
126
|
+
const [, first, last] = range ?? [];
|
|
127
|
+
if (!range || (first && last && Number(last) < Number(first)))
|
|
128
|
+
return reply(res, 200, headers, bytes);
|
|
129
|
+
const size = bytes.length;
|
|
130
|
+
const start = first ? Number(first) : Math.max(size - Number(last), 0);
|
|
131
|
+
const end = first && last ? Math.min(Number(last), size - 1) : size - 1;
|
|
132
|
+
if (start > end)
|
|
133
|
+
return reply(res, 416, { 'Content-Range': `bytes */${size}` });
|
|
134
|
+
reply(res, 206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${size}` }, bytes.subarray(start, end + 1));
|
|
135
|
+
}
|
|
136
|
+
const notFound = (res, why) => reply(res, 404, { 'Content-Type': 'text/plain' }, why);
|
|
137
|
+
function reply(res, status, headers, body = '') {
|
|
138
|
+
const length = Buffer.byteLength(body);
|
|
139
|
+
res.writeHead(status, { ...headers, 'Content-Length': length }).end(body);
|
|
140
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function start(username: string): void;
|
package/dist/dev/host.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { Button, Notice } from '@metacensus/library-ui';
|
|
3
|
+
import { QueryClient, QueryClientProvider, QueryErrorResetBoundary, } from '@tanstack/react-query';
|
|
4
|
+
import { Component, lazy, Suspense, useEffect, useState, } from 'react';
|
|
5
|
+
import { createRoot } from 'react-dom/client';
|
|
6
|
+
import projects from 'virtual:research-projects';
|
|
7
|
+
import { ResearchProvider } from '../react.js';
|
|
8
|
+
const project = projects.project;
|
|
9
|
+
const local = window.location.pathname.startsWith('/local/');
|
|
10
|
+
const base = local ? '/local/' : '/project/';
|
|
11
|
+
const Root = lazy(local ? project.local : project.root);
|
|
12
|
+
function here() {
|
|
13
|
+
const { pathname, search, hash } = window.location;
|
|
14
|
+
return { path: pathname.slice(base.length), search, hash };
|
|
15
|
+
}
|
|
16
|
+
function App({ username }) {
|
|
17
|
+
const [location, setLocation] = useState(here);
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
const pop = () => setLocation(here());
|
|
20
|
+
window.addEventListener('popstate', pop);
|
|
21
|
+
return () => window.removeEventListener('popstate', pop);
|
|
22
|
+
}, []);
|
|
23
|
+
const host = {
|
|
24
|
+
reader: { username },
|
|
25
|
+
base,
|
|
26
|
+
location,
|
|
27
|
+
navigate(to, { replace } = {}) {
|
|
28
|
+
history[replace ? 'replaceState' : 'pushState'](null, '', base + to);
|
|
29
|
+
setLocation(here());
|
|
30
|
+
},
|
|
31
|
+
data: (role) => `/projects/project/data/${role}.json`,
|
|
32
|
+
paper: (sha) => `/projects/project/papers/${sha}`,
|
|
33
|
+
};
|
|
34
|
+
return (_jsx(QueryErrorResetBoundary, { children: ({ reset }) => (_jsx(Boundary, { reset: reset, children: _jsx(Suspense, { fallback: null, children: _jsx(ResearchProvider, { host: host, children: _jsx(Root, {}) }) }) })) }));
|
|
35
|
+
}
|
|
36
|
+
class Boundary extends Component {
|
|
37
|
+
state = {};
|
|
38
|
+
static getDerivedStateFromError = (error) => ({ error });
|
|
39
|
+
render() {
|
|
40
|
+
const { error } = this.state;
|
|
41
|
+
if (!error)
|
|
42
|
+
return this.props.children;
|
|
43
|
+
const retry = () => {
|
|
44
|
+
this.props.reset();
|
|
45
|
+
this.setState({ error: undefined });
|
|
46
|
+
};
|
|
47
|
+
return (_jsx(Notice, { role: "alert", title: error.message, children: _jsx(Button, { onClick: retry, children: "Try again" }) }));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export function start(username) {
|
|
51
|
+
document.title = project.title;
|
|
52
|
+
createRoot(document.getElementById('root')).render(_jsx(QueryClientProvider, { client: new QueryClient(), children: _jsx(App, { username: username }) }));
|
|
53
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Link, ResearchProvider, useCorpus, useData, useDatas, useHost, } from './react.js';
|
package/dist/papers.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Kind } from './types.js';
|
|
2
|
+
export declare function git(root: string, ...args: string[]): string;
|
|
3
|
+
export declare function kindOf(path: string): Kind | undefined;
|
|
4
|
+
export declare const paperPath: (sha: string, kind: Kind) => string;
|
|
5
|
+
export declare function readCorpus(root: string): Record<string, {
|
|
6
|
+
kind: "pdf" | "doc" | "docx" | "xls" | "xlsx" | "zip" | "gif" | "jpg" | "tif" | "txt" | "html" | "xml";
|
|
7
|
+
title?: string | undefined;
|
|
8
|
+
citation?: string | undefined;
|
|
9
|
+
open?: true | undefined;
|
|
10
|
+
}>;
|
|
11
|
+
export declare function checkPapers(root: string): string[];
|
package/dist/papers.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { extname, join } from 'node:path';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { Corpus, kinds } from './schema.js';
|
|
6
|
+
export function git(root, ...args) {
|
|
7
|
+
const { status, stdout, stderr, error } = spawnSync('git', args, {
|
|
8
|
+
cwd: root,
|
|
9
|
+
encoding: 'utf8',
|
|
10
|
+
});
|
|
11
|
+
if (status === 0)
|
|
12
|
+
return stdout;
|
|
13
|
+
throw new Error(`git ${args[0]}: ${error?.message ?? stderr.split('\n')[0]}`);
|
|
14
|
+
}
|
|
15
|
+
export function kindOf(path) {
|
|
16
|
+
const extension = extname(path).slice(1).toLowerCase();
|
|
17
|
+
return Object.hasOwn(kinds, extension) ? extension : undefined;
|
|
18
|
+
}
|
|
19
|
+
export const paperPath = (sha, kind) => `papers/${sha}.${kind}`;
|
|
20
|
+
export function readCorpus(root) {
|
|
21
|
+
const file = join(root, 'corpus.json');
|
|
22
|
+
if (!existsSync(file))
|
|
23
|
+
return {};
|
|
24
|
+
try {
|
|
25
|
+
return Corpus.parse(JSON.parse(readFileSync(file, 'utf8')));
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
const why = error instanceof z.ZodError
|
|
29
|
+
? error.issues
|
|
30
|
+
.map(({ path, message }) => `${path.join('.')}: ${message}`)
|
|
31
|
+
.join('; ')
|
|
32
|
+
: error.message;
|
|
33
|
+
throw new Error(`corpus.json: ${why}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// git-lfs leaves an empty file as is, so `git lfs ls-files` never lists it.
|
|
37
|
+
const emptySha = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
|
|
38
|
+
export function checkPapers(root) {
|
|
39
|
+
const tracked = git(root, 'ls-files', '-z').split('\0').filter(Boolean);
|
|
40
|
+
const index = new Set(tracked);
|
|
41
|
+
const lfs = new Map([...git(root, 'lfs', 'ls-files', '--long').matchAll(/^(\w+) [*-] (.+)$/gm)]
|
|
42
|
+
.filter(([, , path]) => index.has(path))
|
|
43
|
+
.map(([, oid, path]) => [path, oid]));
|
|
44
|
+
const listed = new Map(Object.entries(readCorpus(root)).map(([sha, { kind }]) => [
|
|
45
|
+
paperPath(sha, kind),
|
|
46
|
+
sha,
|
|
47
|
+
]));
|
|
48
|
+
const unstored = (path, sha) => {
|
|
49
|
+
if (sha !== emptySha) {
|
|
50
|
+
if (lfs.get(path) === sha)
|
|
51
|
+
return;
|
|
52
|
+
return lfs.has(path)
|
|
53
|
+
? `its LFS oid ${lfs.get(path)} isn't its sha`
|
|
54
|
+
: 'listed in corpus.json but not in LFS';
|
|
55
|
+
}
|
|
56
|
+
if (!index.has(path))
|
|
57
|
+
return 'listed in corpus.json but not tracked';
|
|
58
|
+
const filter = git(root, 'check-attr', 'filter', '--', path);
|
|
59
|
+
if (filter !== `${path}: filter: lfs\n`)
|
|
60
|
+
return 'not under filter=lfs';
|
|
61
|
+
if (git(root, 'cat-file', '-s', `:${path}`) !== '0\n')
|
|
62
|
+
return "its sha is the empty sha but its file isn't empty";
|
|
63
|
+
};
|
|
64
|
+
const binary = (path) => {
|
|
65
|
+
const kind = kindOf(path);
|
|
66
|
+
return kind && kinds[kind] !== 'text/plain';
|
|
67
|
+
};
|
|
68
|
+
return [
|
|
69
|
+
...[...listed].flatMap(([path, sha]) => {
|
|
70
|
+
const why = unstored(path, sha);
|
|
71
|
+
return why ? [`${path}: ${why}`] : [];
|
|
72
|
+
}),
|
|
73
|
+
...tracked
|
|
74
|
+
.filter((path) => path.startsWith('papers/') && !listed.has(path))
|
|
75
|
+
.map((path) => `${path}: not listed in corpus.json`),
|
|
76
|
+
...tracked
|
|
77
|
+
.filter((path) => !path.startsWith('papers/') && binary(path) && !lfs.has(path))
|
|
78
|
+
.map((path) => `${path}: a binary kind outside LFS`),
|
|
79
|
+
];
|
|
80
|
+
}
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type AnchorHTMLAttributes, type PropsWithChildren } from 'react';
|
|
2
|
+
import type { Corpus, Host } from './types.js';
|
|
3
|
+
export declare function ResearchProvider({ host, children, }: PropsWithChildren<{
|
|
4
|
+
host: Host;
|
|
5
|
+
}>): import("react").JSX.Element;
|
|
6
|
+
export declare function useHost(): Host;
|
|
7
|
+
type Role<T = unknown> = readonly [role: string, parse: (json: unknown) => T];
|
|
8
|
+
export declare function useData<T>(role: string, parse: (json: unknown) => T): T;
|
|
9
|
+
export declare function useDatas<const R extends readonly Role[]>(roles: R): {
|
|
10
|
+
-readonly [K in keyof R]: R[K] extends Role<infer T> ? T : never;
|
|
11
|
+
};
|
|
12
|
+
export declare function useCorpus(): Corpus;
|
|
13
|
+
export declare function Link({ to, replace, ...a }: {
|
|
14
|
+
to: string;
|
|
15
|
+
replace?: boolean;
|
|
16
|
+
} & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>): import("react").JSX.Element;
|
|
17
|
+
export {};
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useSuspenseQueries } from '@tanstack/react-query';
|
|
3
|
+
import { createContext, useContext, useMemo, useRef, } from 'react';
|
|
4
|
+
import * as schema from './schema.js';
|
|
5
|
+
const HostContext = createContext(null);
|
|
6
|
+
export function ResearchProvider({ host, children, }) {
|
|
7
|
+
return _jsx(HostContext.Provider, { value: host, children: children });
|
|
8
|
+
}
|
|
9
|
+
export function useHost() {
|
|
10
|
+
const host = useContext(HostContext);
|
|
11
|
+
if (!host)
|
|
12
|
+
throw new Error('useHost outside a ResearchProvider');
|
|
13
|
+
return host;
|
|
14
|
+
}
|
|
15
|
+
export function useData(role, parse) {
|
|
16
|
+
return useDatas([[role, parse]])[0];
|
|
17
|
+
}
|
|
18
|
+
export function useDatas(roles) {
|
|
19
|
+
const host = useHost();
|
|
20
|
+
const latest = useRef(roles);
|
|
21
|
+
latest.current = roles;
|
|
22
|
+
const names = roles.map(([role]) => role);
|
|
23
|
+
const selects = useMemo(() => names.map((role, i) => (json) => {
|
|
24
|
+
try {
|
|
25
|
+
return latest.current[i][1](json);
|
|
26
|
+
}
|
|
27
|
+
catch (cause) {
|
|
28
|
+
return failed(role, cause);
|
|
29
|
+
}
|
|
30
|
+
}), [JSON.stringify(names)]);
|
|
31
|
+
return useSuspenseQueries({
|
|
32
|
+
queries: names.map((role, i) => {
|
|
33
|
+
const url = host.data(role);
|
|
34
|
+
return {
|
|
35
|
+
queryKey: ['research', url],
|
|
36
|
+
queryFn: () => fetch(url)
|
|
37
|
+
.then((response) => {
|
|
38
|
+
if (!response.ok)
|
|
39
|
+
throw new Error(`${response.status} from ${url}`);
|
|
40
|
+
return response.json();
|
|
41
|
+
})
|
|
42
|
+
.catch((cause) => failed(role, cause)),
|
|
43
|
+
select: selects[i],
|
|
44
|
+
staleTime: Infinity,
|
|
45
|
+
retry: false,
|
|
46
|
+
};
|
|
47
|
+
}),
|
|
48
|
+
}).map(({ data }) => data);
|
|
49
|
+
}
|
|
50
|
+
function failed(role, cause) {
|
|
51
|
+
const why = cause instanceof Error ? cause.message : cause;
|
|
52
|
+
throw new Error(`data role "${role}": ${why}`, { cause });
|
|
53
|
+
}
|
|
54
|
+
export function useCorpus() {
|
|
55
|
+
return useData('corpus', schema.Corpus.parse);
|
|
56
|
+
}
|
|
57
|
+
export function Link({ to, replace, ...a }) {
|
|
58
|
+
const { base, navigate } = useHost();
|
|
59
|
+
const onClick = (event) => {
|
|
60
|
+
a.onClick?.(event);
|
|
61
|
+
if (event.defaultPrevented ||
|
|
62
|
+
event.button !== 0 ||
|
|
63
|
+
event.metaKey ||
|
|
64
|
+
event.ctrlKey ||
|
|
65
|
+
event.shiftKey ||
|
|
66
|
+
event.altKey ||
|
|
67
|
+
(a.target && a.target !== '_self'))
|
|
68
|
+
return;
|
|
69
|
+
event.preventDefault();
|
|
70
|
+
navigate(to, { replace });
|
|
71
|
+
};
|
|
72
|
+
return _jsx("a", { ...a, href: base + to, onClick: onClick });
|
|
73
|
+
}
|
package/dist/roles.d.ts
ADDED
package/dist/roles.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { globSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { Corpus, Research } from './schema.js';
|
|
5
|
+
/** Reads a project's research.json; each role reads its files when called. */
|
|
6
|
+
export function project(dir) {
|
|
7
|
+
const { title, data } = read(dir, 'research.json', Research);
|
|
8
|
+
const roles = {
|
|
9
|
+
corpus: () => read(dir, 'corpus.json', Corpus),
|
|
10
|
+
};
|
|
11
|
+
for (const [role, glob] of Object.entries(data))
|
|
12
|
+
roles[role] = () => match(dir, glob);
|
|
13
|
+
return { title, roles };
|
|
14
|
+
}
|
|
15
|
+
function match(dir, glob) {
|
|
16
|
+
const files = globSync(glob, { cwd: dir }).sort();
|
|
17
|
+
if (!files.length)
|
|
18
|
+
throw new Error(`${join(dir, glob)}: matches no file`);
|
|
19
|
+
const head = glob.indexOf('*');
|
|
20
|
+
if (head < 0)
|
|
21
|
+
return read(dir, files[0]);
|
|
22
|
+
const tail = glob.length - glob.lastIndexOf('*') - 1;
|
|
23
|
+
const key = (file) => file.slice(head, file.length - tail).replace(/^[./]+|[./]+$/g, '');
|
|
24
|
+
return Object.fromEntries(files.map((file) => [key(file), read(dir, file)]));
|
|
25
|
+
}
|
|
26
|
+
function read(dir, file, schema) {
|
|
27
|
+
const path = join(dir, file);
|
|
28
|
+
const fail = (why) => new Error(`${path}: ${why}`);
|
|
29
|
+
let json;
|
|
30
|
+
try {
|
|
31
|
+
json = JSON.parse(readFileSync(path, 'utf8'));
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
throw fail(e.message);
|
|
35
|
+
}
|
|
36
|
+
if (!schema)
|
|
37
|
+
return json;
|
|
38
|
+
const checked = schema.safeParse(json);
|
|
39
|
+
if (!checked.success)
|
|
40
|
+
throw fail(z.prettifyError(checked.error));
|
|
41
|
+
return checked.data;
|
|
42
|
+
}
|
package/dist/root.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function findRoot(dir: string): string;
|
package/dist/root.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
export function findRoot(dir) {
|
|
4
|
+
if (existsSync(join(dir, 'research.json')))
|
|
5
|
+
return dir;
|
|
6
|
+
if (dirname(dir) === dir)
|
|
7
|
+
throw new Error('no research.json here or above');
|
|
8
|
+
return findRoot(dirname(dir));
|
|
9
|
+
}
|