@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/react.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { useMutation, useQueryClient, useSuspenseQueries, useSuspenseQuery, } from '@tanstack/react-query';
2
- import { useContext, useMemo, useState } from 'react';
3
- import { FetchContext, HostContext } from './context.js';
4
- import { DocumentError, documentId, documentPrefix } from './documents.js';
2
+ import { useContext, useMemo } from 'react';
3
+ import { CollectionsContext, DatasetsContext, HostContext } from './context.js';
5
4
  import * as schema from './schema.js';
6
5
  /** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
7
6
  export function useHost() {
@@ -18,43 +17,57 @@ export function useReader() {
18
17
  export function useMembers() {
19
18
  return useHost().members;
20
19
  }
20
+ /** The schemas `defineProject` registered, as `parse` functions by dataset name. */
21
+ function useParsers() {
22
+ const schemas = useContext(DatasetsContext);
23
+ return (dataset) => {
24
+ const schema = Object.hasOwn(schemas, dataset)
25
+ ? schemas[dataset]
26
+ : undefined;
27
+ if (!schema)
28
+ throw new Error(`dataset "${dataset}": defineProject was given no schema for it`);
29
+ return (json) => schema.parse(json);
30
+ };
31
+ }
21
32
  /**
22
- * One dataset's JSON, parsed by `parse`. Suspends while it loads; a failed
23
- * fetch or parse throws to the frame's error notice, naming the dataset. A 401 or
24
- * 403 also calls `Host.sessionLost`. `parse` must be pure: it is read once per
25
- * dataset list, not on every render.
33
+ * One dataset's JSON, parsed by its schema in `ui/datasets.ts`. Suspends while
34
+ * it loads; a failed fetch or parse throws to the frame's error notice,
35
+ * naming the dataset. A 401 or 403 also calls `Host.sessionLost`.
26
36
  */
