@metacensus/library-research 0.14.0 → 0.16.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 (53) hide show
  1. package/README.md +65 -20
  2. package/dist/collection-store.d.ts +31 -0
  3. package/dist/collection-store.js +174 -0
  4. package/dist/collections.gen.d.ts +309 -0
  5. package/dist/collections.gen.js +190 -0
  6. package/dist/commands/add.js +29 -12
  7. package/dist/commands/dev.js +48 -44
  8. package/dist/commands/reshape.d.ts +2 -0
  9. package/dist/commands/reshape.js +21 -0
  10. package/dist/context.d.ts +5 -3
  11. package/dist/context.js +4 -2
  12. package/dist/corpus.d.ts +432 -0
  13. package/dist/corpus.js +348 -0
  14. package/dist/data.d.ts +13 -6
  15. package/dist/data.js +27 -15
  16. package/dist/datasets.d.ts +4 -1
  17. package/dist/datasets.js +48 -8
  18. package/dist/dev/host.js +6 -9
  19. package/dist/host.d.ts +17 -2
  20. package/dist/host.js +26 -2
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +2 -2
  23. package/dist/mount.d.ts +11 -4
  24. package/dist/mount.js +15 -9
  25. package/dist/papers.js +3 -2
  26. package/dist/parity.d.ts +25 -0
  27. package/dist/parity.js +70 -0
  28. package/dist/playwright.d.ts +2 -2
  29. package/dist/playwright.js +30 -8
  30. package/dist/project-id.d.ts +4 -0
  31. package/dist/project-id.js +7 -0
  32. package/dist/react.d.ts +32 -42
  33. package/dist/react.js +121 -118
  34. package/dist/schema.d.ts +19 -34
  35. package/dist/schema.js +47 -31
  36. package/dist/testing.d.ts +26 -11
  37. package/dist/testing.js +64 -26
  38. package/dist/types.d.ts +85 -26
  39. package/dist/urls.d.ts +35 -0
  40. package/dist/urls.js +58 -0
  41. package/dist/vite-config.js +2 -12
  42. package/dist/vite.d.ts +11 -2
  43. package/dist/vite.js +79 -25
  44. package/dist/zod.d.ts +2 -0
  45. package/dist/zod.js +4 -0
  46. package/package.json +19 -12
  47. package/schema/corpus.schema.json +3949 -29
  48. package/schema/project-id.schema.json +6 -0
  49. package/schema/research.schema.json +130 -2
  50. package/dist/document-store.d.ts +0 -14
  51. package/dist/document-store.js +0 -78
  52. package/dist/documents.d.ts +0 -10
  53. package/dist/documents.js +0 -22
