@metacensus/library-research 0.9.0 → 0.10.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 CHANGED
@@ -7,19 +7,23 @@ The research-project contract and dev kit
7
7
  A project is this layout, each path fixed:
8
8
 
9
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
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
+ ui/playwright.config.ts with browser/; export { default } from '@metacensus/library-research/playwright'
18
+ ui/browser/*.spec.ts optional; test and expect from @metacensus/library-research/playwright
17
19
  ```
18
20
 
19
21
  From `ui/`:
20
22
 
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` |
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 |
@@ -0,0 +1 @@
1
+ export default function candidate(args: string[]): Promise<void>;
@@ -0,0 +1,26 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { git } from '../papers.js';
3
+ import { findRoot } from '../root.js';
4
+ import check from './check.js';
5
+ export default async function candidate(args) {
6
+ parseArgs({ args });
7
+ const root = findRoot(process.cwd());
8
+ const origin = git(root, 'remote', 'get-url', 'origin').trim();
9
+ const [, id] = origin.match(/[/:]research-([a-z0-9-]+?)(\.git)?\/?$/) ?? [];
10
+ if (!id)
11
+ throw new Error(`origin isn't named research-<id>: ${origin}`);
12
+ if (git(root, 'status', '--porcelain'))
13
+ throw new Error('the tree has uncommitted changes; commit them first');
14
+ git(root, 'fetch', '--quiet', '--tags', 'origin');
15
+ if (git(root, 'rev-list', 'origin/main..HEAD'))
16
+ throw new Error('HEAD is not on origin/main; merge it first');
17
+ await check([]);
18
+ const day = `${id}-${new Date().toLocaleDateString('sv')}`;
19
+ const taken = new Set(git(root, 'tag', '--list', `${day}*`).split('\n'));
20
+ let tag = day;
21
+ for (let n = 2; taken.has(tag); n++)
22
+ tag = `${day}.${n}`;
23
+ git(root, 'tag', '--annotate', '--message', tag, tag);
24
+ git(root, 'push', '--quiet', 'origin', `refs/tags/${tag}`);
25
+ console.log(`make pin PROJECT=${id} TAG=${tag}`);
26
+ }
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { existsSync, readFileSync, realpathSync } from 'node:fs';
2
3
  import { createRequire } from 'node:module';
3
4
  import { extname, join } from 'node:path';
@@ -28,6 +29,9 @@ const page = `<!doctype html>
28
29
  <script type="module" src="/@id/${entry}"></script>
29
30
  </html>
30
31
  `;
32
+ 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'`;
31
35
  export default async function dev(args) {
32
36
  const { values } = parseArgs({
33
37
  args,
@@ -55,6 +59,7 @@ function devHost(root, reader, local) {
55
59
  const real = realpathSync(root);
56
60
  return {
57
61
  name: 'research:dev',
62
+ config: () => ({ html: { cspNonce: nonce } }),
58
63
  resolveId: (id) => ([entry, css].includes(id) ? '\0' + id : undefined),
59
64
  load(id) {
60
65
  if (id === '\0' + css)
@@ -73,6 +78,7 @@ function devHost(root, reader, local) {
73
78
  },
74
79
  configureServer(server) {
75
80
  server.middlewares.use((req, res, next) => {
81
+ res.setHeader('Content-Security-Policy', policy);
76
82
  const path = req.url?.split('?')[0];
77
83
  if (path === '/')
78
84
  return res.writeHead(302, { Location: '/project/' }).end();
@@ -0,0 +1,8 @@
1
+ import { expect } from '@playwright/test';
2
+ declare const _default: import("@playwright/test").PlaywrightTestConfig<{}, {}>;
3
+ export default _default;
4
+ type Violation = `csp ${string} ${string}` | `axe ${string}`;
5
+ export declare const test: import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & {
6
+ violations: Violation[];
7
+ }, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
8
+ export { expect };
@@ -0,0 +1,24 @@
1
+ import AxeBuilder from '@axe-core/playwright';
2
+ import { defineConfig, expect, test as base } from '@playwright/test';
3
+ const report = 'libraryResearchViolation';
4
+ export default defineConfig({
5
+ testDir: 'browser',
6
+ use: { baseURL: process.env.LIBRARY_RESEARCH_URL },
7
+ webServer: {
8
+ command: 'library-research dev --port 0',
9
+ wait: { stdout: /(?<library_research_url>http:\S+\/project\/)/ },
10
+ },
11
+ });
12
+ export const test = base.extend({
13
+ violations: [[], { option: true }],
14
+ page: async ({ page, violations }, use) => {
15
+ const found = [];
16
+ await page.exposeFunction(report, (v) => found.push(v));
17
+ await page.addInitScript(`document.addEventListener('securitypolicyviolation', (e) => ${report}('csp ' + e.effectiveDirective + ' ' + e.blockedURI))`);
18
+ await use(page);
19
+ const axe = await new AxeBuilder({ page }).analyze();
20
+ found.push(...axe.violations.map((v) => `axe ${v.id}`));
21
+ expect(found.filter((v) => !violations.includes(v)), 'unlisted violations').toEqual([]);
22
+ },
23
+ });
24
+ export { expect };
package/dist/schema.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ z.config({ jitless: true });
2
3
  export const kinds = {
3
4
  pdf: 'application/pdf',
4
5
  doc: 'application/msword',
package/dist/vite.js CHANGED
@@ -18,17 +18,13 @@ export function research({ projects, }) {
18
18
  let config;
19
19
  let dirs = [];
20
20
  const owner = (file) => dirs.find(([, dir]) => inside(file, dir))?.[0];
21
- const scope = (files) => {
21
+ const place = (files, pattern, info) => {
22
22
  const owned = files.filter(owner).sort();
23
23
  const slugs = [...new Set(owned.map(owner))];
24
24
  if (slugs.length > 1)
25
25
  throw new Error(`${owned.join(', ')}: mixes ${slugs.join(' and ')}`);
26
- return slugs[0];
27
- };
28
- const place = (files, pattern, info) => {
29
- const slug = scope(files);
30
26
  const name = typeof pattern === 'string' ? pattern : pattern(info);
31
- return slug ? `${prefix}/${slug}/assets/${basename(name)}` : name;
27
+ return slugs[0] ? `${prefix}/${slugs[0]}/assets/${basename(name)}` : name;
32
28
  };
33
29
  const sources = (asset) => asset.originalFileNames.map((file) => resolve(config.root, file));
34
30
  /**
@@ -94,10 +90,12 @@ export function research({ projects, }) {
94
90
  {
95
91
  name: 'research:checks',
96
92
  apply: 'build',
97
- configResolved({ build, publicDir }) {
93
+ configResolved({ base, build, publicDir }) {
98
94
  const fail = (why) => {
99
95
  throw new Error(`research() ${why}`);
100
96
  };
97
+ if (base === './')
98
+ fail("needs an absolute base (not './' or ''), for project CSS url() paths to resolve");
101
99
  if (build.minify !== 'oxc')
102
100
  fail('needs the default build.minify, which keeps its canary');
103
101
  if (!build.cssCodeSplit)
@@ -173,11 +171,35 @@ export function research({ projects, }) {
173
171
  assetFileNames: (asset) => place(sources(asset), assets, asset),
174
172
  };
175
173
  },
176
- /** Rolldown merges a byte-identical asset into one it already named. */
174
+ /**
175
+ * Rolldown merges a byte-identical asset into one it already named, and
176
+ * Vite emits a shared chunk's CSS with no originalFileNames. Moving it
177
+ * here, after vite:build-html and before vite:build-import-analysis,
178
+ * reaches the preload lists but not the HTML, which links host CSS only.
179
+ */
177
180
  generateBundle(_options, bundle) {
178
- for (const file of Object.values(bundle))
179
- if (file.type === 'asset')
180
- scope(sources(file));
181
+ const chunks = Object.values(bundle).filter((f) => f.type === 'chunk');
182
+ for (const file of Object.values(bundle)) {
183
+ if (file.type !== 'asset')
184
+ continue;
185
+ const importers = chunks.filter((chunk) => chunk.viteMetadata?.importedCss.has(file.fileName));
186
+ const fileName = place([...sources(file), ...importers.flatMap((c) => c.moduleIds)], file.fileName, file);
187
+ if (!importers.length || fileName === file.fileName)
188
+ continue;
189
+ if (importers.some((c) => !c.moduleIds.some(owner)))
190
+ this.error(`${importers.map((c) => c.fileName).join(', ')}: share ${file.fileName}, mixing the host and a project`);
191
+ delete bundle[file.fileName];
192
+ this.emitFile({
193
+ type: 'asset',
194
+ fileName,
195
+ name: file.names[0],
196
+ source: file.source,
197
+ });
198
+ for (const { viteMetadata } of importers) {
199
+ viteMetadata.importedCss.delete(file.fileName);
200
+ viteMetadata.importedCss.add(fileName);
201
+ }
202
+ }
181
203
  },
