@extantape/payload-plugin-onephylogeny 0.1.0-alpha.8 → 0.1.0-alpha.9

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 CHANGED
@@ -35,3 +35,38 @@ The read is trimmed by quality and bases below Q20 become N (OnePhylogeny's `ass
35
35
 
36
36
  On a multi-site host, set `tenantField` if the site field isn't called `tenant`. A result, sample or sequence keeps the site it was made for, so nobody can move it to another site's readers.
37
37
 
38
+ ## External samples
39
+
40
+ A sample is `internal` (the host's own material, from a kit, an upload or a historic record) or `external` (a record from a paper, a public database, a validated panel or an institution). `origin` is set once. Internal samples have `source`, and may have a kit and consent. External samples have none of those, and instead fill the `external` group:
41
+
42
+ | Field | What it holds |
43
+ | --- | --- |
44
+ | `sourceType` | `paper`, `public-database`, `validated-panel` or `institution`. Required. |
45
+ | `accession`, `database` | The source's own identifier and the database it belongs to. Unique together where both are set, without regard to case or spacing: `GenBank AB000001` and ` genbank ab000001` are one record. A hidden `sourceKey` holds the normalized pair under a sparse unique index, so two writes in the same instant can't both land. |
46
+ | `voucher.institution`, `voucher.catalogNumber` | The specimen, as a collection names it. |
47
+ | `collector`, `permit` | Restricted: read and changed only by the check you pass as `external.restrictedAccess`. Default nobody. |
48
+ | `collectionDatePrecision` | `day`, `month`, `year` or `unknown`, for the sample's `collectedAt`. |
49
+ | `dataLicense` | `cc0`, `cc-by`, `cc-by-nc`, `insdc`, `other` or `unknown`. Left out, it is `unknown`. `other` and `unknown` both allow nothing. |
50
+ | `dataLicenseNote`, `citation`, `doi` | The terms as written, and the paper or dataset. |
51
+ | `url` | The source's own page. Readable only by the check you pass as `external.urlAccess`. Default nobody. |
52
+ | `sourceRelease`, `importRun` | Relations to your own collections, added when you name them in `external.relations`. |
53
+
54
+ The plugin knows no roles. Pass your own checks:
55
+
56
+ ```ts
57
+ records: {
58
+ external: {
59
+ restrictedAccess: ({ req }) => req.user?.role === 'super-admin', // collector and permit
60
+ urlAccess: ({ req }) => Boolean(req.user?.role), // the source link
61
+ relations: { sourceReleases: 'source-releases', importRuns: 'import-runs' },
62
+ },
63
+ ecoregions: { land: { dataset: 'RESOLVE Ecoregions', version: '2017' } },
64
+ }
65
+ ```
66
+
67
+ **The data license fails closed.** `unknown` means the record is a pointer to the source: no copy of its reads may be kept and nothing may be passed on, until a curator sets a real license. `other` gets the same answer: its terms are in `dataLicenseNote`, which only a person can read, and a check that can't decide says no. Once someone has read them, move the record to a real license. `licenseTerms(license)` gives the same answers to your own code (`keepCopy`, `redistribute`, `commercial`, `pointerOnly`).
68
+
69
+ `rawReads[]` holds pointers to raw reads (an SRA run, a URL, your storage key), each with its SHA-256 and a `tier`: `external` (the source holds it), `cache` (a copy that may be cleared), `hot` or `deep-archive` (your own reads). An external sample's reads are `external`, or `cache` once its license allows a copy. An internal sample's reads are `hot` or `deep-archive`. The reads themselves are never stored here.
70
+
71
+ `ecoregion` is the most any page may show of where a sample came from, in three realms: `land`, `marine` and `freshwater`. Each value carries the dataset and version it came from, and a realm you pin in `ecoregions` refuses any other set. Precise localities never enter the plugin: a sample with a coordinate anywhere in it is refused. Keep them in your own collection, with your own audit.
72
+
package/dist/index.d.ts CHANGED
@@ -1,5 +1,60 @@
1
+ import { FieldAccess, Access, PayloadRequest, Payload, Where, Plugin } from 'payload';
1
2
  import { Result } from '@extantape/onephylogeny-core';
2
- import { Access, PayloadRequest, Payload, Where, Plugin } from 'payload';
3
+
4
+ /**
5
+ * Settings for samples that came from outside the host: a paper, a public database, a validated panel or an institution.
6
+ * The plugin knows no roles. Every rule about who sees what is a function the host passes, and each defaults to nobody.
7
+ */
8
+ type ExternalOptions = {
9
+ /**
10
+ * Who may read and change a source's collector name and permit reference. They name people, so the default is nobody:
11
+ * only scripts that bypass access see them. Hosts pass their strictest check here.
12
+ */
13
+ restrictedAccess?: FieldAccess;
14
+ /** Who may read the source's own page for a record (`external.url`). Default: nobody. Hosts usually pass their admin check. */
15
+ urlAccess?: FieldAccess;
16
+ /** Host collections for the release an import came from and the run that created the sample. Left out, the field isn't added. */
17
+ relations?: {
18
+ sourceReleases?: string;
19
+ importRuns?: string;
20
+ };
21
+ };
22
+ /** One ecoregion set, fixed by version so a stored name can always be traced to the dataset that gave it. */
23
+ type EcoregionPin = {
24
+ dataset: string;
25
+ version: string;
26
+ };
27
+ /**
28
+ * The ecoregion sets a host uses, one per realm. A pinned realm refuses any value from another dataset or version. An
29
+ * unpinned realm still needs every value to carry its dataset and version.
30
+ */
31
+ type EcoregionOptions = {
32
+ land?: EcoregionPin;
33
+ marine?: EcoregionPin;
34
+ freshwater?: EcoregionPin;
35
+ };
36
+ declare const SOURCE_TYPES: readonly ["paper", "public-database", "validated-panel", "institution"];
37
+ declare const DATA_LICENSES: readonly ["cc0", "cc-by", "cc-by-nc", "insdc", "other", "unknown"];
38
+ declare const READ_TIERS: readonly ["external", "cache", "hot", "deep-archive"];
39
+ type DataLicense = (typeof DATA_LICENSES)[number];
40
+ /**
41
+ * What a data license lets a host do with a sequence, read so a license the plugin can't decide on allows nothing: the
42
+ * record is a pointer to the source, with no copy kept and nothing passed on, until a curator sets a real license. That
43
+ * covers `unknown`, nothing at all, and `other`: its terms are written in `dataLicenseNote`, which only a person can read,
44
+ * so the plugin answers no. A host that has read them moves the record to a real license.
45
+ */
46
+ declare function licenseTerms(license: string | null | undefined): {
47
+ keepCopy: boolean;
48
+ redistribute: boolean;
49
+ commercial: boolean;
50
+ pointerOnly: boolean;
51
+ };
52
+ /**
53
+ * The key the unique index holds for a source record: `database:accession`, both normalized. Accessions are folded to
54
+ * lower case because GenBank, ENA and BOLD read them without regard to case. Undefined when either part is missing, so
55
+ * the sparse index skips samples with no public record.
56
+ */
57
+ declare const sourceKeyOf: (database: unknown, accession: unknown) => string | undefined;
3
58
 
4
59
  /** Settings for the optional `samples` and `sequences` collections. */
5
60
  type RecordsOptions = {
@@ -21,6 +76,13 @@ type RecordsOptions = {
21
76
  }>;
22
77
  /** The host's tenant field, filled from `registerSequence`'s `tenant` and copied onto results. Default `tenant`. */
23
78
  tenantField?: string;
79
+ /**
80
+ * Samples from outside the host (papers, public databases, validated panels, institutions). The fields are always
81
+ * added; this sets who may read the restricted ones, which default to nobody, and which host collections they relate to.
82
+ */
83
+ external?: ExternalOptions;
84
+ /** The ecoregion sets this host uses, one per realm, each pinned by version. Default: none pinned. */
85
+ ecoregions?: EcoregionOptions;
24
86
  };
25
87
  /** Reads one FASTA file as one sequence, or says in plain words why it can't. */
26
88
  declare function readSingleSequence(text: string, marker: string, markers?: RecordsOptions['markers']): {
@@ -189,4 +251,4 @@ type OnePhylogenyPluginOptions = {
189
251
  */
190
252
  declare const onePhylogeny: (options?: OnePhylogenyPluginOptions) => Plugin;
191
253
 
192
- export { type Evaluate, type OnePhylogenyPluginOptions, type RecordsOptions, type RegisterSequenceInput, type RegisterTraceInput, type TraceSummary, anyOf, assignWaiting, either, onePhylogeny, readSingleSequence, readTrace, registerSequence, registerTrace, summarize };
254
+ export { DATA_LICENSES, type DataLicense, type EcoregionOptions, type EcoregionPin, type Evaluate, type ExternalOptions, type OnePhylogenyPluginOptions, READ_TIERS, type RecordsOptions, type RegisterSequenceInput, type RegisterTraceInput, SOURCE_TYPES, type TraceSummary, anyOf, assignWaiting, either, licenseTerms, onePhylogeny, readSingleSequence, readTrace, registerSequence, registerTrace, sourceKeyOf, summarize };
package/dist/index.js CHANGED
@@ -10,17 +10,216 @@ function either(...grants) {
10
10
  }
11
11
  var anyOf = (...rules) => async (args) => either(...await Promise.all(rules.map((r) => r ? r(args) : false)));
12
12
 
13
+ // src/external.ts
14
+ import { APIError, ValidationError } from "payload";
15
+ var ORIGINS = ["internal", "external"];
16
+ var SOURCE_TYPES = ["paper", "public-database", "validated-panel", "institution"];
17
+ var DATA_LICENSES = ["cc0", "cc-by", "cc-by-nc", "insdc", "other", "unknown"];
18
+ var DATE_PRECISIONS = ["day", "month", "year", "unknown"];
19
+ var READ_TIERS = ["external", "cache", "hot", "deep-archive"];
20
+ var REALMS = ["land", "marine", "freshwater"];
21
+ function licenseTerms(license) {
22
+ switch (license) {
23
+ case "cc0":
24
+ case "insdc":
25
+ case "cc-by":
26
+ return { keepCopy: true, redistribute: true, commercial: true, pointerOnly: false };
27
+ case "cc-by-nc":
28
+ return { keepCopy: true, redistribute: true, commercial: false, pointerOnly: false };
29
+ default:
30
+ return { keepCopy: false, redistribute: false, commercial: false, pointerOnly: true };
31
+ }
32
+ }
33
+ var normalize = (v) => String(v).replace(/\s+/g, "").toLowerCase();
34
+ var sourceKeyOf = (database, accession) => hasValue(database) && hasValue(accession) ? `${normalize(database)}:${normalize(accession)}` : void 0;
35
+ var SOURCE_KEY_PATH = /source[_.]?key$/i;
36
+ var duplicateMessage = (database, accession) => `Another sample already records ${String(database)} ${String(accession)}. Edit that sample instead of adding a second.`;
37
+ var collidedMessage = (database, accession) => `Another write landed in the same instant, most likely a sample with ${String(database)} ${String(accession)}. Try again: if that sample exists, you'll be told so.`;
38
+ var isDuplicateKey = (e) => e instanceof ValidationError && Boolean(e.data?.errors?.some((f) => SOURCE_KEY_PATH.test(String(f.path ?? ""))));
39
+ var isWriteConflict = (e) => {
40
+ const err = e;
41
+ return Boolean(err && typeof err === "object" && (err.code === 112 || err.codeName === "WriteConflict" || /WriteConflict|retry your operation/i.test(String(err.message ?? ""))));
42
+ };
43
+ var withSourceKeyErrors = (db, samples) => {
44
+ if (!db) return db;
45
+ const rethrow = (e, args) => {
46
+ const ext = args.data?.external;
47
+ if (args.collection !== samples || !hasValue(ext?.sourceKey)) throw e;
48
+ if (isDuplicateKey(e)) throw new APIError(duplicateMessage(ext?.database, ext?.accession), 400, void 0, true);
49
+ if (isWriteConflict(e)) throw new APIError(collidedMessage(ext?.database, ext?.accession), 409, void 0, true);
50
+ throw e;
51
+ };
52
+ return {
53
+ ...db,
54
+ init: (args) => {
55
+ const adapter = db.init(args);
56
+ for (const op of ["create", "updateOne", "upsert"]) {
57
+ const original = adapter[op];
58
+ if (typeof original !== "function") continue;
59
+ adapter[op] = async (a) => {
60
+ try {
61
+ return await original.call(adapter, a);
62
+ } catch (e) {
63
+ return rethrow(e, a);
64
+ }
65
+ };
66
+ }
67
+ return adapter;
68
+ }
69
+ };
70
+ };
71
+ var fail = (message) => {
72
+ throw new APIError(message, 400, void 0, true);
73
+ };
74
+ var nobody = () => false;
75
+ var COORDINATES = /^(lat|lon|lng|latitude|longitude|latlon|lat_lon|coordinates?|geometry|point)$/i;
76
+ var SHA256 = /^[0-9a-f]{64}$/;
77
+ var hasValue = (v) => {
78
+ if (v == null || v === "") return false;
79
+ if (Array.isArray(v)) return v.some(hasValue);
80
+ if (typeof v === "object") return v instanceof Date || Object.values(v).some(hasValue);
81
+ return true;
82
+ };
83
+ var hasCoordinates = (value) => {
84
+ if (Array.isArray(value)) return value.some(hasCoordinates);
85
+ if (!value || typeof value !== "object") return false;
86
+ return Object.entries(value).some(([k, v]) => COORDINATES.test(k) || hasCoordinates(v));
87
+ };
88
+ var whenExternal = { condition: ((data) => data?.origin === "external") };
89
+ var whenInternal = (data) => data?.origin !== "external";
90
+ var relation = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
91
+ var realm = (name, example) => ({
92
+ name,
93
+ type: "group",
94
+ admin: { description: `Set with its dataset and version, for example ${example}. Never a coordinate.` },
95
+ fields: [
96
+ { name: "code", type: "text", admin: { description: "The ecoregion's identifier in its dataset." } },
97
+ { name: "name", type: "text" },
98
+ { name: "dataset", type: "text" },
99
+ { name: "version", type: "text" }
100
+ ]
101
+ });
102
+ function externalFields(o) {
103
+ const restricted = o.restrictedAccess ?? nobody;
104
+ const url = o.urlAccess ?? nobody;
105
+ return {
106
+ origin: {
107
+ name: "origin",
108
+ type: "select",
109
+ required: true,
110
+ defaultValue: "internal",
111
+ index: true,
112
+ options: [...ORIGINS],
113
+ admin: { description: "Internal: the host's own material. External: a record from a paper, database, panel or institution. Set once." }
114
+ },
115
+ external: {
116
+ name: "external",
117
+ type: "group",
118
+ admin: { ...whenExternal, description: "Where an external sample came from. Never a keeper's data, and never a locality." },
119
+ fields: [
120
+ { name: "sourceType", type: "select", options: [...SOURCE_TYPES] },
121
+ { name: "accession", type: "text", index: true, admin: { description: "The source's own identifier, such as a GenBank or ENA accession. Unique with its database, without regard to case or spacing." } },
122
+ { name: "database", type: "text", admin: { description: "The database the accession belongs to, such as GenBank, ENA, BOLD or GBIF. Empty for a paper or institution with no public record." } },
123
+ // Filled by the hook, never by hand. Not required, so the adapters give it a sparse unique index that skips samples with no public record.
124
+ { name: "sourceKey", type: "text", unique: true, hidden: true, admin: { readOnly: true, hidden: true } },
125
+ { name: "voucher", type: "group", fields: [{ name: "institution", type: "text", admin: { description: "The collection's code." } }, { name: "catalogNumber", type: "text" }] },
126
+ { name: "collector", type: "text", access: { read: restricted, update: restricted }, admin: { description: "Who collected it, as the source names them. Restricted." } },
127
+ { name: "collectionDatePrecision", type: "select", options: [...DATE_PRECISIONS], admin: { description: "How much of the collection date to trust. Sources often give a year only." } },
128
+ { name: "permit", type: "text", access: { read: restricted, update: restricted }, admin: { description: "The permit reference the source gives, as written. Restricted." } },
129
+ { name: "dataLicense", type: "select", options: [...DATA_LICENSES], admin: { description: "Decides what may be done with the sequence. Unknown and other mean pointer only: no copy kept and nothing passed on, until a curator who has read the terms sets a real license." } },
130
+ { name: "dataLicenseNote", type: "text", admin: { description: "For other: the terms as written, or a link to them, for a person to read." } },
131
+ { name: "citation", type: "text" },
132
+ { name: "doi", type: "text" },
133
+ { name: "url", type: "text", access: { read: url }, admin: { description: "The source's own page for this record. Shown only where the host allows." } },
134
+ ...relation("sourceRelease", o.relations?.sourceReleases, { admin: { description: "The release this sample came in with, when it was imported." } }),
135
+ ...relation("importRun", o.relations?.importRuns, { admin: { description: "The run that created it, for the audit trail." } })
136
+ ]
137
+ },
138
+ rawReads: {
139
+ name: "rawReads",
140
+ type: "array",
141
+ admin: { description: "Where the raw reads are, never the reads themselves. The host's own download rules apply." },
142
+ fields: [
143
+ { name: "pointer", type: "text", required: true, admin: { description: "An SRA run accession, a URL or the host's own storage key." } },
144
+ { name: "sha256", type: "text", required: true, admin: { description: "Checked whenever the file is fetched." } },
145
+ { name: "bytes", type: "number" },
146
+ { name: "tier", type: "select", required: true, options: [...READ_TIERS], admin: { description: "External: the source holds it, no copy here. Cache: a copy that may be cleared. Hot and deep-archive: the host's own reads." } },
147
+ { name: "fetchedAt", type: "date", admin: { description: "Last time the cache held it." } }
148
+ ]
149
+ },
150
+ ecoregion: {
151
+ name: "ecoregion",
152
+ type: "group",
153
+ admin: { description: "The most any page may show of where a sample came from. Precise localities live in the host's own collection, never here." },
154
+ fields: [
155
+ realm("land", "RESOLVE Ecoregions 2017"),
156
+ realm("marine", "Marine Ecoregions of the World 2007"),
157
+ realm("freshwater", "Freshwater Ecoregions of the World 2008"),
158
+ { name: "source", type: "select", options: ["lookup", "curator", "source-record"], admin: { description: "How the ecoregion was found: a lookup from the locality, a curator, or the source record itself." } }
159
+ ]
160
+ }
161
+ };
162
+ }
163
+ var group = (doc, data, name) => ({ ...doc?.[name] ?? {}, ...data[name] ?? {} });
164
+ var sampleRules = (c) => async ({ data, originalDoc, operation, req }) => {
165
+ if (hasCoordinates(data)) fail("Samples never hold coordinates. Keep precise localities in your own collection, outside the plugin.");
166
+ const doc = { ...originalDoc, ...data };
167
+ const origin = String(doc.origin ?? "internal");
168
+ const external = group(originalDoc, data, "external");
169
+ if (origin === "internal") {
170
+ if (hasValue(external)) fail("An internal sample has no external source. Record a sample from a paper, database, panel or institution with origin set to external.");
171
+ if (!hasValue(doc.source)) fail("An internal sample needs how its material arrived: kit, upload or historic.");
172
+ } else {
173
+ if (c.hasKit && hasValue(doc.kit)) fail("An external sample has no kit. Kits are the host's own material.");
174
+ if (hasValue(doc.consent)) fail("An external sample has no keeper consent. Its terms are its data license.");
175
+ if (hasValue(doc.source)) fail("An external sample has no source; that field says how the host's own material arrived.");
176
+ if (!hasValue(external.sourceType)) fail("An external sample needs its source type: paper, public database, validated panel or institution.");
177
+ if (!hasValue(external.dataLicense)) {
178
+ external.dataLicense = "unknown";
179
+ data.external = { ...data.external, dataLicense: "unknown" };
180
+ }
181
+ const key = sourceKeyOf(external.database, external.accession);
182
+ const sent = { ...data.external };
183
+ delete sent.sourceKey;
184
+ data.external = key ? { ...sent, sourceKey: key } : sent;
185
+ if (key) {
186
+ const where = { and: [{ "external.sourceKey": { equals: key } }, ...operation === "update" && originalDoc?.id != null ? [{ id: { not_equals: originalDoc.id } }] : []] };
187
+ const taken = await req.payload.find({ collection: c.samples, where, limit: 1, depth: 0, overrideAccess: true });
188
+ if (taken.docs.length) fail(duplicateMessage(external.database, external.accession));
189
+ }
190
+ }
191
+ const terms = licenseTerms(origin === "external" ? String(external.dataLicense) : "cc0");
192
+ for (const read of doc.rawReads ?? []) {
193
+ const sha = String(read.sha256 ?? "").replace(/^sha256:/i, "").toLowerCase();
194
+ if (!SHA256.test(sha)) fail(`A raw read's SHA-256 is missing or malformed (${String(read.pointer ?? "no pointer")}).`);
195
+ read.sha256 = sha;
196
+ const tier = String(read.tier);
197
+ if (origin === "internal" && (tier === "external" || tier === "cache")) fail("The host's own reads are kept as hot or deep-archive, never as an outside pointer or a cache copy only.");
198
+ if (origin === "external" && (tier === "hot" || tier === "deep-archive")) fail("An external sample's reads stay the source's: external, or a cache copy that may be cleared.");
199
+ if (origin === "external" && tier !== "external" && !terms.keepCopy) fail("This source's data license is unknown, so only a pointer may be kept, with no copy, until a curator sets the license.");
200
+ }
201
+ const eco = group(originalDoc, data, "ecoregion");
202
+ for (const name of REALMS) {
203
+ const value = eco[name];
204
+ if (!hasValue(value)) continue;
205
+ const pin = c.ecoregions[name];
206
+ if (!hasValue(value.dataset) || !hasValue(value.version)) fail(`A ${name} ecoregion needs the dataset and version it came from.`);
207
+ if (pin && (value.dataset !== pin.dataset || value.version !== pin.version)) fail(`This site's ${name} ecoregions are ${pin.dataset} ${pin.version}; ${value.dataset} ${value.version} isn't that set.`);
208
+ }
209
+ return data;
210
+ };
211
+
13
212
  // src/records.ts
14
213
  import { assessRead, ChromatogramError, parseFasta, readAbif, sha256Hex, sha256HexBytes } from "@extantape/onephylogeny-core";
15
- import { APIError } from "payload";
214
+ import { APIError as APIError2 } from "payload";
16
215
  var CUSTOM_KEY = "onePhylogenyRecords";
17
216
  var DNA = /^[ACGTRYKMSWBDHVN]+$/;
18
217
  var DEFAULT_LENGTH = { minLength: 100, maxLength: 5e4 };
19
- var fail = (message) => {
20
- throw new APIError(message, 400, void 0, true);
218
+ var fail2 = (message) => {
219
+ throw new APIError2(message, 400, void 0, true);
21
220
  };
22
221
  var idOf = (v) => v && typeof v === "object" ? String(v.id) : v == null ? void 0 : String(v);
23
- var relation = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
222
+ var relation2 = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
24
223
  var comparable = (v) => {
25
224
  if (v == null) return null;
26
225
  if (typeof v !== "object") return String(v);
@@ -31,7 +230,7 @@ var comparable = (v) => {
31
230
  };
32
231
  var locked = (fields, message) => ({ data, originalDoc, operation }) => {
33
232
  if (operation === "update") {
34
- for (const f of fields) if (f in data && JSON.stringify(comparable(data[f])) !== JSON.stringify(comparable(originalDoc[f]))) fail(message);
233
+ for (const f of fields) if (f in data && JSON.stringify(comparable(data[f])) !== JSON.stringify(comparable(originalDoc[f]))) fail2(message);
35
234
  }
36
235
  return data;
37
236
  };
@@ -42,21 +241,29 @@ function recordCollections(o, base) {
42
241
  const read = anyOf(manage, o.readAccess);
43
242
  const access = { read, create: manage, update: manage, delete: () => false };
44
243
  const tenantField = o.tenantField ?? "tenant";
244
+ const ext = externalFields(o.external ?? {});
45
245
  const sampleCollection = {
46
246
  slug: samples,
47
247
  labels: { singular: "Sample", plural: "Samples" },
48
- admin: { group: "Genetics", defaultColumns: ["subject", "source", "kit", "createdAt"] },
248
+ admin: { group: "Genetics", defaultColumns: ["subject", "origin", "source", "kit", "createdAt"] },
49
249
  access,
50
250
  fields: [
51
- ...relation("subject", base.subject, { required: true }),
52
- ...relation("kit", o.relations?.kit),
53
- ...relation("taxon", base.taxa),
54
- { name: "source", type: "select", required: true, defaultValue: "kit", options: ["kit", "upload", "historic"] },
251
+ ...relation2("subject", base.subject, { required: true }),
252
+ ext.origin,
253
+ ...relation2("kit", o.relations?.kit, { admin: { condition: whenInternal } }),
254
+ ...relation2("taxon", base.taxa),
255
+ { name: "source", type: "select", options: ["kit", "upload", "historic"], admin: { condition: whenInternal, description: "How the host's own material arrived. Internal samples only." } },
55
256
  { name: "material", type: "text", admin: { description: "What was sampled, such as a shell scrape or blood." } },
56
- { name: "collectedAt", type: "date" },
57
- { name: "consent", type: "text", admin: { description: "The keeper's consent, as recorded with the kit or upload." } }
257
+ { name: "collectedAt", type: "date", admin: { description: "For an external sample, see collectionDatePrecision for how much of it to trust." } },
258
+ { name: "consent", type: "text", admin: { condition: whenInternal, description: "The keeper's consent, as recorded with the kit or upload. Internal samples only." } },
259
+ ext.external,
260
+ ext.rawReads,
261
+ ext.ecoregion
58
262
  ],
59
- hooks: { beforeChange: [locked(["subject", "kit", "source", tenantField], "A sample's animal, kit, source and site can't change. Record a new sample instead.")] }
263
+ hooks: { beforeChange: [
264
+ locked(["subject", "kit", "source", "origin", tenantField], "A sample's animal, kit, source, origin and site can't change. Record a new sample instead."),
265
+ sampleRules({ samples, hasKit: Boolean(o.relations?.kit), ecoregions: o.ecoregions ?? {} })
266
+ ] }
60
267
  };
61
268
  const sequenceCollection = {
62
269
  slug: sequences,
@@ -66,8 +273,8 @@ function recordCollections(o, base) {
66
273
  fields: [
67
274
  { name: "sample", type: "relationship", relationTo: samples, required: true, index: true },
68
275
  { name: "marker", type: "text", required: true, index: true },
69
- ...relation("lab", o.relations?.lab),
70
- ...relation("file", base.files, { admin: { description: "The file the lab sent. It stays the record of what was received." } }),
276
+ ...relation2("lab", o.relations?.lab),
277
+ ...relation2("file", base.files, { admin: { description: "The file the lab sent. It stays the record of what was received." } }),
71
278
  { name: "sha256", type: "text", required: true, index: true, admin: { description: "SHA-256 of the file, checked against its text when it was registered." } },
72
279
  { name: "recordId", type: "text", admin: { description: "The FASTA header the lab gave this sequence." } },
73
280
  { name: "residues", type: "textarea", required: true, admin: { description: "The bases, cleaned of gaps and line breaks. Used for analysis." } },
@@ -113,30 +320,30 @@ var configOf = (payload) => {
113
320
  return c;
114
321
  };
115
322
  function readSingleSequence(text, marker, markers) {
116
- if (markers && !markers[marker]) fail(`This site doesn't test the marker "${marker}".`);
323
+ if (markers && !markers[marker]) fail2(`This site doesn't test the marker "${marker}".`);
117
324
  let entries;
118
325
  try {
119
326
  entries = parseFasta(text.replace(/^/, ""));
120
327
  } catch {
121
- return fail(`This file isn't FASTA: it has bases before the first ">" header line.`);
328
+ return fail2(`This file isn't FASTA: it has bases before the first ">" header line.`);
122
329
  }
123
- if (!entries.length) fail(`This file is empty or has no ">" header line, so it isn't FASTA.`);
124
- if (entries.length > 1) fail(`This file holds ${entries.length} sequences. Send one file per kit, with one sequence in it.`);
330
+ if (!entries.length) fail2(`This file is empty or has no ">" header line, so it isn't FASTA.`);
331
+ if (entries.length > 1) fail2(`This file holds ${entries.length} sequences. Send one file per kit, with one sequence in it.`);
125
332
  const entry = entries[0];
126
333
  return { recordId: entry.id, residues: checkResidues(entry.sequence.replace(/[\s\-.]/g, "").toUpperCase(), marker, markers) };
127
334
  }
128
335
  function checkResidues(residues, marker, markers) {
129
- if (markers && !markers[marker]) fail(`This site doesn't test the marker "${marker}".`);
336
+ if (markers && !markers[marker]) fail2(`This site doesn't test the marker "${marker}".`);
130
337
  const { minLength, maxLength } = { ...DEFAULT_LENGTH, ...markers?.[marker] };
131
- if (!residues) fail("This file's sequence is empty.");
338
+ if (!residues) fail2("This file's sequence is empty.");
132
339
  if (!DNA.test(residues)) {
133
340
  const bad = [...new Set(residues.replace(/[ACGTRYKMSWBDHVN]/g, ""))].slice(0, 5).join(" ");
134
- fail(`This sequence has characters that aren't DNA bases: ${bad}.`);
341
+ fail2(`This sequence has characters that aren't DNA bases: ${bad}.`);
135
342
  }
136
- if (residues.length < minLength) fail(`This sequence is ${residues.length} bases long, shorter than the ${minLength} needed for ${marker}.`);
137
- if (residues.length > maxLength) fail(`This sequence is ${residues.length} bases long, longer than the ${maxLength} expected for ${marker}.`);
343
+ if (residues.length < minLength) fail2(`This sequence is ${residues.length} bases long, shorter than the ${minLength} needed for ${marker}.`);
344
+ if (residues.length > maxLength) fail2(`This sequence is ${residues.length} bases long, longer than the ${maxLength} expected for ${marker}.`);
138
345
  const unresolved = (residues.match(/[^ACGT]/g) ?? []).length;
139
- if (unresolved > residues.length / 2) fail(`More than half of this sequence's bases are unresolved (${unresolved} of ${residues.length}).`);
346
+ if (unresolved > residues.length / 2) fail2(`More than half of this sequence's bases are unresolved (${unresolved} of ${residues.length}).`);
140
347
  return residues;
141
348
  }
142
349
  function readTrace(bytes, marker, markers) {
@@ -144,11 +351,11 @@ function readTrace(bytes, marker, markers) {
144
351
  try {
145
352
  read = readAbif(bytes);
146
353
  } catch (e) {
147
- return fail(e instanceof ChromatogramError ? `${e.message}.` : "This file couldn't be read as a chromatogram (.ab1).");
354
+ return fail2(e instanceof ChromatogramError ? `${e.message}.` : "This file couldn't be read as a chromatogram (.ab1).");
148
355
  }
149
356
  const a = assessRead(read);
150
- if (a.status === "failed") fail(`This read failed, so it isn't stored or tested. ${a.notes[0]}`);
151
- if (a.status === "short") fail(`This read is too short to use: only ${a.sequence.length} bases are good enough, under the ${a.settings.minLength} needed. It isn't stored or tested.`);
357
+ if (a.status === "failed") fail2(`This read failed, so it isn't stored or tested. ${a.notes[0]}`);
358
+ if (a.status === "short") fail2(`This read is too short to use: only ${a.sequence.length} bases are good enough, under the ${a.settings.minLength} needed. It isn't stored or tested.`);
152
359
  const residues = checkResidues(a.sequence, marker, markers);
153
360
  return {
154
361
  recordId: read.sampleName,
@@ -158,13 +365,13 @@ function readTrace(bytes, marker, markers) {
158
365
  }
159
366
  function registerSequence(payload, input) {
160
367
  return register(payload, input, (sha256) => {
161
- if (sha256Hex(input.text) !== sha256) fail("This file's text doesn't match its SHA-256. It may have changed after upload; upload it again.");
368
+ if (sha256Hex(input.text) !== sha256) fail2("This file's text doesn't match its SHA-256. It may have changed after upload; upload it again.");
162
369
  return readSingleSequence(input.text, input.marker, configOf(payload).markers);
163
370
  });
164
371
  }
165
372
  function registerTrace(payload, input) {
166
373
  return register(payload, input, (sha256) => {
167
- if (sha256HexBytes(input.bytes) !== sha256) fail("This file doesn't match its SHA-256. It may have changed after upload; upload it again.");
374
+ if (sha256HexBytes(input.bytes) !== sha256) fail2("This file doesn't match its SHA-256. It may have changed after upload; upload it again.");
168
375
  const { recordId, residues, trace } = readTrace(input.bytes, input.marker, configOf(payload).markers);
169
376
  return { recordId: recordId ?? input.fileName ?? "chromatogram", residues, trace };
170
377
  });
@@ -173,20 +380,20 @@ async function register(payload, input, read) {
173
380
  const c = configOf(payload);
174
381
  const opts = { req: input.req, overrideAccess: true, depth: 0 };
175
382
  const sha256 = input.sha256.replace(/^sha256:/i, "").toLowerCase();
176
- if (!/^[0-9a-f]{64}$/.test(sha256)) fail("The file's SHA-256 is missing or malformed.");
383
+ if (!/^[0-9a-f]{64}$/.test(sha256)) fail2("The file's SHA-256 is missing or malformed.");
177
384
  const { recordId, residues, trace } = read(sha256);
178
- if ((input.source ?? "kit") === "kit" && input.kit == null) fail("A kit sample needs its kit.");
179
- if (input.animal == null || input.animal === "") fail("This kit isn't linked to an animal yet. It has to be activated first.");
385
+ if ((input.source ?? "kit") === "kit" && input.kit == null) fail2("A kit sample needs its kit.");
386
+ if (input.animal == null || input.animal === "") fail2("This kit isn't linked to an animal yet. It has to be activated first.");
180
387
  let taxon = input.taxon;
181
388
  if (taxon == null && c.hasTaxa) {
182
389
  const subject = c.subject ? await payload.findByID({ collection: c.subject, id: input.animal, ...opts }).catch(() => null) : null;
183
390
  taxon = idOf(subject?.taxon);
184
391
  }
185
- if (c.hasTaxa && taxon == null) fail("This animal has no species recorded, so its sequence can't be matched to a panel.");
392
+ if (c.hasTaxa && taxon == null) fail2("This animal has no species recorded, so its sequence can't be matched to a panel.");
186
393
  let sample;
187
394
  if (input.kit != null && c.hasKit) {
188
395
  sample = (await payload.find({ collection: c.samples, where: { kit: { equals: input.kit } }, limit: 1, ...opts })).docs[0];
189
- if (sample && idOf(sample.subject) !== String(input.animal)) fail("This kit is already recorded for another animal.");
396
+ if (sample && idOf(sample.subject) !== String(input.animal)) fail2("This kit is already recorded for another animal.");
190
397
  }
191
398
  if (sample) {
192
399
  const existing = (await payload.find({ collection: c.sequences, where: { and: [{ sample: { equals: sample.id } }, { sha256: { equals: sha256 } }] }, limit: 1, ...opts })).docs[0];
@@ -273,18 +480,18 @@ async function assignWaiting(payload, args) {
273
480
  }
274
481
 
275
482
  // src/index.ts
276
- import { APIError as APIError2 } from "payload";
483
+ import { APIError as APIError3 } from "payload";
277
484
  var PANEL_TRANSITIONS = { candidate: ["active", "withdrawn"], active: ["superseded", "withdrawn"], superseded: ["withdrawn"], withdrawn: [] };
278
485
  var LOCKED_PANEL_FIELDS = ["key", "version", "marker", "checksum", "artifact", "importRun", "taxa", "groups", "notCovered", "validatedScope"];
279
486
  var REVIEW_TRANSITIONS = { pending: ["approved", "rejected"], approved: ["withdrawn"], rejected: [], withdrawn: [] };
280
- var COORDINATES = /^(lat|lon|lng|latitude|longitude|latlon|lat_lon|coordinates?)$/i;
281
- var hasCoordinates = (value) => {
282
- if (Array.isArray(value)) return value.some(hasCoordinates);
487
+ var COORDINATES2 = /^(lat|lon|lng|latitude|longitude|latlon|lat_lon|coordinates?)$/i;
488
+ var hasCoordinates2 = (value) => {
489
+ if (Array.isArray(value)) return value.some(hasCoordinates2);
283
490
  if (!value || typeof value !== "object") return false;
284
- return Object.entries(value).some(([k, v]) => COORDINATES.test(k) || hasCoordinates(v));
491
+ return Object.entries(value).some(([k, v]) => COORDINATES2.test(k) || hasCoordinates2(v));
285
492
  };
286
- var fail2 = (message) => {
287
- throw new APIError2(message, 400, void 0, true);
493
+ var fail3 = (message) => {
494
+ throw new APIError3(message, 400, void 0, true);
288
495
  };
289
496
  var idOf2 = (v) => v && typeof v === "object" ? String(v.id) : v == null ? void 0 : String(v);
290
497
  var same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
@@ -297,31 +504,31 @@ var ACTIVATION_FIELDS = ["activatedBy", "activatedAt"];
297
504
  var panelBeforeChange = ({ data, originalDoc, operation, req }) => {
298
505
  const leaving = operation === "update" && String(data.status ?? originalDoc.status) !== "candidate";
299
506
  if (leaving) {
300
- if (data.shownAsExploratory === true && String(originalDoc.status) !== "candidate") fail2("Only a candidate panel can be shown as exploratory.");
507
+ if (data.shownAsExploratory === true && String(originalDoc.status) !== "candidate") fail3("Only a candidate panel can be shown as exploratory.");
301
508
  data.shownAsExploratory = false;
302
509
  }
303
- if (hasCoordinates(data.groups)) fail2("Panels use generalized regions and never hold coordinates.");
510
+ if (hasCoordinates2(data.groups)) fail3("Panels use generalized regions and never hold coordinates.");
304
511
  if (operation === "create") {
305
- if ((data.status ?? "candidate") !== "candidate") fail2("A new panel starts as a candidate.");
306
- if (ACTIVATION_FIELDS.some((f) => stamp(data[f]))) fail2("Who activated a panel, and when, are set by activating.");
512
+ if ((data.status ?? "candidate") !== "candidate") fail3("A new panel starts as a candidate.");
513
+ if (ACTIVATION_FIELDS.some((f) => stamp(data[f]))) fail3("Who activated a panel, and when, are set by activating.");
307
514
  return data;
308
515
  }
309
516
  const from = String(originalDoc.status);
310
517
  const to = String(data.status ?? from);
311
- if (to !== from && !PANEL_TRANSITIONS[from]?.includes(to)) fail2(`A panel can't go from ${from} to ${to}.`);
518
+ if (to !== from && !PANEL_TRANSITIONS[from]?.includes(to)) fail3(`A panel can't go from ${from} to ${to}.`);
312
519
  if (from === "candidate" && to === "active") {
313
- if (!(data.validatedScope ?? originalDoc.validatedScope)?.length) fail2("A panel with no validated claims can't become active.");
314
- if (!req.user) fail2("Activating a panel needs a signed-in person, who is recorded.");
520
+ if (!(data.validatedScope ?? originalDoc.validatedScope)?.length) fail3("A panel with no validated claims can't become active.");
521
+ if (!req.user) fail3("Activating a panel needs a signed-in person, who is recorded.");
315
522
  data.activatedBy = String(req.user.id);
316
523
  data.activatedAt = (/* @__PURE__ */ new Date()).toISOString();
317
524
  } else if (ACTIVATION_FIELDS.some((f) => f in data && stamp(data[f]) !== stamp(originalDoc[f]))) {
318
- fail2("Who activated a panel, and when, are set by activating.");
525
+ fail3("Who activated a panel, and when, are set by activating.");
319
526
  }
320
527
  if (from !== "candidate") {
321
528
  for (const f of LOCKED_PANEL_FIELDS) {
322
529
  if (!(f in data)) continue;
323
530
  const changed = f === "groups" ? !same(stripIds(data[f]), stripIds(originalDoc[f])) : Array.isArray(data[f]) ? !same(data[f].map(idOf2), (originalDoc[f] ?? []).map(idOf2)) : idOf2(data[f]) !== idOf2(originalDoc[f]);
324
- if (changed) fail2(`A ${from} panel can't be edited. Build a new version instead.`);
531
+ if (changed) fail3(`A ${from} panel can't be edited. Build a new version instead.`);
325
532
  }
326
533
  }
327
534
  return data;
@@ -334,45 +541,45 @@ var supersedeOthers = (panels) => async ({ doc, previousDoc, req }) => {
334
541
  };
335
542
  var assignmentBeforeChange = (panels, againstShown, tenantField) => async ({ data, originalDoc, operation, req }) => {
336
543
  if (operation === "create") {
337
- if ((data.reviewStatus ?? "pending") !== "pending") fail2("A new result starts as pending review.");
544
+ if ((data.reviewStatus ?? "pending") !== "pending") fail3("A new result starts as pending review.");
338
545
  const panel = await req.payload.findByID({ collection: panels, id: idOf2(data.panel), depth: 0, req, overrideAccess: true });
339
546
  const shown = panel.status === "candidate" && panel.shownAsExploratory === true;
340
- if (panel.status !== "active" && !(againstShown && shown)) fail2(againstShown ? "Results can only be made against an active panel, or a candidate shown as exploratory." : "Results can only be made against an active panel.");
547
+ if (panel.status !== "active" && !(againstShown && shown)) fail3(againstShown ? "Results can only be made against an active panel, or a candidate shown as exploratory." : "Results can only be made against an active panel.");
341
548
  data.panelStatus = panel.status;
342
549
  data.panelShownAsExploratory = shown;
343
550
  const result = data.result;
344
551
  const problems = validateResult(result).filter((d) => d.severity === "error");
345
- if (problems.length) fail2(problems.map((p) => p.message).join("; "));
346
- if (result.panel.version !== panel.version || result.panel.checksum !== panel.checksum) fail2("This result was not made with this panel version.");
552
+ if (problems.length) fail3(problems.map((p) => p.message).join("; "));
553
+ if (result.panel.version !== panel.version || result.panel.checksum !== panel.checksum) fail3("This result was not made with this panel version.");
347
554
  const found = new Set(result.findings.map((f) => f.group));
348
555
  const missing = (panel.groups ?? []).filter((g) => !found.has(g.groupId)).map((g) => g.groupId);
349
- if (missing.length) fail2(`Every group must be reported. Missing: ${missing.join(", ")}.`);
350
- if (hasCoordinates(result)) fail2("Results never hold coordinates.");
556
+ if (missing.length) fail3(`Every group must be reported. Missing: ${missing.join(", ")}.`);
557
+ if (hasCoordinates2(result)) fail3("Results never hold coordinates.");
351
558
  return data;
352
559
  }
353
560
  const from = String(originalDoc.reviewStatus);
354
561
  const to = String(data.reviewStatus ?? from);
355
562
  for (const f of ["result", "panel", "sequence", "subject", "summary", "importRun"]) {
356
- if (f in data && (f === "result" || f === "summary" ? !same(data[f], originalDoc[f]) : idOf2(data[f]) !== idOf2(originalDoc[f]))) fail2("A result can't be edited. Make a new one instead.");
563
+ if (f in data && (f === "result" || f === "summary" ? !same(data[f], originalDoc[f]) : idOf2(data[f]) !== idOf2(originalDoc[f]))) fail3("A result can't be edited. Make a new one instead.");
357
564
  }
358
- if (tenantField in data && idOf2(data[tenantField]) !== idOf2(originalDoc[tenantField])) fail2("A result stays on the site it was made for.");
565
+ if (tenantField in data && idOf2(data[tenantField]) !== idOf2(originalDoc[tenantField])) fail3("A result stays on the site it was made for.");
359
566
  for (const f of ["panelStatus", "panelShownAsExploratory"]) {
360
- if (f in data && !same(data[f], originalDoc[f])) fail2("The panel status a result was made against is set when it is made.");
567
+ if (f in data && !same(data[f], originalDoc[f])) fail3("The panel status a result was made against is set when it is made.");
361
568
  }
362
569
  if (to !== from) {
363
- if (!REVIEW_TRANSITIONS[from]?.includes(to)) fail2(`A result can't go from ${from} to ${to}.`);
570
+ if (!REVIEW_TRANSITIONS[from]?.includes(to)) fail3(`A result can't go from ${from} to ${to}.`);
364
571
  if (to === "approved") {
365
- if (!req.user) fail2("Approving a result needs a signed-in reviewer.");
572
+ if (!req.user) fail3("Approving a result needs a signed-in reviewer.");
366
573
  data.reviewer = String(req.user.id);
367
574
  data.releasedAt = (/* @__PURE__ */ new Date()).toISOString();
368
575
  }
369
576
  } else {
370
- if ("reviewer" in data && data.reviewer !== originalDoc.reviewer) fail2("The reviewer is set by approving.");
371
- if ("releasedAt" in data && String(data.releasedAt) !== String(originalDoc.releasedAt)) fail2("The release date is set by approving.");
577
+ if ("reviewer" in data && data.reviewer !== originalDoc.reviewer) fail3("The reviewer is set by approving.");
578
+ if ("releasedAt" in data && String(data.releasedAt) !== String(originalDoc.releasedAt)) fail3("The release date is set by approving.");
372
579
  }
373
580
  return data;
374
581
  };
375
- var relation2 = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
582
+ var relation3 = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
376
583
  var checkedWhenMade = { validate: (value, options) => options.operation === "update" ? true : validateRelationship(value, options) };
377
584
  var onePhylogeny = (options = {}) => (config) => {
378
585
  const panels = options.slugs?.panels ?? "panels";
@@ -380,7 +587,7 @@ var onePhylogeny = (options = {}) => (config) => {
380
587
  const tenantField = options.tenantField ?? options.records?.tenantField ?? "tenant";
381
588
  const records = options.records ? recordCollections({ tenantField, ...options.records }, { panels, assignments, subject: options.relations?.subject, taxa: options.relations?.taxa, files: options.relations?.files, manage: options.manageAccess ?? (() => false), againstShown: options.resultsAgainst === "activeOrShown" }) : void 0;
382
589
  const r = { ...options.relations, ...records && !options.relations?.sequence ? { sequence: records.config.sequences } : {} };
383
- const group = options.group ?? "Genetics";
590
+ const group2 = options.group ?? "Genetics";
384
591
  const manage = options.manageAccess ?? (() => false);
385
592
  const review = options.reviewAccess ?? manage;
386
593
  const readReleased = options.readReleasedAccess ?? (({ req }) => Boolean(req.user));
@@ -388,7 +595,7 @@ var onePhylogeny = (options = {}) => (config) => {
388
595
  const panelCollection = {
389
596
  slug: panels,
390
597
  labels: { singular: "Reference panel", plural: "Reference panels" },
391
- admin: { group, useAsTitle: "key", defaultColumns: ["key", "version", "status", "marker"] },
598
+ admin: { group: group2, useAsTitle: "key", defaultColumns: ["key", "version", "status", "marker"] },
392
599
  access: {
393
600
  read: async (args) => {
394
601
  const published = { status: { in: ["active", "superseded"] } };
@@ -406,9 +613,9 @@ var onePhylogeny = (options = {}) => (config) => {
406
613
  { name: "shownAsExploratory", type: "checkbox", defaultValue: false, index: true, admin: { description: "Show this candidate as exploratory, before review. Only candidates; cleared when it moves on." } },
407
614
  { name: "marker", type: "text", required: true },
408
615
  { name: "checksum", type: "text", required: true, index: true },
409
- ...relation2("taxa", r.taxa, { hasMany: true }),
410
- ...relation2("artifact", r.files, { admin: { description: "The full panel: JSON manifest and sequences." } }),
411
- ...relation2("importRun", r.importRuns),
616
+ ...relation3("taxa", r.taxa, { hasMany: true }),
617
+ ...relation3("artifact", r.files, { admin: { description: "The full panel: JSON manifest and sequences." } }),
618
+ ...relation3("importRun", r.importRuns),
412
619
  { name: "validatedScope", type: "text", hasMany: true, admin: { description: "The claims this panel is validated for. Pages show only these." } },
413
620
  { name: "notCovered", type: "text", hasMany: true },
414
621
  { name: "groups", type: "array", fields: [{ name: "groupId", type: "text", required: true }, { name: "label", type: "text", required: true }, { name: "regionName", type: "text", admin: { description: "A general region, never coordinates." } }] },
@@ -420,7 +627,7 @@ var onePhylogeny = (options = {}) => (config) => {
420
627
  const assignmentCollection = {
421
628
  slug: assignments,
422
629
  labels: { singular: "Lineage result", plural: "Lineage results" },
423
- admin: { group, useAsTitle: "summary", defaultColumns: ["summary", "panel", "reviewStatus", "releasedAt"] },
630
+ admin: { group: group2, useAsTitle: "summary", defaultColumns: ["summary", "panel", "reviewStatus", "releasedAt"] },
424
631
  access: {
425
632
  // Managers and reviewers see what their own rules allow, including pending results; everyone else only released ones.
426
633
  read: async (args) => {
@@ -433,12 +640,12 @@ var onePhylogeny = (options = {}) => (config) => {
433
640
  delete: () => false
434
641
  },
435
642
  fields: [
436
- ...relation2("subject", r.subject, checkedWhenMade),
437
- ...relation2("sequence", r.sequence, checkedWhenMade),
643
+ ...relation3("subject", r.subject, checkedWhenMade),
644
+ ...relation3("sequence", r.sequence, checkedWhenMade),
438
645
  { name: "panel", type: "relationship", relationTo: panels, required: true, index: true, ...checkedWhenMade },
439
646
  { name: "summary", type: "text", required: true },
440
647
  { name: "result", type: "json", required: true, admin: { description: "The OnePhylogeny result, stored exactly as computed." } },
441
- ...relation2("importRun", r.importRuns, checkedWhenMade),
648
+ ...relation3("importRun", r.importRuns, checkedWhenMade),
442
649
  { name: "reviewStatus", type: "select", required: true, defaultValue: "pending", index: true, options: ["pending", "approved", "rejected", "withdrawn"] },
443
650
  { name: "reviewer", type: "text", admin: { readOnly: true } },
444
651
  { name: "releasedAt", type: "date", admin: { readOnly: true } },
@@ -459,19 +666,25 @@ var onePhylogeny = (options = {}) => (config) => {
459
666
  };
460
667
  return {
461
668
  ...config,
669
+ ...records ? { db: withSourceKeyErrors(config.db, records.config.samples) } : {},
462
670
  collections: [...config.collections ?? [], ...records?.collections ?? [], panelCollection, assignmentCollection],
463
671
  endpoints: [...config.endpoints ?? [], released],
464
672
  ...records ? { custom: { ...config.custom, [records.customKey]: records.config } } : {}
465
673
  };
466
674
  };
467
675
  export {
676
+ DATA_LICENSES,
677
+ READ_TIERS,
678
+ SOURCE_TYPES,
468
679
  anyOf,
469
680
  assignWaiting,
470
681
  either,
682
+ licenseTerms,
471
683
  onePhylogeny,
472
684
  readSingleSequence,
473
685
  readTrace,
474
686
  registerSequence,
475
687
  registerTrace,
688
+ sourceKeyOf,
476
689
  summarize
477
690
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-onephylogeny",
3
- "version": "0.1.0-alpha.8",
3
+ "version": "0.1.0-alpha.9",
4
4
  "description": "OnePhylogeny for Payload: immutable reference panels and released results on your own collections, with server-enforced review, safe endpoints and no coordinates.",
5
5
  "keywords": [
6
6
  "phylogenetics",
@@ -35,7 +35,7 @@
35
35
  "node": ">=22"
36
36
  },
37
37
  "dependencies": {
38
- "@extantape/onephylogeny-core": "^0.1.0-alpha.8"
38
+ "@extantape/onephylogeny-core": "^0.1.0-alpha.9"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "payload": "^3.80.0"