@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/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { AnyProject, Corpus, Doc, Host, Kind, Member, Paper, Mount, Project, Reader, RouterOf, } from './types.js';
1
+ export type { AnyProject, Body, CollectionSchemas, Corpus, Csl, Data, Edition, Host, Item, Judgment, Kind, Member, Paper, Register, Schema, Mount, Project, Reader, RouterOf, Work, WriteRequest, WriteResult, } from './types.js';
2
+ export { papers } from './corpus.js';
2
3
  export { defineProject } from './mount.js';
3
- export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, useMembers, usePrivate, useReader, useSaveDocument, } from './react.js';
4
- export { DocumentError } from './documents.js';
4
+ export { useCollection, useCorpus, useData, useDatas, useHost, useMembers, usePrivate, useReader, useWrite, WriteError, } from './react.js';
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
+ export { papers } from './corpus.js';
1
2
  export { defineProject } from './mount.js';
2
- export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, useMembers, usePrivate, useReader, useSaveDocument, } from './react.js';
3
- export { DocumentError } from './documents.js';
3
+ export { useCollection, useCorpus, useData, useDatas, useHost, useMembers, usePrivate, useReader, useWrite, WriteError, } from './react.js';
package/dist/mount.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type AnyRoute } from '@tanstack/react-router';
2
+ import type { CollectionSchemas, Schema, Schemas } from './types.js';
2
3
  declare function mountRoute<P extends string>(path: P): {
3
4
  root: import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>;
4
5
  route: import("@tanstack/react-router").Route<unknown, import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, P, import("@tanstack/react-router").ResolveFullPath<import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, P, import("@tanstack/router-core").RoutePrefix<"/", P>>, string, import("@tanstack/router-core").RoutePrefix<"__root__", P>, undefined, import("@tanstack/react-router").ResolveParams<P>, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>;
@@ -9,20 +10,26 @@ export type Mount<P extends string> = ReturnType<typeof mountRoute<P>>['route'];
9
10
  /** A project's routes under the first path segment it names. */
10
11
  export interface Project<P extends string = string, C = readonly AnyRoute[]> {
11
12
  readonly path: P;
13
+ readonly datasets: Record<string, Schema>;
14
+ readonly collections: Record<string, Schema>;
12
15
  routes(parent: Mount<P>): C;
13
16
  }
14
17
  /** Any project, for a list or a constraint: a `Project<'a'>` is not a `Project<string>`. */
15
18
  export interface AnyProject {
16
19
  readonly path: string;
20
+ readonly datasets: Record<string, Schema>;
21
+ readonly collections: Record<string, Schema>;
17
22
  routes(parent: never): readonly AnyRoute[];
18
23
  }
19
24
  /**
20
25
  * What `ui/index.tsx` and `ui/local/index.tsx` default-export. `path` is the
21
- * project's first URL segment, matching `^[a-z0-9][a-z0-9-]*$` and not
22
- * `projects`, `local` or `pdfjs`, which dev and the host reserve; `routes`
23
- * creates its routes against `parent`.
26
+ * project's first URL segment, matching `projectIdPattern` and not
27
+ * `projects`, `api`, `local` or `pdfjs`, which dev and the host reserve; `routes`
28
+ * creates its routes against `parent`; `datasets` and `collections` are
29
+ * ui/datasets.ts's exports, which `useData` and `usePrivate`, and
30
+ * `useCollection`, read the schemas from.
24
31
  */
25
- export declare function defineProject<P extends string, const C>(path: P, routes: (parent: Mount<P>) => C): Project<P, C>;
32
+ export declare function defineProject<P extends string, const C>(path: P, routes: (parent: Mount<P>) => C, datasets?: Schemas, collections?: CollectionSchemas): Project<P, C>;
26
33
  /** A project's `Register`: `router: RouterOf<typeof project>`. */
27
34
  export type RouterOf<R extends AnyProject> = ReturnType<R['routes']> extends infer C extends readonly AnyRoute[] ? ReturnType<typeof routerOf<R['path'], C>> : never;
28
35
  export {};
package/dist/mount.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRootRoute, createRoute, createRouter, } from '@tanstack/react-router';
2
- const format = /^[a-z0-9][a-z0-9-]*$/;
2
+ import { checkProjectId } from './project-id.js';
3
3
  // First segments that dev and the host serve themselves.
