@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.
- package/README.md +65 -20
- package/dist/collection-store.d.ts +31 -0
- package/dist/collection-store.js +174 -0
- package/dist/collections.gen.d.ts +309 -0
- package/dist/collections.gen.js +190 -0
- package/dist/commands/add.js +29 -12
- package/dist/commands/dev.js +48 -44
- package/dist/commands/reshape.d.ts +2 -0
- package/dist/commands/reshape.js +21 -0
- package/dist/context.d.ts +5 -3
- package/dist/context.js +4 -2
- package/dist/corpus.d.ts +432 -0
- package/dist/corpus.js +348 -0
- package/dist/data.d.ts +13 -6
- package/dist/data.js +27 -15
- package/dist/datasets.d.ts +4 -1
- package/dist/datasets.js +48 -8
- package/dist/dev/host.js +6 -9
- package/dist/host.d.ts +17 -2
- package/dist/host.js +26 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/mount.d.ts +11 -4
- package/dist/mount.js +15 -9
- package/dist/papers.js +3 -2
- package/dist/parity.d.ts +25 -0
- package/dist/parity.js +70 -0
- package/dist/playwright.d.ts +2 -2
- package/dist/playwright.js +30 -8
- package/dist/project-id.d.ts +4 -0
- package/dist/project-id.js +7 -0
- package/dist/react.d.ts +32 -42
- package/dist/react.js +121 -118
- package/dist/schema.d.ts +19 -34
- package/dist/schema.js +47 -31
- package/dist/testing.d.ts +26 -11
- package/dist/testing.js +64 -26
- package/dist/types.d.ts +85 -26
- package/dist/urls.d.ts +35 -0
- package/dist/urls.js +58 -0
- package/dist/vite-config.js +2 -12
- package/dist/vite.d.ts +11 -2
- package/dist/vite.js +79 -25
- package/dist/zod.d.ts +2 -0
- package/dist/zod.js +4 -0
- package/package.json +19 -12
- package/schema/corpus.schema.json +3949 -29
- package/schema/project-id.schema.json +6 -0
- package/schema/research.schema.json +130 -2
- package/dist/document-store.d.ts +0 -14
- package/dist/document-store.js +0 -78
- package/dist/documents.d.ts +0 -10
- package/dist/documents.js +0 -22
package/README.md
CHANGED
|
@@ -7,8 +7,8 @@ The research-project contract and its tools
|
|
|
7
7
|
A project is this layout, each path fixed, which `npx @metacensus/library-research init` writes into an empty repository:
|
|
8
8
|
|
|
9
9
|
```
|
|
10
|
-
research.json title, datasets, private datasets, roles
|
|
11
|
-
corpus.json
|
|
10
|
+
research.json title, datasets, private datasets, roles, test people and collections
|
|
11
|
+
corpus.json works by DOI or citation key: CSL-JSON, editions, papers by sha
|
|
12
12
|
papers/<sha>.<kind> through LFS
|
|
13
13
|
ui/package.json depends on @metacensus/library-research, which brings @playwright/test; scripts dev, check and test
|
|
14
14
|
ui/tsconfig.json extends @metacensus/library-research/tsconfig.json
|
|
@@ -25,8 +25,9 @@ From `ui/`:
|
|
|
25
25
|
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
26
26
|
| `npm run dev -- [--reader NAME] [--port N]` | serves the project at `/<path>/` and `ui/local/`'s at `/local/<path>/`, live from the files, as reader `NAME` (else `local`) to a context that names none, under the host's CSP |
|
|
27
27
|
| `npm run check` | gates the project, one line per failure, as a host's build does |
|
|
28
|
-
| `npx playwright test` | runs `browser/` in Chromium on a dev server; a CSP or
|
|
28
|
+
| `npx playwright test` | runs `browser/` in Chromium, light and dark, on a dev server; a CSP, WCAG 2.2, console-error or other-origin violation fails its spec unless `violations` lists it |
|
|
29
29
|
| `npx library-research add <file> [--title T] [--citation C] [--open]` | adds a paper to `papers/` and `corpus.json` |
|
|
30
|
+
| `npx library-research reshape` | rewrites a legacy `corpus.json`, one sha per paper, as works under placeholder keys, and prints what waits on a person |
|
|
30
31
|
| `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 |
|
|
31
32
|
|
|
32
33
|
## Rendering
|
|
@@ -37,11 +38,31 @@ A project renders in the browser only: the host is one single-page app and each
|
|
|
37
38
|
|
|
38
39
|
Each key of research.json's `data` is a dataset, and `ui/datasets.ts` exports `datasets`, one Zod schema per dataset over the dataset's whole value; a glob dataset's is a `z.record` keyed by what its wildcard matched. The UI parses with it and `check` fails, one line per record file, on data that does not. A dataset with no schema fails, and `corpus.json` is no dataset: library-research's `Corpus` parses it.
|
|
39
40
|
|
|
41
|
+
`defineProject` takes `datasets` as its third argument, and `useData('items')` and `useDatas(['items', 'decisions'])` return what each name's schema parses, with no parser at the call. A project registers the types by augmenting `Register` beside its `defineProject`:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// ui/datasets.ts
|
|
45
|
+
export const roles = ['author', 'leader'] as const
|
|
46
|
+
export const datasets = { items: z.record(z.string(), Item) /* … */ }
|
|
47
|
+
|
|
48
|
+
// ui/index.tsx
|
|
49
|
+
declare module '@metacensus/library-research' {
|
|
50
|
+
interface Register {
|
|
51
|
+
datasets: typeof datasets
|
|
52
|
+
roles: (typeof roles)[number]
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
An undeclared name or a wrong result type then fails to compile. `roles` is the tuple research.json's `roles` copies: `check` fails when they differ.
|
|
58
|
+
|
|
59
|
+
A glob in `data` is relative, holds no `..`, at most one `*` and none of `?[]{}()!`; the grammar is in `schema/research.schema.json`.
|
|
60
|
+
|
|
40
61
|
## Private data
|
|
41
62
|
|
|
42
|
-
`research.json`'s `private` maps a dataset to a glob holding exactly one
|
|
63
|
+
`research.json`'s `private` maps a dataset to a glob holding exactly one `*` and otherwise the `data` grammar, such as `{ "private": { "ask": "research_notes/coauthors/*/questions.json" } }`. What the `*` matches is the page key, and the build emits each match at the host's `private(dataset)` URL (see [Routes](#routes)), never among the shared `data/` files. A host serves that path only to the people who hold the page. A page key matches `^[a-z0-9][a-z0-9-]*$` and a dataset is in `data` or `private`, not both; `check` fails otherwise, naming the dataset.
|
|
43
64
|
|
|
44
|
-
`usePrivate(dataset
|
|
65
|
+
`usePrivate(dataset)` returns `{ page: parsed }` for the pages the host names for the person the project is viewed as: none, one or several, and a page not yet built is left out. `Object.values(usePrivate('ask'))` is that person's questions. The dataset's schema in `ui/datasets.ts` parses one page's file, and `load` returns the dataset as `{ page: parsed }`. A host's `private(dataset)` returns the page-to-URL map.
|
|
45
66
|
|
|
46
67
|
In `dev` and `testHost`, a reader holds the pages [`people`](#people) gives them, and `testHost`'s `private: { dataset: { page: json } }` holds each page's JSON.
|
|
47
68
|
|
|
@@ -51,14 +72,39 @@ Node loads `ui/datasets.ts` by stripping its types: no `enum` or namespace, rela
|
|
|
51
72
|
|
|
52
73
|
`research.json`'s optional `roles` lists the roles a person of the project holds one of, each matching `^[a-z][a-z0-9-]*$`, none repeated: `{ "roles": ["author", "leader"] }`.
|
|
53
74
|
|
|
54
|
-
- `useReader()` returns the host's `reader`, the person the project is viewed as: `{ username, name, role, self }`. `role` is one of `roles
|
|
75
|
+
- `useReader()` returns the host's `reader`, the person the project is viewed as: `{ username, name, role, self }`. `role` is one of `roles` (`Register`'s union where the project declares it), or null in a project that declares none. `self` is false while the host views the project as a person other than the one signed in.
|
|
55
76
|
- `useMembers()` returns the host's `members`, every person of the project, each `{ username, name, role }`.
|
|
56
77
|
|
|
57
78
|
In `dev` and `testHost`, `research.json`'s optional `people` stands in for production's people.json: it maps a username to `{ name, role, pages }`, `role` and `pages` optional, as `{ "people": { "dan.hertz": { "name": "Hertz", "role": "author", "pages": ["hertz"] } } }`. Every entry is a member. `dev --reader dan.hertz` and `testHost`'s `reader: 'dan.hertz'` serve that person as `reader` with `self` true, holding `hertz`'s page; another page answers 403. In a project that declares `roles`, a reader `people` omits is refused, naming them: by `testHost`, by `dev` before it serves when `--reader` names them, and by a `dev` page read as them, the default `local` included; in one that declares none, such a reader is served with their username as `name`, no role and no pages, and is no member. `check` fails, naming the person, on a role not in `roles`, on a person with no role where the project declares roles, and on a person with a role where it declares none. Production ignores `people`.
|
|
58
79
|
|
|
80
|
+
## Collections
|
|
81
|
+
|
|
82
|
+
`research.json`'s optional `collections` declares the project's collections in the API's `Collections` schema, by name: each a `mode`, a JSON Schema `body`, and `read` and `write` grants, as `{ "collections": { "reviews": { "mode": "log", "body": { "type": "object" }, "read": [{ "own": true }], "write": [{ "roles": ["author"] }] } } }`. `check` fails on a declaration off that schema, on a grant naming a role `roles` does not declare, and on a gate whose collection is not a `log`, as the API refuses such a manifest.
|
|
83
|
+
|
|
84
|
+
`ui/datasets.ts` exports `collections`, one Zod schema per collection over an item's body, registered as `Register['collections']` and passed to `defineProject` as its fourth argument. Once `ui/datasets.ts` exports `collections`, `check` fails, one line per collection, on a collection one of the two lacks, or on a schema whose JSON Schema (`z.toJSONSchema`, without `$schema`) is not research.json's `body`, printing the one it expects:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// ui/datasets.ts
|
|
88
|
+
export const collections = { reviews: z.object({ text: z.string() }) }
|
|
89
|
+
declare module '@metacensus/library-research' {
|
|
90
|
+
interface Register {
|
|
91
|
+
collections: typeof collections
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
- `useCollection('reviews')` returns `{ items, refresh }`: the items the signed-in person may read, each `{ collection, writer, id, revision, sequence, body }` at its current revision, in write order, the body parsed by its schema. It suspends while it loads; a failed read or parse throws to the frame's error notice, naming the collection and the item. `refresh()` reads it again, and rejects when that read fails.
|
|
97
|
+
- `useWrite()` is a mutation taking `{ requestId, items: [{ collection, id, revision, body }] }`, which writes every item or none, each `body` typed by its `collection`. `revision` is the item's current revision, or `0` for a new one; a retry of the same write reuses its `requestId`, and a new write takes a new one. A write, and a write refused 409, read each collection it names again.
|
|
98
|
+
- A refused write is the mutation's `error`, a `WriteError` with its status and a code (`stale`, `exists`, `forbidden`, `invalid`, `full` or `unauthenticated`; absent for 413 and 415); `stale` and `exists` carry `conflicts` at their current revisions.
|
|
99
|
+
- An item is keyed by its writer and id, so an id is the writer's alone. The `writer` is the signed-in person, set by the store.
|
|
100
|
+
- A 401 on either hook, and a read's 403, call `Host.sessionLost`; a write's 403 is a refused grant.
|
|
101
|
+
- `dev` and `testHost` serve one in-memory store with the API's checks and outcomes, which `make check` runs every scenario of the API's `api/scenarios/` through; a restart empties it. In a project without `people`, the reader is its one member.
|
|
102
|
+
|
|
103
|
+
`contract/` is service-api-research pinned at a commit. `make contract` clones it and rewrites `src/collections.gen.ts`, the types of the two collection routes and of the schemas they and `Collections` reach, and `test/scenario.gen.ts`, the scenarios' types; both are committed, and `make generated`, in `check`, fails when either differs. Moving the pin is `git -C contract checkout <sha>`, then `make contract`, in one PR.
|
|
104
|
+
|
|
59
105
|
## Routes
|
|
60
106
|
|
|
61
|
-
A project default-exports `defineProject('<path>', routes)`: its first URL segment, matching `^[a-z0-9][a-z0-9-]*$` and not `projects`, `local` or `pdfjs` (dev and the host reserve them), and its routes created against the `parent` it is handed, a route at that path; the host owns the router. `Register` types the project's own links. A link names its path in full and passes `from="/<path>"`, so a wrong path fails to compile:
|
|
107
|
+
A project default-exports `defineProject('<path>', routes, datasets, collections)`: its first URL segment, a project id matching `^[a-z0-9][a-z0-9-]*$` (`projectIdPattern` from `@metacensus/library-research/host`, and `schema/project-id.schema.json`) and not `projects`, `api`, `local` or `pdfjs` (dev and the host reserve them), and its routes created against the `parent` it is handed, a route at that path; the host owns the router. `Register` types the project's own links. A link names its path in full and passes `from="/<path>"`, so a wrong path fails to compile:
|
|
62
108
|
|
|
63
109
|
```tsx
|
|
64
110
|
const dpyd = defineProject('dpyd', (parent) => [
|
|
@@ -75,24 +121,23 @@ declare module '@tanstack/react-router' {
|
|
|
75
121
|
|
|
76
122
|
A host mounts each project with `mount(parent, project, options)` from `@metacensus/library-research/host`: it creates the route at the path the project names, with `options` as the route's options, adds the project's routes, and returns it. Two projects at one path are refused by TanStack's duplicate-route-id check, in development builds only.
|
|
77
123
|
|
|
78
|
-
`
|
|
124
|
+
A host builds with `research({ projects })` and `tailwind({ projects })` from `@metacensus/library-research/vite`, `projects` mapping each project's id to its directory: `plugins: [react(), research({ projects }), tailwind({ projects })]`. It builds with library-research's `tailwindcss` and `@tailwindcss/vite`, and carries neither of its own. The host's stylesheet opens with `@layer theme, base, mc, components, utilities;`, then `@import "tailwindcss";` and `@import "@metacensus/library-ui/theme.css";`; each project's `ui/` becomes a source of the stylesheet a module or `index.html` loads, not of one reached through a nested CSS `@import`. The same stylesheet paints `body` with library-ui's `--mc-ground` and `--mc-ink`, so a page reads as its readers see it in either color scheme. A project's stylesheets `@apply` Tailwind's and library-ui's utilities as they are.
|
|
79
125
|
|
|
80
|
-
|
|
126
|
+
`options` takes `frame(useHost)`, spread in: it provides the `Host` that `useHost` returns, shows a resettable error and an announced loading state. `createHost({ project, reader, members, pages, store, sessionLost, origin })` from `./host` builds that `Host`: `pages` the viewed person's private pages, `origin` what the URLs are under (default `location.origin`). Every hook fetches through `store`. The URLs are one rule, each segment `encodeURIComponent`ed:
|
|
81
127
|
|
|
82
|
-
|
|
128
|
+
| `Host` field | URL |
|
|
129
|
+
| ------------------ | --------------------------------------------------- |
|
|
130
|
+
| `data(dataset)` | `/projects/{project}/data/{dataset}.json` |
|
|
131
|
+
| `private(dataset)` | `/projects/{project}/private/{page}/{dataset}.json` |
|
|
132
|
+
| `paper(sha)` | `/api/papers/{project}/{sha}` |
|
|
133
|
+
| `collections()` | `/api/projects/{project}/collections` |
|
|
134
|
+
| `collection(name)` | `/api/projects/{project}/collections/{name}` |
|
|
83
135
|
|
|
84
|
-
|
|
85
|
-
- `useDocuments(prefix, parse)` lists the documents whose id starts with `prefix`.
|
|
86
|
-
- `useSaveDocument(id)` is a mutation taking `{ body, when }`. `when` is `'absent'` (refuse if the document exists) or a `revision` (refuse unless the document is at it).
|
|
87
|
-
- A refused save, a 412 or a 413, is the mutation's `error`: a `DocumentError` with its `status`.
|
|
88
|
-
- Ids match `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`; a body is at most 256 KiB.
|
|
89
|
-
- The `writer` is the signed-in person, set by the store.
|
|
90
|
-
- A host's `document(id)` and `documents(prefix)` return the URLs of the store's routes.
|
|
91
|
-
- `dev` keeps one in-memory store for every reader; a restart empties it.
|
|
136
|
+
A host sets no `defaultPendingComponent` or `defaultErrorComponent` on its router, which would override the frame's for a project's routes. A host serves `@metacensus/library-research/csp.json` as its Content-Security-Policy (directive → sources, adding its own origins and nonces) and `pdfAssets`, `/pdfjs/`, for `configurePdf({ assets })`.
|
|
92
137
|
|
|
93
138
|
## Testing
|
|
94
139
|
|
|
95
|
-
`testHost(project, { data, private,
|
|
140
|
+
`testHost(project, { data, private, collections, items, people, roles, reader, self, url, sessionLost })` from `@metacensus/library-research/testing` returns `{ element, router, host, items }`: the project in the frame and mount a real host uses, at its path, its `Host` built by `createHost` over an in-memory store, `data` giving each dataset's JSON (a dataset it omits answers 404), `people`, `roles` and `collections` as research.json's, `reader` the username (default `test`) and the writer of every write, `self` false to view the project as `reader` while signed in as another (default true; `testHost` holds the one identity, so writes are still `reader`'s), `items` the items the project starts with as `[{ collection, id, body, writer? }]`, written in order, a refused one throwing, `url` the path below the project (default `/`). Render `element` with any DOM renderer; `router.state.location` says where the project navigated, and `items()` each current item's `{ collection, writer, id, revision, sequence }`, in write order. `parity(host, { data, private, collections: { document, log } })` from `./testing` runs a fixed set of requests through `host.store`, writing to a `document` and a `log` collection the reader may read and write, each accepting `{}` as a body, and returns the answers, which two hosts serving the same files return equally. `membersOf(research.people)` and `readerOf(research, username, self)` from `./testing` build the `members` and `reader` `testHost` serves, so a fixture reads them from research.json rather than copying them. `init` scaffolds `ui/index.test.tsx` on vitest, jsdom and Testing Library, which a project installs itself.
|
|
96
141
|
|
|
97
142
|
```tsx
|
|
98
143
|
render(
|
|
@@ -100,7 +145,7 @@ render(
|
|
|
100
145
|
)
|
|
101
146
|
```
|
|
102
147
|
|
|
103
|
-
One dev server serves several readers: a browser context names its reader by the cookie `library-research-reader`, and an empty one is signed out, so data answers 401 and the host reports the session lost. In a browser spec, `as(reader)` opens a page in a new context read as `reader` (`null` signed out), each checked for CSP and axe violations as `page` is.
|
|
148
|
+
One dev server serves several readers: a browser context names its reader by the cookie `library-research-reader`, and an empty one is signed out, so data answers 401 and the host reports the session lost. In a browser spec, `as(reader)` opens a page in a new context read as `reader` (`null` signed out), each checked for CSP and axe violations as `page` is. The context takes the project's `use` options, as `page`'s does. A leftover `library-research-reader` cookie in a browser overrides `--reader`:
|
|
104
149
|
|
|
105
150
|
```ts
|
|
106
151
|
test('a leader sees what an author saved', async ({ as }) => {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type Collections, type components } from './collections.gen.js';
|
|
2
|
+
import type { Route } from './urls.js';
|
|
3
|
+
type Schemas = components['schemas'];
|
|
4
|
+
type Item = Schemas['Item'];
|
|
5
|
+
type Outcome = Schemas['Outcome'];
|
|
6
|
+
/** How a request ended: for `ok` and `replayed`, the items written or read; for `stale` and `exists`, those in conflict. */
|
|
7
|
+
export interface Answer {
|
|
8
|
+
outcome: Outcome;
|
|
9
|
+
items: Item[];
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A project's collections as service-api-research serves them, held in
|
|
13
|
+
* memory: its checks in their order, its outcomes, and its answers to a
|
|
14
|
+
* request `match` reads as a collection route. `people` are the project's
|
|
15
|
+
* members, each with their role; a person `undefined` holds no session.
|
|
16
|
+
*/
|
|
17
|
+
export declare function collectionStore({ collections, people, }: {
|
|
18
|
+
collections?: Collections;
|
|
19
|
+
people?: Record<string, {
|
|
20
|
+
role?: string;
|
|
21
|
+
}>;
|
|
22
|
+
}): {
|
|
23
|
+
write: (person: string | undefined, request: unknown) => Answer;
|
|
24
|
+
read: (person: string | undefined, collection: string) => Answer | undefined;
|
|
25
|
+
handle(request: Request, route: Extract<Route, {
|
|
26
|
+
route: "collections" | "collection";
|
|
27
|
+
}>, person: string | undefined): Promise<Response>;
|
|
28
|
+
/** Every current item, in sequence order. */
|
|
29
|
+
items: () => Item[];
|
|
30
|
+
};
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { collectionName, maxWriteBytes, status, writeRequest, } from './collections.gen.js';
|
|
2
|
+
import { z } from './zod.js';
|
|
3
|
+
const WriteRequest = z.fromJSONSchema(writeRequest);
|
|
4
|
+
const namePattern = new RegExp(collectionName.pattern);
|
|
5
|
+
/** `value` as JSON with every object's keys sorted, so equal values print alike. */
|
|
6
|
+
const canonical = (value) => JSON.stringify(value, (_, v) => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
7
|
+
? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : 1)))
|
|
8
|
+
: v);
|
|
9
|
+
const json = (code, value) => new Response(value === undefined ? null : JSON.stringify(value), {
|
|
10
|
+
status: code,
|
|
11
|
+
headers: {
|
|
12
|
+
'Cache-Control': 'private, no-cache',
|
|
13
|
+
...(value === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
14
|
+
},
|
|
15
|
+
});
|
|
16
|
+
/** An answer as the API sends it: 201 for a write's `ok`, 200 for a read or a replay, else `Error` at its status. */
|
|
17
|
+
const respond = ({ outcome, items }, written) => outcome === 'ok' || outcome === 'replayed'
|
|
18
|
+
? json(outcome === 'ok' && written ? 201 : 200, { items })
|
|
19
|
+
: json(status[outcome], {
|
|
20
|
+
code: outcome,
|
|
21
|
+
...(items.length ? { conflicts: items } : {}),
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* A project's collections as service-api-research serves them, held in
|
|
25
|
+
* memory: its checks in their order, its outcomes, and its answers to a
|
|
26
|
+
* request `match` reads as a collection route. `people` are the project's
|
|
27
|
+
* members, each with their role; a person `undefined` holds no session.
|
|
28
|
+
*/
|
|
29
|
+
export function collectionStore({ collections = {}, people = {}, }) {
|
|
30
|
+
const stored = [];
|
|
31
|
+
const requests = new Map();
|
|
32
|
+
const bodies = Object.fromEntries(Object.entries(collections).map(([named, { body }]) => [
|
|
33
|
+
named,
|
|
34
|
+
z.fromJSONSchema(body),
|
|
35
|
+
]));
|
|
36
|
+
const refuse = (outcome, items = []) => ({ outcome, items });
|
|
37
|
+
const admit = (person) => person === undefined
|
|
38
|
+
? refuse('unauthenticated')
|
|
39
|
+
: Object.hasOwn(people, person)
|
|
40
|
+
? undefined
|
|
41
|
+
: refuse('forbidden');
|
|
42
|
+
// A grant's conditions, for `person`; `members` holds for every member.
|
|
43
|
+
const holds = ({ roles, after }, person) => {
|
|
44
|
+
const role = people[person]?.role;
|
|
45
|
+
return ((!roles || (role !== undefined && roles.includes(role))) &&
|
|
46
|
+
(!after ||
|
|
47
|
+
stored.some((it) => it.collection === after.collection && it.id === after.id)));
|
|
48
|
+
};
|
|
49
|
+
const current = (collection, writer, id) => stored
|
|
50
|
+
.filter((it) => it.collection === collection && it.writer === writer && it.id === id)
|
|
51
|
+
.at(-1);
|
|
52
|
+
const shown = (it) => {
|
|
53
|
+
const item = { ...it };
|
|
54
|
+
delete item.body;
|
|
55
|
+
return item;
|
|
56
|
+
};
|
|
57
|
+
const latest = (keep) => {
|
|
58
|
+
const found = new Map();
|
|
59
|
+
for (const it of stored)
|
|
60
|
+
if (keep(it))
|
|
61
|
+
found.set(canonical([it.collection, it.writer, it.id]), it);
|
|
62
|
+
return [...found.values()].sort((a, b) => a.sequence - b.sequence);
|
|
63
|
+
};
|
|
64
|
+
function write(person, request) {
|
|
65
|
+
const refused = admit(person);
|
|
66
|
+
if (refused)
|
|
67
|
+
return refused;
|
|
68
|
+
const writer = person;
|
|
69
|
+
const parsed = WriteRequest.safeParse(request);
|
|
70
|
+
if (!parsed.success)
|
|
71
|
+
return refuse('invalid');
|
|
72
|
+
const { requestId, items } = parsed.data;
|
|
73
|
+
const named = new Set();
|
|
74
|
+
for (const { collection, id } of items) {
|
|
75
|
+
const key = canonical([collection, id]);
|
|
76
|
+
if (!Object.hasOwn(collections, collection) || named.has(key))
|
|
77
|
+
return refuse('invalid');
|
|
78
|
+
named.add(key);
|
|
79
|
+
}
|
|
80
|
+
const digest = canonical(items);
|
|
81
|
+
const replay = requests.get(canonical([writer, requestId]));
|
|
82
|
+
if (replay)
|
|
83
|
+
return replay.digest === digest
|
|
84
|
+
? { outcome: 'replayed', items: replay.items }
|
|
85
|
+
: refuse('exists');
|
|
86
|
+
if (!items.every(({ collection }) => collections[collection].write.some((grant) => holds(grant, writer))))
|
|
87
|
+
return refuse('forbidden');
|
|
88
|
+
if (!items.every(({ collection, body }) => bodies[collection].safeParse(body).success))
|
|
89
|
+
return refuse('invalid');
|
|
90
|
+
const conflicts = [];
|
|
91
|
+
let refusal;
|
|
92
|
+
for (const { collection, id, revision } of items) {
|
|
93
|
+
const have = current(collection, writer, id)?.revision ?? 0;
|
|
94
|
+
const log = collections[collection].mode === 'log';
|
|
95
|
+
const stale = log ? revision !== 0 : revision !== have;
|
|
96
|
+
if (stale)
|
|
97
|
+
refusal = 'stale';
|
|
98
|
+
else if (log && have !== 0)
|
|
99
|
+
refusal ??= 'exists';
|
|
100
|
+
else
|
|
101
|
+
continue;
|
|
102
|
+
if (have !== 0)
|
|
103
|
+
conflicts.push({ collection, writer, id, revision: have });
|
|
104
|
+
}
|
|
105
|
+
if (refusal)
|
|
106
|
+
return refuse(refusal, conflicts);
|
|
107
|
+
const written = items.map(({ collection, id, revision, body }) => {
|
|
108
|
+
const item = {
|
|
109
|
+
collection,
|
|
110
|
+
writer,
|
|
111
|
+
id,
|
|
112
|
+
revision: revision + 1,
|
|
113
|
+
sequence: stored.length + 1,
|
|
114
|
+
body,
|
|
115
|
+
};
|
|
116
|
+
stored.push(item);
|
|
117
|
+
return shown(item);
|
|
118
|
+
});
|
|
119
|
+
requests.set(canonical([writer, requestId]), { digest, items: written });
|
|
120
|
+
return { outcome: 'ok', items: written };
|
|
121
|
+
}
|
|
122
|
+
/** `collection`'s items `person` may read, each at its current revision; undefined when the project declares no such collection. */
|
|
123
|
+
function read(person, collection) {
|
|
124
|
+
const refused = admit(person);
|
|
125
|
+
if (refused)
|
|
126
|
+
return refused;
|
|
127
|
+
if (!namePattern.test(collection))
|
|
128
|
+
return refuse('invalid');
|
|
129
|
+
if (!Object.hasOwn(collections, collection))
|
|
130
|
+
return;
|
|
131
|
+
const grants = collections[collection].read.filter((grant) => holds(grant, person));
|
|
132
|
+
const all = grants.some((grant) => !grant.own);
|
|
133
|
+
const own = grants.some((grant) => grant.own);
|
|
134
|
+
return {
|
|
135
|
+
outcome: 'ok',
|
|
136
|
+
items: latest((it) => it.collection === collection &&
|
|
137
|
+
(all || (own && it.writer === person))),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
write,
|
|
142
|
+
read,
|
|
143
|
+
async handle(request, route, person) {
|
|
144
|
+
if (route.route === 'collection') {
|
|
145
|
+
if (request.method !== 'GET')
|
|
146
|
+
return json(405);
|
|
147
|
+
const answer = read(person, route.collection);
|
|
148
|
+
return answer ? respond(answer, false) : json(404);
|
|
149
|
+
}
|
|
150
|
+
if (request.method !== 'POST')
|
|
151
|
+
return json(405);
|
|
152
|
+
// In service-api-research's middleware order: the media type, then the session.
|
|
153
|
+
const type = request.headers.get('Content-Type')?.split(';')[0]?.trim();
|
|
154
|
+
if (type?.toLowerCase() !== 'application/json')
|
|
155
|
+
return json(415);
|
|
156
|
+
const refused = admit(person);
|
|
157
|
+
if (refused)
|
|
158
|
+
return respond(refused, true);
|
|
159
|
+
const text = await request.text();
|
|
160
|
+
if (new TextEncoder().encode(text).length > maxWriteBytes)
|
|
161
|
+
return json(413);
|
|
162
|
+
let body;
|
|
163
|
+
try {
|
|
164
|
+
body = JSON.parse(text);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return respond(refuse('invalid'), true);
|
|
168
|
+
}
|
|
169
|
+
return respond(write(person, body), true);
|
|
170
|
+
},
|
|
171
|
+
/** Every current item, in sequence order. */
|
|
172
|
+
items: () => latest(() => true).map(shown),
|
|
173
|
+
};
|
|
174
|
+
}
|