package/dist/corpus.js ADDED
@@ -0,0 +1,348 @@
1
+ import { z } from './zod.js';
2
+ export const kinds = {
3
+ pdf: 'application/pdf',
4
+ doc: 'application/msword',
5
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
6
+ xls: 'application/vnd.ms-excel',
7
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
8
+ zip: 'application/zip',
9
+ gif: 'image/gif',
10
+ jpg: 'image/jpeg',
11
+ tif: 'image/tiff',
12
+ txt: 'text/plain',
13
+ html: 'text/plain',
14
+ xml: 'text/plain',
15
+ };
16
+ const kind = z
17
+ .enum(Object.keys(kinds))
18
+ .describe('the file kind, one of kinds.json; the file is papers/<sha>.<kind>');
19
+ const sha = z
20
+ .string()
21
+ .regex(/^[0-9a-f]{64}$/)
22
+ .describe("the sha256 of the file's bytes, lowercase hex");
23
+ // CSL-JSON 1.0.2's item types and variables (csl-data.json), less `id`, `DOI`
24
+ // and `citation-key`, which a work's id holds.
25
+ const types = [
26
+ 'article',
27
+ 'article-journal',
28
+ 'article-magazine',
29
+ 'article-newspaper',
30
+ 'bill',
31
+ 'book',
32
+ 'broadcast',
33
+ 'chapter',
34
+ 'classic',
35
+ 'collection',
36
+ 'dataset',
37
+ 'document',
38
+ 'entry',
39
+ 'entry-dictionary',
40
+ 'entry-encyclopedia',
41
+ 'event',
42
+ 'figure',
43
+ 'graphic',
44
+ 'hearing',
45
+ 'interview',
46
+ 'legal_case',
47
+ 'legislation',
48
+ 'manuscript',
49
+ 'map',
50
+ 'motion_picture',
51
+ 'musical_score',
52
+ 'pamphlet',
53
+ 'paper-conference',
54
+ 'patent',
55
+ 'performance',
56
+ 'periodical',
57
+ 'personal_communication',
58
+ 'post',
59
+ 'post-weblog',
60
+ 'regulation',
61
+ 'report',
62
+ 'review',
63
+ 'review-book',
64
+ 'software',
65
+ 'song',
66
+ 'speech',
67
+ 'standard',
68
+ 'thesis',
69
+ 'treaty',
70
+ 'webpage',
71
+ ];
72
+ const names = [
73
+ 'author',
74
+ 'chair',
75
+ 'collection-editor',
76
+ 'compiler',
77
+ 'composer',
78
+ 'container-author',
79
+ 'contributor',
80
+ 'curator',
81
+ 'director',
82
+ 'editor',
83
+ 'editorial-director',
84
+ 'executive-producer',
85
+ 'guest',
86
+ 'host',
87
+ 'illustrator',
88
+ 'interviewer',
89
+ 'narrator',
90
+ 'organizer',
91
+ 'original-author',
92
+ 'performer',
93
+ 'producer',
94
+ 'recipient',
95
+ 'reviewed-author',
96
+ 'script-writer',
97
+ 'series-creator',
98
+ 'translator',
99
+ ];
100
+ const dates = [
101
+ 'accessed',
102
+ 'available-date',
103
+ 'event-date',
104
+ 'issued',
105
+ 'original-date',
106
+ 'submitted',
107
+ ];
108
+ const numbers = [
109
+ 'chapter-number',
110
+ 'citation-number',
111
+ 'collection-number',
112
+ 'edition',
113
+ 'first-reference-note-number',
114
+ 'issue',
115
+ 'number',
116
+ 'number-of-pages',
117
+ 'number-of-volumes',
118
+ 'page',
119
+ 'page-first',
120
+ 'part',
121
+ 'printing',
122
+ 'supplement',
123
+ 'version',
124
+ 'volume',
125
+ ];
126
+ const strings = [
127
+ 'abstract',
128
+ 'annote',
129
+ 'archive',
130
+ 'archive_collection',
131
+ 'archive_location',
132
+ 'archive-place',
133
+ 'authority',
134
+ 'call-number',
135
+ 'citation-label',
136
+ 'collection-title',
137
+ 'container-title',
138
+ 'container-title-short',
139
+ 'dimensions',
140
+ 'division',
141
+ 'event',
142
+ 'event-place',
143
+ 'event-title',
144
+ 'genre',
145
+ 'ISBN',
146
+ 'ISSN',
147
+ 'journalAbbreviation',
148
+ 'jurisdiction',
149
+ 'keyword',
150
+ 'language',
151
+ 'locator',
152
+ 'medium',
153
+ 'note',
154
+ 'original-publisher',
155
+ 'original-publisher-place',
156
+ 'original-title',
157
+ 'part-title',
158
+ 'PMCID',
159
+ 'PMID',
160
+ 'publisher',
161
+ 'publisher-place',
162
+ 'references',
163
+ 'reviewed-genre',
164
+ 'reviewed-title',
165
+ 'scale',
166
+ 'section',
167
+ 'shortTitle',
168
+ 'source',
169
+ 'status',
170
+ 'title',
171
+ 'title-short',
172
+ 'URL',
173
+ 'volume-title',
174
+ 'volume-title-short',
175
+ 'year-suffix',
176
+ ];
177
+ const name = z
178
+ .array(z.strictObject({
179
+ family: z.string().optional(),
180
+ given: z.string().optional(),
181
+ 'dropping-particle': z.string().optional(),
182
+ 'non-dropping-particle': z.string().optional(),
183
+ suffix: z.string().optional(),
184
+ 'comma-suffix': z.union([z.string(), z.number(), z.boolean()]).optional(),
185
+ 'static-ordering': z
186
+ .union([z.string(), z.number(), z.boolean()])
187
+ .optional(),
188
+ literal: z.string().optional(),
189
+ 'parse-names': z.union([z.string(), z.number(), z.boolean()]).optional(),
190
+ }))
191
+ .describe('a CSL name variable: its people, in order');
192
+ const part = z.union([z.string(), z.number()]);
193
+ const date = z
194
+ .union([
195
+ z.string(),
196
+ z.strictObject({
197
+ 'date-parts': z
198
+ .array(z.array(part).min(1).max(3))
199
+ .min(1)
200
+ .max(2)
201
+ .optional(),
202
+ season: part.optional(),
203
+ circa: z.union([z.string(), z.number(), z.boolean()]).optional(),
204
+ literal: z.string().optional(),
205
+ raw: z.string().optional(),
206
+ }),
207
+ ])
208
+ .describe('a CSL date variable: an EDTF string, or date-parts');
209
+ const number = z.union([z.string(), z.number()]);
210
+ const string = z.string();
211
+ const variables = (keys, schema) => Object.fromEntries(keys.map((key) => [key, schema.optional()]));
212
+ const base = {
213
+ type: z.enum(types).optional(),
214
+ categories: z.array(z.string()).optional(),
215
+ custom: z.record(z.string(), z.unknown()).optional(),
216
+ };
217
+ export const Csl = z
218
+ .strictObject({
219
+ ...base,
220
+ ...variables(names, name),
221
+ ...variables(dates, date),
222
+ ...variables(numbers, number),
223
+ ...variables(strings, string),
224
+ })
225
+ .describe("CSL-JSON 1.0.2's item metadata; its id, DOI and citation-key are the work's id");
226
+ const field = Csl.keyof();
227
+ export const Paper = z
228
+ .strictObject({
229
+ kind,
230
+ open: z
231
+ .literal(true)
232
+ .optional()
233
+ .describe('the file may be served to anyone, not only the project'),
234
+ })
235
+ .describe('one held file');
236
+ export const Edition = z
237
+ .strictObject({
238
+ csl: Csl.optional().describe("the fields where it differs from its work's"),
239
+ papers: z
240
+ .record(sha, Paper)
241
+ .describe('the files held of it, by sha; empty for one named but not held'),
242
+ })
243
+ .describe('one edition of a work');
244
+ export const Work = z
245
+ .strictObject({
246
+ csl: Csl,
247
+ editions: z.array(Edition).min(1).describe('its editions, at least one'),
248
+ pending: z
249
+ .array(field)
250
+ .refine((pending) => new Set(pending).size === pending.length, 'pending repeats')
251
+ .meta({ uniqueItems: true })
252
+ .optional()
253
+ .describe('the CSL fields that wait on a person'),
254
+ })
255
+ .superRefine(({ csl, pending = [] }, ctx) => {
256
+ for (const key of ['title', 'type'])
257
+ if (csl[key] === undefined && !pending.includes(key))
258
+ ctx.addIssue({
259
+ code: 'custom',
260
+ path: ['csl', key],
261
+ message: `${key} is required unless pending lists it`,
262
+ });
263
+ })
264
+ .describe('one work: its metadata and its editions; csl.title and csl.type are required unless pending lists them');
265
+ const doi = z
266
+ .string()
267
+ .regex(/^10\.\d{4,9}(\.\d+)*\/[^\sA-Z]+$/)
268
+ .describe('a DOI, lowercase so a key is unique');
269
+ const minted = z
270
+ .string()
271
+ .regex(/^(?!sha-)[a-z][a-z0-9-]*$/)
272
+ .describe('a citation key the project mints');
273
+ const placeholder = z
274
+ .string()
275
+ .regex(/^sha-[0-9a-f]{12}$/)
276
+ .describe("the loader's key, from its sha; the key waits on a person");
277
+ export const Corpus = z
278
+ .record(z.union([doi, minted, placeholder]), Work)
279
+ .superRefine((corpus, ctx) => {
280
+ const seen = new Map();
281
+ for (const [key, work] of Object.entries(corpus))
282
+ for (const edition of work.editions)
283
+ for (const held of Object.keys(edition.papers)) {
284
+ if (seen.has(held))
285
+ ctx.addIssue({
286
+ code: 'custom',
287
+ path: [key],
288
+ message: `${held} is held by ${seen.get(held)} and ${key}`,
289
+ });
290
+ seen.set(held, key);
291
+ }
292
+ })
293
+ .describe('every work by id: a DOI, a minted citation key, or a placeholder');
294
+ /** The corpus before works: one entry per file, by sha. */
295
+ export const LegacyCorpus = z.record(sha, z.strictObject({
296
+ kind,
297
+ title: z.string().optional(),
298
+ citation: z.string().optional(),
299
+ open: z.literal(true).optional(),
300
+ }));
301
+ /** Every held file by sha, with the work and edition holding it. */
302
+ export function papers(corpus) {
303
+ const index = new Map();
304
+ for (const [key, work] of Object.entries(corpus))
305
+ for (const edition of work.editions)
306
+ for (const [sha, paper] of Object.entries(edition.papers))
307
+ index.set(sha, { key, work, edition, paper });
308
+ return index;
309
+ }
310
+ /** What waits on a person: each placeholder's key, and each pending field. */
311
+ export function pending(corpus) {
312
+ return Object.entries(corpus).flatMap(([key, work]) => {
313
+ const shas = work.editions.flatMap(({ papers }) => Object.keys(papers));
314
+ const judgments = [
315
+ ...(placeholder.safeParse(key).success ? ['key'] : []),
316
+ ...(work.pending ?? []),
317
+ ];
318
+ return judgments.map((judgment) => ({ work: key, shas, judgment }));
319
+ });
320
+ }
321
+ /** The placeholder key of the file `sha`. */
322
+ export const placeholderOf = (sha) => `sha-${sha.slice(0, 12)}`;
323
+ /** One legacy entry as a work of one edition, judging nothing. */
324
+ export function workOf(sha, { kind, title, citation, open }) {
325
+ const csl = {};
326
+ if (title !== undefined)
327
+ csl.title = title;
328
+ if (citation !== undefined)
329
+ csl.note = citation;
330
+ const pending = [
331
+ ...(title === undefined ? ['title'] : []),
332
+ 'type',
333
+ ...(citation === undefined ? [] : ['note']),
334
+ ];
335
+ const paper = open ? { kind, open } : { kind };
336
+ return { csl, editions: [{ papers: { [sha]: paper } }], pending };
337
+ }
338
+ /** Today's corpus in the new shape, one work per sha, and the judgments it leaves. */
339
+ export function reshape(legacy) {
340
+ const corpus = {};
341
+ for (const [sha, entry] of Object.entries(legacy)) {
342
+ const key = placeholderOf(sha);
343
+ if (corpus[key])
344
+ throw new Error(`${key}: ${Object.keys(corpus[key].editions[0].papers)[0]} and ${sha} share a key`);
345
+ corpus[key] = workOf(sha, entry);
346
+ }
347
+ return { corpus, judgments: pending(corpus) };
348
+ }
package/dist/data.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import type { Corpus as Parsed } from './types.js';
2
3
  /** Reads a project's research.json; each dataset reads its files when called. */