182
204
  writeBundle({ dir: out = '' }) {
183
205
  const marks = dirs.map(([slug, dir]) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metacensus/library-research",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "license": "AGPL-3.0-only",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,6 +27,10 @@
27
27
  "types": "./dist/vite.d.ts",
28
28
  "default": "./dist/vite.js"
29
29
  },
30
+ "./playwright": {
31
+ "types": "./dist/playwright.d.ts",
32
+ "default": "./dist/playwright.js"
33
+ },
30
34
  "./virtual": {
31
35
  "types": "./src/virtual.d.ts"
32
36
  },
@@ -39,6 +43,8 @@
39
43
  "tsconfig.project.json"
40
44
  ],
41
45
  "dependencies": {
46
+ "@axe-core/playwright": "^4.14.0",
47
+ "@playwright/test": "^1.65.1",
42
48
  "@types/react": "^18.3.31",
43
49
  "@types/react-dom": "^18.3.7",
44
50
  "@vitejs/plugin-react": "^6.3.0",
@@ -54,7 +60,7 @@
54
60
  "react-dom": "^18.3.1"
55
61
  },
56
62
  "devDependencies": {
57
- "@metacensus/library-ui": "^0.6.0",
63
+ "@metacensus/library-ui": "^0.12.0",
58
64
  "@tanstack/react-query": "^5.108.0",
59
65
  "@types/jsdom": "^30.0.0",
60
66
  "@types/node": "^24.19.2",