stanford-openarch 0.0.0 → 0.1.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/cli/init.js ADDED
@@ -0,0 +1,511 @@
1
+ // init.js — `openarch member init`: from a catalog and a folder of files to a running member,
2
+ // with no code to write (2026-11-26, Daniel: the member path must be flawless).
3
+ //
4
+ // It asks who the archive is, where it will live, where its catalog is; reads the catalog's
5
+ // columns and guesses which is which (the member confirms or corrects each, with a preview);
6
+ // asks the declarations once, and the sharing question only for the kinds of material the
7
+ // catalog actually holds. Then it writes a member that runs on the kit:
8
+ //
9
+ // openarch-member.json everything the member serves, in one file it can edit
10
+ // index.js three lines: start the kit
11
+ // package.json · .env the kit as a dependency; a provisional hub credential (never sent anywhere)
12
+ // deploy/ a Dockerfile, a systemd unit and a Caddyfile for going live
13
+ // README.md the next steps
14
+ //
15
+ // and loads the catalog once, so a problem shows now, with its line, not at the first search.
16
+ // On a pipe there is nobody to ask: --answers <file.json> (the same answers as JSON), or
17
+ // --example for the demonstration archive. Never the example silently (walkthrough finding 14).
18
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, readdirSync, statSync, copyFileSync, rmSync, realpathSync } from "node:fs";
19
+ import { join, resolve, relative, dirname, isAbsolute, basename, extname, sep, posix } from "node:path";
20
+ import { isPublicHttps } from "./check.js";
21
+ import { randomBytes } from "node:crypto";
22
+ import { parseCsv } from "../members/kit/csv.js";
23
+ import { refusal, writeReplacing } from "./safeFile.js";
24
+ import { readConfig, loadCatalog, kindOf } from "../members/kit/catalog.js";
25
+ import { RIGHTS_BASIS, REUSE_GRANT, MATERIAL_KINDS, SERVE_MODES, WITHHOLD_REASONS } from "../server/lib/vocabulary.js";
26
+
27
+ /** The member kit's npm package: the dependency key and the import every generated member uses.
28
+ * It was "openarch", a name that on the public npm registry is someone else's, so a name-based
29
+ * npm run (npm audit fix --force) could swap the kit for their code (ind-sec run-3 P2). */
30
+ export const KIT_PACKAGE = "stanford-openarch";
31
+
32
+ const GUESS = {
33
+ id: ["accession", "identifier", "id", "doc_id", "docid", "record_id", "item_id", "call_number", "callnumber", "bates", "object_id"],
34
+ title: ["title", "name", "headline", "subject", "label"],
35
+ date: ["date", "year", "created", "date_created", "issued", "date_issued"],
36
+ authors: ["author", "authors", "creator", "creators", "by", "sender", "from"],
37
+ collection: ["collection", "series", "fonds", "subseries", "set", "record_group"],
38
+ type: ["type", "doctype", "document_type", "genre", "format"],
39
+ file: ["file", "filename", "file_name", "path", "file_path", "pdf", "scan", "image", "media"],
40
+ text: ["transcript", "text", "ocr", "fulltext", "full_text", "transcription", "txt", "ocr_text"],
41
+ source_url: ["source_url", "url", "link", "source", "uri"],
42
+ pages: ["pages", "page_count", "pagecount", "num_pages", "number_of_pages"],
43
+ };
44
+ const FIELD_NOTE = {
45
+ id: "a unique, unchanging identifier for each document (letters, digits, . _ ~ -)",
46
+ title: "the document's title",
47
+ date: "its date (YYYY, YYYY-MM or YYYY-MM-DD), optional",
48
+ authors: "who made it; several separated by ;, optional",
49
+ collection: "which collection a row belongs to, optional",
50
+ type: "letter, report, minutes …, optional",
51
+ file: "the path of its file (PDF, image …) relative to the catalog; several separated by ;, optional",
52
+ text: "its text: the path of a .txt file, or the text itself, optional",
53
+ source_url: "where the original lives, optional",
54
+ pages: "how many pages it has (a number), optional",
55
+ };
56
+ const norm = (h) => h.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
57
+ export const slugify = (s) => String(s).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "archive";
58
+ export function guessColumns(header) {
59
+ const byNorm = new Map(header.map((h) => [norm(h), h]));
60
+ const out = {}, used = new Set();
61
+ for (const [field, names] of Object.entries(GUESS)) for (const n of names) { const h = byNorm.get(n); if (h && !used.has(h)) { out[field] = h; used.add(h); break; } }
62
+ return out;
63
+ }
64
+
65
+ /** Why an answer cannot be the public address (null when it can). Asked at its own prompt, so a
66
+ * test address is caught there and not 25 questions later (walkthrough 2, finding 9). */
67
+ export function publicBaseProblem(a) {
68
+ let u; try { u = new URL(String(a).trim()); } catch { return "that is not an address; it looks like https://openarch.your-library.edu"; }
69
+ if (u.pathname.replace(/\/+$/, "") || u.search || u.hash) return "give the address alone, with no path (https://openarch.your-library.edu): the adapter answers at its root, and every permalink is built from it";
70
+ if (!isPublicHttps(`https://${u.host}`)) return `${u.host} is on this machine or a private network. This is the address the hub will reach over the internet, and permalinks and citations are built from it. Testing here needs none: npm start serves the adapter on this machine, and openarch member check finds it. Give the public address you plan to use; it can change later, in openarch-member.json`;
71
+ if (u.protocol !== "https:") return "the hub reaches members over https only: https://" + u.host;
72
+ return null;
73
+ }
74
+ /** Why an answer cannot be the pattern of the archive's own document pages (null when it can). */
75
+ export function permalinkPatternProblem(p) {
76
+ const t = String(p ?? "").trim();
77
+ if ((t.match(/\{id\}/g) || []).length !== 1) return "put {id} once, where the document's id goes: https://library.example.edu/item/{id}";
78
+ let u; try { u = new URL(t.replace("{id}", "x")); } catch { return "that is not an address: https://library.example.edu/item/{id}"; }
79
+ if (u.protocol !== "https:") return "permalinks are https addresses";
80
+ if (t.length > 300) return "at most 300 characters";
81
+ return null;
82
+ }
83
+
84
+ /** Every row of the catalog (peekCatalog keeps the first 2,000 of a JSONL file). */
85
+ function allRows(path, peek) {
86
+ if (!/\.jsonl?$/i.test(path)) return peek.rows;
87
+ return readFileSync(path, "utf8").split(/\r?\n/).filter((l) => l.trim()).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
88
+ }
89
+ const fmtBytes = (n) => n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(1)} GB` : n >= 1024 ** 2 ? `${(n / 1024 ** 2).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`;
90
+
91
+ /** Read the catalog's header and first rows (CSV, TSV or JSONL). */
92
+ export function peekCatalog(path) {
93
+ const raw = readFileSync(path, "utf8");
94
+ if (/\.jsonl?$/i.test(path)) {
95
+ const rows = raw.split(/\r?\n/).filter((l) => l.trim()).slice(0, 2000).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
96
+ return { header: [...new Set(rows.flatMap((r) => Object.keys(r)))], rows, total: raw.split(/\r?\n/).filter((l) => l.trim()).length };
97
+ }
98
+ const p = parseCsv(raw);
99
+ return { header: p.header, rows: p.rows, total: p.rows.length, problems: p.problems };
100
+ }
101
+
102
+ const ENV = (cred, port) => `# openarch member — this adapter's environment. Never commit this file.
103
+ #
104
+ # OPENARCH_HUB_CREDENTIAL is the secret the hub presents on every call. This one is
105
+ # PROVISIONAL: openarch member init made it so you can test the gate before you apply. It
106
+ # has never been sent anywhere. When the hub approves you, the operator sends you the
107
+ # hub's own credential: run openarch member credential set here (it asks), which replaces
108
+ # this line (only its SHA-256 is needed on the server: OPENARCH_HUB_CREDENTIAL_SHA256).
109
+ OPENARCH_HUB_CREDENTIAL=${cred}
110
+ PORT=${port}
111
+ # 127.0.0.1 behind a reverse proxy on the same machine (deploy/Caddyfile); 0.0.0.0 in a container
112
+ HOST=127.0.0.1
113
+ `;
114
+
115
+ const INDEX = `// index.js — your openarch member. Everything it serves comes from openarch-member.json
116
+ // and your catalog; the protocol is the kit's job (update the stanford-openarch package to update the kit).
117
+ import { startMember } from "${KIT_PACKAGE}/member-kit";
118
+
119
+ await startMember(new URL("./openarch-member.json", import.meta.url).pathname);
120
+ `;
121
+
122
+ const README = (c, kitSource, { outside, view, devKit }) => `# ${c.name} — an openarch member
123
+
124
+ This directory is your archive's adapter: it answers the openarch hub from your catalog
125
+ (\`${c.catalog.path}\`) and your files, as \`${c.member}\`, at ${c.public_base}.
126
+
127
+ ## Run it here
128
+ \`\`\`sh
129
+ npm install # the member kit (${kitSource})
130
+ npm start # http://127.0.0.1:3101/openarch/v1/manifest
131
+ openarch member check # in this directory: the conformance walk, on this machine
132
+ \`\`\`
133
+ The port is \`PORT\` in \`.env\` (3101); \`openarch member check\` reads it from there. If you
134
+ change it, change \`deploy/Caddyfile\`'s \`reverse_proxy\` (and the Dockerfile's \`-p\`) to the
135
+ same number; \`openarch member check\` warns when they differ.
136
+ ${devKit ? `
137
+ ## Before going live
138
+ \`package.json\` installs the member kit from ${devKit}, which a server cannot reach. Point the
139
+ \`${KIT_PACKAGE}\` dependency at your hub's tarball (its /cli/ page names it) before \`npm install\` there.
140
+ ` : ""}${outside ? `
141
+ ## Where your catalog lives
142
+ ${outside}
143
+ ` : ""}
144
+ ## Its public pages
145
+ ${view}
146
+
147
+ ## Change what it serves
148
+ Edit \`openarch-member.json\` (identity, collections, terms, the catalog's columns, the
149
+ declarations) or the catalog itself, then restart — or send the running adapter a SIGHUP
150
+ (\`systemctl reload openarch-member\`) and it re-reads the catalog, keeping the old one if the
151
+ new one has a problem.
152
+
153
+ ## Go live
154
+ 1. Put it on a server where ${c.public_base} reaches it over https: \`deploy/\` has a
155
+ Dockerfile, a systemd unit and a Caddyfile (Caddy gets the certificate for you).
156
+ 2. \`openarch member check --public\` checks the public address. When it says
157
+ **Ready to apply**: \`openarch member apply\`.
158
+ 3. When the hub approves you, the operator sends you the hub's credential:
159
+ \`openarch member credential set\` here (it asks for it), copy \`.env\` to the server, restart.
160
+
161
+ Your catalog changes? Edit it and reload the adapter; the hub re-reads your manifest
162
+ within six hours (an operator can refresh it at once: openarch admin members refresh <you>).
163
+
164
+ ## Update the kit
165
+ The kit is the package \`${KIT_PACKAGE}\`, installed from ${kitSource}. To update it, point that
166
+ dependency in \`package.json\` at the new tarball (your hub's /cli/ page names it) and run
167
+ \`npm install\`. Never run \`npm audit fix --force\` here until ${KIT_PACKAGE} is published on the
168
+ npm registry by this network: npm looks a package up there by its name, and could replace the
169
+ kit with whatever that name holds.
170
+ `;
171
+
172
+ const DOCKERFILE = (mount) => `# A container for this member. Build and run, from this directory:
173
+ # docker build -t openarch-member -f deploy/Dockerfile .
174
+ # docker run -d --restart unless-stopped --env-file .env -e HOST=0.0.0.0 -p 127.0.0.1:3101:3101 \\
175
+ # -v "$PWD":/member:ro${mount ? ` -v "${mount.from}":${mount.to}:ro` : ""} openarch-member
176
+ # The port is PORT in .env (3101): change the -p mapping with it. .dockerignore keeps .env and your
177
+ # application's receipt out of the image (the credential arrives with --env-file).${mount ? `
178
+ # Your catalog lives outside this directory; the second -v mounts it where catalog.path points
179
+ # from /member (${mount.to}). On another machine, put it there and change the left-hand path.` : ""}
180
+ FROM node:22-slim
181
+ ENV NODE_ENV=production
182
+ WORKDIR /member
183
+ COPY package.json ./
184
+ RUN npm install --omit=dev
185
+ COPY . .
186
+ USER node
187
+ EXPOSE 3101
188
+ CMD ["node", "index.js"]
189
+ `;
190
+ // The server's copy of this directory: /srv/openarch-member (README §4). Never this machine's path.
191
+ const SERVER_DIR = "/srv/openarch-member";
192
+ const UNIT = (catalogOnServer) => `# /etc/systemd/system/openarch-member.service — keeps the adapter running, restarts it on
193
+ # failure, reloads the catalog on \`systemctl reload openarch-member\`.
194
+ # It expects this directory at ${SERVER_DIR} on the server; put it elsewhere and change the
195
+ # two paths below.${catalogOnServer ? ` Your catalog lives outside it: with catalog.path as written, put it at
196
+ # ${catalogOnServer} on the server.` : ""} The files${catalogOnServer ? " (the catalog's too)" : ""} must be readable by any
197
+ # user (the service runs as a dynamic one); .env is read by systemd itself and stays mode 600.
198
+ [Unit]
199
+ Description=openarch member adapter
200
+ After=network-online.target
201
+
202
+ [Service]
203
+ WorkingDirectory=${SERVER_DIR}
204
+ EnvironmentFile=${SERVER_DIR}/.env
205
+ ExecStart=/usr/bin/env node index.js
206
+ ExecReload=/bin/kill -HUP $MAINPID
207
+ Restart=on-failure
208
+ DynamicUser=yes
209
+ CacheDirectory=openarch-member
210
+ Environment=OPENARCH_CACHE_DIR=/var/cache/openarch-member
211
+ Environment=NODE_ENV=production
212
+ ProtectSystem=strict
213
+ NoNewPrivileges=yes
214
+
215
+ [Install]
216
+ WantedBy=multi-user.target
217
+ `;
218
+ const CADDY = (c) => `# Caddyfile — Caddy obtains and renews the https certificate for ${new URL(c.public_base).host}
219
+ # and passes requests to the adapter on this machine. Install Caddy, put this file at
220
+ # /etc/caddy/Caddyfile, and point the name's DNS at the server.
221
+ ${new URL(c.public_base).host} {
222
+ reverse_proxy 127.0.0.1:3101
223
+ }
224
+ `;
225
+
226
+ /**
227
+ * @param {{ dir: string, flags: object, ui: object, hub: string, version: string, root: string, askDeclarations: Function }} o
228
+ */
229
+ /** Every file init writes; it refuses to start when any of them exists, and writes each with "wx". */
230
+ export const INIT_FILES = ["openarch-member.json", "index.js", "package.json", ".env", ".gitignore", ".dockerignore", "README.md", "deploy/Dockerfile", "deploy/openarch-member.service", "deploy/Caddyfile", "archive"];
231
+
232
+ export async function memberInit(o) {
233
+ const { dir, flags, ui } = o;
234
+ const target = resolve(dir || "openarch-member");
235
+ // never overwrite: a replaced .gitignore could expose .env to a commit (ind-sec PR #3 review, S15)
236
+ const taken = INIT_FILES.filter((f) => existsSync(join(target, f)));
237
+ if (taken.length) return ui.fail(`${target} already has ${taken.slice(0, 4).join(", ")}${taken.length > 4 ? ", …" : ""}.`, "openarch member init writes a new directory: pick another (or an empty one); to change a member, edit its openarch-member.json.");
238
+ if (!process.stdin.isTTY && !flags.answers && !flags.example) return ui.fail("openarch member init asks questions, and this is not a terminal.", "Run it in a terminal; or pass --answers <file.json> with the same answers (see openarch member init --help); or --example for the demonstration archive.");
239
+ let A = {};
240
+ if (flags.answers) { try { A = JSON.parse(readFileSync(resolve(flags.answers), "utf8")); } catch (e) { return ui.fail(`Could not read ${flags.answers}: ${e.message}`); } }
241
+ // Answers are kept if init stops before it writes (a refusal, Ctrl-C): nobody answers 25
242
+ // questions twice (walkthrough 2, finding 9). The file is marked so a rerun with it asks
243
+ // only what is missing; a hand-written --answers file stays a script and asks nothing.
244
+ const given = { ...A, _resume: true };
245
+ const state = { written: false };
246
+ const answersFile = `${target}.answers.json`;
247
+ const keep = () => {
248
+ if (state.written || flags.example || Object.keys(given).filter((k) => k !== "_resume").length < 2) return null;
249
+ const rel = relative(process.cwd(), answersFile);
250
+ // The name is predictable and sits beside the target, in a folder someone else may have
251
+ // supplied: never write through a link there (ind-sec run-3 P2; run-3 P3, resume-answers-
252
+ // written-through-symlink). A new file and a rename, so a link swapped in is replaced.
253
+ const unsafe = refusal(answersFile);
254
+ if (unsafe) return `Your answers were not kept: ${unsafe}, so nothing was written to it. Remove it, then run openarch member init again.`;
255
+ writeReplacing(answersFile, JSON.stringify(given, null, 2) + "\n", 0o600);
256
+ return `Your answers so far are kept in ${rel} (mode 600). To pick up where you stopped: openarch member init ${relative(process.cwd(), target) || "."} --answers ${rel}`;
257
+ };
258
+ // Ctrl-C between prompts (a catalog loading, files copying) reaches the process, not a prompt
259
+ const onSigint = () => { const hint = keep(); process.stderr.write(`\n ${ui.red("✗")} Stopped.\n${hint ? ` ${ui.dim(hint)}\n` : ""}\n`); process.exit(130); };
260
+ process.once("SIGINT", onSigint);
261
+ try { await runInit(o, { target, A, given, state }); }
262
+ catch (e) { const hint = keep(); if (hint) e.hint = hint; throw e; }
263
+ finally { process.removeListener("SIGINT", onSigint); }
264
+ if (!state.written) { const hint = keep(); if (hint) ui.out(` ${ui.dim(hint)}\n`); }
265
+ else if (flags.answers && A._resume) rmSync(resolve(flags.answers), { force: true }); // done with it; it held the contact address
266
+ }
267
+
268
+ async function runInit({ dir, flags, ui, hub, version, askDeclarations }, { target, A, given, state }) {
269
+ const interactive = Boolean(process.stdin.isTTY) && (!flags.answers || Boolean(A._resume));
270
+ const kitSource = flags.kit || `${hub}/cli/${KIT_PACKAGE}-${version}.tgz`;
271
+
272
+ if (flags.example) {
273
+ // the demonstration archive: clearly the example, and `member check` says so (R4)
274
+ mkdirSync(join(target, "files"), { recursive: true });
275
+ writeFileSync(join(target, "catalog.csv"), "accession,title,date,creator,file,transcript\nharbor-1904,Harbor ledger 1904,1904-03-11,Port of Example,,files/harbor-1904.txt\n");
276
+ writeFileSync(join(target, "files", "harbor-1904.txt"), "Ledger of arrivals, March 1904. The schooner Marigold arrived with timber from Bergen and her dues were paid in full by the master before noon.\fThe steamer Halcyon arrived with coal; dues deferred to April by order of the harbor council.\n");
277
+ A = { member: "example", name: "Example Harbor Archive", institution: "Example University", contact: "archive@example.edu", public_base: "https://archive.example.edu", catalog: { path: "catalog.csv", columns: { id: "accession", title: "title", date: "date", authors: "creator", text: "transcript" } }, text: { kind: "ocr", from: "file" }, default_kind: "text",
278
+ declarations: { rights: { basis: "public-domain", grant: "open", license: "CC0-1.0", attribution: "none", automated_access: "allowed" }, accepted_by: "Example Archivist", sharing: { share: { text: "text" }, withhold: {} } } };
279
+ }
280
+
281
+ // ── who, and where ────────────────────────────────────────────────────────
282
+ if (interactive && !(A.name && A.institution && A.contact && A.member && A.public_base)) { ui.blank(); ui.out(` ${ui.bold("Your archive.")} ${ui.dim("It is listed under these words; every one can be changed later in openarch-member.json.")}`); }
283
+ const name = given.name = A.name ?? await ui.ask("the archive's name, as researchers know it");
284
+ const institution = given.institution = A.institution ?? await ui.ask("the institution that holds it");
285
+ const contact = given.contact = A.contact ?? await ui.ask("a contact email for the archive");
286
+ const member = given.member = A.member ?? await ui.ask("a short name for it: lowercase, it prefixes every id you serve", { fallback: slugify(name.replace(/\b(the|of|and|archives?|library|collections?|special)\b/gi, " ")) });
287
+ const domain = (contact.split("@")[1] || "example.edu").toLowerCase();
288
+ let public_base = A.public_base ? String(A.public_base).trim().replace(/\/+$/, "") : null;
289
+ if (public_base) { const why = publicBaseProblem(public_base); if (why) return ui.fail(`public_base ${public_base}: ${why}.`); }
290
+ else {
291
+ if (interactive) ui.out(` ${ui.dim("The public address is where the hub will reach your adapter, over https. You may not have it yet; give the one you plan to use, and change it later.")}`);
292
+ for (;;) {
293
+ public_base = (await ui.ask("its public https address", { fallback: `https://openarch.${domain}` })).trim().replace(/\/+$/, "");
294
+ const why = publicBaseProblem(public_base);
295
+ if (!why) break;
296
+ ui.out(` ${ui.amber("!")} ${ui.dim(why + ".")}`);
297
+ }
298
+ }
299
+ given.public_base = public_base;
300
+ const home = given.home = A.home ?? (interactive ? await ui.ask("the archive's own website (blank to skip)", { fallback: "" }) : "");
301
+
302
+ // ── the catalog ───────────────────────────────────────────────────────────
303
+ let catalogPath = A.catalog?.path;
304
+ if (!catalogPath) {
305
+ if (interactive) { ui.blank(); ui.out(` ${ui.bold("Your catalog.")} ${ui.dim("A spreadsheet saved as CSV (or TSV, or a JSONL file): one row per document. Its files and transcripts sit in a folder beside it.")}`); }
306
+ const near = readdirSync(process.cwd()).filter((f) => /\.(csv|tsv|jsonl?)$/i.test(f));
307
+ catalogPath = await ui.ask("the catalog file", { fallback: near.length === 1 ? near[0] : "" });
308
+ }
309
+ const catAbs = isAbsolute(catalogPath) ? catalogPath : resolve(flags.example ? target : process.cwd(), catalogPath);
310
+ if (!existsSync(catAbs)) return ui.fail(`No catalog at ${catAbs}.`, "Export your catalog as CSV (one row per document, one column per field) and give its path.");
311
+ given.catalog = { ...(given.catalog ?? {}), path: catAbs };
312
+ const peek = peekCatalog(catAbs);
313
+ if (!peek.header.length) return ui.fail(`${catAbs} has no header row.`, "The first row names the columns: id, title, file …");
314
+ let columns = { ...(A.catalog?.columns ?? {}) };
315
+ if (!A.catalog?.columns) {
316
+ const g = guessColumns(peek.header);
317
+ ui.blank(); ui.out(` ${ui.bold(ui.cleanLine(basename(catAbs)))} ${ui.dim(`· ${peek.total.toLocaleString("en-US")} rows · columns: ${ui.cleanLine(peek.header.join(", "))}`)}`);
318
+ ui.out(` ${ui.dim("Which column is which? Enter accepts the guess; - leaves a field out.")}`);
319
+ for (const f of Object.keys(GUESS)) {
320
+ const required = f === "id" || f === "title";
321
+ for (;;) {
322
+ const a = await ui.ask(`${f.padEnd(10)} ${ui.dim(FIELD_NOTE[f])}`, { fallback: g[f] ?? (required ? "" : "-") });
323
+ if (a === "-" && !required) break;
324
+ if (peek.header.includes(a)) { columns[f] = a; break; }
325
+ ui.out(` ${ui.amber("!")} ${ui.dim(`"${ui.cleanLine(a)}" is not a column. The columns are: ${ui.cleanLine(peek.header.join(", "))}`)}`);
326
+ }
327
+ }
328
+ // a preview, so a wrong guess shows before anything is written
329
+ ui.blank(); ui.out(` ${ui.bold("As read:")}`);
330
+ ui.out(ui.table(Object.keys(columns).map((k) => ({ key: k, title: k })), peek.rows.slice(0, 3).map((r) => Object.fromEntries(Object.entries(columns).map(([k, h]) => [k, String(r[h] ?? "")])))));
331
+ if (!(await ui.confirm("Is that right?", true))) return ui.fail("Nothing written.", "Run openarch member init again and name the columns.");
332
+ }
333
+ given.catalog = { ...given.catalog, columns };
334
+ if (!columns.id || !columns.title) return ui.fail("The catalog needs an id column and a title column.", "Name them in the answers: catalog.columns.id, catalog.columns.title.");
335
+ const sampleText = columns.text ? String(peek.rows.find((r) => r[columns.text])?.[columns.text] ?? "") : "";
336
+ const textFrom = A.text?.from ?? (sampleText && sampleText.length < 300 && /\.(txt|text|md)$/i.test(sampleText.trim()) ? "file" : "column");
337
+ const textKind = A.text?.kind ?? (columns.text ? await ui.choose("What kind of text is it?", [{ id: "ocr", label: "OCR", note: "recognized by software from scans or photographs" }, { id: "born-digital", label: "Born-digital", note: "the documents were text from the start (word processing, email, web pages)" }, { id: "transcript", label: "Transcript of speech", note: "what was said in a recording (oral history, film, audio), written out" }], { fallback: "ocr" }) : "none");
338
+ given.text = { kind: textKind, from: textFrom };
339
+
340
+ // The catalog outside the member's directory: the adapter reads it where it is, so a server
341
+ // needs it at the same place relative to the adapter. Offer to copy it in, so the directory
342
+ // is everything the server needs (walkthrough 2, finding 13).
343
+ const catRoot = dirname(catAbs);
344
+ const insideTarget = (p) => p === target || p.startsWith(target + sep);
345
+ let copy = null, outside = null, outsidePaths = null;
346
+ if (!insideTarget(catAbs)) {
347
+ const refs = new Set();
348
+ for (const r of allRows(catAbs, peek)) {
349
+ if (columns.file) for (const f of String(r[columns.file] ?? "").split(";").map((x) => x.trim()).filter(Boolean)) refs.add(f);
350
+ if (columns.text && textFrom === "file") { const t = String(r[columns.text] ?? "").trim(); if (t) refs.add(t); }
351
+ }
352
+ const files = []; let bytes = statSync(catAbs).size;
353
+ for (const f of refs) {
354
+ const rel = relative(catRoot, resolve(catRoot, f));
355
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) continue;
356
+ try {
357
+ // the file itself, inside the catalog's folder: a link pointing out of it is never copied (review nit)
358
+ const real = realpathSync(join(catRoot, rel)), rootReal = realpathSync(catRoot);
359
+ if (!real.startsWith(rootReal + sep)) continue;
360
+ const st = statSync(real); if (st.isFile()) { files.push(rel); bytes += st.size; }
361
+ } catch { /* the load below reports it, with its line */ }
362
+ }
363
+ let yes = A.copy_catalog;
364
+ if (yes === undefined && interactive) {
365
+ ui.blank(); ui.out(` ${ui.bold("Where the catalog lives.")} ${ui.dim(`${basename(catAbs)} and its ${files.length.toLocaleString("en-US")} file${files.length === 1 ? "" : "s"} (${fmtBytes(bytes)}) are in ${catRoot}, outside ${target}. The adapter reads them where they are, so a server needs them at the same place relative to it.`)}`);
366
+ yes = await ui.confirm(`Copy them into ${relative(process.cwd(), target) || "."}${sep}archive, so this one directory is everything the server needs?`, bytes < 2 * 1024 ** 3);
367
+ }
368
+ given.copy_catalog = Boolean(yes);
369
+ if (yes) copy = { files, bytes };
370
+ else {
371
+ const rel = relative(target, catRoot).split(sep).join("/");
372
+ outsidePaths = { rel, server: posix.resolve(SERVER_DIR, rel), container: posix.resolve("/member", rel), here: catRoot };
373
+ outside = `The catalog and its files stay in ${catRoot}; \`catalog.path\` in openarch-member.json points there (\`${rel}\`, relative to this directory). On the server, with this directory at ${SERVER_DIR}, put them at ${outsidePaths.server}${outsidePaths.server === "/srv" ? " (or copy them in and change `catalog.path`)" : ""}; the Dockerfile's run line mounts them at ${outsidePaths.container}.`;
374
+ }
375
+ }
376
+
377
+ // the kinds of material the catalog actually holds: the sharing question is asked for these only
378
+ const kinds = new Map();
379
+ for (const r of peek.rows) {
380
+ const f = columns.file ? String(r[columns.file] ?? "").split(";")[0].trim() : "";
381
+ const k = f ? kindOf(f) : (A.default_kind ?? "text");
382
+ kinds.set(k, (kinds.get(k) ?? 0) + 1);
383
+ }
384
+
385
+ // collections: from the collection column's values, or one
386
+ let collections = A.collections;
387
+ if (!collections) {
388
+ const values = columns.collection ? [...new Set(peek.rows.map((r) => String(r[columns.collection] ?? "").trim()).filter(Boolean))] : [];
389
+ if (values.length > 1 && values.length <= 50) collections = values.map((v) => ({ id: `${member}/${slugify(v)}`, title: v, match: v }));
390
+ else {
391
+ if (values.length > 50) ui.out(` ${ui.amber("!")} ${ui.dim(`${columns.collection} has ${values.length} values — too many for collections; serving one collection (edit openarch-member.json to split it).`)}`);
392
+ const title = values.length === 1 ? values[0] : (interactive ? await ui.ask("the collection's title", { fallback: name }) : name);
393
+ collections = [{ id: `${member}/${slugify(title)}`, title, ...(values.length === 1 ? { match: values[0] } : {}) }];
394
+ if (values.length !== 1) delete columns.collection;
395
+ }
396
+ given.collections = collections;
397
+ }
398
+
399
+ // ── the declarations, once ────────────────────────────────────────────────
400
+ let sharing = A.declarations?.sharing;
401
+ if (!sharing) {
402
+ sharing = { share: {}, withhold: {} };
403
+ ui.blank(); ui.out(` ${ui.bold("What you share.")} ${ui.dim("For each kind your catalog holds: share it (how far) or withhold it (why).")}`);
404
+ const choices = [...SERVE_MODES.map((m) => ({ id: `share:${m.id}`, label: `Share — ${m.label}`, note: m.note })), ...WITHHOLD_REASONS.map((r) => ({ id: `withhold:${r.id}`, label: `Withhold — ${r.label}`, note: r.note }))];
405
+ for (const [k, n] of kinds) {
406
+ const kd = MATERIAL_KINDS.find((x) => x.id === k);
407
+ const where = peek.rows.length >= peek.total ? "in your catalog" : `in its first ${peek.rows.length.toLocaleString("en-US")} rows`;
408
+ const c = await ui.choose(`${kd?.label ?? k} — ${n.toLocaleString("en-US")} ${where}`, choices, { fallback: k === "text" ? "share:text" : "share:files" });
409
+ if (c.startsWith("share:")) sharing.share[k] = c.slice(6); else sharing.withhold[k] = c.slice(9);
410
+ }
411
+ }
412
+ given.declarations = { ...(given.declarations ?? {}), sharing };
413
+ let pattern = A.declarations?.permalink_pattern;
414
+ if (pattern !== undefined && pattern !== null) { const why = permalinkPatternProblem(pattern); if (why) return ui.fail(`declarations.permalink_pattern ${pattern}: ${why}.`); }
415
+ if (pattern === undefined && interactive) {
416
+ const own = await ui.confirm("Do your documents already have their own pages on your website (with a stable address per document)?", false);
417
+ if (own) for (;;) {
418
+ pattern = (await ui.ask("their address, with {id} where the document's id goes, e.g. https://library.example.edu/item/{id}")).trim();
419
+ const why = permalinkPatternProblem(pattern);
420
+ if (!why) break;
421
+ ui.out(` ${ui.amber("!")} ${ui.dim(why + ".")}`);
422
+ }
423
+ }
424
+ if (pattern === undefined) pattern = `${public_base}/view/{id}`;
425
+ given.declarations.permalink_pattern = pattern;
426
+ const decl = A.declarations?.rights
427
+ ? { rights: { ...A.declarations.rights, declared_by: A.declarations.accepted_by, declared_on: new Date().toLocaleDateString("en-CA") }, permalinks: { pattern, stable: true, legacy_resolve: true, human_readable: true }, agreement: { version: "0.1", accepted_by: A.declarations.accepted_by, accepted_on: new Date().toLocaleDateString("en-CA") }, sharing }
428
+ : await askDeclarations({ who: A.declarations?.accepted_by, presetSharing: sharing, presetPattern: pattern, preset: A.declarations?.partial ?? {},
429
+ record: (k, v) => { given.declarations = { ...given.declarations, partial: { ...(given.declarations?.partial ?? {}), [k]: v } }; } });
430
+ if (!decl) return;
431
+ const grant = REUSE_GRANT.find((g) => g.id === decl.rights.grant);
432
+ const termsId = decl.rights.grant;
433
+ for (const col of collections) col.terms = col.terms ?? termsId;
434
+ const terms = A.terms ?? { [termsId]: { label: grant?.label ?? termsId, reuse: termsId, ...(decl.rights.license ? { license: decl.rights.license } : {}) } };
435
+
436
+ // ── write it ──────────────────────────────────────────────────────────────
437
+ mkdirSync(join(target, "deploy"), { recursive: true });
438
+ let catalogConf;
439
+ if (copy) {
440
+ const sp = ui.spinner(`copying the catalog and ${copy.files.length.toLocaleString("en-US")} files (${fmtBytes(copy.bytes)})`);
441
+ try {
442
+ const into = join(target, "archive");
443
+ mkdirSync(into, { recursive: true });
444
+ copyFileSync(catAbs, join(into, basename(catAbs)));
445
+ for (const rel of copy.files) { mkdirSync(dirname(join(into, rel)), { recursive: true }); copyFileSync(join(catRoot, rel), join(into, rel)); }
446
+ } finally { sp.stop(); }
447
+ catalogConf = { path: `archive/${basename(catAbs)}`, columns };
448
+ } else {
449
+ catalogConf = { path: relative(target, catAbs) || basename(catAbs), columns, ...(catRoot !== target ? { files_root: relative(target, catRoot) || "." } : {}) };
450
+ }
451
+ const config = {
452
+ member, name, institution, contact, ...(home ? { home } : {}), public_base,
453
+ catalog: catalogConf,
454
+ text: { kind: textKind, from: textFrom },
455
+ ...(A.default_kind || !columns.file ? { default_kind: A.default_kind ?? "text" } : {}),
456
+ collections, terms,
457
+ rights: decl.rights, permalinks: decl.permalinks, agreement: decl.agreement, sharing: decl.sharing,
458
+ limits: { search_results_max: 50, document_bytes_max: 2_000_000 },
459
+ };
460
+ delete config.permalinks.pattern_is_default;
461
+ const W = (rel, body, mode) => writeFileSync(join(target, rel), body, { flag: "wx", ...(mode ? { mode } : {}) });
462
+ W("openarch-member.json", JSON.stringify(config, null, 2) + "\n");
463
+ W("index.js", INDEX);
464
+ W("package.json", JSON.stringify({ name: `openarch-member-${member}`, version: "0.1.0", private: true, type: "module", engines: { node: ">=20.6" }, scripts: { start: "node --env-file=.env index.js", check: "openarch member check --local" }, dependencies: { [KIT_PACKAGE]: kitSource } }, null, 2) + "\n");
465
+ const cred = `oa_hub_${randomBytes(20).toString("hex")}`;
466
+ W(".env", ENV(cred, 3101), 0o600);
467
+ chmodSync(join(target, ".env"), 0o600);
468
+ W(".gitignore", "node_modules/\n.env\n.openarch-cache.json\n.openarch-application.json\n*.answers.json\n");
469
+ W(".dockerignore", "node_modules\n.env\n.openarch-cache.json\n.openarch-application.json\n*.answers.json\n.git\n");
470
+ // what each document's public page shows, said plainly (walkthrough 2, finding 15; the kit's /view/)
471
+ const auto = decl.rights.automated_access;
472
+ const sharesText = Object.values(decl.sharing?.share ?? {}).some((m) => m === "text" || m === "files");
473
+ const view = decl.permalinks.pattern !== `${public_base}/view/{id}`
474
+ ? `Your permalinks are your own pages (${decl.permalinks.pattern}); the adapter serves none.`
475
+ : `Each document has a page at ${public_base}/view/<id>, the address its citation names, open to anyone on the web: its record and citation${auto === "allowed" && sharesText ? ", and its text" : ""}.${auto === "allowed" ? ' To keep the text off it, set "view": { "text": false } in openarch-member.json.' : ` Search engines and scripts are asked not to index it (robots.txt, noindex), as you declared automated access.${auto !== "forbidden" && sharesText ? ' Its text is not shown there; to show it to anyone on the web, set "view": { "text": true } in openarch-member.json.' : ""}`}`;
476
+ // a kit from a hub on this machine (a rehearsal) cannot be installed on a server (walkthrough 3, finding 6)
477
+ const devKit = /^https?:\/\//.test(kitSource) && !isPublicHttps(kitSource) ? kitSource : null;
478
+ W("README.md", README(config, kitSource, { outside, view, devKit }));
479
+ W("deploy/Dockerfile", DOCKERFILE(outsidePaths && outsidePaths.container !== "/" ? { from: outsidePaths.here, to: outsidePaths.container } : null));
480
+ W("deploy/openarch-member.service", UNIT(outsidePaths?.server ?? null));
481
+ W("deploy/Caddyfile", CADDY(config));
482
+ state.written = true;
483
+
484
+ // ── load it once: a problem shows now, with its line ──────────────────────
485
+ let summary = null, problem = null;
486
+ try {
487
+ const c = readConfig(join(target, "openarch-member.json"));
488
+ const { docs, skipped, warnings } = await loadCatalog(c);
489
+ const byKind = {}; let withText = 0, files = 0;
490
+ for (const d of docs.values()) { byKind[d.kind] = (byKind[d.kind] ?? 0) + 1; if (d.text) withText++; files += d.files.length; }
491
+ summary = { documents: docs.size, byKind, withText, files, skipped, warnings };
492
+ } catch (e) { problem = e.message; }
493
+ if (flags.json) return ui.json({ dir: target, config: "openarch-member.json", summary, problem });
494
+ ui.blank();
495
+ ui.out(` ${ui.glyph.pass} ${ui.bold(member)} · ${name} — written to ${ui.bold(target)}`);
496
+ if (summary) {
497
+ ui.out(` ${summary.documents.toLocaleString("en-US")} document${summary.documents === 1 ? "" : "s"} (${Object.entries(summary.byKind).map(([k, n]) => `${n} ${k}`).join(", ")}) · ${summary.withText} with text · ${summary.files} file${summary.files === 1 ? "" : "s"} shared${summary.skipped.withheld ? ` · ${summary.skipped.withheld} withheld` : ""}`);
498
+ for (const w of summary.warnings) ui.out(` ${ui.amber("!")} ${ui.dim(ui.cleanLine(w))}`);
499
+ } else {
500
+ ui.out(` ${ui.red("✗")} the catalog does not load yet:`);
501
+ ui.out(` ${ui.dim(problem.split("\n").map(ui.cleanLine).join("\n "))}`);
502
+ ui.out(` ${ui.dim("Fix the catalog (or openarch-member.json) and run npm start; it reports the same way.")}`);
503
+ }
504
+ if (copy) ui.out(` ${ui.dim(`catalog and files copied into ${relative(process.cwd(), join(target, "archive")) || "archive"}`)}`);
505
+ if (outside) ui.out(` ${ui.amber("!")} ${ui.dim(outside.replaceAll("`", ""))}`);
506
+ if (devKit) ui.out(` ${ui.amber("!")} ${ui.dim(`package.json installs the kit from ${devKit}, a hub a server cannot reach: change it before going live (README.md says how).`)}`);
507
+ ui.out(` ${ui.dim(view)}`);
508
+ ui.out(ui.kv([["next", `cd ${relative(process.cwd(), target) || "."} && npm install && npm start`], ["then", "openarch member check (in that directory, while it runs)"], ["live", "README.md in that directory: deploy/, then openarch member check --public"]]));
509
+ ui.out(` ${ui.dim(".env holds a provisional hub credential for testing; it has not been sent anywhere.")}`);
510
+ ui.blank();
511
+ }