4
- const reserved = ['projects', 'local', 'pdfjs'];
4
+ const reserved = ['projects', 'api', 'local', 'pdfjs'];
5
5
  function mountRoute(path) {
6
6
  const root = createRootRoute();
7
7
  return { root, route: createRoute({ getParentRoute: () => root, path }) };
@@ -16,14 +16,20 @@ function routerOf(path, children) {
16
16
  }
17
17
  /**
18
18
  * What `ui/index.tsx` and `ui/local/index.tsx` default-export. `path` is the
19
- * project's first URL segment, matching `^[a-z0-9][a-z0-9-]*$` and not
20
- * `projects`, `local` or `pdfjs`, which dev and the host reserve; `routes`
21
- * creates its routes against `parent`.
19
+ * project's first URL segment, matching `projectIdPattern` and not
20
+ * `projects`, `api`, `local` or `pdfjs`, which dev and the host reserve; `routes`
21
+ * creates its routes against `parent`; `datasets` and `collections` are
22
+ * ui/datasets.ts's exports, which `useData` and `usePrivate`, and
23
+ * `useCollection`, read the schemas from.
22
24
  */
23
- export function defineProject(path, routes) {
24
- if (!format.test(path))
25
- throw new Error(`project path "${path}" does not match ${format}`);
25
+ export function defineProject(path, routes, datasets, collections) {
26
+ checkProjectId(path, 'project path');
26
27
  if (reserved.includes(path))
27
28
  throw new Error(`project path "${path}" is reserved by dev and the host`);
28
- return { path, routes };
29
+ return {
30
+ path,
31
+ routes,
32
+ datasets: datasets ?? {},
33
+ collections: collections ?? {},
34
+ };
29
35
  }
package/dist/papers.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { extname } from 'node:path';
3
+ import { papers } from './corpus.js';
3
4
  import { readCorpus } from './data.js';
4
5
  import { kinds } from './schema.js';
5
6
  export function git(root, ...args) {
@@ -28,8 +29,8 @@ export function checkPapers(root) {
28
29
  const lfs = new Map([...git(root, 'lfs', 'ls-files', '--long').matchAll(/^(\w+) [*-] (.+)$/gm)]
29
30
  .filter(([, , path]) => index.has(path))
30
31
  .map(([, oid, path]) => [path, oid]));
31
- const listed = new Map(Object.entries(readCorpus(root)).map(([sha, { kind }]) => [
32
- paperPath(sha, kind),
32
+ const listed = new Map([...papers(readCorpus(root))].map(([sha, { paper }]) => [
33
+ paperPath(sha, paper.kind),
33
34
  sha,
34
35
  ]));
35
36
  const unstored = (path, sha) => {
@@ -0,0 +1,25 @@
1
+ import type { Host } from './types.js';
2
+ /** One request of `parity`'s run, named the same on every host, and its answer: JSON, or null for a body that is not. */
3
+ export interface Exchange {
4
+ request: string;
5
+ status: number;
6
+ json: unknown;
7
+ }
8
+ /**
9
+ * A fixed run of requests through `host.store` at `host`'s URLs, and their
10
+ * answers: each dataset of `data`; for each private dataset of `private`, each
11
+ * of the reader's pages and the page it maps to, which the reader does not
12
+ * hold; and the collection routes, writes and refusals alike, each request
13
+ * carrying one fault. `collections` names a `document` and a `log` collection
14
+ * the reader may read and write, each accepting `{}` as a body. Reads keep
15
+ * only the run's items, and each `sequence` is its rank within the run, so two
16
+ * hosts' runs compare equal whatever each held before.
17
+ */
18
+ export declare function parity(host: Host, { data, private: held, collections: { document, log }, }: {
19
+ data: string[];
20
+ private: Record<string, string>;
21
+ collections: {
22
+ document: string;
23
+ log: string;
24
+ };
25
+ }): Promise<Exchange[]>;
package/dist/parity.js ADDED
@@ -0,0 +1,70 @@
1
+ import { maxWriteBytes } from './collections.gen.js';
2
+ import { match, urls } from './urls.js';
3
+ /**
4
+ * A fixed run of requests through `host.store` at `host`'s URLs, and their
5
+ * answers: each dataset of `data`; for each private dataset of `private`, each
6
+ * of the reader's pages and the page it maps to, which the reader does not
7
+ * hold; and the collection routes, writes and refusals alike, each request
8
+ * carrying one fault. `collections` names a `document` and a `log` collection
9
+ * the reader may read and write, each accepting `{}` as a body. Reads keep
10
+ * only the run's items, and each `sequence` is its rank within the run, so two
11
+ * hosts' runs compare equal whatever each held before.
12
+ */
13
+ export async function parity(host, { data, private: held, collections: { document, log }, }) {
14
+ const run = `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
15
+ const exchanges = [];
16
+ const sequences = new Set();
17
+ const send = async (request, url, init) => {
18
+ const response = await host.store(new Request(url, init));
19
+ const text = await response.text();
20
+ let json = null;
21
+ if (response.headers.get('Content-Type')?.startsWith('application/json')) {
22
+ const { items, ...rest } = JSON.parse(text);
23
+ json = JSON.parse(JSON.stringify(items
24
+ ? { ...rest, items: items.filter(({ id }) => id.startsWith(run)) }
25
+ : rest).replaceAll(run, 'run'), (key, value) => {
26
+ if (key === 'sequence' && typeof value === 'number')
27
+ sequences.add(value);
28
+ return value;
29
+ });
30
+ }
31
+ exchanges.push({ request, status: response.status, json });
32
+ };
33
+ const post = (request, body, type = 'application/json') => send(request, host.collections(), {
34
+ method: 'POST',
35
+ headers: { 'Content-Type': type },
36
+ body,
37
+ });
38
+ const write = (request, requestId, collection, id, revision) => post(request, JSON.stringify({
39
+ requestId: `${run}-${requestId}`,
40
+ items: [{ collection, id: `${run}.${id}`, revision, body: {} }],
41
+ }));
42
+ for (const dataset of data)
43
+ await send(`GET data ${dataset}`, host.data(dataset));
44
+ const { origin } = new URL(host.collections());
45
+ const { project } = match(host.collections());
46
+ for (const [dataset, other] of Object.entries(held)) {
47
+ for (const [page, url] of Object.entries(host.private(dataset)))
48
+ await send(`GET private ${dataset} ${page}`, url);
49
+ await send(`GET private ${dataset} ${other}, not the reader's`, origin + urls.private(project, other, dataset));
50
+ }
51
+ await write('POST new', '1', document, 'a', 0);
52
+ await write('POST the same request again', '1', document, 'a', 0);
53
+ await write('POST its request id with other items', '1', document, 'b', 0);
54
+ await write('POST at a stale revision', '2', document, 'a', 0);
55
+ await write('POST at its revision', '3', document, 'a', 1);
56
+ await write('POST a log entry', '4', log, 'e', 0);
57
+ await write('POST the log entry again', '5', log, 'e', 0);
58
+ await send('GET the document collection', host.collection(document));
59
+ await send('GET the log collection', host.collection(log));
60
+ await send('GET an undeclared collection', host.collection(`${run}-none`));
61
+ await send('GET a bad collection name', host.collection('Bad'));
62
+ await post('POST a body not JSON', '{}', 'text/plain');
63
+ await post('POST over the limit', `"${'x'.repeat(maxWriteBytes)}"`);
64
+ await post('POST no items', JSON.stringify({ requestId: run, items: [] }));
65
+ await write('POST to an undeclared collection', '6', `${run}-none`, 'a', 0);
66
+ const rank = [...sequences].sort((a, b) => a - b);
67
+ return JSON.parse(JSON.stringify(exchanges), (key, value) => key === 'sequence' && typeof value === 'number'
68
+ ? rank.indexOf(value) + 1
69
+ : value);
70
+ }
@@ -1,10 +1,10 @@
1
1
  import { expect, type Page } from '@playwright/test';
2
2
  declare const _default: import("@playwright/test").PlaywrightTestConfig<{}, {}>;
3
3
  export default _default;
4
- type Violation = `csp ${string} ${string}` | `axe ${string}`;
4
+ type Violation = `csp ${string} ${string}` | `axe ${string}` | `console ${string}` | `origin ${string}`;
5
5
  export declare const test: import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & {
6
6
  violations: Violation[];
7
- /** A page in a new context on the dev server, read as `reader`; `null` is signed out. The context takes the project's `contextOptions` and `baseURL`, no other `use` option. */
7
+ /** A page in a new context on the dev server, read as `reader`; `null` is signed out. The context takes the project's `use` options, as `page`'s does. */
8
8
  as: (reader: string | null) => Promise<Page>;
9
9
  }, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
10
10
  export { expect };
@@ -7,36 +7,58 @@ const server = `const index = require('node:url').pathToFileURL(require.resolve(
7
7
  export default defineConfig({
8
8
  testDir: 'browser',
9
9
  use: { baseURL: process.env.LIBRARY_RESEARCH_URL },
10
+ projects: [
11
+ { name: 'light', use: { colorScheme: 'light' } },
12
+ { name: 'dark', use: { colorScheme: 'dark' } },
13
+ ],
10
14
  webServer: {
11
15
  command: `"${process.execPath}" -e "${server}"`,
12
16
  wait: { stdout: /(?<library_research_url>http:\S+\/)/ },
13
17
  },
14
18
  });
15
- /** Collects a page's CSP and axe violations; the returned function fails on those not listed. */
16
- async function watch(page) {
19
+ /**
20
+ * Collects a page's CSP and axe violations, the console errors its own script logs or throws, and its requests to other origins; the returned function fails on those not listed. A request to another origin is aborted whether or not it is listed.
21
+ */
22
+ async function watch(page, baseURL) {
17
23
  const found = [];
18
24
  await page.exposeFunction(report, (v) => found.push(v));
25
+ // The browser's own console lines (a CSP refusal, a failed load) carry no arguments and are reported, or left to the spec, elsewhere.
26
+ page.on('console', (message) => {
27
+ if (message.type() === 'error' && message.args().length > 0)
28
+ found.push(`console ${message.text()}`);
29
+ });
30
+ page.on('pageerror', (error) => found.push(`console ${error}`));
31
+ await page.context().route('**/*', (route) => {
32
+ const { protocol, origin } = new URL(route.request().url());
33
+ if (!protocol.startsWith('http') || origin === new URL(baseURL).origin)
34
+ return route.fallback();
35
+ found.push(`origin ${origin}`);
36
+ return route.abort('blockedbyclient');
37
+ });
19
38
  await page.addInitScript(`window.${sent} = []; document.addEventListener('securitypolicyviolation', (e) => ${sent}.push(${report}('csp ' + e.effectiveDirective + ' ' + e.blockedURI)))`);
20
39
  return async (listed) => {
21
40
  await page.evaluate(`Promise.all(window.${sent} ?? [])`);
22
- const axe = await new AxeBuilder({ page }).analyze();
41
+ const axe = await new AxeBuilder({ page })
42
+ .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'])
43
+ .analyze();
23
44
  found.push(...axe.violations.map((v) => `axe ${v.id}`));
24
45
  expect(found.filter((v) => !listed.includes(v)), 'unlisted violations').toEqual([]);
25
46
  };
26
47
  }
27
48
  export const test = base.extend({
49
+ /** What a spec excuses, by entry: `axe <rule>`, `csp <directive> <blocked uri>`, `console <message>` for a console error or uncaught error, `origin <origin>` for a request to another origin (still aborted). */
28
50
  violations: [[], { option: true }],
29
- page: async ({ page, violations }, provide) => {
30
- const finish = await watch(page);
51
+ page: async ({ page, baseURL, violations }, provide) => {
52
+ const finish = await watch(page, baseURL);
31
53
  await provide(page);
32
54
  await finish(violations);
33
55
  },
34
- as: async ({ browser, baseURL, contextOptions, violations }, provide) => {
56
+ as: async ({ browser, baseURL, violations }, provide) => {
35
57
  const finishers = [];
36
58
  const contexts = [];
37
59
  try {
38
60
  await provide(async (reader) => {
39
- const context = await browser.newContext({ ...contextOptions, baseURL });
61
+ const context = await browser.newContext({ baseURL });
40
62
  contexts.push(context);
41
63
  await context.addCookies([
42
64
  {
@@ -47,7 +69,7 @@ export const test = base.extend({
47
69
  },
48
70
  ]);
49
71
  const page = await context.newPage();
50
- finishers.push(await watch(page));
72
+ finishers.push(await watch(page, baseURL));
51
73
  return page;
52
74
  });
53
75
  // Every page is checked, and the first failure is the one thrown.
@@ -0,0 +1,4 @@
1
+ /** What a project's id, its first URL segment and its key in the host's `projects`, matches. */
2
+ export declare const projectIdPattern: RegExp;
3
+ /** Throws unless `id` matches `projectIdPattern`, naming it as `what`. */
4
+ export declare function checkProjectId(id: string, what: string): void;
@@ -0,0 +1,7 @@
1
+ /** What a project's id, its first URL segment and its key in the host's `projects`, matches. */
2
+ export const projectIdPattern = /^[a-z0-9][a-z0-9-]*$/;
3
+ /** Throws unless `id` matches `projectIdPattern`, naming it as `what`. */
4
+ export function checkProjectId(id, what) {
5
+ if (!projectIdPattern.test(id))
6
+ throw new Error(`${what} "${id}" does not match ${projectIdPattern}`);
7
+ }
package/dist/react.d.ts CHANGED
@@ -1,58 +1,48 @@
1
- import { DocumentError } from './documents.js';
2
- import type { Corpus, Doc, Host, Member, Reader } from './types.js';
1
+ import type { components } from './collections.gen.js';
2
+ import type { Body, CollectionSchemas, Corpus, Data, Host, Item, Member, Reader, Schemas, WriteRequest } from './types.js';
3
3
  /** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
4
4
  export declare function useHost(): Host;
5
5
  /** The person the project is viewed as; `self` is false while the host views it as another. */
6
6
  export declare function useReader(): Reader;
7
7
  /** Every person of the project, each with their role. */
8
8
  export declare function useMembers(): Member[];
9
- type Dataset<T = unknown> = readonly [
10
- dataset: string,
11
- parse: (json: unknown) => T
12
- ];
13
9
  /**
14
- * One dataset's JSON, parsed by `parse`. Suspends while it loads; a failed
15
- * fetch or parse throws to the frame's error notice, naming the dataset. A 401 or
16
- * 403 also calls `Host.sessionLost`. `parse` must be pure: it is read once per
17
- * dataset list, not on every render.
10
+ * One dataset's JSON, parsed by its schema in `ui/datasets.ts`. Suspends while
11
+ * it loads; a failed fetch or parse throws to the frame's error notice,
12
+ * naming the dataset. A 401 or 403 also calls `Host.sessionLost`.
18
13
  */
19
- export declare function useData<T>(dataset: string, parse: (json: unknown) => T): T;
14
+ export declare function useData<K extends keyof Schemas>(dataset: K): Data<K>;
20
15
  /**
21
- * `useData` for several datasets at once, fetched in parallel: a `[dataset, parse]`
22
- * tuple each, the values returned in the same order and typed by their parsers.
23
- * Each parser must be pure: it is read once per dataset list, not on every render.
16
+ * `useData` for several datasets at once, fetched in parallel: the names in a
17
+ * tuple, the values returned in the same order and typed by their schemas.
24
18
  */
25
- export declare function useDatas<const R extends readonly Dataset[]>(datasets: R): {
26
- -readonly [K in keyof R]: R[K] extends Dataset<infer T> ? T : never;
19
+ export declare function useDatas<const R extends readonly (keyof Schemas)[]>(datasets: R): {
20
+ -readonly [K in keyof R]: R[K] extends keyof Schemas ? Data<R[K]> : never;
27
21
  };
28
22
  /**
29
23
  * The viewed person's pages of a private dataset, as `{ page: parsed }`: empty
30
24
  * when they hold none, a page the host names but the build did not emit left
31
- * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
32
- * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
25
+ * out. Its schema parses each page's JSON. Its cache entry, `{ json } | null`,
26
+ * is not `useData`'s raw JSON, under the same key prefix.
33
27
  */
34
- export declare function usePrivate<T>(dataset: string, parse: (json: unknown) => T): Record<string, T>;
35
- /** The `corpus` dataset, parsed by the library's own schema, through `useData`. */
28
+ export declare function usePrivate<K extends keyof Schemas>(dataset: K): Record<string, Data<K>>;
29
+ /** The `corpus` dataset, every work by id, parsed by the library's own schema. */
36
30
  export declare function useCorpus(): Corpus;
37
- /**
38
- * One document of the project, or `null` when none has that id. Suspends while
39
- * it loads; a failed read throws a `DocumentError` to the frame's error
40
- * notice. `parse` runs on the body only and must be pure.
41
- */
42
- export declare function useDocument<T>(id: string, parse: (json: unknown) => T): Doc<T> | null;
43
- /**
44
- * The project's documents whose id starts with `prefix`, sorted by id; every
45
- * save of the project refetches them. `parse` runs on each body and must be pure.
46
- */
47
- export declare function useDocuments<T>(prefix: string, parse: (json: unknown) => T): Doc<T>[];
48
- /**
49
- * Saves a JSON `body` as the document `id`, written by the signed-in person.
50
- * `when` makes the save conditional: `'absent'` refuses (412) if the document
51
- * exists, a revision refuses unless the document is at it; without it the
52
- * save replaces. A failure is the mutation's `error`, a `DocumentError`.
53
- */
54
- export declare function useSaveDocument(id: string): import("@tanstack/react-query").UseMutationResult<Doc<unknown>, DocumentError, {
55
- body: unknown;
56
- when?: "absent" | number;
57
- }, unknown>;
58
- export {};
31
+ /** The items of one collection the signed-in person may read, and `refresh` to read them again. */
32
+ export declare function useCollection<K extends keyof CollectionSchemas>(collection: K): {
33
+ items: Item<Body<K>>[];
34
+ refresh: () => Promise<void>;
35
+ };
36
+ /** A write the host refused. */
37
+ export declare class WriteError extends Error {
38
+ status: number;
39
+ /** The store's term for the refusal; absent where the status alone answers, such as 413. */
40
+ code?: components['schemas']['Outcome'];
41
+ /** For `stale` and `exists`, each item in conflict at the revision it holds, to retry from. */
42
+ conflicts: components['schemas']['Item'][];
43
+ constructor(status: number, code: WriteError['code'], conflicts?: WriteError['conflicts']);
44
+ }
45
+ /** Writes items across the project's collections in one atomic request: every item, or none. */
46
+ export declare function useWrite(): import("@tanstack/react-query").UseMutationResult<{
47
+ items: components["schemas"]["Item"][];
48
+ }, WriteError, WriteRequest, unknown>;