3
4
  export declare function project(dir: string): {
4
5
  title: string;
@@ -10,6 +11,14 @@ export declare function project(dir: string): {
10
11
  pages?: string[] | undefined;
11
12
  }> | undefined;
12
13
  roles: string[] | undefined;
14
+ collections: {
15
+ [key: string]: {
16
+ mode: "document" | "log";
17
+ body: Record<string, unknown>;
18
+ read: import("./collections.gen.js").components["schemas"]["ReadGrant"][];
19
+ write: import("./collections.gen.js").components["schemas"]["WriteGrant"][];
20
+ };
21
+ } | undefined;
13
22
  };
14
23
  /** The files a private dataset's glob matches, by the page each names; throws on a key a page cannot have. */
15
24
  export declare function privatePages(dir: string, dataset: string, glob: string): Record<string, string>;
@@ -19,10 +28,8 @@ export declare function files(dir: string, glob: string): {
19
28
  entries: [file: string, key: string][];
20
29
  };
21
30
  export declare function match(dir: string, { keyed, entries }: ReturnType<typeof files>): unknown;
22
- export declare function readCorpus(dir: string): Record<string, {
23
- kind: "pdf" | "doc" | "docx" | "xls" | "xlsx" | "zip" | "gif" | "jpg" | "tif" | "txt" | "html" | "xml";
24
- title?: string | undefined;
25
- citation?: string | undefined;
26
- open?: true | undefined;
27
- }>;
31
+ /** The project's corpus.json, `{}` where it has none; a legacy corpus fails, naming `reshape`. */
32
+ export declare function readCorpus(dir: string): Parsed;
33
+ /** Writes corpus.json, one work per line, sorted by key. */
34
+ export declare function writeCorpus(dir: string, corpus: Parsed): void;
28
35
  export declare function read<T>(dir: string, file: string, schema?: z.ZodType<T>): T;