27
- export function useData(dataset, parse) {
28
- return useDatas([[dataset, parse]])[0];
37
+ export function useData(dataset) {
38
+ return useDatas([dataset])[0];
29
39
  }
30
40
  /**
31
- * `useData` for several datasets at once, fetched in parallel: a `[dataset, parse]`
32
- * tuple each, the values returned in the same order and typed by their parsers.
33
- * Each parser must be pure: it is read once per dataset list, not on every render.
41
+ * `useData` for several datasets at once, fetched in parallel: the names in a
42
+ * tuple, the values returned in the same order and typed by their schemas.
34
43
  */
35
44
  export function useDatas(datasets) {
45
+ const parser = useParsers();
46
+ return useFetched(datasets.map((dataset) => [String(dataset), parser(String(dataset))]));
47
+ }
48
+ /** Fetches each dataset and parses it; the parsers are those of a project's fixed schemas, so they are read once per dataset list. */
49
+ function useFetched(datasets) {
36
50
  const host = useHost();
37
- // The parsers and select functions are kept until the dataset list changes, so
38
- // an inline parse does not rerun on every render.
39
51
  const key = JSON.stringify(datasets.map(([dataset]) => dataset));
40
- const [held, hold] = useState({ key, datasets });
41
- if (held.key !== key)
42
- hold({ key, datasets });
43
- const names = held.datasets.map(([dataset]) => dataset);
44
- const selects = useMemo(() => held.datasets.map(([dataset, parse]) => (json) => {
52
+ const names = datasets.map(([dataset]) => dataset);
53
+ const selects = useMemo(() => datasets.map(([dataset, parse]) => (json) => {
45
54
  try {
46
55
  return parse(json);
47
56
  }
48
57
  catch (cause) {
49
58
  return failed(`dataset "${dataset}"`, cause);
50
59
  }
51
- }), [held]);
60
+ }),
61
+ // The datasets are named by `key`, and their parsers do not change.
62
+ // eslint-disable-next-line react-hooks/exhaustive-deps
63
+ [key]);
52
64
  return useSuspenseQueries({
53
65
  queries: names.map((dataset, i) => {
54
66
  const url = host.data(dataset);
55
67
  return {
56
68
  queryKey: ['research', url],
57
- queryFn: () => fetch(url)
69
+ queryFn: () => host
70
+ .store(new Request(url))
58
71
  .then((response) => {
59
72
  if (response.status === 401 || response.status === 403)
60
73
  host.sessionLost();
@@ -80,34 +93,36 @@ function failed(what, cause) {
80
93
  /**
81
94
  * The viewed person's pages of a private dataset, as `{ page: parsed }`: empty
82
95
  * when they hold none, a page the host names but the build did not emit left
83
- * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
84
- * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
96
+ * out. Its schema parses each page's JSON. Its cache entry, `{ json } | null`,
97
+ * is not `useData`'s raw JSON, under the same key prefix.
85
98
  */
86
- export function usePrivate(dataset, parse) {
99
+ export function usePrivate(dataset) {
100
+ const name = String(dataset);
101
+ const parse = useParsers()(name);
87
102
  const host = useHost();
88
- const urls = host.private(dataset);
103
+ const urls = host.private(name);
89
104
  const pages = Object.keys(urls);
90
105
  const key = pages.join();
91
- const held = useHeld(dataset, parse);
92
106
  const selects = useMemo(() => pages.map((page) => (found) => {
93
107
  if (!found)
94
108
  return null;
95
109
  try {
96
- return { value: held(found.json) };
110
+ return { value: parse(found.json) };
97
111
  }
98
112
  catch (cause) {
99
- return failed(`private dataset "${dataset}" page "${page}"`, cause);
113
+ return failed(`private dataset "${name}" page "${page}"`, cause);
100
114
  }
101
115
  }),
102
- // The pages are named by `key`.
116
+ // The pages are named by `key`, and a project's schemas do not change.
103
117
  // eslint-disable-next-line react-hooks/exhaustive-deps
104
- [held, key]);
118
+ [key]);
105
119
  return useSuspenseQueries({
106
120
  queries: pages.map((page, i) => {
107
121
  const url = urls[page];
108
122
  return {
109
123
  queryKey: ['research', url],
110
- queryFn: () => fetch(url)
124
+ queryFn: () => host
125
+ .store(new Request(url))
111
126
  .then((response) => {
112
127
  if (response.status === 401 || response.status === 403)
113
128
  host.sessionLost();
@@ -117,7 +132,7 @@ export function usePrivate(dataset, parse) {
117
132
  throw new Error(`${response.status} from ${url}`);
118
133
  return response.json().then((json) => ({ json }));
119
134
  })
120
- .catch((cause) => failed(`private dataset "${dataset}" page "${page}"`, cause)),
135
+ .catch((cause) => failed(`private dataset "${name}" page "${page}"`, cause)),
121
136
  select: selects[i],
122
137
  staleTime: Infinity,
123
138
  retry: false,
@@ -126,101 +141,89 @@ export function usePrivate(dataset, parse) {
126
141
  combine: (results) => Object.fromEntries(results.flatMap(({ data }, i) => data ? [[pages[i], data.value]] : [])),
127
142
  });
128
143
  }
129
- /** The `corpus` dataset, parsed by the library's own schema, through `useData`. */
144
+ const corpusDataset = ['corpus', (json) => schema.Corpus.parse(json)];
145
+ /** The `corpus` dataset, every work by id, parsed by the library's own schema. */
130
146
  export function useCorpus() {
131
- return useData('corpus', (json) => schema.Corpus.parse(json));
147
+ return useFetched([corpusDataset])[0];
132
148
  }
133
- /** A fetch whose 401 and 403 are the host's lost session, and whose other failures are a `DocumentError`. */
134
- function useSend() {
149
+ /** The items of one collection the signed-in person may read, and `refresh` to read them again. */
150
+ export function useCollection(collection) {
151
+ const name = String(collection);
152
+ const schemas = useContext(CollectionsContext);
153
+ const parse = Object.hasOwn(schemas, name) ? schemas[name] : undefined;
154
+ if (!parse)
155
+ throw new Error(`collection "${name}": defineProject was given no schema for it`);
135
156
  const host = useHost();
136
- const get = useContext(FetchContext) ?? fetch;
137
- return async (url, init, absent = false) => {
138
- const response = await get(url, init);
139
- if (response.status === 401 || response.status === 403)
140
- host.sessionLost();
141
- if (absent && response.status === 404)
142
- return null;
143
- if (!response.ok)
144
- throw new DocumentError(response.status, `${response.status} from ${url}`);
145
- return response.json();
146
- };
147
- }
148
- /** `parse`, held until `key` changes, so an inline one is not read again on every render. */
149
- function useHeld(key, parse) {
150
- const [held, hold] = useState({ key, parse });
151
- if (held.key !== key)
152
- hold({ key, parse });
153
- return held.parse;
154
- }
155
- const parsed = (parse) => (doc) => {
156
- try {
157
- return { ...doc, body: parse(doc.body) };
158
- }
159
- catch (cause) {
160
- const why = cause instanceof Error ? cause.message : String(cause);
161
- throw new Error(`document "${doc.id}": ${why}`, { cause });
162
- }
163
- };
164
- /**
165
- * One document of the project, or `null` when none has that id. Suspends while
166
- * it loads; a failed read throws a `DocumentError` to the frame's error
167
- * notice. `parse` runs on the body only and must be pure.
168
- */
169
- export function useDocument(id, parse) {
170
- const url = useHost().document(documentId(id));
171
- const send = useSend();
172
- const held = useHeld(url, parse);
173
- const select = useMemo(() => (doc) => doc && parsed(held)(doc), [held]);
174
- return useSuspenseQuery({
175
- queryKey: ['research-document', url],
176
- queryFn: () => send(url, undefined, true),
157
+ const client = useQueryClient();
158
+ const url = host.collection(name);
159
+ const select = useMemo(() => ({ items }) => items.map((item) => {
160
+ try {
161
+ return { ...item, body: parse.parse(item.body) };
162
+ }
163
+ catch (cause) {
164
+ return failed(`collection "${name}" item "${item.id}"`, cause);
165
+ }
166
+ }), [name, parse]);
167
+ const key = ['research-collection', url];
168
+ const { data } = useSuspenseQuery({
169
+ queryKey: key,
170
+ queryFn: () => host
171
+ .store(new Request(url))
172
+ .then((response) => {
173
+ if (response.status === 401 || response.status === 403)
174
+ host.sessionLost();
175
+ if (!response.ok)
176
+ throw new Error(`${response.status} from ${url}`);
177
+ return response.json();
178
+ })
179
+ .catch((cause) => failed(`collection "${name}"`, cause)),
177
180
  select,
178
181
  retry: false,
179
- }).data;
182
+ });
183
+ return {
184
+ items: data,
185
+ refresh: () => client.refetchQueries({ queryKey: key, exact: true }, { throwOnError: true }),
186
+ };
180
187
  }
181
- /**
182
- * The project's documents whose id starts with `prefix`, sorted by id; every
183
- * save of the project refetches them. `parse` runs on each body and must be pure.
184
- */
185
- export function useDocuments(prefix, parse) {
186
- const url = useHost().documents(documentPrefix(prefix));
187
- const send = useSend();
188
- const held = useHeld(url, parse);
189
- const select = useMemo(() => ({ items }) => items.map(parsed(held)), [held]);
190
- return useSuspenseQuery({
191
- queryKey: ['research-documents', url],
192
- queryFn: () => send(url),
193
- select,
194
- retry: false,
195
- }).data;
188
+ /** A write the host refused. */
189
+ export class WriteError extends Error {
190
+ status;
191
+ /** The store's term for the refusal; absent where the status alone answers, such as 413. */
192
+ code;
193
+ /** For `stale` and `exists`, each item in conflict at the revision it holds, to retry from. */
194
+ conflicts;
195
+ constructor(status, code, conflicts = []) {
196
+ super(`write refused: ${code ?? status}`);
197
+ this.name = 'WriteError';
198
+ this.status = status;
199
+ this.code = code;
200
+ this.conflicts = conflicts;
201
+ }
196
202
  }
197
- /**
198
- * Saves a JSON `body` as the document `id`, written by the signed-in person.
199
- * `when` makes the save conditional: `'absent'` refuses (412) if the document
200
- * exists, a revision refuses unless the document is at it; without it the
201
- * save replaces. A failure is the mutation's `error`, a `DocumentError`.
202
- */
203
- export function useSaveDocument(id) {
204
- const url = useHost().document(documentId(id));
205
- const send = useSend();
203
+ /** Writes items across the project's collections in one atomic request: every item, or none. */
204
+ export function useWrite() {
205
+ const host = useHost();
206
206
  const client = useQueryClient();
207
+ const reread = ({ items }) => Promise.all([...new Set(items.map(({ collection }) => String(collection)))].map((name) => client.invalidateQueries({
208
+ queryKey: ['research-collection', host.collection(name)],
209
+ exact: true,
210
+ })));
207
211
  return useMutation({
208
- mutationFn: ({ body, when }) => {
209
- const headers = {
210
- 'Content-Type': 'application/json',
211
- };
212
- if (when === 'absent')
213
- headers['If-None-Match'] = '*';
214
- else if (when !== undefined)
215
- headers['If-Match'] = `"${when}"`;
216
- const text = JSON.stringify(body);
217
- if (text === undefined)
218
- throw new Error(`document "${id}": no JSON body`);
219
- return send(url, { method: 'PUT', headers, body: text });
220
- },
221
- onSuccess: (doc) => {
222
- client.setQueryData(['research-document', url], doc);
223
- return client.invalidateQueries({ queryKey: ['research-documents'] });
212
+ mutationFn: async (request) => {
213
+ const response = await host.store(new Request(host.collections(), {
214
+ method: 'POST',
215
+ headers: { 'Content-Type': 'application/json' },
216
+ body: JSON.stringify(request),
217
+ }));
218
+ if (response.status === 401)
219
+ host.sessionLost();
220
+ const json = (await response.json().catch(() => ({})));
221
+ if (!response.ok)
222
+ throw new WriteError(response.status, json.code, json.conflicts);
223
+ return json;
224
224
  },
225
+ onSuccess: (_, request) => reread(request),
226
+ // A conflict's list is read again, so it shows the revisions the refusal names.
227
+ onError: (error, request) => error.status === 409 ? reread(request) : undefined,
225
228
  });
226
229
  }
package/dist/schema.d.ts CHANGED
@@ -1,18 +1,7 @@
1
- import { z } from 'zod';
2
- export declare const kinds: {
3
- readonly pdf: "application/pdf";
4
- readonly doc: "application/msword";
5
- readonly docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
6
- readonly xls: "application/vnd.ms-excel";
7
- readonly xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
8
- readonly zip: "application/zip";
9
- readonly gif: "image/gif";
10
- readonly jpg: "image/jpeg";
11
- readonly tif: "image/tiff";
12
- readonly txt: "text/plain";
13
- readonly html: "text/plain";
14
- readonly xml: "text/plain";
15
- };
1
+ import { z } from './zod.js';
2
+ export { Corpus, kinds } from './corpus.js';
3
+ /** A project's id, matching `projectIdPattern`. */
4
+ export declare const ProjectId: z.ZodString;
16
5
  export declare const Research: z.ZodObject<{
17
6
  title: z.ZodString;
18
7
  data: z.ZodRecord<z.ZodString, z.ZodString>;
@@ -23,23 +12,19 @@ export declare const Research: z.ZodObject<{
23
12
  role: z.ZodOptional<z.ZodString>;
24
13
  pages: z.ZodOptional<z.ZodArray<z.ZodString>>;
25
14
  }, z.core.$strict>>>;
15
+ collections: z.ZodOptional<z.ZodType<{
16
+ [key: string]: {
17
+ mode: "document" | "log";
18
+ body: Record<string, unknown>;
19
+ read: import("./collections.gen.js").components["schemas"]["ReadGrant"][];
20
+ write: import("./collections.gen.js").components["schemas"]["WriteGrant"][];
21
+ };
22
+ }, unknown, z.core.$ZodTypeInternals<{
23
+ [key: string]: {
24
+ mode: "document" | "log";
25
+ body: Record<string, unknown>;
26
+ read: import("./collections.gen.js").components["schemas"]["ReadGrant"][];
27
+ write: import("./collections.gen.js").components["schemas"]["WriteGrant"][];
28
+ };
29
+ }, unknown>>>;
26
30
  }, z.core.$strict>;
27
- export declare const Corpus: z.ZodRecord<z.ZodString, z.ZodObject<{
28
- kind: z.ZodEnum<{
29
- pdf: "pdf";
30
- doc: "doc";
31
- docx: "docx";
32
- xls: "xls";
33
- xlsx: "xlsx";
34
- zip: "zip";
35
- gif: "gif";
36
- jpg: "jpg";
37
- tif: "tif";
38
- txt: "txt";
39
- html: "html";
40
- xml: "xml";
41
- }>;
42
- title: z.ZodOptional<z.ZodString>;
43
- citation: z.ZodOptional<z.ZodString>;
44
- open: z.ZodOptional<z.ZodLiteral<true>>;
45
- }, z.core.$strict>>;
package/dist/schema.js CHANGED
@@ -1,28 +1,32 @@
1
- import { z } from 'zod';
2
- z.config({ jitless: true });
3
- export const kinds = {
4
- pdf: 'application/pdf',
5
- doc: 'application/msword',
6
- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
7
- xls: 'application/vnd.ms-excel',
8
- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
9
- zip: 'application/zip',
10
- gif: 'image/gif',
11
- jpg: 'image/jpeg',
12
- tif: 'image/tiff',
13
- txt: 'text/plain',
14
- html: 'text/plain',
15
- xml: 'text/plain',
16
- };
1
+ import { collections } from './collections.gen.js';
2
+ import { projectIdPattern } from './project-id.js';
3
+ import { z } from './zod.js';
4
+ export { Corpus, kinds } from './corpus.js';
17
5
  const dataset = z.string().regex(/^(?!corpus$)[a-z][A-Za-z0-9]*$/);
18
- const glob = z.string().regex(/^(?!\/)(?!.*\.\.).+$/);
6
+ /** A project's id, matching `projectIdPattern`. */
7
+ export const ProjectId = z
8
+ .string()
9
+ .regex(projectIdPattern)
10
+ .describe('A project id: lower-case letters, digits and hyphens, not starting with a hyphen');
19
11
  const role = z.string().regex(/^[a-z][a-z0-9-]*$/);
20
12
  const page = z.string().regex(/^[a-z0-9][a-z0-9-]*$/);
13
+ // Relative and without `..`, then `*`s only as `stars` says, and no other glob character.
14
+ const other = String.raw `[^*?[\]{}()!]*`;
15
+ const glob = (stars, rule) => {
16
+ const grammar = `a glob that is relative, has no .., ${rule}, and has none of ?[]{}()!`;
17
+ return z
18
+ .string()
19
+ .regex(new RegExp(`^(?!/)(?!.*\\.\\.)(?=.)${stars}$`), `must be ${grammar}`)
20
+ .describe(grammar);
21
+ };
22
+ const dataGlob = glob(`${other}(?:\\*${other})?`, 'has at most one *');
23
+ const privateGlob = glob(`${other}\\*${other}`, 'has exactly one *');
24
+ const collectionsSchema = z.fromJSONSchema(collections);
21
25
  export const Research = z
22
26
  .strictObject({
23
27
  title: z.string().min(1),
24
- data: z.record(dataset, glob),
25
- private: z.record(dataset, glob).optional(),
28
+ data: z.record(dataset, dataGlob),
29
+ private: z.record(dataset, privateGlob).optional(),
26
30
  /** The roles a person of the project holds one of. */
27
31
  roles: z
28
32
  .array(role)
@@ -37,6 +41,7 @@ export const Research = z
37
41
  pages: z.array(page).optional(),
38
42
  }))
39
43
  .optional(),
44
+ collections: collectionsSchema.optional(),
40
45
  })
41
46
  .superRefine(({ data, private: held = {}, roles, people = {} }, ctx) => {
42
47
  for (const [username, person] of Object.entries(people)) {
@@ -54,17 +59,28 @@ export const Research = z
54
59
  else if (!roles.includes(person.role))
55
60
  issue(`has role "${person.role}", which is not in roles`);
56
61
  }
57
- for (const [name, pattern] of Object.entries(held)) {
58
- const issue = (message) => ctx.addIssue({ code: 'custom', path: ['private', name], message });
62
+ for (const name of Object.keys(held))
59
63
  if (Object.hasOwn(data, name))
60
- issue(`dataset "${name}" is in data and private`);
61
- if (pattern.split('*').length !== 2 || /[?[\]{}()!]/.test(pattern))
62
- issue(`dataset "${name}": glob "${pattern}" must hold exactly one * and no other glob character`);
63
- }
64
+ ctx.addIssue({
65
+ code: 'custom',
66
+ path: ['private', name],
67
+ message: `dataset "${name}" is in data and private`,
68
+ });
69
+ })
70
+ // The API's manifest checks: each role a grant names is declared, and each gate is a log.
71
+ .superRefine(({ roles, collections = {} }, ctx) => {
72
+ for (const [name, collection] of Object.entries(collections))
73
+ for (const kind of ['read', 'write'])
74
+ collection[kind].forEach(({ roles: named = [], after }, i) => {
75
+ const issue = (message) => ctx.addIssue({
76
+ code: 'custom',
77
+ path: ['collections', name, kind, i],
78
+ message,
79
+ });
80
+ for (const role of named)
81
+ if (!roles?.includes(role))
82
+ issue(`role "${role}" is not in roles`);
83
+ if (after && collections[after.collection]?.mode !== 'log')
84
+ issue(`gate collection "${after.collection}" is not a log`);
85
+ });
64
86
  });
65
- export const Corpus = z.record(z.string().regex(/^[0-9a-f]{64}$/), z.strictObject({
66
- kind: z.enum(Object.keys(kinds)),
67
- title: z.string().optional(),
68
- citation: z.string().optional(),
69
- open: z.literal(true).optional(),
70
- }));
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { ReactElement } from 'react';
2
+ import type { Collections } from './collections.gen.js';
2
3
  import { type People } from './reader.js';
3
4
  import type { AnyProject } from './mount.js';
5
+ export { parity, type Exchange } from './parity.js';
4
6
  export { membersOf, readerOf, type People } from './reader.js';
5
7
  /** What `testHost` is given besides the project; every field is optional. */
6
8
  export interface TestHostOptions {
@@ -8,18 +10,22 @@ export interface TestHostOptions {
8
10
  data?: Record<string, unknown>;
9
11
  /** Each private dataset's pages, `{ dataset: { page: JSON } }`; the reader sees those `people` gives them. */
10
12
  private?: Record<string, Record<string, unknown>>;
11
- /** Each document the project starts with, by id; `writer` defaults to the reader. */
12
- documents?: Record<string, {
13
+ /** The project's collections, as research.json's `collections`. */
14
+ collections?: Collections;
15
+ /** The items the project starts with, written in order, each as its `writer`, the reader by default; a refused one throws, naming its outcome. */
16
+ items?: {
17
+ collection: string;
18
+ id: string;
13
19
  body: unknown;
14
20
  writer?: string;
15
- }>;
16
- /** The project's people, as research.json's `people`: each is a member, and `reader` holds their `pages`. */
21
+ }[];
22
+ /** The project's people, as research.json's `people`: each is a member, and `reader` holds their `pages`; without them, the reader is the one member. */
17
23
  people?: People;
18
24
  /** The project's roles, as research.json's `roles`; with them, `reader` must be in `people`. */
19
25
  roles?: string[];
20
- /** The reader's username, and the writer of every save: `testHost` holds this one identity. */
26
+ /** The reader's username, and the writer of every write: `testHost` holds this one identity. */
21
27
  reader?: string;
22
- /** False to view the project as `reader` while signed in as another; saves are still written as `reader`. */
28
+ /** False to view the project as `reader` while signed in as another; writes are still written as `reader`. */
23
29
  self?: boolean;
24
30
  /** The path below the project, with search and hash. */
25
31
  url?: string;
@@ -28,11 +34,20 @@ export interface TestHostOptions {
28
34
  }
29
35
  /**
30
36
  * A project rendered through the frame and the mount a real host uses, at the
31
- * path it names. Render `element` with any DOM renderer; `router` says where
32
- * the project navigated, and `documents()` what it saved, sorted by id.
37
+ * path it names, its store in memory. Render `element` with any DOM renderer;
38
+ * `router` says where the project navigated, `items()` each item's current
39
+ * revision in write order, and `host` is the `Host` the frame provides.
33
40
  */
34
- export declare function testHost(project: AnyProject, { data, documents, private: held, people, roles, reader, self, url, sessionLost, }?: TestHostOptions): {
35
- element: ReactElement<any, string | import("react").JSXElementConstructor<any>>;
41
+ export declare function testHost(project: AnyProject, { data, collections, items, private: held, people, roles, reader, self, url, sessionLost, }?: TestHostOptions): {
42
+ element: ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
36
43
  router: import("@tanstack/router-core").RouterCore<import("@tanstack/router-core").Route<import("@tanstack/react-router").Register, any, "/", "/", string, "__root__", undefined, {}, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, readonly [import("@tanstack/react-router").AnyRoute], unknown, unknown, unknown, undefined>, "preserve", false, import("@tanstack/history").RouterHistory, Record<string, any>>;
37
- documents: () => import("./types.js").Doc<unknown>[];
44
+ host: import("./types.js").Host;
45
+ items: () => {
46
+ collection: import("./collections.gen.js").components["schemas"]["CollectionName"];
47
+ writer: string;
48
+ id: import("./collections.gen.js").components["schemas"]["ItemID"];
49
+ revision: number;
50
+ sequence?: number;
51
+ body?: unknown;
52
+ }[];
38
53
  };