package/dist/data.js CHANGED
@@ -1,9 +1,10 @@
1
- import { globSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
1
+ import { globSync, lstatSync, readFileSync, realpathSync, writeFileSync, } from 'node:fs';
2
2
  import { join, sep } from 'node:path';
3
+ import { LegacyCorpus } from './corpus.js';
3
4
  import { Corpus, Research } from './schema.js';
4
5
  /** Reads a project's research.json; each dataset reads its files when called. */
5
6
  export function project(dir) {
6
- const { title, data, private: held = {}, people, roles, } = read(dir, 'research.json', Research);
7
+ const { title, data, private: held = {}, people, roles, collections, } = read(dir, 'research.json', Research);
7
8
  const datasets = {
8
9
  corpus: () => readCorpus(dir),
9
10
  };
@@ -12,7 +13,7 @@ export function project(dir) {
12
13
  const pages = {};
13
14
  for (const [dataset, glob] of Object.entries(held))
14
15
  pages[dataset] = () => privatePages(dir, dataset, glob);
15
- return { title, datasets, pages, people, roles };
16
+ return { title, datasets, pages, people, roles, collections };
16
17
  }
17
18
  /** The files a private dataset's glob matches, by the page each names; throws on a key a page cannot have. */
18
19
  export function privatePages(dir, dataset, glob) {
@@ -48,14 +49,24 @@ export function match(dir, { keyed, entries }) {
48
49
  ? Object.fromEntries(entries.map(([file, key]) => [key, read(dir, file)]))
49
50
  : read(dir, entries[0][0]);
50
51
  }
52
+ /** The project's corpus.json, `{}` where it has none; a legacy corpus fails, naming `reshape`. */
51
53
  export function readCorpus(dir) {
52
- return lstatSync(join(dir, 'corpus.json'), { throwIfNoEntry: false })
53
- ? read(dir, 'corpus.json', Corpus)
54
- : {};
54
+ if (!lstatSync(join(dir, 'corpus.json'), { throwIfNoEntry: false }))
55
+ return {};
56
+ const json = read(dir, 'corpus.json');
57
+ if (!Corpus.safeParse(json).success && LegacyCorpus.safeParse(json).success)
58
+ throw new Error(`${join(dir, 'corpus.json')}: the legacy shape; run npx library-research reshape`);
59
+ return checked(join(dir, 'corpus.json'), json, Corpus);
60
+ }
61
+ /** Writes corpus.json, one work per line, sorted by key. */
62
+ export function writeCorpus(dir, corpus) {
63
+ const lines = Object.entries(Corpus.parse(corpus))
64
+ .sort(([a], [b]) => a.localeCompare(b))
65
+ .map(([key, work]) => ` "${key}": ${JSON.stringify(work)}`);
66
+ writeFileSync(join(dir, 'corpus.json'), `{\n${lines.join(',\n')}\n}\n`);
55
67
  }
56
68
  export function read(dir, file, schema) {
57
69
  const path = join(dir, file);
58
- const fail = (why) => new Error(`${path}: ${why}`);
59
70
  let json;
60
71
  try {
61
72
  if (!realpathSync(path).startsWith(realpathSync(dir) + sep))
@@ -63,14 +74,15 @@ export function read(dir, file, schema) {
63
74
  json = JSON.parse(readFileSync(path, 'utf8'));
64
75
  }
65
76
  catch (e) {
66
- throw fail(e.message);
77
+ throw new Error(`${path}: ${e.message}`);
67
78
  }
68
- if (!schema)
69
- return json;
70
- const checked = schema.safeParse(json);
71
- if (!checked.success)
72
- throw fail(checked.error.issues
79
+ return schema ? checked(path, json, schema) : json;
80
+ }
81
+ function checked(path, json, schema) {
82
+ const parsed = schema.safeParse(json);
83
+ if (!parsed.success)
84
+ throw new Error(`${path}: ${parsed.error.issues
73
85
  .map(({ path, message }) => `${path.join('.')}: ${message}`)
74
- .join('; '));
75
- return checked.data;
86
+ .join('; ')}`);
87
+ return parsed.data;
76
88
  }
@@ -2,6 +2,9 @@
2
2
  * Reads each dataset of the project in `dir`, the folder holding
3
3
  * research.json, parsed by its schema in ui/datasets.ts, and its corpus. A
4
4
  * private dataset is read as `{ page: parsed }`, its schema parsing one page's
5
- * file. Throws one line per failure.
5
+ * file. A `roles` that ui/datasets.ts exports, the tuple `Register` types
6
+ * roles from, must equal research.json's; a `collections` it exports must
7
+ * name research.json's collections, each schema's JSON Schema equal to its
8
+ * `body`. Throws one line per failure.
6
9
  */
7
10
  export declare function load(dir: string): Promise<Record<string, unknown>>;
package/dist/datasets.js CHANGED
@@ -1,40 +1,80 @@
1
1
  import { lstatSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
+ import { isDeepStrictEqual } from 'node:util';
4
5
  import { files, match, privatePages, read, readCorpus } from './data.js';
5
6
  import { Research } from './schema.js';
7
+ import { z } from './zod.js';
6
8
  const schemaFile = 'ui/datasets.ts';
7
- /** The `datasets` ui/datasets.ts exports, which Node loads by stripping its types. */
9
+ /** The `datasets`, `roles` and `collections` ui/datasets.ts exports, which Node loads by stripping its types. */
8
10
  async function schemas(dir) {
9
11
  const path = join(dir, schemaFile);
10
12
  if (!lstatSync(path, { throwIfNoEntry: false }))
11
- return {};
13
+ return { datasets: {} };
12
14
  const manifest = join(dir, 'ui/package.json');
13
15
  const { type } = JSON.parse(readFileSync(manifest, 'utf8'));
14
16
  if (type !== 'module')
15
17
  throw new Error(`${manifest}: needs "type": "module" for ${schemaFile}`);
16
- let datasets;
18
+ let exported;
17
19
  try {
18
- datasets = (await import(pathToFileURL(path).href)).datasets;
20
+ exported = (await import(pathToFileURL(path).href));
19
21
  }
20
22
  catch (error) {
21
23
  throw new Error(`${path}: ${error.message.split('\n')[0]}`);
22
24
  }
25
+ const { datasets, roles, collections } = exported;
23
26
  if (typeof datasets !== 'object' || !datasets)
24
27
  throw new Error(`${path}: exports no datasets object`);
25
- return datasets;
28
+ return { datasets: datasets, roles, collections };
26
29
  }
30
+ /** One line per collection whose schema in `typed` does not hold research.json's `body`, or that one of the two lacks. */
31
+ function collectionFailures(file, typed, declared) {
32
+ if (typeof typed !== 'object' || !typed)
33
+ return [`${file}: collections is not an object of schemas`];
34
+ const schemas = typed;
35
+ const failures = Object.keys(schemas)
36
+ .filter((name) => !Object.hasOwn(declared, name))
37
+ .map((name) => `${file}: schema for collection "${name}", which research.json does not declare`);
38
+ for (const [name, { body }] of Object.entries(declared)) {
39
+ if (!Object.hasOwn(schemas, name)) {
40
+ failures.push(`${file}: no schema for collection "${name}"`);
41
+ continue;
42
+ }
43
+ let expected;
44
+ try {
45
+ expected = z.toJSONSchema(schemas[name]);
46
+ delete expected.$schema;
47
+ }
48
+ catch (error) {
49
+ failures.push(`${file}: collection "${name}": ${error.message}`);
50
+ continue;
51
+ }
52
+ if (!isDeepStrictEqual(expected, body))
53
+ failures.push(`${file}: collection "${name}": research.json's body differs from its schema, which is ${JSON.stringify(expected)}`);
54
+ }
55
+ return failures;
56
+ }
57
+ const sameRoles = (typed, roles) => Array.isArray(typed) &&
58
+ typed.length === roles.length &&
59
+ roles.every((role) => typed.includes(role));
27
60
  /**
28
61
  * Reads each dataset of the project in `dir`, the folder holding
29
62
  * research.json, parsed by its schema in ui/datasets.ts, and its corpus. A
30
63
  * private dataset is read as `{ page: parsed }`, its schema parsing one page's
31
- * file. Throws one line per failure.
64
+ * file. A `roles` that ui/datasets.ts exports, the tuple `Register` types
65
+ * roles from, must equal research.json's; a `collections` it exports must
66
+ * name research.json's collections, each schema's JSON Schema equal to its
67
+ * `body`. Throws one line per failure.
32
68
  */
33
69
  export async function load(dir) {
34
- const { data, private: held = {} } = read(dir, 'research.json', Research);
35
- const found = await schemas(dir);
70
+ const { data, private: held = {}, roles = [], collections = {}, } = read(dir, 'research.json', Research);
71
+ const { datasets: found, roles: typed, collections: typedCollections, } = await schemas(dir);
36
72
  const loaded = {};
37
73
  const failures = [];
74
+ if (typed !== undefined && !sameRoles(typed, roles))
75
+ failures.push(`${join(dir, schemaFile)}: roles ${JSON.stringify(typed)} differ from research.json's ${JSON.stringify(roles)}`);
76
+ if (typedCollections !== undefined)
77
+ failures.push(...collectionFailures(join(dir, schemaFile), typedCollections, collections));
38
78
  for (const dataset of Object.keys(found))
39
79
  if (!Object.hasOwn(data, dataset) && !Object.hasOwn(held, dataset))
40
80
  failures.push(`${join(dir, schemaFile)}: schema for "${dataset}", which research.json does not name`);
package/dist/dev/host.js CHANGED
@@ -5,24 +5,21 @@ import { RouterProvider } from '@tanstack/react-router';
5
5
  import { createContext, useContext, useMemo, useState } from 'react';
6
6
  import { createRoot } from 'react-dom/client';
7
7
  import projects from 'virtual:research-projects';
8
+ import { createHost } from '../host.js';
8
9
  import { membersOf, pagesOf, readerCookie, readerOf, } from '../reader.js';
9
10
  import { projectRouter } from '../router.js';
10
11
  const project = projects.project;
11
12
  const Reader = createContext({ username: '', cast: {}, lost: () => { } });
12
13
  function useHost() {
13
14
  const { username, cast, lost } = useContext(Reader);
14
- return useMemo(() => ({
15
+ return useMemo(() => createHost({
16
+ project: 'project',
15
17
  // A signed-out context is no one, refused by its first request's 401.
16
18
  reader: readerOf(username ? cast : {}, username, true),
17
19
  members: membersOf(cast.people),
18
- data: (dataset) => `/projects/project/data/${dataset}.json`,
19
- private: (dataset) => Object.fromEntries(pagesOf(cast.people, username).map((page) => [
20
- page,
21
- `/projects/project/private/${encodeURIComponent(page)}/${dataset}.json`,
22
- ])),
23
- paper: (sha) => `/projects/project/papers/${sha}`,
24
- document: (id) => `/projects/project/documents/${id}`,
25
- documents: (prefix) => `/projects/project/documents?prefix=${prefix}`,
20
+ pages: pagesOf(cast.people, username),
21
+ // The dev server answers with its one collectionStore, shared by every browser context.
22
+ store: (request) => fetch(request),
26
23
  sessionLost: lost,
27
24
  }), [username, cast, lost]);
28
25
  }
package/dist/host.d.ts CHANGED
@@ -1,8 +1,22 @@
1
1
  import { type AnyRoute, type ErrorComponentProps } from '@tanstack/react-router';
2
2
  import type { AnyProject } from './mount.js';
3
- import type { Host } from './types.js';
3
+ import type { Host, Member, Reader } from './types.js';
4
4
  export type { Host };
5
5
  export { pdfAssets } from './pdf.js';
6
+ export { projectIdPattern } from './project-id.js';
7
+ /** The `Host` of one project, its URLs built by the one rule every host serves. */
8
+ export declare function createHost({ project, reader, members, pages, store, sessionLost, origin, }: {
9
+ /** The project's id, matching `projectIdPattern`. */
10
+ project: string;
11
+ reader: Reader;
12
+ members: Member[];
13
+ /** The viewed person's private pages. */
14
+ pages: string[];
15
+ store: (request: Request) => Promise<Response>;
16
+ sessionLost: () => void;
17
+ /** What the URLs are under; Node's `Request` refuses a relative URL. */
18
+ origin?: string;
19
+ }): Host;
6
20
  declare function Failed({ error, reset }: ErrorComponentProps): import("react").JSX.Element;
7
21
  /**
8
22
  * The route options of a project's mount: the project's `Host` from
@@ -16,6 +30,7 @@ export declare function frame(useHost: () => Host): {
16
30
  };
17
31
  /**
18
32
  * Mounts `project` under `parent` at the path it names, with `options` as the
19
- * route's options (`frame(useHost)`, and any `loader` or `head`); returns the route.
33
+ * route's options (`frame(useHost)`, and any `loader` or `head`); returns the
34
+ * route. The route's component renders in the project's datasets and collections.
20
35
  */
21
36
  export declare function mount(parent: AnyRoute, project: AnyProject, options: Partial<Omit<AnyRoute['options'], 'getParentRoute' | 'path'>>): AnyRoute;
package/dist/host.js CHANGED
@@ -2,8 +2,29 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { Button, Notice } from '@metacensus/library-ui';
3
3
  import { useQueryErrorResetBoundary } from '@tanstack/react-query';
4
4
  import { createRoute, Outlet, } from '@tanstack/react-router';
5
- import { HostContext } from './context.js';
5
+ import { CollectionsContext, DatasetsContext, HostContext } from './context.js';
6
+ import { checkProjectId } from './project-id.js';
7
+ import { urls } from './urls.js';
6
8
  export { pdfAssets } from './pdf.js';
9
+ export { projectIdPattern } from './project-id.js';
10
+ /** The `Host` of one project, its URLs built by the one rule every host serves. */
11
+ export function createHost({ project, reader, members, pages, store, sessionLost, origin = location.origin, }) {
12
+ checkProjectId(project, 'project');
13
+ return {
14
+ reader,
15
+ members,
16
+ data: (dataset) => origin + urls.data(project, dataset),
17
+ private: (dataset) => Object.fromEntries(pages.map((page) => [
18
+ page,
19
+ origin + urls.private(project, page, dataset),
20
+ ])),
21
+ paper: (sha) => origin + urls.paper(project, sha),
22
+ collections: () => origin + urls.collections(project),
23
+ collection: (name) => origin + urls.collection(project, name),
24
+ store,
25
+ sessionLost,
26
+ };
27
+ }
7
28
  function Failed({ error, reset }) {
8
29
  const queries = useQueryErrorResetBoundary();
9
30
  return (_jsx(Notice, { role: "alert", title: error instanceof Error ? error.message : String(error), children: _jsx(Button, { onClick: () => {
@@ -27,11 +48,14 @@ export function frame(useHost) {
27
48
  }
28
49
  /**
29
50
  * Mounts `project` under `parent` at the path it names, with `options` as the
30
- * route's options (`frame(useHost)`, and any `loader` or `head`); returns the route.
51
+ * route's options (`frame(useHost)`, and any `loader` or `head`); returns the
52
+ * route. The route's component renders in the project's datasets and collections.
31
53
  */
32
54
  export function mount(parent, project, options) {
55
+ const Inner = (options.component ?? Outlet);
33
56
  const route = createRoute({
34
57
  ...options,
58
+ component: () => (_jsx(DatasetsContext.Provider, { value: project.datasets, children: _jsx(CollectionsContext.Provider, { value: project.collections, children: _jsx(Inner, {}) }) })),
35
59
  getParentRoute: () => parent,
36
60
  path: project.path,
37
61
  });