@mark1russell7/ontology 0.1.0 → 0.2.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 +20 -1
- package/build/{generate-D6Vazln0.mjs → generate-Dv-t-uia.mjs} +49 -10
- package/build/generate-Dv-t-uia.mjs.map +1 -0
- package/build/{header-nlcc_Vh2.d.mts → header-BluJvnVP.d.mts} +22 -2
- package/build/index.d.mts +4 -2
- package/build/index.mjs +2 -2
- package/build/index.mjs.map +1 -1
- package/build/node.d.mts +1 -1
- package/build/node.mjs +1 -1
- package/package.json +1 -1
- package/build/generate-D6Vazln0.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -30,6 +30,8 @@ The spine is the general part of each registry:
|
|
|
30
30
|
|
|
31
31
|
`instance-of` names no kind of particular. An add-on adds its kinds to it with an extension.
|
|
32
32
|
|
|
33
|
+
The attribute `name` of `entity` is optional. `nameOf(entity)` gives the name, or the id when the entity has no name.
|
|
34
|
+
|
|
33
35
|
## Make a registry with an add-on
|
|
34
36
|
|
|
35
37
|
```ts
|
|
@@ -57,6 +59,23 @@ registry.validateEntity({ id: "lib.book.dune", kind: "book", attrs: { name: "Dun
|
|
|
57
59
|
|
|
58
60
|
`spineRegistry(...addOns)` joins the spine and the add-ons with `composeRegistryInput`. The registry refuses a kind, a relation kind or a facet that two parts declare. An extension can only add kinds to the ends of a relation kind. A narrower relation kind must stay inside the ends of its parent, so an add-on extends the parent too.
|
|
59
61
|
|
|
62
|
+
## Rules across attributes
|
|
63
|
+
|
|
64
|
+
A kind can have requirements: when each attribute of `when` has its value, each attribute of `then` has a value. A subkind gets the requirements of its parent.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const task = {
|
|
68
|
+
name: "task",
|
|
69
|
+
parent: "entity",
|
|
70
|
+
mode: "occurrent",
|
|
71
|
+
description: "A task.",
|
|
72
|
+
attributes: { state: z.enum(["planned", "done"]), due: z.string().optional() },
|
|
73
|
+
requirements: [{ description: "a planned task has a due date", when: { state: "planned" }, then: ["due"] }],
|
|
74
|
+
};
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The registry refuses a requirement that names an attribute that the kind does not have. The JSON Schema of the kind shows each requirement as `if` and `then` in `allOf`.
|
|
78
|
+
|
|
60
79
|
## Check entities and edges
|
|
61
80
|
|
|
62
81
|
- `validateEntity(raw)` checks the attributes of the kind, its ancestors and their facets. It gives the default scope of the kind to an entity with no scope.
|
|
@@ -89,7 +108,7 @@ const stale = await staleGenerated(registry, "generated"); // [] when the files
|
|
|
89
108
|
|
|
90
109
|
| File | Contents |
|
|
91
110
|
| --- | --- |
|
|
92
|
-
| `duckdb.sql` | The tables `entities` and `edges`, and a view `v_<kind>` with a column for each attribute. A quantity gives a number column and a unit column. |
|
|
111
|
+
| `duckdb.sql` | The tables `entities` and `edges`, and a view `v_<kind>` with a column for each attribute. A quantity gives a number column and a unit column. The envelope columns are `envelope_scope`, `envelope_valid_from`, `envelope_valid_to` and `envelope_observed_at`. |
|
|
93
112
|
| `sqlite.sql` | The tables `entities` and `edges`, with JSON attributes. |
|
|
94
113
|
| `registry.json` | Each kind and each relation kind, with the JSON Schema of its attributes and qualifiers. |
|
|
95
114
|
| `jsonschema.json` | The JSON Schemas of an entity, an edge and the full attributes of each kind. |
|
|
@@ -258,6 +258,14 @@ var Registry = class {
|
|
|
258
258
|
const inherited = this.effectiveShape(RELATION_ROOT);
|
|
259
259
|
for (const relation of relations.values()) for (const [what, names] of [["qualifier", Object.keys(relation.qualifiers ?? {})], ["role", Object.keys(relation.roles ?? {})]]) for (const name of names) if (name in inherited) throw new RegistryError(`relation kind ${relation.name} declares ${what} ${name}, which every relation instance already has`);
|
|
260
260
|
}
|
|
261
|
+
for (const kind of kinds.values()) {
|
|
262
|
+
const shape = this.effectiveShape(kind.name);
|
|
263
|
+
for (const requirement of kind.requirements ?? []) {
|
|
264
|
+
const names = [...Object.keys(requirement.when), ...requirement.then];
|
|
265
|
+
if (Object.keys(requirement.when).length === 0 || requirement.then.length === 0) throw new RegistryError(`kind ${kind.name}: a requirement needs a when and a then`);
|
|
266
|
+
for (const name of names) if (!(name in shape)) throw new RegistryError(`kind ${kind.name}: a requirement names unknown attribute ${name}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
261
269
|
for (const deadline of input.deadlines ?? []) {
|
|
262
270
|
if (!kinds.has(deadline.kind)) throw new RegistryError(`deadline ${deadline.attribute} is on unknown kind ${deadline.kind}`);
|
|
263
271
|
if (deadline.after !== void 0) {
|
|
@@ -390,11 +398,26 @@ var Registry = class {
|
|
|
390
398
|
}
|
|
391
399
|
return shape;
|
|
392
400
|
}
|
|
393
|
-
/** This method gives the
|
|
401
|
+
/** This method gives the requirements of a kind: the requirements of its ancestors, then its own. */
|
|
402
|
+
effectiveRequirements(kindName) {
|
|
403
|
+
return this.ancestry(kindName).flatMap((kind) => kind.requirements ?? []);
|
|
404
|
+
}
|
|
405
|
+
/** This method gives the strict schema of the attributes of a kind, with the check of its requirements. */
|
|
394
406
|
effectiveSchema(kindName) {
|
|
395
407
|
const cached = this.schemaCache.get(kindName);
|
|
396
408
|
if (cached !== void 0) return cached;
|
|
397
|
-
const
|
|
409
|
+
const requirements = this.effectiveRequirements(kindName);
|
|
410
|
+
const object = z.strictObject(this.effectiveShape(kindName));
|
|
411
|
+
const schema = requirements.length === 0 ? object : object.superRefine((attrs, context) => {
|
|
412
|
+
for (const requirement of requirements) {
|
|
413
|
+
if (!Object.entries(requirement.when).every(([name, value]) => attrs[name] === value)) continue;
|
|
414
|
+
for (const name of requirement.then) if (attrs[name] === void 0) context.addIssue({
|
|
415
|
+
code: "custom",
|
|
416
|
+
path: [name],
|
|
417
|
+
message: `required: ${requirement.description}`
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
});
|
|
398
421
|
this.schemaCache.set(kindName, schema);
|
|
399
422
|
return schema;
|
|
400
423
|
}
|
|
@@ -656,10 +679,10 @@ const attrColumn = (key, shape) => {
|
|
|
656
679
|
/** This function gives the view columns of an attribute. A quantity has two columns. */
|
|
657
680
|
const columnNames = (key, shape) => shape.kind === "quantity" ? [key, `${key}_unit`] : [key];
|
|
658
681
|
const ENVELOPE_COLUMNS = [
|
|
659
|
-
"envelope->>'scope' AS
|
|
660
|
-
"envelope->>'valid_from' AS
|
|
661
|
-
"envelope->>'valid_to' AS
|
|
662
|
-
"envelope->>'observed_at' AS
|
|
682
|
+
"envelope->>'scope' AS envelope_scope",
|
|
683
|
+
"envelope->>'valid_from' AS envelope_valid_from",
|
|
684
|
+
"envelope->>'valid_to' AS envelope_valid_to",
|
|
685
|
+
"envelope->>'observed_at' AS envelope_observed_at"
|
|
663
686
|
];
|
|
664
687
|
const RESERVED_COLUMNS = /* @__PURE__ */ new Set([
|
|
665
688
|
"id",
|
|
@@ -723,6 +746,15 @@ CREATE INDEX IF NOT EXISTS idx_edges_to ON edges (to_id);
|
|
|
723
746
|
CREATE INDEX IF NOT EXISTS idx_edges_type ON edges (type);
|
|
724
747
|
`;
|
|
725
748
|
// src/codegen/jsonschema.ts
|
|
749
|
+
/** This function gives the JSON Schema of the requirements of a kind: an `if` and a `then` for each. */
|
|
750
|
+
const requirementsJson = (requirements) => requirements.length === 0 ? {} : { allOf: requirements.map((requirement) => ({
|
|
751
|
+
description: requirement.description,
|
|
752
|
+
if: {
|
|
753
|
+
properties: Object.fromEntries(Object.entries(requirement.when).map(([name, value]) => [name, { const: value }])),
|
|
754
|
+
required: Object.keys(requirement.when)
|
|
755
|
+
},
|
|
756
|
+
then: { required: [...requirement.then] }
|
|
757
|
+
})) };
|
|
726
758
|
/** This function gives one kind as data. The schema includes the attributes of the facets of the kind. */
|
|
727
759
|
const kindJson = (registry, kind) => {
|
|
728
760
|
const facets = kind.facets ?? [];
|
|
@@ -732,10 +764,14 @@ const kindJson = (registry, kind) => {
|
|
|
732
764
|
parent: kind.parent,
|
|
733
765
|
mode: kind.mode,
|
|
734
766
|
description: kind.description,
|
|
735
|
-
attributes:
|
|
767
|
+
attributes: {
|
|
768
|
+
...z.toJSONSchema(z.strictObject(shape)),
|
|
769
|
+
...requirementsJson(kind.requirements ?? [])
|
|
770
|
+
},
|
|
736
771
|
...facets.length > 0 ? { facets: [...facets] } : {},
|
|
737
772
|
...kind.defaultScope !== void 0 ? { defaultScope: kind.defaultScope } : {},
|
|
738
|
-
...kind.staleAfterDays !== void 0 ? { staleAfterDays: kind.staleAfterDays } : {}
|
|
773
|
+
...kind.staleAfterDays !== void 0 ? { staleAfterDays: kind.staleAfterDays } : {},
|
|
774
|
+
...kind.requirements !== void 0 && kind.requirements.length > 0 ? { requirements: [...kind.requirements] } : {}
|
|
739
775
|
};
|
|
740
776
|
};
|
|
741
777
|
/** This function gives one relation kind as data. */
|
|
@@ -765,7 +801,10 @@ const registryJson = (registry) => ({
|
|
|
765
801
|
const generateJsonSchemas = (registry) => ({
|
|
766
802
|
entity: z.toJSONSchema(entitySchema),
|
|
767
803
|
edge: z.toJSONSchema(edgeSchema),
|
|
768
|
-
kinds: Object.fromEntries([...registry.kinds.keys()].map((name) => [name,
|
|
804
|
+
kinds: Object.fromEntries([...registry.kinds.keys()].map((name) => [name, {
|
|
805
|
+
...z.toJSONSchema(z.strictObject(registry.effectiveShape(name))),
|
|
806
|
+
...requirementsJson(registry.effectiveRequirements(name))
|
|
807
|
+
}]))
|
|
769
808
|
});
|
|
770
809
|
// src/generate.ts
|
|
771
810
|
/** This function gives each generated file of a registry: the SQL of two stores, the registry and the JSON Schemas. */
|
|
@@ -777,4 +816,4 @@ const generateAll = (registry, options) => ({
|
|
|
777
816
|
});
|
|
778
817
|
export { visibleTo as A, isRelationId as C, relationId as D, nameOf as E, scopeRank as O, envelopeSchema as S, maxScope as T, SCOPES as _, relationJson as a, entityIdSchema as b, DEFAULT_HEADER as c, Registry as d, RegistryError as f, NAME_PATTERN as g, MODES as h, registryJson as i, scopeSchema as k, columnShape as l, ENTITY_ID_PATTERN as m, generateJsonSchemas as n, generateSqliteDdl as o, composeRegistryInput as p, kindJson as r, generateDuckDbDdl as s, generateAll as t, RELATION_ROOT as u, edgeRowSchema as v, keyedRelationId as w, entitySchema as x, edgeSchema as y };
|
|
779
818
|
|
|
780
|
-
//# sourceMappingURL=generate-
|
|
819
|
+
//# sourceMappingURL=generate-Dv-t-uia.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-Dv-t-uia.mjs","names":[],"sources":["../src/grammar.ts","../src/registry.ts","../src/codegen/columns.ts","../src/codegen/header.ts","../src/codegen/duckdb.ts","../src/codegen/sqlite.ts","../src/codegen/jsonschema.ts","../src/generate.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { z } from \"zod\";\n\n/**\n * The mode of a kind. Each relation kind has the mode `relation`. Only the root kind has the mode `top`.\n */\nexport type Mode = \"top\" | \"continuant\" | \"occurrent\" | \"abstract\" | \"information\" | \"relation\";\n\n/** The modes of being, in the order of `Mode`. */\nexport const MODES: readonly Mode[] = [\"top\", \"continuant\", \"occurrent\", \"abstract\", \"information\", \"relation\"];\n\n/** The scopes of a record, from the least sensitive to the most sensitive. */\nexport const SCOPES = [\"public\", \"shared\", \"private\", \"intimate\"] as const;\n\n/** The scope of a record: who can see it. */\nexport type Scope = (typeof SCOPES)[number];\n\n/** The schema of a scope. */\nexport const scopeSchema: z.ZodEnum<{ [K in Scope]: K }> = z.enum(SCOPES);\n\n/**\n * The rank of each scope. The scopes are an order, not a set. An audience sees each scope at its rank or below.\n * A record that comes from a more sensitive record gets the more sensitive scope.\n */\nconst SCOPE_RANK: Readonly<Record<Scope, number>> = { public: 0, shared: 1, private: 2, intimate: 3 };\n\n/** This function gives the rank of a scope: 0 for `public`, 3 for `intimate`. */\nexport const scopeRank = (scope: Scope): number => SCOPE_RANK[scope];\n\n/** This function gives the more sensitive of two scopes. */\nexport const maxScope = (a: Scope, b: Scope): Scope => (SCOPE_RANK[a] >= SCOPE_RANK[b] ? a : b);\n\n/** This function tells if an audience at the scope `audience` can see a record at the scope `scope`. */\nexport const visibleTo = (scope: Scope, audience: Scope): boolean => SCOPE_RANK[scope] <= SCOPE_RANK[audience];\n\n/** The form of the name of a kind, a relation kind, a facet or a role. */\nexport const NAME_PATTERN: RegExp = /^[a-z0-9][a-z0-9-]*$/;\n\n/** The form of the id of an entity: two or more names, with a dot between each two. */\nexport const ENTITY_ID_PATTERN: RegExp = /^[a-z0-9][a-z0-9-]*(\\.[a-z0-9][a-z0-9-]*)+$/;\n\n/** The schema of the id of an entity. */\nexport const entityIdSchema: z.ZodString = z.string().regex(ENTITY_ID_PATTERN);\n\nconst isoDateTime = z.iso.datetime({ offset: true });\n\n/** The envelope of a record: the time, the source, the trust and the scope of its data. */\nexport interface Envelope {\n /** The start of the time in which the record is true. */\n readonly valid_from?: string | undefined;\n /** The end of the time in which the record is true. */\n readonly valid_to?: string | undefined;\n /** The time of the observation of the record. */\n readonly observed_at?: string | undefined;\n /** The time of the write of the record. */\n readonly recorded_at?: string | undefined;\n /** The ids of the sources of the record. */\n readonly source_ids?: readonly string[] | undefined;\n /** It is `true` when a calculation made the record from other records. */\n readonly derived?: boolean | undefined;\n /** The confidence in the record, from 0 to 1. */\n readonly confidence?: number | undefined;\n /** The text that tells who or what gave the record. */\n readonly attribution?: string | undefined;\n /** Who can see the record. */\n readonly scope?: Scope | undefined;\n /** The id of the record that replaces this record. */\n readonly superseded_by?: string | undefined;\n /** The id of the record that this record was retired from, when no record replaces it. */\n readonly retired_from?: string | undefined;\n}\n\n/** An entity: a record with an id, a kind, its attributes and its envelope. */\nexport interface Entity {\n readonly id: string;\n readonly kind: string;\n readonly attrs: Record<string, unknown>;\n readonly envelope: Envelope;\n}\n\n/** An entity as a writer gives it: the envelope is optional. */\nexport interface EntityInput {\n readonly id: string;\n readonly kind: string;\n readonly attrs: Record<string, unknown>;\n readonly envelope?: Envelope | undefined;\n}\n\n/** This function gives the name of an entity: its attribute `name` when it is a string, or else its id. */\nexport const nameOf = (entity: Pick<Entity, \"id\" | \"attrs\">): string => {\n const name = entity.attrs[\"name\"];\n return typeof name === \"string\" ? name : entity.id;\n};\n\n/**\n * The other entities of a relation, by role, in addition to its two ends. A role with one filler holds an id.\n * A role with many fillers holds a list of ids.\n */\nexport type RoleFillers = Readonly<Record<string, string | readonly string[]>>;\n\n/**\n * A relation instance, as seen from its two ends: an edge. Its id comes from what it relates (`relationId`).\n * Thus a link, a citation and a claim can refer to it.\n */\nexport interface Edge {\n readonly id: string;\n readonly from: string;\n readonly type: string;\n readonly to: string;\n /** The other participants of the relation. Each filler is an entity, with the same check as an end. */\n readonly roles?: RoleFillers | undefined;\n readonly qualifiers: Record<string, unknown>;\n readonly envelope: Envelope;\n /**\n * It is `true` on the second row of a symmetric relation: the same relation, read from its other end. A writer\n * does not set it.\n */\n readonly inverse?: true | undefined;\n}\n\n/** An edge as a writer gives it. The registry calculates the id. A writer does not type it. */\nexport interface EdgeInput {\n readonly id?: string | undefined;\n readonly from: string;\n readonly type: string;\n readonly to: string;\n readonly roles?: RoleFillers | undefined;\n readonly qualifiers?: Record<string, unknown> | undefined;\n readonly envelope?: Envelope | undefined;\n}\n\n/** An edge after the check of its shape, before the check of the registry. */\nexport interface ParsedEdge {\n readonly id?: string | undefined;\n readonly from: string;\n readonly type: string;\n readonly to: string;\n readonly roles?: RoleFillers | undefined;\n readonly qualifiers: Record<string, unknown>;\n readonly envelope: Envelope;\n}\n\n/** This function gives the FNV-1a hash of 64 bits of a text, in hexadecimal. It is the same in Node.js and a browser. */\nconst fnv1a64 = (text: string): string => {\n let hash = 0xcbf29ce484222325n;\n for (const byte of new TextEncoder().encode(text)) {\n hash ^= BigInt(byte);\n hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn;\n }\n return hash.toString(16).padStart(16, \"0\");\n};\n\n/**\n * This function gives the id of a relation instance from its kind and its two ends. The same fact always gets\n * the same id. A symmetric kind sorts its two ends first, so each pair has one relation.\n *\n * @remarks\n * A space joins the two ends, and no entity id contains a space. A kind with a key of more parts gets its id from\n * `keyedRelationId`, through `Registry.relationIdOf`.\n */\nexport const relationId = (type: string, from: string, to: string, symmetric = false): string => {\n const [a, b] = symmetric && to < from ? [to, from] : [from, to];\n return `rel.${type}.${fnv1a64(`${a} ${b}`)}`;\n};\n\n/**\n * This function gives the id of a relation whose key has more parts than its two ends. The hash is of the parts\n * of the key, as name and value, in the order of the key.\n *\n * @remarks\n * The JSON of the parts starts with a bracket, and no entity id does. Thus the id is not an id of `relationId` at any time.\n */\nexport const keyedRelationId = (type: string, parts: ReadonlyArray<readonly [string, unknown]>): string =>\n `rel.${type}.${fnv1a64(JSON.stringify(parts))}`;\n\n/** This function tells if an id is the id of a relation instance. */\nexport const isRelationId = (id: string): boolean => id.startsWith(\"rel.\");\n\n/**\n * The schema of an envelope. A record has `superseded_by` or `retired_from`, not the two. The time `valid_from`\n * is not after `valid_to`.\n */\nexport const envelopeSchema: z.ZodType<Envelope, Envelope> = z\n .strictObject({\n valid_from: isoDateTime.optional(),\n valid_to: isoDateTime.optional(),\n observed_at: isoDateTime.optional(),\n recorded_at: isoDateTime.optional(),\n source_ids: z.array(z.string()).optional(),\n derived: z.boolean().optional(),\n confidence: z.number().min(0).max(1).optional(),\n attribution: z.string().optional(),\n scope: scopeSchema.optional(),\n superseded_by: entityIdSchema.optional(),\n retired_from: entityIdSchema.optional(),\n })\n .refine((e) => e.superseded_by === undefined || e.retired_from === undefined, {\n message: \"superseded_by and retired_from are mutually exclusive\",\n })\n .refine((e) => e.valid_from === undefined || e.valid_to === undefined || e.valid_from <= e.valid_to, {\n message: \"valid_from must not be after valid_to\",\n }) as unknown as z.ZodType<Envelope, Envelope>;\n\n/** The schema of an entity, before the check of its kind. */\nexport const entitySchema: z.ZodType<Entity, EntityInput> = z.strictObject({\n id: entityIdSchema,\n kind: z.string().regex(NAME_PATTERN),\n attrs: z.record(z.string(), z.unknown()),\n envelope: envelopeSchema.default({}),\n});\n\nconst roleFillersSchema = z.record(z.string().regex(NAME_PATTERN), z.union([entityIdSchema, z.array(entityIdSchema)]));\n\n/** The schema of an edge as a writer gives it. */\nexport const edgeSchema: z.ZodType<ParsedEdge, EdgeInput> = z.strictObject({\n id: entityIdSchema.optional(),\n from: entityIdSchema,\n type: z.string().regex(NAME_PATTERN),\n to: entityIdSchema,\n roles: roleFillersSchema.optional(),\n qualifiers: z.record(z.string(), z.unknown()).default({}),\n envelope: envelopeSchema.default({}),\n});\n\n/** The schema of an edge as a store gives it back: always with its id, and with `inverse` on a second row. */\nexport const edgeRowSchema: z.ZodType<Edge, Edge> = z.strictObject({\n id: entityIdSchema,\n from: entityIdSchema,\n type: z.string().regex(NAME_PATTERN),\n to: entityIdSchema,\n roles: roleFillersSchema.optional(),\n qualifiers: z.record(z.string(), z.unknown()),\n envelope: envelopeSchema,\n inverse: z.literal(true).optional(),\n});\n\n/** The attributes of a kind or a facet: a schema for each name. */\nexport type AttrShape = Record<string, z.ZodType>;\n\n/** A kind of entity. */\nexport interface KindDef {\n readonly name: string;\n /** The kind above this kind. Only the root kind has `null`. */\n readonly parent: string | null;\n readonly mode: Mode;\n readonly description: string;\n readonly attributes: AttrShape;\n /** The facets of the kind. Their attributes are attributes of the kind. */\n readonly facets?: readonly string[];\n /** The scope of an entity of the kind when its envelope has no scope. */\n readonly defaultScope?: Scope;\n /** The age in days after which a record of the kind is old. */\n readonly staleAfterDays?: number;\n /**\n * The name of the evidence ladder that grades the facts of the kind. A subkind gets the ladder of its parent\n * when it has no ladder.\n */\n readonly ladder?: string;\n /**\n * The name of the type of option that a choice about the kind is between. A subkind gets the type of its parent\n * when it has no type.\n */\n readonly option?: string;\n /**\n * The rules across the attributes of the kind. A subkind gets the rules of its parent. The JSON Schema of the kind\n * shows each rule as `if` and `then`.\n */\n readonly requirements?: readonly Requirement[];\n}\n\n/** A value that a requirement compares with an attribute. */\nexport type RequirementValue = string | number | boolean | null;\n\n/**\n * A rule across the attributes of a kind: when each attribute of `when` has its value, each attribute of `then` has\n * a value. Example: a planned function has a size and an acceptance.\n */\nexport interface Requirement {\n readonly description: string;\n /** The attributes and the values that start the rule. */\n readonly when: Readonly<Record<string, RequirementValue>>;\n /** The attributes that then have a value. */\n readonly then: readonly string[];\n}\n\n/**\n * A date attribute of a kind with a consequence: a due date, an end of a warranty or the date of a last check.\n * A reader of deadlines finds the records with a date that is near.\n */\nexport interface Deadline {\n readonly kind: string;\n readonly attribute: string;\n /** The text that tells the consequence on the date: \"due\", \"warranty ends\". */\n readonly label: string;\n /** The time after a last check at which the consequence occurs, in whole days. */\n readonly after?: Quantity;\n}\n\n/**\n * An attribute whose value is the name of an entity. A projection makes an edge from each value. Thus the two\n * ends show the link, and a reader gets the attributes of the named entity.\n */\nexport interface NamedReference {\n /** The attribute that holds the name. */\n readonly attribute: string;\n /** The relation kind of the edge from the holder to the named entity. */\n readonly relation: string;\n /** The kind of the named entities. The value is their attribute `name`. */\n readonly toKind: string;\n}\n\n/**\n * A relation kind: the type of an edge. The registry makes each relation kind a kind of the mode `relation`\n * under the kind `relation`. Its qualifiers and roles are the attributes of that kind.\n */\nexport interface RelationKindDef {\n readonly name: string;\n /**\n * The relation kind that this kind narrows. The kind can make the ends of its parent narrower, but not wider.\n * It gets the qualifiers, the roles and the key of its parent. A reader of the parent also finds this kind.\n */\n readonly parent?: string;\n readonly description: string;\n /** The kinds of the end `from`. A subkind of each kind is also correct. */\n readonly from: readonly string[];\n /** The kinds of the end `to`. A subkind of each kind is also correct. */\n readonly to: readonly string[];\n readonly qualifiers?: AttrShape;\n /** It is `true` for a relation of an unordered pair: one relation for each pair, read from the two ends. */\n readonly symmetric?: boolean;\n readonly transitive?: boolean;\n /**\n * It is `true` for a family of relation kinds with no instances of its own. A reader of the family finds the\n * kinds that narrow it.\n */\n readonly abstract?: boolean;\n /**\n * The other participants of the relation, by role, in addition to its two ends. Each role names the kinds of\n * its fillers. The check of a filler is the same as the check of an end.\n */\n readonly roles?: Readonly<Record<string, RoleDef>>;\n /**\n * The parts that identify one relation of the kind. The default is its two ends. A key part is `from`, `to`, a\n * role with one filler or a qualifier.\n */\n readonly key?: readonly string[];\n}\n\n/** A role of a relation kind, in addition to its two ends. */\nexport interface RoleDef {\n readonly description: string;\n /** The kinds of the fillers of the role. A subkind of each kind is also correct. */\n readonly kinds: readonly string[];\n /** It is `true` when the role takes a list of fillers. Otherwise it takes one filler. */\n readonly many?: boolean;\n}\n\n/** A facet: a set of attributes that many kinds share, with no common parent kind. */\nexport interface FacetDef {\n readonly name: string;\n readonly description: string;\n readonly attributes: AttrShape;\n}\n\n/**\n * An extension of a relation kind by an add-on: more kinds at its ends. Thus an add-on can relate its own kinds\n * with a relation kind of the core.\n */\nexport interface RelationExtension {\n /** The relation kind that the add-on extends. */\n readonly relation: string;\n /** The kinds that the add-on adds to the end `from`. */\n readonly from?: readonly string[];\n /** The kinds that the add-on adds to the end `to`. */\n readonly to?: readonly string[];\n}\n","import { valueIn, whyNotConvertible } from \"@mark1russell7/quantity\";\nimport { z } from \"zod\";\nimport type {\n AttrShape,\n Deadline,\n Edge,\n EdgeInput,\n Entity,\n FacetDef,\n KindDef,\n NamedReference,\n RelationExtension,\n RelationKindDef,\n Requirement,\n RoleFillers,\n} from \"./grammar.ts\";\nimport { edgeSchema, entityIdSchema, entitySchema, isRelationId, keyedRelationId, NAME_PATTERN, relationId } from \"./grammar.ts\";\n\n/** The name of the kind above each relation kind. */\nexport const RELATION_ROOT = \"relation\";\n\n/** The key of a relation kind that names no key: its two ends. */\nconst ENDS_KEY: readonly string[] = [\"from\", \"to\"];\n\n/** The parts of a relation that `Registry.relationIdOf` reads: an edge, or the attributes of a relation entity. */\nexport interface RelationLike {\n readonly type: string;\n readonly from: string;\n readonly to: string;\n readonly roles?: RoleFillers | undefined;\n readonly qualifiers?: Record<string, unknown> | undefined;\n}\n\n/** The parts of a registry: a core, or a core and its add-ons after `composeRegistryInput`. */\nexport interface RegistryInput {\n readonly kinds: readonly KindDef[];\n /** Each type of edge, as a relation kind. Each relation kind is also a kind under `relation`. */\n readonly relations: readonly RelationKindDef[];\n readonly facets?: readonly FacetDef[];\n /** The attributes whose values are names of entities. A projection makes an edge from each value. */\n readonly namedReferences?: readonly NamedReference[];\n /** The date attributes of kinds with a consequence. */\n readonly deadlines?: readonly Deadline[];\n /** The kinds that add-ons add to the ends of relation kinds. */\n readonly extensions?: readonly RelationExtension[];\n}\n\n/** A problem of a record: the path of the value and the message. */\nexport interface ValidationIssue {\n readonly path: string;\n readonly message: string;\n}\n\n/** The error of a registry that is not correct, or of a record that the registry refuses. */\nexport class RegistryError extends Error {\n readonly issues: readonly ValidationIssue[];\n\n constructor(message: string, issues: readonly ValidationIssue[] = []) {\n const detail = issues.map((i) => ` ${i.path}: ${i.message}`).join(\"\\n\");\n super(detail.length > 0 ? `${message}\\n${detail}` : message);\n this.name = \"RegistryError\";\n this.issues = issues;\n }\n}\n\nconst zodIssues = (prefix: string, error: z.ZodError): ValidationIssue[] =>\n error.issues.map((issue) => ({\n path: issue.path.length > 0 ? `${prefix}.${issue.path.join(\".\")}` : prefix,\n message: issue.message,\n }));\n\n/**\n * This function joins the parts of a core and its add-ons into one input of a registry. The registry refuses a\n * kind, a relation kind or a facet that two parts declare.\n */\nexport const composeRegistryInput = (...parts: readonly RegistryInput[]): RegistryInput => ({\n kinds: parts.flatMap((part) => part.kinds),\n relations: parts.flatMap((part) => part.relations),\n facets: parts.flatMap((part) => part.facets ?? []),\n namedReferences: parts.flatMap((part) => part.namedReferences ?? []),\n deadlines: parts.flatMap((part) => part.deadlines ?? []),\n extensions: parts.flatMap((part) => part.extensions ?? []),\n});\n\n/** This function adds the kinds of the extensions to the ends of the relation kinds. A kind is not added two times. */\nconst extend = (relations: Map<string, RelationKindDef>, extensions: readonly RelationExtension[]): void => {\n for (const extension of extensions) {\n const relation = relations.get(extension.relation);\n if (relation === undefined) {\n throw new RegistryError(`an extension names unknown relation kind ${extension.relation}`);\n }\n const add = (ends: readonly string[], more: readonly string[] | undefined): readonly string[] => [\n ...ends,\n ...(more ?? []).filter((kind, at, all) => !ends.includes(kind) && all.indexOf(kind) === at),\n ];\n relations.set(relation.name, { ...relation, from: add(relation.from, extension.from), to: add(relation.to, extension.to) });\n }\n};\n\n/**\n * A registry of kinds, relation kinds and facets. It checks itself when it is made, and it checks each entity and\n * each edge.\n */\nexport class Registry {\n readonly kinds: ReadonlyMap<string, KindDef>;\n readonly relations: ReadonlyMap<string, RelationKindDef>;\n readonly facets: ReadonlyMap<string, FacetDef>;\n readonly namedReferences: readonly NamedReference[];\n readonly deadlines: readonly Deadline[];\n readonly rootKind: string;\n\n private readonly schemaCache = new Map<string, z.ZodType>();\n private readonly closureCache = new Map<string, ReadonlySet<string>>();\n\n /** @throws RegistryError when the parts of the registry are not correct */\n constructor(input: RegistryInput) {\n const kinds = new Map<string, KindDef>();\n for (const kind of input.kinds) {\n if (!NAME_PATTERN.test(kind.name)) {\n throw new RegistryError(`invalid kind name: ${kind.name}`);\n }\n if (kinds.has(kind.name)) {\n throw new RegistryError(`duplicate kind: ${kind.name}`);\n }\n kinds.set(kind.name, kind);\n }\n\n const facets = new Map<string, FacetDef>();\n for (const facet of input.facets ?? []) {\n // toGraph makes an entity id of each facet name, so a facet name has the form of an id part\n if (!NAME_PATTERN.test(facet.name)) {\n throw new RegistryError(`invalid facet name: ${facet.name}`);\n }\n if (facets.has(facet.name)) {\n throw new RegistryError(`duplicate facet: ${facet.name}`);\n }\n facets.set(facet.name, facet);\n }\n\n // Each relation kind is also a kind: its instances are entities, and its qualifiers are their attributes\n const relations = new Map<string, RelationKindDef>();\n for (const relation of input.relations) {\n if (!NAME_PATTERN.test(relation.name)) {\n throw new RegistryError(`invalid relation kind name: ${relation.name}`);\n }\n if (relations.has(relation.name)) {\n throw new RegistryError(`duplicate relation kind: ${relation.name}`);\n }\n if (kinds.has(relation.name)) {\n throw new RegistryError(`relation kind ${relation.name} collides with a kind`);\n }\n const qualifiers = Object.keys(relation.qualifiers ?? {});\n for (const [role, def] of Object.entries(relation.roles ?? {})) {\n if (!NAME_PATTERN.test(role)) {\n throw new RegistryError(`relation kind ${relation.name}: invalid role name ${role}`);\n }\n if (qualifiers.includes(role)) {\n throw new RegistryError(`relation kind ${relation.name}: ${role} is both a role and a qualifier`);\n }\n if (def.kinds.length === 0) {\n throw new RegistryError(`relation kind ${relation.name}: role ${role} names no kind`);\n }\n }\n relations.set(relation.name, relation);\n }\n extend(relations, input.extensions ?? []);\n // A relation can fill an end or a role, so the check of the names waits for each relation kind\n for (const relation of relations.values()) {\n const known = (name: string): boolean => kinds.has(name) || relations.has(name);\n for (const kindName of [...relation.from, ...relation.to]) {\n if (!known(kindName)) {\n throw new RegistryError(`relation kind ${relation.name} references unknown kind ${kindName}`);\n }\n }\n for (const [role, def] of Object.entries(relation.roles ?? {})) {\n for (const kindName of def.kinds) {\n if (!known(kindName)) {\n throw new RegistryError(`relation kind ${relation.name}: role ${role} references unknown kind ${kindName}`);\n }\n }\n }\n }\n if (relations.size > 0 && !kinds.has(RELATION_ROOT)) {\n throw new RegistryError(`relation kinds need the ${RELATION_ROOT} kind to descend from`);\n }\n for (const relation of relations.values()) {\n if (relation.parent !== undefined && !relations.has(relation.parent)) {\n throw new RegistryError(`relation kind ${relation.name} narrows ${relation.parent}, which is not a relation kind`);\n }\n }\n for (const relation of relations.values()) {\n // The attributes of its instances: its qualifiers, and its roles\n const roles = Object.fromEntries(\n Object.entries(relation.roles ?? {}).map(([role, def]) => [\n role,\n def.many === true ? z.array(entityIdSchema).min(1).optional() : entityIdSchema.optional(),\n ]),\n );\n // A narrower relation kind is a subkind of the kind that it narrows\n kinds.set(relation.name, {\n name: relation.name,\n parent: relation.parent ?? RELATION_ROOT,\n mode: \"relation\",\n description: relation.description,\n attributes: { ...(relation.qualifiers ?? {}), ...roles },\n });\n }\n\n const roots: string[] = [];\n for (const kind of kinds.values()) {\n if (kind.parent === null) {\n roots.push(kind.name);\n } else if (!kinds.has(kind.parent)) {\n throw new RegistryError(`kind ${kind.name} has unknown parent ${kind.parent}`);\n }\n for (const facet of kind.facets ?? []) {\n if (!facets.has(facet)) {\n throw new RegistryError(`kind ${kind.name} declares unknown facet ${facet}`);\n }\n }\n }\n const root = roots[0];\n if (root === undefined || roots.length !== 1) {\n throw new RegistryError(`expected exactly one root kind, found: ${roots.join(\", \")}`);\n }\n for (const kind of kinds.values()) {\n const seen = new Set<string>([kind.name]);\n let current = kind.parent;\n while (current !== null) {\n if (seen.has(current)) {\n throw new RegistryError(`kind cycle through ${current}`);\n }\n seen.add(current);\n current = kinds.get(current)?.parent ?? null;\n }\n }\n\n for (const reference of input.namedReferences ?? []) {\n if (!relations.has(reference.relation)) {\n throw new RegistryError(`named reference ${reference.attribute} draws unknown relation kind ${reference.relation}`);\n }\n if (!kinds.has(reference.toKind)) {\n throw new RegistryError(`named reference ${reference.attribute} names unknown kind ${reference.toKind}`);\n }\n }\n\n this.kinds = kinds;\n this.relations = this.inherit(relations);\n this.facets = facets;\n // A qualifier or a role with the name of an attribute of each relation (name, from, to) replaces it with no error\n if (relations.size > 0) {\n const inherited = this.effectiveShape(RELATION_ROOT);\n for (const relation of relations.values()) {\n for (const [what, names] of [\n [\"qualifier\", Object.keys(relation.qualifiers ?? {})],\n [\"role\", Object.keys(relation.roles ?? {})],\n ] as const) {\n for (const name of names) {\n if (name in inherited) {\n throw new RegistryError(\n `relation kind ${relation.name} declares ${what} ${name}, which every relation instance already has`,\n );\n }\n }\n }\n }\n }\n for (const kind of kinds.values()) {\n const shape = this.effectiveShape(kind.name);\n for (const requirement of kind.requirements ?? []) {\n const names = [...Object.keys(requirement.when), ...requirement.then];\n if (Object.keys(requirement.when).length === 0 || requirement.then.length === 0) {\n throw new RegistryError(`kind ${kind.name}: a requirement needs a when and a then`);\n }\n for (const name of names) {\n if (!(name in shape)) {\n throw new RegistryError(`kind ${kind.name}: a requirement names unknown attribute ${name}`);\n }\n }\n }\n }\n for (const deadline of input.deadlines ?? []) {\n if (!kinds.has(deadline.kind)) {\n throw new RegistryError(`deadline ${deadline.attribute} is on unknown kind ${deadline.kind}`);\n }\n // A time after a check counts calendar days, so it is a whole number of days\n if (deadline.after !== undefined) {\n const why = whyNotConvertible(deadline.after.unit, \"d\");\n const days = why === undefined ? valueIn(deadline.after, \"d\") : Number.NaN;\n if (!Number.isInteger(days)) {\n throw new RegistryError(\n `deadline ${deadline.attribute} on ${deadline.kind}: after must be whole days${why === undefined ? \"\" : ` (${why})`}`,\n );\n }\n }\n }\n this.namedReferences = input.namedReferences ?? [];\n this.deadlines = input.deadlines ?? [];\n this.rootKind = root;\n }\n\n /**\n * This method gives each relation kind with the parts that it gets from the kinds that it narrows. A child makes\n * the ends of its parent narrower, and it adds qualifiers and roles. It does not declare a part of its parent again.\n * It gets the key, the symmetry and the transitivity of its parent when it does not declare them.\n */\n private inherit(declared: ReadonlyMap<string, RelationKindDef>): Map<string, RelationKindDef> {\n const merged = new Map<string, RelationKindDef>();\n const resolve = (name: string): RelationKindDef => {\n const done = merged.get(name);\n if (done !== undefined) return done;\n const own = declared.get(name);\n if (own === undefined) throw new RegistryError(`unknown relation kind: ${name}`);\n let effective = own;\n if (own.parent !== undefined) {\n const parent = resolve(own.parent);\n for (const [end, mine, theirs] of [\n [\"from\", own.from, parent.from],\n [\"to\", own.to, parent.to],\n ] as const) {\n for (const kind of mine) {\n if (!theirs.some((wider) => this.isSubkindOf(kind, wider))) {\n throw new RegistryError(\n `relation kind ${name}: ${end} kind ${kind} is wider than ${own.parent} allows (${theirs.join(\"|\")})`,\n );\n }\n }\n }\n const fields = [...Object.keys(parent.qualifiers ?? {}), ...Object.keys(parent.roles ?? {})];\n for (const field of [...Object.keys(own.qualifiers ?? {}), ...Object.keys(own.roles ?? {})]) {\n if (fields.includes(field)) {\n throw new RegistryError(`relation kind ${name} redeclares ${field}, which it has from ${own.parent}`);\n }\n }\n const qualifiers = { ...(parent.qualifiers ?? {}), ...(own.qualifiers ?? {}) };\n const roles = { ...(parent.roles ?? {}), ...(own.roles ?? {}) };\n const key = own.key ?? parent.key;\n const symmetric = own.symmetric ?? parent.symmetric;\n const transitive = own.transitive ?? parent.transitive;\n effective = {\n ...own,\n ...(Object.keys(qualifiers).length > 0 ? { qualifiers } : {}),\n ...(Object.keys(roles).length > 0 ? { roles } : {}),\n ...(key !== undefined ? { key } : {}),\n ...(symmetric !== undefined ? { symmetric } : {}),\n ...(transitive !== undefined ? { transitive } : {}),\n };\n }\n // A key part is a part that a relation has one of: an end, a role with one filler, a qualifier\n const key = effective.key ?? ENDS_KEY;\n if (key.length === 0 || new Set(key).size !== key.length) {\n throw new RegistryError(`relation kind ${name}: a key names each part once`);\n }\n for (const part of key) {\n const role = effective.roles?.[part];\n const keyable =\n part === \"from\" ||\n part === \"to\" ||\n Object.keys(effective.qualifiers ?? {}).includes(part) ||\n (role !== undefined && role.many !== true);\n if (!keyable) {\n throw new RegistryError(`relation kind ${name}: key part ${part} is not an end, a single role or a qualifier`);\n }\n }\n merged.set(name, effective);\n return effective;\n };\n for (const name of declared.keys()) resolve(name);\n return merged;\n }\n\n /**\n * This method gives the kinds from the root to the kind, in that order.\n *\n * @throws RegistryError when a kind is not known\n */\n ancestry(kindName: string): readonly KindDef[] {\n const chain: KindDef[] = [];\n let current: string | null = kindName;\n while (current !== null) {\n const kind = this.kinds.get(current);\n if (kind === undefined) {\n throw new RegistryError(`unknown kind: ${current}`);\n }\n chain.unshift(kind);\n current = kind.parent;\n }\n return chain;\n }\n\n /** This method tells if a kind is the ancestor kind or a subkind of it. */\n isSubkindOf(kindName: string, ancestorName: string): boolean {\n return this.ancestry(kindName).some((kind) => kind.name === ancestorName);\n }\n\n /**\n * This method gives the kind and each of its subkinds.\n *\n * @throws RegistryError when the kind is not known\n */\n subkindClosure(kindName: string): ReadonlySet<string> {\n const cached = this.closureCache.get(kindName);\n if (cached !== undefined) return cached;\n if (!this.kinds.has(kindName)) {\n throw new RegistryError(`unknown kind: ${kindName}`);\n }\n const closure = new Set<string>();\n for (const kind of this.kinds.keys()) {\n if (this.isSubkindOf(kind, kindName)) {\n closure.add(kind);\n }\n }\n this.closureCache.set(kindName, closure);\n return closure;\n }\n\n /** This method gives the ladder of a kind: its own ladder, or the ladder of the nearest kind above it. */\n ladderOf(kindName: string): string | undefined {\n const chain = this.ancestry(kindName);\n for (let at = chain.length - 1; at >= 0; at -= 1) {\n const ladder = chain[at]?.ladder;\n if (ladder !== undefined) return ladder;\n }\n return undefined;\n }\n\n /** This method gives the type of option of a kind: its own type, or the type of the nearest kind above it. */\n optionOf(kindName: string): string | undefined {\n const chain = this.ancestry(kindName);\n for (let at = chain.length - 1; at >= 0; at -= 1) {\n const option = chain[at]?.option;\n if (option !== undefined) return option;\n }\n return undefined;\n }\n\n /** This method gives each attribute of a kind: the attributes of its ancestors and their facets, then its own. */\n effectiveShape(kindName: string): AttrShape {\n const shape: Record<string, z.ZodType> = {};\n for (const kind of this.ancestry(kindName)) {\n for (const facetName of kind.facets ?? []) {\n const facet = this.facets.get(facetName);\n if (facet !== undefined) {\n Object.assign(shape, facet.attributes);\n }\n }\n Object.assign(shape, kind.attributes);\n }\n return shape;\n }\n\n /** This method gives the requirements of a kind: the requirements of its ancestors, then its own. */\n effectiveRequirements(kindName: string): readonly Requirement[] {\n return this.ancestry(kindName).flatMap((kind) => kind.requirements ?? []);\n }\n\n /** This method gives the strict schema of the attributes of a kind, with the check of its requirements. */\n effectiveSchema(kindName: string): z.ZodType {\n const cached = this.schemaCache.get(kindName);\n if (cached !== undefined) return cached;\n const requirements = this.effectiveRequirements(kindName);\n const object = z.strictObject(this.effectiveShape(kindName));\n const schema =\n requirements.length === 0\n ? object\n : object.superRefine((attrs: Record<string, unknown>, context) => {\n for (const requirement of requirements) {\n if (!Object.entries(requirement.when).every(([name, value]) => attrs[name] === value)) continue;\n for (const name of requirement.then) {\n if (attrs[name] === undefined) {\n context.addIssue({ code: \"custom\", path: [name], message: `required: ${requirement.description}` });\n }\n }\n }\n });\n this.schemaCache.set(kindName, schema);\n return schema;\n }\n\n /**\n * This method checks an entity and gives it with its parsed attributes. An entity with no scope gets the default\n * scope of its kind.\n *\n * @throws RegistryError when the entity is not correct\n */\n validateEntity(raw: unknown): Entity {\n const parsed = entitySchema.safeParse(raw);\n if (!parsed.success) {\n throw new RegistryError(\"invalid entity\", zodIssues(\"entity\", parsed.error));\n }\n const entity = parsed.data;\n if (!this.kinds.has(entity.kind)) {\n throw new RegistryError(`entity ${entity.id} has unknown kind ${entity.kind}`);\n }\n const attrs = this.effectiveSchema(entity.kind).safeParse(entity.attrs);\n if (!attrs.success) {\n throw new RegistryError(`invalid attrs for ${entity.id}`, zodIssues(entity.id, attrs.error));\n }\n // The id of a relation instance comes from its kind and its ends, and only a relation instance has such an id\n const relation = this.relations.get(entity.kind);\n if (relation !== undefined) {\n const data = attrs.data as Record<string, unknown> & { from: string; to: string };\n const roles = Object.fromEntries(\n Object.keys(relation.roles ?? {})\n .filter((role) => data[role] !== undefined)\n .map((role) => [role, data[role] as string | readonly string[]]),\n );\n const id = this.relationIdOf({ type: entity.kind, from: data.from, to: data.to, roles, qualifiers: data });\n if (entity.id !== id) {\n throw new RegistryError(`${entity.id}: a ${entity.kind} from ${data.from} to ${data.to} is ${id}`);\n }\n } else if (isRelationId(entity.id)) {\n throw new RegistryError(`${entity.id}: rel. ids belong to relation instances, not a ${entity.kind}`);\n }\n const defaultScope = this.kinds.get(entity.kind)?.defaultScope;\n const envelope =\n defaultScope !== undefined && entity.envelope[\"scope\"] === undefined\n ? { ...entity.envelope, scope: defaultScope }\n : entity.envelope;\n return { ...entity, envelope, attrs: attrs.data as Record<string, unknown> };\n }\n\n /**\n * This method gives the id of a relation from the key of its kind. A symmetric kind sorts its two ends, so the two\n * orders give the same id. A key with only the two ends gives the id of `relationId`.\n *\n * @throws RegistryError when the relation kind is not known\n */\n relationIdOf(edge: RelationLike): string {\n const relation = this.relations.get(edge.type);\n if (relation === undefined) throw new RegistryError(`unknown relation kind: ${edge.type}`);\n const symmetric = relation.symmetric === true;\n const [a, b] = symmetric && edge.to < edge.from ? [edge.to, edge.from] : [edge.from, edge.to];\n const parts: Array<readonly [string, unknown]> = [];\n for (const part of relation.key ?? ENDS_KEY) {\n const value =\n part === \"from\"\n ? a\n : part === \"to\"\n ? b\n : relation.roles?.[part] !== undefined\n ? edge.roles?.[part]\n : edge.qualifiers?.[part];\n if (value !== undefined) parts.push([part, value]);\n }\n const ends = parts.length === 2 && parts[0]?.[0] === \"from\" && parts[1]?.[0] === \"to\";\n return ends ? relationId(edge.type, edge.from, edge.to, symmetric) : keyedRelationId(edge.type, parts);\n }\n\n /**\n * This method checks an edge: its kind, the kinds of its ends and its role fillers, and its qualifiers. It gives\n * the edge with its id.\n *\n * @param kindOf - This function gives the kind of an entity id, or `undefined` for an id with no entity.\n * @throws RegistryError when the edge is not correct\n */\n validateEdge(raw: unknown, kindOf: (id: string) => string | undefined): Edge {\n const parsed = edgeSchema.safeParse(raw);\n if (!parsed.success) {\n throw new RegistryError(\"invalid edge\", zodIssues(\"edge\", parsed.error));\n }\n const input = parsed.data;\n const relation = this.relations.get(input.type);\n if (relation === undefined) {\n throw new RegistryError(`unknown relation kind: ${input.type}`);\n }\n const label = `${input.from} -${input.type}-> ${input.to}`;\n if (relation.abstract === true) {\n const narrower = [...this.relations.values()]\n .filter((candidate) => candidate.parent === input.type)\n .map((candidate) => candidate.name)\n .sort();\n throw new RegistryError(\n `${label}: ${input.type} is abstract, a family with no instances of its own: say which, ${narrower.join(\" or \")}`,\n );\n }\n const check = (part: string, endId: string, allowed: readonly string[]): void => {\n const kind = kindOf(endId);\n if (kind === undefined) {\n throw new RegistryError(`${label}: ${part} entity ${endId} not found`);\n }\n if (allowed.length === 0) {\n throw new RegistryError(`${label}: ${input.type} allows no ${part} kind yet: an add-on extends it`);\n }\n if (!allowed.some((ancestor) => this.isSubkindOf(kind, ancestor))) {\n throw new RegistryError(`${label}: ${part} kind ${kind} not allowed (expected ${allowed.join(\"|\")})`);\n }\n };\n check(\"from\", input.from, relation.from);\n check(\"to\", input.to, relation.to);\n const roles = input.roles ?? {};\n for (const [role, fillers] of Object.entries(roles)) {\n const def = relation.roles?.[role];\n if (def === undefined) {\n throw new RegistryError(`${label}: relation kind ${input.type} has no role ${role}`);\n }\n const many = def.many === true;\n if (many !== Array.isArray(fillers)) {\n throw new RegistryError(`${label}: role ${role} takes ${many ? \"a list of entities\" : \"one entity\"}`);\n }\n const list: readonly string[] = typeof fillers === \"string\" ? [fillers] : fillers;\n if (list.length === 0 || new Set(list).size !== list.length) {\n throw new RegistryError(`${label}: role ${role} lists each filler once, and at least one`);\n }\n for (const filler of list) check(`role ${role}`, filler, def.kinds);\n }\n let qualifiers = input.qualifiers;\n if (relation.qualifiers !== undefined) {\n const checked = z.strictObject(relation.qualifiers).safeParse(input.qualifiers);\n if (!checked.success) {\n throw new RegistryError(`invalid qualifiers for ${label}`, zodIssues(label, checked.error));\n }\n qualifiers = checked.data as Record<string, unknown>;\n } else if (Object.keys(input.qualifiers).length > 0) {\n throw new RegistryError(`${label}: relation kind ${input.type} declares no qualifiers`);\n }\n // The registry calculates the id. An id that is not the id of the key is an edit by hand\n const hasRoles = Object.keys(roles).length > 0;\n const id = this.relationIdOf({ ...input, roles, qualifiers });\n if (input.id !== undefined && input.id !== id) {\n throw new RegistryError(`${label}: id ${input.id} is not this relation's (${id})`);\n }\n return {\n id,\n from: input.from,\n type: input.type,\n to: input.to,\n ...(hasRoles ? { roles } : {}),\n qualifiers,\n envelope: input.envelope,\n };\n }\n\n /**\n * This method gives the registry as data: an entity for each kind and each facet. Each parent gives an edge\n * `subkind-of`, and each facet of a kind gives an edge `has-facet`.\n */\n toGraph(): { entities: Entity[]; edges: EdgeInput[] } {\n const entities: Entity[] = [];\n const edges: EdgeInput[] = [];\n for (const facet of this.facets.values()) {\n entities.push({\n id: `ontology.facet.${facet.name}`,\n kind: \"facet\",\n attrs: { name: facet.name, description: facet.description },\n envelope: {},\n });\n }\n for (const kind of this.kinds.values()) {\n const relation = this.relations.get(kind.name);\n entities.push({\n id: `ontology.kind.${kind.name}`,\n kind: \"kind\",\n attrs: {\n name: kind.name,\n mode: kind.mode,\n description: kind.description,\n ...(relation !== undefined\n ? {\n from_kinds: [...relation.from],\n to_kinds: [...relation.to],\n ...(relation.symmetric === true ? { symmetric: true } : {}),\n ...(relation.transitive === true ? { transitive: true } : {}),\n ...(relation.roles !== undefined ? { roles: Object.keys(relation.roles) } : {}),\n ...(relation.key !== undefined ? { key: [...relation.key] } : {}),\n }\n : {}),\n },\n envelope: {},\n });\n if (kind.parent !== null) {\n edges.push({\n from: `ontology.kind.${kind.name}`,\n type: \"subkind-of\",\n to: `ontology.kind.${kind.parent}`,\n qualifiers: {},\n envelope: {},\n });\n }\n for (const facetName of kind.facets ?? []) {\n edges.push({\n from: `ontology.kind.${kind.name}`,\n type: \"has-facet\",\n to: `ontology.facet.${facetName}`,\n qualifiers: {},\n envelope: {},\n });\n }\n }\n return { entities, edges };\n }\n}\n","import { isQuantitySchema } from \"@mark1russell7/quantity/schema\";\nimport type { z } from \"zod\";\n\n/** The column shape of an attribute in a view of a store. */\nexport type ColumnShape =\n | { readonly kind: \"text\" }\n | { readonly kind: \"number\" }\n | { readonly kind: \"boolean\" }\n | { readonly kind: \"array\"; readonly element: \"text\" | \"number\" | \"json\" }\n /** A quantity `{ value, unit }` becomes a number column and a unit column. */\n | { readonly kind: \"quantity\" }\n | { readonly kind: \"json\" };\n\ninterface AnyDef {\n readonly type: string;\n readonly innerType?: z.ZodType;\n readonly element?: z.ZodType;\n}\n\nconst defOf = (schema: z.ZodType): AnyDef => (schema as unknown as { def: AnyDef }).def;\n\nconst WRAPPERS = new Set([\"optional\", \"nullable\", \"default\", \"readonly\", \"nonoptional\"]);\n\nconst unwrap = (schema: z.ZodType): AnyDef => {\n let def = defOf(schema);\n while (WRAPPERS.has(def.type) && def.innerType !== undefined) {\n def = defOf(def.innerType);\n }\n return def;\n};\n\nconst scalar = (def: AnyDef): \"text\" | \"number\" | \"boolean\" | \"json\" => {\n switch (def.type) {\n case \"string\":\n case \"enum\":\n case \"literal\":\n return \"text\";\n case \"number\":\n case \"int\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n default:\n return \"json\";\n }\n};\n\n/** This function gives the column shape of the schema of an attribute. */\nexport const columnShape = (schema: z.ZodType): ColumnShape => {\n if (isQuantitySchema(schema)) return { kind: \"quantity\" };\n const def = unwrap(schema);\n if (def.type === \"array\" && def.element !== undefined) {\n const element = scalar(unwrap(def.element));\n return { kind: \"array\", element: element === \"boolean\" ? \"json\" : element };\n }\n const kind = scalar(def);\n return kind === \"json\" ? { kind: \"json\" } : { kind };\n};\n","/** The options of a generator of a store. */\nexport interface GenerateOptions {\n /** The first line of each generated SQL file. An add-on names its own command here. */\n readonly header?: string;\n}\n\n/** The default first line of each generated SQL file. */\nexport const DEFAULT_HEADER = \"-- Generated by @mark1russell7/ontology from the kinds of a registry. Do not edit by hand.\";\n\n/** This function gives the header line of a generated SQL file, with its line end. */\nexport const headerOf = (options: GenerateOptions | undefined): string => `${options?.header ?? DEFAULT_HEADER}\\n`;\n","import { RegistryError } from \"../registry.ts\";\nimport type { Registry } from \"../registry.ts\";\nimport type { ColumnShape } from \"./columns.ts\";\nimport { columnShape } from \"./columns.ts\";\nimport type { GenerateOptions } from \"./header.ts\";\nimport { headerOf } from \"./header.ts\";\n\nconst BASE_TABLES = `CREATE TABLE IF NOT EXISTS entities (\n id VARCHAR PRIMARY KEY,\n kind VARCHAR NOT NULL,\n attrs JSON NOT NULL DEFAULT '{}',\n envelope JSON NOT NULL DEFAULT '{}'\n);\n\nCREATE TABLE IF NOT EXISTS edges (\n id VARCHAR NOT NULL,\n from_id VARCHAR NOT NULL,\n type VARCHAR NOT NULL,\n to_id VARCHAR NOT NULL,\n roles JSON NOT NULL DEFAULT '{}',\n qualifiers JSON NOT NULL DEFAULT '{}',\n envelope JSON NOT NULL DEFAULT '{}',\n inverse BOOLEAN NOT NULL DEFAULT FALSE,\n PRIMARY KEY (id, from_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_entities_kind ON entities (kind);\nCREATE INDEX IF NOT EXISTS idx_edges_from ON edges (from_id);\nCREATE INDEX IF NOT EXISTS idx_edges_to ON edges (to_id);\nCREATE INDEX IF NOT EXISTS idx_edges_type ON edges (type);\n`;\n\nconst identifier = (name: string): string => name.replace(/-/g, \"_\");\n\n// SQL reserves the names of the two ends of a relation (from, to), so each attribute column has quotes\nconst column = (key: string): string => `\"${identifier(key)}\"`;\n\nconst attrColumn = (key: string, shape: ColumnShape): string => {\n switch (shape.kind) {\n case \"text\":\n return `attrs->>'${key}' AS ${column(key)}`;\n case \"number\":\n return `CAST(attrs->>'${key}' AS DOUBLE) AS ${column(key)}`;\n case \"boolean\":\n return `CAST(attrs->>'${key}' AS BOOLEAN) AS ${column(key)}`;\n case \"array\":\n if (shape.element === \"text\") {\n return `CAST(attrs->'${key}' AS VARCHAR[]) AS ${column(key)}`;\n }\n if (shape.element === \"number\") {\n return `CAST(attrs->'${key}' AS DOUBLE[]) AS ${column(key)}`;\n }\n return `attrs->'${key}' AS ${column(key)}`;\n case \"json\":\n return `attrs->'${key}' AS ${column(key)}`;\n case \"quantity\":\n // The amount is a number that a query can add, and its unit is the next column. An infinite amount is NULL\n return `TRY_CAST(attrs->'${key}'->>'value' AS DOUBLE) AS ${column(key)},\\n attrs->'${key}'->>'unit' AS ${column(`${key}_unit`)}`;\n }\n};\n\n/** This function gives the view columns of an attribute. A quantity has two columns. */\nconst columnNames = (key: string, shape: ColumnShape): string[] =>\n shape.kind === \"quantity\" ? [key, `${key}_unit`] : [key];\n\n// The envelope columns have the prefix envelope_, so an attribute of an add-on can have the name scope or valid_from\nconst ENVELOPE_COLUMNS = [\n \"envelope->>'scope' AS envelope_scope\",\n \"envelope->>'valid_from' AS envelope_valid_from\",\n \"envelope->>'valid_to' AS envelope_valid_to\",\n \"envelope->>'observed_at' AS envelope_observed_at\",\n];\n\n// An attribute with the name of one of these columns hides the column in the view, so the generator refuses it\nconst RESERVED_COLUMNS = new Set([\n \"id\",\n \"kind\",\n ...ENVELOPE_COLUMNS.map((line) => line.slice(line.lastIndexOf(\" AS \") + 4)),\n]);\n\n/**\n * This function gives the DuckDB tables of a store of entities and edges, and one view for each kind. The view of a\n * kind has a column for each attribute, and it shows the entities of the kind and of each of its subkinds.\n *\n * @throws RegistryError when an attribute has the name of a fixed column, or two attributes give the same column\n */\nexport const generateDuckDbDdl = (registry: Registry, options?: GenerateOptions): string => {\n const sections: string[] = [headerOf(options), BASE_TABLES];\n for (const kind of registry.kinds.values()) {\n const closure = [...registry.subkindClosure(kind.name)].sort();\n const kindList = closure.map((name) => `'${name}'`).join(\", \");\n const columns = [\"id\", \"kind\"];\n const taken = new Set<string>();\n for (const [key, schema] of Object.entries(registry.effectiveShape(kind.name))) {\n if (RESERVED_COLUMNS.has(key)) {\n throw new RegistryError(\n `kind ${kind.name}: attribute ${key} has the name of a fixed view column (id, kind or an envelope column)`,\n );\n }\n const shape = columnShape(schema);\n for (const name of columnNames(key, shape)) {\n if (taken.has(identifier(name))) {\n throw new RegistryError(\n `kind ${kind.name} has two view columns named ${identifier(name)}: the unit column of a quantity is <attribute>_unit`,\n );\n }\n taken.add(identifier(name));\n }\n columns.push(attrColumn(key, shape));\n }\n columns.push(...ENVELOPE_COLUMNS);\n sections.push(\n `CREATE OR REPLACE VIEW v_${identifier(kind.name)} AS\\nSELECT\\n ${columns.join(\",\\n \")}\\nFROM entities\\nWHERE kind IN (${kindList});\\n`,\n );\n }\n return sections.join(\"\\n\");\n};\n","import type { Registry } from \"../registry.ts\";\nimport type { GenerateOptions } from \"./header.ts\";\nimport { headerOf } from \"./header.ts\";\n\n/**\n * This function gives the SQLite tables of a store of entities and edges. The tables are the same for each\n * registry: a kind is a value of the column `kind`, and the attributes are JSON.\n */\nexport const generateSqliteDdl = (_registry: Registry, options?: GenerateOptions): string => `${headerOf(options)}\nCREATE TABLE IF NOT EXISTS entities (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL,\n attrs TEXT NOT NULL DEFAULT '{}',\n envelope TEXT NOT NULL DEFAULT '{}'\n);\n\nCREATE TABLE IF NOT EXISTS edges (\n id TEXT NOT NULL,\n from_id TEXT NOT NULL,\n type TEXT NOT NULL,\n to_id TEXT NOT NULL,\n roles TEXT NOT NULL DEFAULT '{}',\n qualifiers TEXT NOT NULL DEFAULT '{}',\n envelope TEXT NOT NULL DEFAULT '{}',\n inverse INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (id, from_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_entities_kind ON entities (kind);\nCREATE INDEX IF NOT EXISTS idx_edges_from ON edges (from_id);\nCREATE INDEX IF NOT EXISTS idx_edges_to ON edges (to_id);\nCREATE INDEX IF NOT EXISTS idx_edges_type ON edges (type);\n`;\n","import { z } from \"zod\";\nimport type { KindDef, RelationKindDef, Requirement } from \"../grammar.ts\";\nimport { edgeSchema, entitySchema } from \"../grammar.ts\";\nimport type { Registry } from \"../registry.ts\";\n\n/** One kind as data: the JSON Schema of its attributes and of the attributes of its facets. */\nexport interface KindJson {\n readonly name: string;\n readonly parent: string | null;\n readonly mode: string;\n readonly description: string;\n /** The attributes of its facets, then its own attributes. The attributes of a parent come through `parent`. */\n readonly attributes: Record<string, unknown>;\n /** Its facets. Their attributes are in `attributes`. */\n readonly facets?: string[];\n readonly defaultScope?: string;\n readonly staleAfterDays?: number;\n /** Its own requirements. The requirements of a parent come through `parent`. */\n readonly requirements?: Requirement[];\n}\n\n/** One relation kind as data: the JSON Schema of its qualifiers, and its roles. */\nexport interface RelationJson {\n readonly name: string;\n /** The relation kind that it narrows. */\n readonly parent?: string;\n readonly description: string;\n readonly from: string[];\n readonly to: string[];\n readonly qualifiers?: Record<string, unknown>;\n readonly symmetric?: boolean;\n readonly transitive?: boolean;\n readonly abstract?: boolean;\n readonly roles?: Readonly<\n Record<string, { readonly description: string; readonly kinds: string[]; readonly many?: boolean }>\n >;\n readonly key?: string[];\n}\n\n/** A registry as data. */\nexport interface RegistryJson {\n readonly kinds: readonly KindJson[];\n /** Each relation kind. Each relation kind is also in `kinds`, with the mode `relation`. */\n readonly relations: readonly RelationJson[];\n}\n\n/** The JSON Schemas of a registry: an entity, an edge, and the attributes of each kind. */\nexport interface JsonSchemas {\n readonly entity: Record<string, unknown>;\n readonly edge: Record<string, unknown>;\n readonly kinds: Record<string, Record<string, unknown>>;\n}\n\n/** This function gives the JSON Schema of the requirements of a kind: an `if` and a `then` for each. */\nconst requirementsJson = (requirements: readonly Requirement[]): Record<string, unknown> =>\n requirements.length === 0\n ? {}\n : {\n allOf: requirements.map((requirement) => ({\n description: requirement.description,\n if: {\n properties: Object.fromEntries(Object.entries(requirement.when).map(([name, value]) => [name, { const: value }])),\n required: Object.keys(requirement.when),\n },\n then: { required: [...requirement.then] },\n })),\n };\n\n/** This function gives one kind as data. The schema includes the attributes of the facets of the kind. */\nexport const kindJson = (registry: Registry, kind: KindDef): KindJson => {\n const facets = kind.facets ?? [];\n const shape = Object.assign(\n {},\n ...facets.map((name) => registry.facets.get(name)?.attributes ?? {}),\n kind.attributes,\n ) as Record<string, z.ZodType>;\n return {\n name: kind.name,\n parent: kind.parent,\n mode: kind.mode,\n description: kind.description,\n attributes: {\n ...(z.toJSONSchema(z.strictObject(shape)) as Record<string, unknown>),\n ...requirementsJson(kind.requirements ?? []),\n },\n ...(facets.length > 0 ? { facets: [...facets] } : {}),\n ...(kind.defaultScope !== undefined ? { defaultScope: kind.defaultScope } : {}),\n ...(kind.staleAfterDays !== undefined ? { staleAfterDays: kind.staleAfterDays } : {}),\n ...(kind.requirements !== undefined && kind.requirements.length > 0 ? { requirements: [...kind.requirements] } : {}),\n };\n};\n\n/** This function gives one relation kind as data. */\nexport const relationJson = (relation: RelationKindDef): RelationJson => ({\n name: relation.name,\n ...(relation.parent !== undefined ? { parent: relation.parent } : {}),\n description: relation.description,\n from: [...relation.from],\n to: [...relation.to],\n ...(relation.qualifiers !== undefined\n ? { qualifiers: z.toJSONSchema(z.strictObject(relation.qualifiers)) as Record<string, unknown> }\n : {}),\n ...(relation.symmetric !== undefined ? { symmetric: relation.symmetric } : {}),\n ...(relation.transitive !== undefined ? { transitive: relation.transitive } : {}),\n ...(relation.abstract === true ? { abstract: true } : {}),\n ...(relation.roles !== undefined\n ? {\n roles: Object.fromEntries(\n Object.entries(relation.roles).map(([role, def]) => [\n role,\n { description: def.description, kinds: [...def.kinds], ...(def.many === true ? { many: true } : {}) },\n ]),\n ),\n }\n : {}),\n ...(relation.key !== undefined ? { key: [...relation.key] } : {}),\n});\n\n/** This function gives a registry as data: each kind and each relation kind. */\nexport const registryJson = (registry: Registry): RegistryJson => ({\n kinds: [...registry.kinds.values()].map((kind) => kindJson(registry, kind)),\n relations: [...registry.relations.values()].map(relationJson),\n});\n\n/** This function gives the JSON Schemas of an entity, an edge, and the full attributes of each kind. */\nexport const generateJsonSchemas = (registry: Registry): JsonSchemas => ({\n entity: z.toJSONSchema(entitySchema) as Record<string, unknown>,\n edge: z.toJSONSchema(edgeSchema) as Record<string, unknown>,\n kinds: Object.fromEntries(\n [...registry.kinds.keys()].map((name) => [\n name,\n {\n ...(z.toJSONSchema(z.strictObject(registry.effectiveShape(name))) as Record<string, unknown>),\n ...requirementsJson(registry.effectiveRequirements(name)),\n },\n ]),\n ),\n});\n","import { generateDuckDbDdl } from \"./codegen/duckdb.ts\";\nimport type { GenerateOptions } from \"./codegen/header.ts\";\nimport { generateJsonSchemas, registryJson } from \"./codegen/jsonschema.ts\";\nimport { generateSqliteDdl } from \"./codegen/sqlite.ts\";\nimport type { Registry } from \"./registry.ts\";\n\n/** The generated files of a registry, by file name. */\nexport interface GeneratedFiles {\n readonly \"duckdb.sql\": string;\n readonly \"sqlite.sql\": string;\n readonly \"registry.json\": string;\n readonly \"jsonschema.json\": string;\n}\n\n/** This function gives each generated file of a registry: the SQL of two stores, the registry and the JSON Schemas. */\nexport const generateAll = (registry: Registry, options?: GenerateOptions): GeneratedFiles => ({\n \"duckdb.sql\": generateDuckDbDdl(registry, options),\n \"sqlite.sql\": generateSqliteDdl(registry, options),\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,mBAAmB,GAAG,KAAK,UAAU,oBAAoB,QAAQ,GAAG,MAAM,CAAC,EAAE;AAC/E"}
|
|
@@ -165,6 +165,24 @@ interface KindDef {
|
|
|
165
165
|
* when it has no type.
|
|
166
166
|
*/
|
|
167
167
|
readonly option?: string;
|
|
168
|
+
/**
|
|
169
|
+
* The rules across the attributes of the kind. A subkind gets the rules of its parent. The JSON Schema of the kind
|
|
170
|
+
* shows each rule as `if` and `then`.
|
|
171
|
+
*/
|
|
172
|
+
readonly requirements?: readonly Requirement[];
|
|
173
|
+
}
|
|
174
|
+
/** A value that a requirement compares with an attribute. */
|
|
175
|
+
type RequirementValue = string | number | boolean | null;
|
|
176
|
+
/**
|
|
177
|
+
* A rule across the attributes of a kind: when each attribute of `when` has its value, each attribute of `then` has
|
|
178
|
+
* a value. Example: a planned function has a size and an acceptance.
|
|
179
|
+
*/
|
|
180
|
+
interface Requirement {
|
|
181
|
+
readonly description: string;
|
|
182
|
+
/** The attributes and the values that start the rule. */
|
|
183
|
+
readonly when: Readonly<Record<string, RequirementValue>>;
|
|
184
|
+
/** The attributes that then have a value. */
|
|
185
|
+
readonly then: readonly string[];
|
|
168
186
|
}
|
|
169
187
|
/**
|
|
170
188
|
* A date attribute of a kind with a consequence: a due date, an end of a warranty or the date of a last check.
|
|
@@ -331,7 +349,9 @@ declare class Registry {
|
|
|
331
349
|
optionOf(kindName: string): string | undefined;
|
|
332
350
|
/** This method gives each attribute of a kind: the attributes of its ancestors and their facets, then its own. */
|
|
333
351
|
effectiveShape(kindName: string): AttrShape;
|
|
334
|
-
/** This method gives the
|
|
352
|
+
/** This method gives the requirements of a kind: the requirements of its ancestors, then its own. */
|
|
353
|
+
effectiveRequirements(kindName: string): readonly Requirement[];
|
|
354
|
+
/** This method gives the strict schema of the attributes of a kind, with the check of its requirements. */
|
|
335
355
|
effectiveSchema(kindName: string): z.ZodType;
|
|
336
356
|
/**
|
|
337
357
|
* This method checks an entity and gives it with its parsed attributes. An entity with no scope gets the default
|
|
@@ -371,4 +391,4 @@ interface GenerateOptions {
|
|
|
371
391
|
}
|
|
372
392
|
/** The default first line of each generated SQL file. */
|
|
373
393
|
declare const DEFAULT_HEADER = "-- Generated by @mark1russell7/ontology from the kinds of a registry. Do not edit by hand.";
|
|
374
|
-
export {
|
|
394
|
+
export { RoleFillers as A, maxScope as B, NamedReference as C, Requirement as D, RelationKindDef as E, entityIdSchema as F, visibleTo as G, relationId as H, entitySchema as I, envelopeSchema as L, Scope as M, edgeRowSchema as N, RequirementValue as O, edgeSchema as P, isRelationId as R, NAME_PATTERN as S, RelationExtension as T, scopeRank as U, nameOf as V, scopeSchema as W, Envelope as _, RegistryError as a, MODES as b, ValidationIssue as c, Deadline as d, ENTITY_ID_PATTERN as f, EntityInput as g, Entity as h, Registry as i, SCOPES as j, RoleDef as k, composeRegistryInput as l, EdgeInput as m, GenerateOptions as n, RegistryInput as o, Edge as p, RELATION_ROOT as r, RelationLike as s, DEFAULT_HEADER as t, AttrShape as u, FacetDef as v, ParsedEdge as w, Mode as x, KindDef as y, keyedRelationId as z };
|
package/build/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as RoleFillers, B as maxScope, C as NamedReference, D as Requirement, E as RelationKindDef, F as entityIdSchema, G as visibleTo, H as relationId, I as entitySchema, L as envelopeSchema, M as Scope, N as edgeRowSchema, O as RequirementValue, P as edgeSchema, R as isRelationId, S as NAME_PATTERN, T as RelationExtension, U as scopeRank, V as nameOf, W as scopeSchema, _ as Envelope, a as RegistryError, b as MODES, c as ValidationIssue, d as Deadline, f as ENTITY_ID_PATTERN, g as EntityInput, h as Entity, i as Registry, j as SCOPES, k as RoleDef, l as composeRegistryInput, m as EdgeInput, n as GenerateOptions, o as RegistryInput, p as Edge, r as RELATION_ROOT, s as RelationLike, t as DEFAULT_HEADER, u as AttrShape, v as FacetDef, w as ParsedEdge, x as Mode, y as KindDef, z as keyedRelationId } from "./header-BluJvnVP.mjs";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
/** The verdicts of a claim. */
|
|
4
4
|
export declare const CLAIM_VERDICTS: readonly ["supported", "equivalent", "disputed", "refuted", "speculative"];
|
|
@@ -55,6 +55,8 @@ interface KindJson {
|
|
|
55
55
|
readonly facets?: string[];
|
|
56
56
|
readonly defaultScope?: string;
|
|
57
57
|
readonly staleAfterDays?: number;
|
|
58
|
+
/** Its own requirements. The requirements of a parent come through `parent`. */
|
|
59
|
+
readonly requirements?: Requirement[];
|
|
58
60
|
}
|
|
59
61
|
/** One relation kind as data: the JSON Schema of its qualifiers, and its roles. */
|
|
60
62
|
interface RelationJson {
|
|
@@ -170,4 +172,4 @@ type Condition = {
|
|
|
170
172
|
export declare const versionRangeSchema: z.ZodType<string, string>;
|
|
171
173
|
/** The schema of one condition of a claim. A system or a model is the id of an entity. */
|
|
172
174
|
export declare const conditionSchema: z.ZodType<Condition, Condition>;
|
|
173
|
-
export { type AttrShape, type ClaimVerdict, type ColumnShape, type Condition, DEFAULT_HEADER, type Deadline, ENTITY_ID_PATTERN, type Edge, type EdgeInput, type Entity, type EntityInput, type Envelope, type FacetDef, type GenerateOptions, type GeneratedFiles, type JsonSchemas, type KindDef, type KindJson, MODES, type Mode, NAME_PATTERN, type NamedReference, type ParsedEdge, RELATION_ROOT, Registry, RegistryError, type RegistryInput, type RegistryJson, type RelationExtension, type RelationJson, type RelationKindDef, type RelationLike, type RoleDef, type RoleFillers, SCOPES, type Scope, type ValidationIssue, type Version, type VersionSpan, composeRegistryInput, edgeRowSchema, edgeSchema, entityIdSchema, entitySchema, envelopeSchema, isRelationId, keyedRelationId, maxScope, nameOf, relationId, scopeRank, scopeSchema, visibleTo };
|
|
175
|
+
export { type AttrShape, type ClaimVerdict, type ColumnShape, type Condition, DEFAULT_HEADER, type Deadline, ENTITY_ID_PATTERN, type Edge, type EdgeInput, type Entity, type EntityInput, type Envelope, type FacetDef, type GenerateOptions, type GeneratedFiles, type JsonSchemas, type KindDef, type KindJson, MODES, type Mode, NAME_PATTERN, type NamedReference, type ParsedEdge, RELATION_ROOT, Registry, RegistryError, type RegistryInput, type RegistryJson, type RelationExtension, type RelationJson, type RelationKindDef, type RelationLike, type Requirement, type RequirementValue, type RoleDef, type RoleFillers, SCOPES, type Scope, type ValidationIssue, type Version, type VersionSpan, composeRegistryInput, edgeRowSchema, edgeSchema, entityIdSchema, entitySchema, envelopeSchema, isRelationId, keyedRelationId, maxScope, nameOf, relationId, scopeRank, scopeSchema, visibleTo };
|
package/build/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as visibleTo, C as isRelationId, D as relationId, E as nameOf, O as scopeRank, S as envelopeSchema, T as maxScope, _ as SCOPES, a as relationJson, b as entityIdSchema, c as DEFAULT_HEADER, d as Registry, f as RegistryError, g as NAME_PATTERN, h as MODES, i as registryJson, k as scopeSchema, l as columnShape, m as ENTITY_ID_PATTERN, n as generateJsonSchemas, o as generateSqliteDdl, p as composeRegistryInput, r as kindJson, s as generateDuckDbDdl, t as generateAll, u as RELATION_ROOT, v as edgeRowSchema, w as keyedRelationId, x as entitySchema, y as edgeSchema } from "./generate-
|
|
1
|
+
import { A as visibleTo, C as isRelationId, D as relationId, E as nameOf, O as scopeRank, S as envelopeSchema, T as maxScope, _ as SCOPES, a as relationJson, b as entityIdSchema, c as DEFAULT_HEADER, d as Registry, f as RegistryError, g as NAME_PATTERN, h as MODES, i as registryJson, k as scopeSchema, l as columnShape, m as ENTITY_ID_PATTERN, n as generateJsonSchemas, o as generateSqliteDdl, p as composeRegistryInput, r as kindJson, s as generateDuckDbDdl, t as generateAll, u as RELATION_ROOT, v as edgeRowSchema, w as keyedRelationId, x as entitySchema, y as edgeSchema } from "./generate-Dv-t-uia.mjs";
|
|
2
2
|
import { extentSchema, statisticSchema, unknownSchema } from "@mark1russell7/quantity/schema";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
// src/versions.ts
|
|
@@ -186,7 +186,7 @@ const spineKinds = [
|
|
|
186
186
|
mode: "top",
|
|
187
187
|
description: "The root kind. Each entity is an entity.",
|
|
188
188
|
attributes: {
|
|
189
|
-
name: z.string(),
|
|
189
|
+
name: z.string().optional(),
|
|
190
190
|
notes: z.string().optional()
|
|
191
191
|
}
|
|
192
192
|
},
|
package/build/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/versions.ts","../src/spine.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { entityIdSchema } from \"./grammar.ts\";\n\n/**\n * Versions and version ranges, for the conditions of a claim: \"the default is 15 on Linux >=2.6.12\".\n *\n * A version starts with dotted numbers (\"6.6.87.2\"). The order ignores the text after the numbers, so\n * \"6.6.87.2-custom\" has the order of 6.6.87.2. A range is a list of comparators with spaces between them\n * (\">=6.6 <6.7\"). Each comparator must hold. Alternatives have \"||\" between them.\n *\n * A version with no operator names its series: \"6.6\" is each 6.6.x. \"=6.6.87.2\" names that release and its patches.\n */\n\n/** A version: its dotted numbers. */\nexport type Version = readonly number[];\n\n/** One end of a span of versions. */\ninterface Bound {\n readonly at: Version;\n readonly inclusive: boolean;\n}\n\n/** A span of versions from `lo` to `hi`. An end with no bound is open. */\nexport interface VersionSpan {\n readonly lo?: Bound;\n readonly hi?: Bound;\n}\n\n/** The error of a text that is not a version or a range. */\nexport class VersionError extends Error {\n override readonly name = \"VersionError\";\n}\n\n/**\n * This function gives the dotted numbers at the start of a version.\n *\n * @throws VersionError when the text does not start with a number\n */\nexport const parseVersion = (text: string): Version => {\n const match = /^v?(\\d+(?:\\.\\d+)*)/.exec(text.trim());\n if (match?.[1] === undefined) throw new VersionError(`not a version: ${text}`);\n return match[1].split(\".\").map(Number);\n};\n\n/** This function gives -1, 0 or 1. It adds zeros to a shorter version, so 6.6 is 6.6.0. */\nexport const compareVersions = (a: Version, b: Version): number => {\n for (let i = 0; i < Math.max(a.length, b.length); i += 1) {\n const x = a[i] ?? 0;\n const y = b[i] ?? 0;\n if (x !== y) return x < y ? -1 : 1;\n }\n return 0;\n};\n\n/** This function gives the release after a series: 6.7 after 6.6, and 7 after 6. */\nconst next = (series: Version): Version => [...series.slice(0, -1), (series[series.length - 1] ?? 0) + 1];\n\n/** This function gives a series as a span: 6.6 is from 6.6 up to 6.7, and 6.7 is not in it. */\nexport const seriesSpan = (series: Version): VersionSpan => ({\n lo: { at: series, inclusive: true },\n hi: { at: next(series), inclusive: false },\n});\n\nconst tighterLo = (a: Bound | undefined, b: Bound | undefined): Bound | undefined => {\n if (a === undefined) return b;\n if (b === undefined) return a;\n const order = compareVersions(a.at, b.at);\n return order > 0 ? a : order < 0 ? b : { at: a.at, inclusive: a.inclusive && b.inclusive };\n};\n\nconst tighterHi = (a: Bound | undefined, b: Bound | undefined): Bound | undefined => {\n if (a === undefined) return b;\n if (b === undefined) return a;\n const order = compareVersions(a.at, b.at);\n return order < 0 ? a : order > 0 ? b : { at: a.at, inclusive: a.inclusive && b.inclusive };\n};\n\nconst intersect = (a: VersionSpan, b: VersionSpan): VersionSpan => {\n const lo = tighterLo(a.lo, b.lo);\n const hi = tighterHi(a.hi, b.hi);\n return { ...(lo !== undefined ? { lo } : {}), ...(hi !== undefined ? { hi } : {}) };\n};\n\nconst isEmpty = (span: VersionSpan): boolean => {\n if (span.lo === undefined || span.hi === undefined) return false;\n const order = compareVersions(span.lo.at, span.hi.at);\n return order > 0 || (order === 0 && !(span.lo.inclusive && span.hi.inclusive));\n};\n\nconst comparator = (token: string, whole: string): VersionSpan => {\n const match = /^(>=|<=|>|<|=)?\\s*(.+)$/.exec(token);\n const [, operator, rest = \"\"] = match ?? [];\n let at: Version;\n try {\n at = parseVersion(rest);\n } catch {\n throw new VersionError(`version range ${whole}: ${token} names no version`);\n }\n switch (operator) {\n case \">=\":\n return { lo: { at, inclusive: true } };\n case \">\":\n return { lo: { at, inclusive: false } };\n case \"<=\":\n return { hi: { at, inclusive: true } };\n case \"<\":\n return { hi: { at, inclusive: false } };\n // \"=6.6.87.2\" is that release: the series that it names\n case \"=\":\n default:\n return seriesSpan(at);\n }\n};\n\n/**\n * This function gives the spans of a range: one span for each alternative.\n *\n * @throws VersionError when the range has an empty alternative or a comparator with no version\n */\nexport const parseRange = (range: string): VersionSpan[] => {\n const alternatives = range.split(\"||\").map((part) => part.trim());\n if (alternatives.some((part) => part === \"\")) {\n throw new VersionError(`version range ${range}: an empty alternative`);\n }\n return alternatives.map((alternative) =>\n alternative\n .replace(/(>=|<=|>|<|=)\\s+/g, \"$1\")\n .split(/\\s+/)\n .map((token) => comparator(token, range))\n .reduce<VersionSpan>((span, part) => intersect(span, part), {}),\n );\n};\n\nconst contains = (outer: VersionSpan, inner: VersionSpan): boolean => {\n const lo = tighterLo(outer.lo, inner.lo);\n const hi = tighterHi(outer.hi, inner.hi);\n // The inner span is inside the outer span when the outer span does not make it tighter\n const same = (a: Bound | undefined, b: Bound | undefined): boolean =>\n (a === undefined && b === undefined) ||\n (a !== undefined && b !== undefined && compareVersions(a.at, b.at) === 0 && a.inclusive === b.inclusive);\n return same(lo, inner.lo) && same(hi, inner.hi);\n};\n\n/**\n * This function tells how a range meets the series of a version. The result is `all` when the full series is in the\n * range. It is `some` when a part of the series is in the range, and `none` when no part is in the range.\n *\n * @throws VersionError when the range or the version is not correct\n */\nexport const rangeMeets = (range: string, version: string): \"all\" | \"some\" | \"none\" => {\n const asked = seriesSpan(parseVersion(version));\n const spans = parseRange(range);\n if (spans.some((span) => contains(span, asked))) return \"all\";\n if (spans.some((span) => !isEmpty(intersect(span, asked)))) return \"some\";\n return \"none\";\n};\n\n/**\n * One condition of a claim: a system at a range of versions, the hardware or the provider, an architecture, or\n * the population of a study. A claim holds where each of its conditions holds.\n */\nexport type Condition =\n | { readonly of: string; readonly versions: string }\n | { readonly on: string }\n | { readonly architecture: string }\n | { readonly population: string };\n\n/** The schema of a version range of a condition: \">=6.6 <6.7\", \"=6.6.87.2\" or \"6.6\". */\nexport const versionRangeSchema: z.ZodType<string, string> = z.string().superRefine((range, ctx) => {\n try {\n if (parseRange(range).every(isEmpty)) {\n ctx.addIssue({ code: \"custom\", message: `version range ${range} allows no version at all` });\n }\n } catch (error) {\n ctx.addIssue({ code: \"custom\", message: error instanceof Error ? error.message : String(error) });\n }\n});\n\n/** The schema of one condition of a claim. A system or a model is the id of an entity. */\nexport const conditionSchema: z.ZodType<Condition, Condition> = z.union([\n // The system and its versions\n z.strictObject({ of: entityIdSchema, versions: versionRangeSchema }),\n // The hardware model or the provider\n z.strictObject({ on: entityIdSchema }),\n z.strictObject({ architecture: z.string().min(1) }),\n // The population of a study, in words\n z.strictObject({ population: z.string().min(1) }),\n]);\n","import { extentSchema, statisticSchema, unknownSchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport type { FacetDef, KindDef, Mode, RelationKindDef } from \"./grammar.ts\";\nimport { MODES, entityIdSchema } from \"./grammar.ts\";\nimport type { RegistryInput } from \"./registry.ts\";\nimport { Registry, composeRegistryInput } from \"./registry.ts\";\nimport { conditionSchema } from \"./versions.ts\";\n\n/** The verdicts of a claim. */\nexport const CLAIM_VERDICTS = [\"supported\", \"equivalent\", \"disputed\", \"refuted\", \"speculative\"] as const;\n\n/** The verdict of a claim. */\nexport type ClaimVerdict = (typeof CLAIM_VERDICTS)[number];\n\n/** The facets of the spine. */\nexport const spineFacets: readonly FacetDef[] = [\n {\n name: \"evidenced\",\n description: \"An evidence grade, an agreement score, the date of the last check, and the sources.\",\n attributes: {\n // The name of a rung of the ladder that grades the kind\n evidence_grade: z.string().optional(),\n agreement_score: z.number().optional(),\n last_verified: z.string().optional(),\n // Each value names a source. A part after a \"#\" tells where in the source: a file and a line, or a section\n supporting_source_ids: z.array(z.string()).optional(),\n contradicting_source_ids: z.array(z.string()).optional(),\n },\n },\n {\n name: \"quantified\",\n description:\n \"An amount: the quantity, no bound, or unknown with the reason, and the statistic of its distribution.\",\n attributes: {\n quantity: z.union([extentSchema(), unknownSchema]).optional(),\n statistic: statisticSchema.optional(),\n },\n },\n];\n\n/** The kinds of the spine: the root, the abstract kinds, the claim, and the kinds of the grammar as data. */\nexport const spineKinds: readonly KindDef[] = [\n {\n name: \"entity\",\n parent: null,\n mode: \"top\",\n description: \"The root kind. Each entity is an entity.\",\n attributes: {\n name: z.string(),\n notes: z.string().optional(),\n },\n },\n {\n name: \"concept\",\n parent: \"entity\",\n mode: \"abstract\",\n description: \"An abstract thing: a class, a topic, a category or a role.\",\n attributes: {},\n },\n {\n name: \"claim\",\n parent: \"entity\",\n mode: \"information\",\n description: \"A statement with a verdict, its evidence and the conditions where it holds.\",\n attributes: {\n statement: z.string(),\n verdict: z.enum(CLAIM_VERDICTS).optional(),\n category: z.string().optional(),\n nuance: z.string().optional(),\n // The conditions where the claim holds: versions of a system, an architecture, a provider, a population\n conditions: z.array(conditionSchema).optional(),\n },\n facets: [\"evidenced\", \"quantified\"],\n },\n {\n name: \"facet\",\n parent: \"entity\",\n mode: \"abstract\",\n description: \"A set of attributes that kinds share with no common parent. A facet is data too.\",\n attributes: {\n description: z.string(),\n },\n },\n {\n name: \"kind\",\n parent: \"entity\",\n mode: \"abstract\",\n description: \"A kind of the registry. The kinds are data too.\",\n attributes: {\n mode: z.enum(MODES as [Mode, ...Mode[]]),\n description: z.string(),\n // The count of the entities of exactly this kind, from the last projection\n instances: z.number().int().min(0).optional(),\n // The ends, the symmetry, the transitivity, the roles and the key of a relation kind\n from_kinds: z.array(z.string()).optional(),\n to_kinds: z.array(z.string()).optional(),\n symmetric: z.boolean().optional(),\n transitive: z.boolean().optional(),\n roles: z.array(z.string()).optional(),\n key: z.array(z.string()).optional(),\n },\n },\n {\n name: \"relation\",\n parent: \"entity\",\n mode: \"relation\",\n description:\n \"A relation instance: an edge with its own id. It can have attributes, and a claim can be about it. Each relation kind is a subkind.\",\n attributes: {\n from: entityIdSchema,\n to: entityIdSchema,\n },\n },\n];\n\n/** The relation kinds of the spine: the grammar as data, the subject of a claim, and the classification. */\nexport const spineRelations: readonly RelationKindDef[] = [\n {\n name: \"has-facet\",\n description: \"A kind has a facet.\",\n from: [\"kind\"],\n to: [\"facet\"],\n },\n {\n name: \"subkind-of\",\n description: \"A kind is a subkind of its parent kind.\",\n from: [\"kind\"],\n to: [\"kind\"],\n transitive: true,\n },\n {\n name: \"about\",\n description: \"A claim is about an entity. An add-on can add more kinds at the start.\",\n from: [\"claim\"],\n to: [\"entity\"],\n },\n {\n name: \"classified-as\",\n abstract: true,\n description:\n \"An entity is in a class. Two relation kinds narrow it: one instance-of, then zero or more subclass-of.\",\n from: [\"concept\"],\n to: [\"concept\"],\n },\n {\n name: \"instance-of\",\n parent: \"classified-as\",\n description:\n \"A particular is in a class. The spine has no kind of particular: each add-on adds its kinds to this relation and to classified-as.\",\n from: [],\n to: [\"concept\"],\n },\n {\n name: \"subclass-of\",\n parent: \"classified-as\",\n description: \"A class is in a wider class. It is transitive: each member of the narrow class is in the wide class.\",\n from: [\"concept\"],\n to: [\"concept\"],\n transitive: true,\n },\n];\n\n/** The spine as the input of a registry. An add-on joins it with its own parts through `composeRegistryInput`. */\nexport const SPINE: RegistryInput = {\n kinds: spineKinds,\n relations: spineRelations,\n facets: spineFacets,\n};\n\n/** This function gives the registry of the spine and of the add-ons that it gets. */\nexport const spineRegistry = (...addOns: readonly RegistryInput[]): Registry =>\n new Registry(composeRegistryInput(SPINE, ...addOns));\n"],"mappings":";;;;;AA6BA,IAAa,eAAb,cAAkC,MAAM;CACpB,OAAO;AAC3B;;;;;;AAOA,MAAa,gBAAgB,SAA0B;CACrD,MAAM,QAAQ,qBAAqB,KAAK,KAAK,KAAK,CAAC;CACnD,IAAI,QAAQ,OAAO,KAAA,GAAW,MAAM,IAAI,aAAa,kBAAkB,MAAM;CAC7E,OAAO,MAAM,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;AACvC;;AAGA,MAAa,mBAAmB,GAAY,MAAuB;CACjE,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,IAAI,EAAE,QAAQ,EAA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
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/versions.ts","../src/spine.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { entityIdSchema } from \"./grammar.ts\";\n\n/**\n * Versions and version ranges, for the conditions of a claim: \"the default is 15 on Linux >=2.6.12\".\n *\n * A version starts with dotted numbers (\"6.6.87.2\"). The order ignores the text after the numbers, so\n * \"6.6.87.2-custom\" has the order of 6.6.87.2. A range is a list of comparators with spaces between them\n * (\">=6.6 <6.7\"). Each comparator must hold. Alternatives have \"||\" between them.\n *\n * A version with no operator names its series: \"6.6\" is each 6.6.x. \"=6.6.87.2\" names that release and its patches.\n */\n\n/** A version: its dotted numbers. */\nexport type Version = readonly number[];\n\n/** One end of a span of versions. */\ninterface Bound {\n readonly at: Version;\n readonly inclusive: boolean;\n}\n\n/** A span of versions from `lo` to `hi`. An end with no bound is open. */\nexport interface VersionSpan {\n readonly lo?: Bound;\n readonly hi?: Bound;\n}\n\n/** The error of a text that is not a version or a range. */\nexport class VersionError extends Error {\n override readonly name = \"VersionError\";\n}\n\n/**\n * This function gives the dotted numbers at the start of a version.\n *\n * @throws VersionError when the text does not start with a number\n */\nexport const parseVersion = (text: string): Version => {\n const match = /^v?(\\d+(?:\\.\\d+)*)/.exec(text.trim());\n if (match?.[1] === undefined) throw new VersionError(`not a version: ${text}`);\n return match[1].split(\".\").map(Number);\n};\n\n/** This function gives -1, 0 or 1. It adds zeros to a shorter version, so 6.6 is 6.6.0. */\nexport const compareVersions = (a: Version, b: Version): number => {\n for (let i = 0; i < Math.max(a.length, b.length); i += 1) {\n const x = a[i] ?? 0;\n const y = b[i] ?? 0;\n if (x !== y) return x < y ? -1 : 1;\n }\n return 0;\n};\n\n/** This function gives the release after a series: 6.7 after 6.6, and 7 after 6. */\nconst next = (series: Version): Version => [...series.slice(0, -1), (series[series.length - 1] ?? 0) + 1];\n\n/** This function gives a series as a span: 6.6 is from 6.6 up to 6.7, and 6.7 is not in it. */\nexport const seriesSpan = (series: Version): VersionSpan => ({\n lo: { at: series, inclusive: true },\n hi: { at: next(series), inclusive: false },\n});\n\nconst tighterLo = (a: Bound | undefined, b: Bound | undefined): Bound | undefined => {\n if (a === undefined) return b;\n if (b === undefined) return a;\n const order = compareVersions(a.at, b.at);\n return order > 0 ? a : order < 0 ? b : { at: a.at, inclusive: a.inclusive && b.inclusive };\n};\n\nconst tighterHi = (a: Bound | undefined, b: Bound | undefined): Bound | undefined => {\n if (a === undefined) return b;\n if (b === undefined) return a;\n const order = compareVersions(a.at, b.at);\n return order < 0 ? a : order > 0 ? b : { at: a.at, inclusive: a.inclusive && b.inclusive };\n};\n\nconst intersect = (a: VersionSpan, b: VersionSpan): VersionSpan => {\n const lo = tighterLo(a.lo, b.lo);\n const hi = tighterHi(a.hi, b.hi);\n return { ...(lo !== undefined ? { lo } : {}), ...(hi !== undefined ? { hi } : {}) };\n};\n\nconst isEmpty = (span: VersionSpan): boolean => {\n if (span.lo === undefined || span.hi === undefined) return false;\n const order = compareVersions(span.lo.at, span.hi.at);\n return order > 0 || (order === 0 && !(span.lo.inclusive && span.hi.inclusive));\n};\n\nconst comparator = (token: string, whole: string): VersionSpan => {\n const match = /^(>=|<=|>|<|=)?\\s*(.+)$/.exec(token);\n const [, operator, rest = \"\"] = match ?? [];\n let at: Version;\n try {\n at = parseVersion(rest);\n } catch {\n throw new VersionError(`version range ${whole}: ${token} names no version`);\n }\n switch (operator) {\n case \">=\":\n return { lo: { at, inclusive: true } };\n case \">\":\n return { lo: { at, inclusive: false } };\n case \"<=\":\n return { hi: { at, inclusive: true } };\n case \"<\":\n return { hi: { at, inclusive: false } };\n // \"=6.6.87.2\" is that release: the series that it names\n case \"=\":\n default:\n return seriesSpan(at);\n }\n};\n\n/**\n * This function gives the spans of a range: one span for each alternative.\n *\n * @throws VersionError when the range has an empty alternative or a comparator with no version\n */\nexport const parseRange = (range: string): VersionSpan[] => {\n const alternatives = range.split(\"||\").map((part) => part.trim());\n if (alternatives.some((part) => part === \"\")) {\n throw new VersionError(`version range ${range}: an empty alternative`);\n }\n return alternatives.map((alternative) =>\n alternative\n .replace(/(>=|<=|>|<|=)\\s+/g, \"$1\")\n .split(/\\s+/)\n .map((token) => comparator(token, range))\n .reduce<VersionSpan>((span, part) => intersect(span, part), {}),\n );\n};\n\nconst contains = (outer: VersionSpan, inner: VersionSpan): boolean => {\n const lo = tighterLo(outer.lo, inner.lo);\n const hi = tighterHi(outer.hi, inner.hi);\n // The inner span is inside the outer span when the outer span does not make it tighter\n const same = (a: Bound | undefined, b: Bound | undefined): boolean =>\n (a === undefined && b === undefined) ||\n (a !== undefined && b !== undefined && compareVersions(a.at, b.at) === 0 && a.inclusive === b.inclusive);\n return same(lo, inner.lo) && same(hi, inner.hi);\n};\n\n/**\n * This function tells how a range meets the series of a version. The result is `all` when the full series is in the\n * range. It is `some` when a part of the series is in the range, and `none` when no part is in the range.\n *\n * @throws VersionError when the range or the version is not correct\n */\nexport const rangeMeets = (range: string, version: string): \"all\" | \"some\" | \"none\" => {\n const asked = seriesSpan(parseVersion(version));\n const spans = parseRange(range);\n if (spans.some((span) => contains(span, asked))) return \"all\";\n if (spans.some((span) => !isEmpty(intersect(span, asked)))) return \"some\";\n return \"none\";\n};\n\n/**\n * One condition of a claim: a system at a range of versions, the hardware or the provider, an architecture, or\n * the population of a study. A claim holds where each of its conditions holds.\n */\nexport type Condition =\n | { readonly of: string; readonly versions: string }\n | { readonly on: string }\n | { readonly architecture: string }\n | { readonly population: string };\n\n/** The schema of a version range of a condition: \">=6.6 <6.7\", \"=6.6.87.2\" or \"6.6\". */\nexport const versionRangeSchema: z.ZodType<string, string> = z.string().superRefine((range, ctx) => {\n try {\n if (parseRange(range).every(isEmpty)) {\n ctx.addIssue({ code: \"custom\", message: `version range ${range} allows no version at all` });\n }\n } catch (error) {\n ctx.addIssue({ code: \"custom\", message: error instanceof Error ? error.message : String(error) });\n }\n});\n\n/** The schema of one condition of a claim. A system or a model is the id of an entity. */\nexport const conditionSchema: z.ZodType<Condition, Condition> = z.union([\n // The system and its versions\n z.strictObject({ of: entityIdSchema, versions: versionRangeSchema }),\n // The hardware model or the provider\n z.strictObject({ on: entityIdSchema }),\n z.strictObject({ architecture: z.string().min(1) }),\n // The population of a study, in words\n z.strictObject({ population: z.string().min(1) }),\n]);\n","import { extentSchema, statisticSchema, unknownSchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport type { FacetDef, KindDef, Mode, RelationKindDef } from \"./grammar.ts\";\nimport { MODES, entityIdSchema } from \"./grammar.ts\";\nimport type { RegistryInput } from \"./registry.ts\";\nimport { Registry, composeRegistryInput } from \"./registry.ts\";\nimport { conditionSchema } from \"./versions.ts\";\n\n/** The verdicts of a claim. */\nexport const CLAIM_VERDICTS = [\"supported\", \"equivalent\", \"disputed\", \"refuted\", \"speculative\"] as const;\n\n/** The verdict of a claim. */\nexport type ClaimVerdict = (typeof CLAIM_VERDICTS)[number];\n\n/** The facets of the spine. */\nexport const spineFacets: readonly FacetDef[] = [\n {\n name: \"evidenced\",\n description: \"An evidence grade, an agreement score, the date of the last check, and the sources.\",\n attributes: {\n // The name of a rung of the ladder that grades the kind\n evidence_grade: z.string().optional(),\n agreement_score: z.number().optional(),\n last_verified: z.string().optional(),\n // Each value names a source. A part after a \"#\" tells where in the source: a file and a line, or a section\n supporting_source_ids: z.array(z.string()).optional(),\n contradicting_source_ids: z.array(z.string()).optional(),\n },\n },\n {\n name: \"quantified\",\n description:\n \"An amount: the quantity, no bound, or unknown with the reason, and the statistic of its distribution.\",\n attributes: {\n quantity: z.union([extentSchema(), unknownSchema]).optional(),\n statistic: statisticSchema.optional(),\n },\n },\n];\n\n/** The kinds of the spine: the root, the abstract kinds, the claim, and the kinds of the grammar as data. */\nexport const spineKinds: readonly KindDef[] = [\n {\n name: \"entity\",\n parent: null,\n mode: \"top\",\n description: \"The root kind. Each entity is an entity.\",\n attributes: {\n // An entity with no name shows its id: see nameOf\n name: z.string().optional(),\n notes: z.string().optional(),\n },\n },\n {\n name: \"concept\",\n parent: \"entity\",\n mode: \"abstract\",\n description: \"An abstract thing: a class, a topic, a category or a role.\",\n attributes: {},\n },\n {\n name: \"claim\",\n parent: \"entity\",\n mode: \"information\",\n description: \"A statement with a verdict, its evidence and the conditions where it holds.\",\n attributes: {\n statement: z.string(),\n verdict: z.enum(CLAIM_VERDICTS).optional(),\n category: z.string().optional(),\n nuance: z.string().optional(),\n // The conditions where the claim holds: versions of a system, an architecture, a provider, a population\n conditions: z.array(conditionSchema).optional(),\n },\n facets: [\"evidenced\", \"quantified\"],\n },\n {\n name: \"facet\",\n parent: \"entity\",\n mode: \"abstract\",\n description: \"A set of attributes that kinds share with no common parent. A facet is data too.\",\n attributes: {\n description: z.string(),\n },\n },\n {\n name: \"kind\",\n parent: \"entity\",\n mode: \"abstract\",\n description: \"A kind of the registry. The kinds are data too.\",\n attributes: {\n mode: z.enum(MODES as [Mode, ...Mode[]]),\n description: z.string(),\n // The count of the entities of exactly this kind, from the last projection\n instances: z.number().int().min(0).optional(),\n // The ends, the symmetry, the transitivity, the roles and the key of a relation kind\n from_kinds: z.array(z.string()).optional(),\n to_kinds: z.array(z.string()).optional(),\n symmetric: z.boolean().optional(),\n transitive: z.boolean().optional(),\n roles: z.array(z.string()).optional(),\n key: z.array(z.string()).optional(),\n },\n },\n {\n name: \"relation\",\n parent: \"entity\",\n mode: \"relation\",\n description:\n \"A relation instance: an edge with its own id. It can have attributes, and a claim can be about it. Each relation kind is a subkind.\",\n attributes: {\n from: entityIdSchema,\n to: entityIdSchema,\n },\n },\n];\n\n/** The relation kinds of the spine: the grammar as data, the subject of a claim, and the classification. */\nexport const spineRelations: readonly RelationKindDef[] = [\n {\n name: \"has-facet\",\n description: \"A kind has a facet.\",\n from: [\"kind\"],\n to: [\"facet\"],\n },\n {\n name: \"subkind-of\",\n description: \"A kind is a subkind of its parent kind.\",\n from: [\"kind\"],\n to: [\"kind\"],\n transitive: true,\n },\n {\n name: \"about\",\n description: \"A claim is about an entity. An add-on can add more kinds at the start.\",\n from: [\"claim\"],\n to: [\"entity\"],\n },\n {\n name: \"classified-as\",\n abstract: true,\n description:\n \"An entity is in a class. Two relation kinds narrow it: one instance-of, then zero or more subclass-of.\",\n from: [\"concept\"],\n to: [\"concept\"],\n },\n {\n name: \"instance-of\",\n parent: \"classified-as\",\n description:\n \"A particular is in a class. The spine has no kind of particular: each add-on adds its kinds to this relation and to classified-as.\",\n from: [],\n to: [\"concept\"],\n },\n {\n name: \"subclass-of\",\n parent: \"classified-as\",\n description: \"A class is in a wider class. It is transitive: each member of the narrow class is in the wide class.\",\n from: [\"concept\"],\n to: [\"concept\"],\n transitive: true,\n },\n];\n\n/** The spine as the input of a registry. An add-on joins it with its own parts through `composeRegistryInput`. */\nexport const SPINE: RegistryInput = {\n kinds: spineKinds,\n relations: spineRelations,\n facets: spineFacets,\n};\n\n/** This function gives the registry of the spine and of the add-ons that it gets. */\nexport const spineRegistry = (...addOns: readonly RegistryInput[]): Registry =>\n new Registry(composeRegistryInput(SPINE, ...addOns));\n"],"mappings":";;;;;AA6BA,IAAa,eAAb,cAAkC,MAAM;CACpB,OAAO;AAC3B;;;;;;AAOA,MAAa,gBAAgB,SAA0B;CACrD,MAAM,QAAQ,qBAAqB,KAAK,KAAK,KAAK,CAAC;CACnD,IAAI,QAAQ,OAAO,KAAA,GAAW,MAAM,IAAI,aAAa,kBAAkB,MAAM;CAC7E,OAAO,MAAM,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;AACvC;;AAGA,MAAa,mBAAmB,GAAY,MAAuB;CACjE,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM,GAAG,KAAK,GAAG;EACxD,MAAM,IAAI,EAAE,MAAM;EAClB,MAAM,IAAI,EAAE,MAAM;EAClB,IAAI,MAAM,GAAG,OAAO,IAAI,IAAI,KAAK;CACnC;CACA,OAAO;AACT;;AAGA,MAAM,QAAQ,WAA6B,CAAC,GAAG,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GACzC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;GACvC,WAAW,EAAE,QAAQ,CAAC,CAAC,SAAS;GAChC,YAAY,EAAE,QAAQ,CAAC,CAAC,SAAS;GACjC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;GACpC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;EACpC;CACF;CACA;EACE,MAAM;EACN,QAAQ;EACR,MAAM;EACN,aACE;EACF,YAAY;GACV,MAAM;GACN,IAAI;EACN;CACF;AACF;;AAGA,MAAa,iBAA6C;CACxD;EACE,MAAM;EACN,aAAa;EACb,MAAM,CAAC,MAAM;EACb,IAAI,CAAC,OAAO;CACd;CACA;EACE,MAAM;EACN,aAAa;EACb,MAAM,CAAC,MAAM;EACb,IAAI,CAAC,MAAM;EACX,YAAY;CACd;CACA;EACE,MAAM;EACN,aAAa;EACb,MAAM,CAAC,OAAO;EACd,IAAI,CAAC,QAAQ;CACf;CACA;EACE,MAAM;EACN,UAAU;EACV,aACE;EACF,MAAM,CAAC,SAAS;EAChB,IAAI,CAAC,SAAS;CAChB;CACA;EACE,MAAM;EACN,QAAQ;EACR,aACE;EACF,MAAM,CAAC;EACP,IAAI,CAAC,SAAS;CAChB;CACA;EACE,MAAM;EACN,QAAQ;EACR,aAAa;EACb,MAAM,CAAC,SAAS;EAChB,IAAI,CAAC,SAAS;EACd,YAAY;CACd;AACF;;AAGA,MAAa,QAAuB;CAClC,OAAO;CACP,WAAW;CACX,QAAQ;AACV;;AAGA,MAAa,iBAAiB,GAAG,WAC/B,IAAI,SAAS,qBAAqB,OAAO,GAAG,MAAM,CAAC"}
|
package/build/node.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as Registry, n as GenerateOptions } from "./header-
|
|
1
|
+
import { i as Registry, n as GenerateOptions } from "./header-BluJvnVP.mjs";
|
|
2
2
|
/** This function writes each generated file of a registry into a folder, and gives the names of the files. */
|
|
3
3
|
export declare const writeGenerated: (registry: Registry, dir: string, options?: GenerateOptions) => Promise<readonly string[]>;
|
|
4
4
|
/**
|
package/build/node.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import { t as generateAll } from "./generate-
|
|
3
|
+
import { t as generateAll } from "./generate-Dv-t-uia.mjs";
|
|
4
4
|
// src/node.ts
|
|
5
5
|
/** This function writes each generated file of a registry into a folder, and gives the names of the files. */
|
|
6
6
|
const writeGenerated = async (registry, dir, options) => {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/ontology",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.2.0",
|
|
5
5
|
"description": "A grammar of kinds and relations, a registry, claims under conditions, and the SQLite, DuckDB and JSON Schema of the kinds.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"ontology",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate-D6Vazln0.mjs","names":[],"sources":["../src/grammar.ts","../src/registry.ts","../src/codegen/columns.ts","../src/codegen/header.ts","../src/codegen/duckdb.ts","../src/codegen/sqlite.ts","../src/codegen/jsonschema.ts","../src/generate.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { z } from \"zod\";\n\n/**\n * The mode of a kind. Each relation kind has the mode `relation`. Only the root kind has the mode `top`.\n */\nexport type Mode = \"top\" | \"continuant\" | \"occurrent\" | \"abstract\" | \"information\" | \"relation\";\n\n/** The modes of being, in the order of `Mode`. */\nexport const MODES: readonly Mode[] = [\"top\", \"continuant\", \"occurrent\", \"abstract\", \"information\", \"relation\"];\n\n/** The scopes of a record, from the least sensitive to the most sensitive. */\nexport const SCOPES = [\"public\", \"shared\", \"private\", \"intimate\"] as const;\n\n/** The scope of a record: who can see it. */\nexport type Scope = (typeof SCOPES)[number];\n\n/** The schema of a scope. */\nexport const scopeSchema: z.ZodEnum<{ [K in Scope]: K }> = z.enum(SCOPES);\n\n/**\n * The rank of each scope. The scopes are an order, not a set. An audience sees each scope at its rank or below.\n * A record that comes from a more sensitive record gets the more sensitive scope.\n */\nconst SCOPE_RANK: Readonly<Record<Scope, number>> = { public: 0, shared: 1, private: 2, intimate: 3 };\n\n/** This function gives the rank of a scope: 0 for `public`, 3 for `intimate`. */\nexport const scopeRank = (scope: Scope): number => SCOPE_RANK[scope];\n\n/** This function gives the more sensitive of two scopes. */\nexport const maxScope = (a: Scope, b: Scope): Scope => (SCOPE_RANK[a] >= SCOPE_RANK[b] ? a : b);\n\n/** This function tells if an audience at the scope `audience` can see a record at the scope `scope`. */\nexport const visibleTo = (scope: Scope, audience: Scope): boolean => SCOPE_RANK[scope] <= SCOPE_RANK[audience];\n\n/** The form of the name of a kind, a relation kind, a facet or a role. */\nexport const NAME_PATTERN: RegExp = /^[a-z0-9][a-z0-9-]*$/;\n\n/** The form of the id of an entity: two or more names, with a dot between each two. */\nexport const ENTITY_ID_PATTERN: RegExp = /^[a-z0-9][a-z0-9-]*(\\.[a-z0-9][a-z0-9-]*)+$/;\n\n/** The schema of the id of an entity. */\nexport const entityIdSchema: z.ZodString = z.string().regex(ENTITY_ID_PATTERN);\n\nconst isoDateTime = z.iso.datetime({ offset: true });\n\n/** The envelope of a record: the time, the source, the trust and the scope of its data. */\nexport interface Envelope {\n /** The start of the time in which the record is true. */\n readonly valid_from?: string | undefined;\n /** The end of the time in which the record is true. */\n readonly valid_to?: string | undefined;\n /** The time of the observation of the record. */\n readonly observed_at?: string | undefined;\n /** The time of the write of the record. */\n readonly recorded_at?: string | undefined;\n /** The ids of the sources of the record. */\n readonly source_ids?: readonly string[] | undefined;\n /** It is `true` when a calculation made the record from other records. */\n readonly derived?: boolean | undefined;\n /** The confidence in the record, from 0 to 1. */\n readonly confidence?: number | undefined;\n /** The text that tells who or what gave the record. */\n readonly attribution?: string | undefined;\n /** Who can see the record. */\n readonly scope?: Scope | undefined;\n /** The id of the record that replaces this record. */\n readonly superseded_by?: string | undefined;\n /** The id of the record that this record was retired from, when no record replaces it. */\n readonly retired_from?: string | undefined;\n}\n\n/** An entity: a record with an id, a kind, its attributes and its envelope. */\nexport interface Entity {\n readonly id: string;\n readonly kind: string;\n readonly attrs: Record<string, unknown>;\n readonly envelope: Envelope;\n}\n\n/** An entity as a writer gives it: the envelope is optional. */\nexport interface EntityInput {\n readonly id: string;\n readonly kind: string;\n readonly attrs: Record<string, unknown>;\n readonly envelope?: Envelope | undefined;\n}\n\n/** This function gives the name of an entity: its attribute `name` when it is a string, or else its id. */\nexport const nameOf = (entity: Pick<Entity, \"id\" | \"attrs\">): string => {\n const name = entity.attrs[\"name\"];\n return typeof name === \"string\" ? name : entity.id;\n};\n\n/**\n * The other entities of a relation, by role, in addition to its two ends. A role with one filler holds an id.\n * A role with many fillers holds a list of ids.\n */\nexport type RoleFillers = Readonly<Record<string, string | readonly string[]>>;\n\n/**\n * A relation instance, as seen from its two ends: an edge. Its id comes from what it relates (`relationId`).\n * Thus a link, a citation and a claim can refer to it.\n */\nexport interface Edge {\n readonly id: string;\n readonly from: string;\n readonly type: string;\n readonly to: string;\n /** The other participants of the relation. Each filler is an entity, with the same check as an end. */\n readonly roles?: RoleFillers | undefined;\n readonly qualifiers: Record<string, unknown>;\n readonly envelope: Envelope;\n /**\n * It is `true` on the second row of a symmetric relation: the same relation, read from its other end. A writer\n * does not set it.\n */\n readonly inverse?: true | undefined;\n}\n\n/** An edge as a writer gives it. The registry calculates the id. A writer does not type it. */\nexport interface EdgeInput {\n readonly id?: string | undefined;\n readonly from: string;\n readonly type: string;\n readonly to: string;\n readonly roles?: RoleFillers | undefined;\n readonly qualifiers?: Record<string, unknown> | undefined;\n readonly envelope?: Envelope | undefined;\n}\n\n/** An edge after the check of its shape, before the check of the registry. */\nexport interface ParsedEdge {\n readonly id?: string | undefined;\n readonly from: string;\n readonly type: string;\n readonly to: string;\n readonly roles?: RoleFillers | undefined;\n readonly qualifiers: Record<string, unknown>;\n readonly envelope: Envelope;\n}\n\n/** This function gives the FNV-1a hash of 64 bits of a text, in hexadecimal. It is the same in Node.js and a browser. */\nconst fnv1a64 = (text: string): string => {\n let hash = 0xcbf29ce484222325n;\n for (const byte of new TextEncoder().encode(text)) {\n hash ^= BigInt(byte);\n hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn;\n }\n return hash.toString(16).padStart(16, \"0\");\n};\n\n/**\n * This function gives the id of a relation instance from its kind and its two ends. The same fact always gets\n * the same id. A symmetric kind sorts its two ends first, so each pair has one relation.\n *\n * @remarks\n * A space joins the two ends, and no entity id contains a space. A kind with a key of more parts gets its id from\n * `keyedRelationId`, through `Registry.relationIdOf`.\n */\nexport const relationId = (type: string, from: string, to: string, symmetric = false): string => {\n const [a, b] = symmetric && to < from ? [to, from] : [from, to];\n return `rel.${type}.${fnv1a64(`${a} ${b}`)}`;\n};\n\n/**\n * This function gives the id of a relation whose key has more parts than its two ends. The hash is of the parts\n * of the key, as name and value, in the order of the key.\n *\n * @remarks\n * The JSON of the parts starts with a bracket, and no entity id does. Thus the id is not an id of `relationId` at any time.\n */\nexport const keyedRelationId = (type: string, parts: ReadonlyArray<readonly [string, unknown]>): string =>\n `rel.${type}.${fnv1a64(JSON.stringify(parts))}`;\n\n/** This function tells if an id is the id of a relation instance. */\nexport const isRelationId = (id: string): boolean => id.startsWith(\"rel.\");\n\n/**\n * The schema of an envelope. A record has `superseded_by` or `retired_from`, not the two. The time `valid_from`\n * is not after `valid_to`.\n */\nexport const envelopeSchema: z.ZodType<Envelope, Envelope> = z\n .strictObject({\n valid_from: isoDateTime.optional(),\n valid_to: isoDateTime.optional(),\n observed_at: isoDateTime.optional(),\n recorded_at: isoDateTime.optional(),\n source_ids: z.array(z.string()).optional(),\n derived: z.boolean().optional(),\n confidence: z.number().min(0).max(1).optional(),\n attribution: z.string().optional(),\n scope: scopeSchema.optional(),\n superseded_by: entityIdSchema.optional(),\n retired_from: entityIdSchema.optional(),\n })\n .refine((e) => e.superseded_by === undefined || e.retired_from === undefined, {\n message: \"superseded_by and retired_from are mutually exclusive\",\n })\n .refine((e) => e.valid_from === undefined || e.valid_to === undefined || e.valid_from <= e.valid_to, {\n message: \"valid_from must not be after valid_to\",\n }) as unknown as z.ZodType<Envelope, Envelope>;\n\n/** The schema of an entity, before the check of its kind. */\nexport const entitySchema: z.ZodType<Entity, EntityInput> = z.strictObject({\n id: entityIdSchema,\n kind: z.string().regex(NAME_PATTERN),\n attrs: z.record(z.string(), z.unknown()),\n envelope: envelopeSchema.default({}),\n});\n\nconst roleFillersSchema = z.record(z.string().regex(NAME_PATTERN), z.union([entityIdSchema, z.array(entityIdSchema)]));\n\n/** The schema of an edge as a writer gives it. */\nexport const edgeSchema: z.ZodType<ParsedEdge, EdgeInput> = z.strictObject({\n id: entityIdSchema.optional(),\n from: entityIdSchema,\n type: z.string().regex(NAME_PATTERN),\n to: entityIdSchema,\n roles: roleFillersSchema.optional(),\n qualifiers: z.record(z.string(), z.unknown()).default({}),\n envelope: envelopeSchema.default({}),\n});\n\n/** The schema of an edge as a store gives it back: always with its id, and with `inverse` on a second row. */\nexport const edgeRowSchema: z.ZodType<Edge, Edge> = z.strictObject({\n id: entityIdSchema,\n from: entityIdSchema,\n type: z.string().regex(NAME_PATTERN),\n to: entityIdSchema,\n roles: roleFillersSchema.optional(),\n qualifiers: z.record(z.string(), z.unknown()),\n envelope: envelopeSchema,\n inverse: z.literal(true).optional(),\n});\n\n/** The attributes of a kind or a facet: a schema for each name. */\nexport type AttrShape = Record<string, z.ZodType>;\n\n/** A kind of entity. */\nexport interface KindDef {\n readonly name: string;\n /** The kind above this kind. Only the root kind has `null`. */\n readonly parent: string | null;\n readonly mode: Mode;\n readonly description: string;\n readonly attributes: AttrShape;\n /** The facets of the kind. Their attributes are attributes of the kind. */\n readonly facets?: readonly string[];\n /** The scope of an entity of the kind when its envelope has no scope. */\n readonly defaultScope?: Scope;\n /** The age in days after which a record of the kind is old. */\n readonly staleAfterDays?: number;\n /**\n * The name of the evidence ladder that grades the facts of the kind. A subkind gets the ladder of its parent\n * when it has no ladder.\n */\n readonly ladder?: string;\n /**\n * The name of the type of option that a choice about the kind is between. A subkind gets the type of its parent\n * when it has no type.\n */\n readonly option?: string;\n}\n\n/**\n * A date attribute of a kind with a consequence: a due date, an end of a warranty or the date of a last check.\n * A reader of deadlines finds the records with a date that is near.\n */\nexport interface Deadline {\n readonly kind: string;\n readonly attribute: string;\n /** The text that tells the consequence on the date: \"due\", \"warranty ends\". */\n readonly label: string;\n /** The time after a last check at which the consequence occurs, in whole days. */\n readonly after?: Quantity;\n}\n\n/**\n * An attribute whose value is the name of an entity. A projection makes an edge from each value. Thus the two\n * ends show the link, and a reader gets the attributes of the named entity.\n */\nexport interface NamedReference {\n /** The attribute that holds the name. */\n readonly attribute: string;\n /** The relation kind of the edge from the holder to the named entity. */\n readonly relation: string;\n /** The kind of the named entities. The value is their attribute `name`. */\n readonly toKind: string;\n}\n\n/**\n * A relation kind: the type of an edge. The registry makes each relation kind a kind of the mode `relation`\n * under the kind `relation`. Its qualifiers and roles are the attributes of that kind.\n */\nexport interface RelationKindDef {\n readonly name: string;\n /**\n * The relation kind that this kind narrows. The kind can make the ends of its parent narrower, but not wider.\n * It gets the qualifiers, the roles and the key of its parent. A reader of the parent also finds this kind.\n */\n readonly parent?: string;\n readonly description: string;\n /** The kinds of the end `from`. A subkind of each kind is also correct. */\n readonly from: readonly string[];\n /** The kinds of the end `to`. A subkind of each kind is also correct. */\n readonly to: readonly string[];\n readonly qualifiers?: AttrShape;\n /** It is `true` for a relation of an unordered pair: one relation for each pair, read from the two ends. */\n readonly symmetric?: boolean;\n readonly transitive?: boolean;\n /**\n * It is `true` for a family of relation kinds with no instances of its own. A reader of the family finds the\n * kinds that narrow it.\n */\n readonly abstract?: boolean;\n /**\n * The other participants of the relation, by role, in addition to its two ends. Each role names the kinds of\n * its fillers. The check of a filler is the same as the check of an end.\n */\n readonly roles?: Readonly<Record<string, RoleDef>>;\n /**\n * The parts that identify one relation of the kind. The default is its two ends. A key part is `from`, `to`, a\n * role with one filler or a qualifier.\n */\n readonly key?: readonly string[];\n}\n\n/** A role of a relation kind, in addition to its two ends. */\nexport interface RoleDef {\n readonly description: string;\n /** The kinds of the fillers of the role. A subkind of each kind is also correct. */\n readonly kinds: readonly string[];\n /** It is `true` when the role takes a list of fillers. Otherwise it takes one filler. */\n readonly many?: boolean;\n}\n\n/** A facet: a set of attributes that many kinds share, with no common parent kind. */\nexport interface FacetDef {\n readonly name: string;\n readonly description: string;\n readonly attributes: AttrShape;\n}\n\n/**\n * An extension of a relation kind by an add-on: more kinds at its ends. Thus an add-on can relate its own kinds\n * with a relation kind of the core.\n */\nexport interface RelationExtension {\n /** The relation kind that the add-on extends. */\n readonly relation: string;\n /** The kinds that the add-on adds to the end `from`. */\n readonly from?: readonly string[];\n /** The kinds that the add-on adds to the end `to`. */\n readonly to?: readonly string[];\n}\n","import { valueIn, whyNotConvertible } from \"@mark1russell7/quantity\";\nimport { z } from \"zod\";\nimport type {\n AttrShape,\n Deadline,\n Edge,\n EdgeInput,\n Entity,\n FacetDef,\n KindDef,\n NamedReference,\n RelationExtension,\n RelationKindDef,\n RoleFillers,\n} from \"./grammar.ts\";\nimport { edgeSchema, entityIdSchema, entitySchema, isRelationId, keyedRelationId, NAME_PATTERN, relationId } from \"./grammar.ts\";\n\n/** The name of the kind above each relation kind. */\nexport const RELATION_ROOT = \"relation\";\n\n/** The key of a relation kind that names no key: its two ends. */\nconst ENDS_KEY: readonly string[] = [\"from\", \"to\"];\n\n/** The parts of a relation that `Registry.relationIdOf` reads: an edge, or the attributes of a relation entity. */\nexport interface RelationLike {\n readonly type: string;\n readonly from: string;\n readonly to: string;\n readonly roles?: RoleFillers | undefined;\n readonly qualifiers?: Record<string, unknown> | undefined;\n}\n\n/** The parts of a registry: a core, or a core and its add-ons after `composeRegistryInput`. */\nexport interface RegistryInput {\n readonly kinds: readonly KindDef[];\n /** Each type of edge, as a relation kind. Each relation kind is also a kind under `relation`. */\n readonly relations: readonly RelationKindDef[];\n readonly facets?: readonly FacetDef[];\n /** The attributes whose values are names of entities. A projection makes an edge from each value. */\n readonly namedReferences?: readonly NamedReference[];\n /** The date attributes of kinds with a consequence. */\n readonly deadlines?: readonly Deadline[];\n /** The kinds that add-ons add to the ends of relation kinds. */\n readonly extensions?: readonly RelationExtension[];\n}\n\n/** A problem of a record: the path of the value and the message. */\nexport interface ValidationIssue {\n readonly path: string;\n readonly message: string;\n}\n\n/** The error of a registry that is not correct, or of a record that the registry refuses. */\nexport class RegistryError extends Error {\n readonly issues: readonly ValidationIssue[];\n\n constructor(message: string, issues: readonly ValidationIssue[] = []) {\n const detail = issues.map((i) => ` ${i.path}: ${i.message}`).join(\"\\n\");\n super(detail.length > 0 ? `${message}\\n${detail}` : message);\n this.name = \"RegistryError\";\n this.issues = issues;\n }\n}\n\nconst zodIssues = (prefix: string, error: z.ZodError): ValidationIssue[] =>\n error.issues.map((issue) => ({\n path: issue.path.length > 0 ? `${prefix}.${issue.path.join(\".\")}` : prefix,\n message: issue.message,\n }));\n\n/**\n * This function joins the parts of a core and its add-ons into one input of a registry. The registry refuses a\n * kind, a relation kind or a facet that two parts declare.\n */\nexport const composeRegistryInput = (...parts: readonly RegistryInput[]): RegistryInput => ({\n kinds: parts.flatMap((part) => part.kinds),\n relations: parts.flatMap((part) => part.relations),\n facets: parts.flatMap((part) => part.facets ?? []),\n namedReferences: parts.flatMap((part) => part.namedReferences ?? []),\n deadlines: parts.flatMap((part) => part.deadlines ?? []),\n extensions: parts.flatMap((part) => part.extensions ?? []),\n});\n\n/** This function adds the kinds of the extensions to the ends of the relation kinds. A kind is not added two times. */\nconst extend = (relations: Map<string, RelationKindDef>, extensions: readonly RelationExtension[]): void => {\n for (const extension of extensions) {\n const relation = relations.get(extension.relation);\n if (relation === undefined) {\n throw new RegistryError(`an extension names unknown relation kind ${extension.relation}`);\n }\n const add = (ends: readonly string[], more: readonly string[] | undefined): readonly string[] => [\n ...ends,\n ...(more ?? []).filter((kind, at, all) => !ends.includes(kind) && all.indexOf(kind) === at),\n ];\n relations.set(relation.name, { ...relation, from: add(relation.from, extension.from), to: add(relation.to, extension.to) });\n }\n};\n\n/**\n * A registry of kinds, relation kinds and facets. It checks itself when it is made, and it checks each entity and\n * each edge.\n */\nexport class Registry {\n readonly kinds: ReadonlyMap<string, KindDef>;\n readonly relations: ReadonlyMap<string, RelationKindDef>;\n readonly facets: ReadonlyMap<string, FacetDef>;\n readonly namedReferences: readonly NamedReference[];\n readonly deadlines: readonly Deadline[];\n readonly rootKind: string;\n\n private readonly schemaCache = new Map<string, z.ZodType>();\n private readonly closureCache = new Map<string, ReadonlySet<string>>();\n\n /** @throws RegistryError when the parts of the registry are not correct */\n constructor(input: RegistryInput) {\n const kinds = new Map<string, KindDef>();\n for (const kind of input.kinds) {\n if (!NAME_PATTERN.test(kind.name)) {\n throw new RegistryError(`invalid kind name: ${kind.name}`);\n }\n if (kinds.has(kind.name)) {\n throw new RegistryError(`duplicate kind: ${kind.name}`);\n }\n kinds.set(kind.name, kind);\n }\n\n const facets = new Map<string, FacetDef>();\n for (const facet of input.facets ?? []) {\n // toGraph makes an entity id of each facet name, so a facet name has the form of an id part\n if (!NAME_PATTERN.test(facet.name)) {\n throw new RegistryError(`invalid facet name: ${facet.name}`);\n }\n if (facets.has(facet.name)) {\n throw new RegistryError(`duplicate facet: ${facet.name}`);\n }\n facets.set(facet.name, facet);\n }\n\n // Each relation kind is also a kind: its instances are entities, and its qualifiers are their attributes\n const relations = new Map<string, RelationKindDef>();\n for (const relation of input.relations) {\n if (!NAME_PATTERN.test(relation.name)) {\n throw new RegistryError(`invalid relation kind name: ${relation.name}`);\n }\n if (relations.has(relation.name)) {\n throw new RegistryError(`duplicate relation kind: ${relation.name}`);\n }\n if (kinds.has(relation.name)) {\n throw new RegistryError(`relation kind ${relation.name} collides with a kind`);\n }\n const qualifiers = Object.keys(relation.qualifiers ?? {});\n for (const [role, def] of Object.entries(relation.roles ?? {})) {\n if (!NAME_PATTERN.test(role)) {\n throw new RegistryError(`relation kind ${relation.name}: invalid role name ${role}`);\n }\n if (qualifiers.includes(role)) {\n throw new RegistryError(`relation kind ${relation.name}: ${role} is both a role and a qualifier`);\n }\n if (def.kinds.length === 0) {\n throw new RegistryError(`relation kind ${relation.name}: role ${role} names no kind`);\n }\n }\n relations.set(relation.name, relation);\n }\n extend(relations, input.extensions ?? []);\n // A relation can fill an end or a role, so the check of the names waits for each relation kind\n for (const relation of relations.values()) {\n const known = (name: string): boolean => kinds.has(name) || relations.has(name);\n for (const kindName of [...relation.from, ...relation.to]) {\n if (!known(kindName)) {\n throw new RegistryError(`relation kind ${relation.name} references unknown kind ${kindName}`);\n }\n }\n for (const [role, def] of Object.entries(relation.roles ?? {})) {\n for (const kindName of def.kinds) {\n if (!known(kindName)) {\n throw new RegistryError(`relation kind ${relation.name}: role ${role} references unknown kind ${kindName}`);\n }\n }\n }\n }\n if (relations.size > 0 && !kinds.has(RELATION_ROOT)) {\n throw new RegistryError(`relation kinds need the ${RELATION_ROOT} kind to descend from`);\n }\n for (const relation of relations.values()) {\n if (relation.parent !== undefined && !relations.has(relation.parent)) {\n throw new RegistryError(`relation kind ${relation.name} narrows ${relation.parent}, which is not a relation kind`);\n }\n }\n for (const relation of relations.values()) {\n // The attributes of its instances: its qualifiers, and its roles\n const roles = Object.fromEntries(\n Object.entries(relation.roles ?? {}).map(([role, def]) => [\n role,\n def.many === true ? z.array(entityIdSchema).min(1).optional() : entityIdSchema.optional(),\n ]),\n );\n // A narrower relation kind is a subkind of the kind that it narrows\n kinds.set(relation.name, {\n name: relation.name,\n parent: relation.parent ?? RELATION_ROOT,\n mode: \"relation\",\n description: relation.description,\n attributes: { ...(relation.qualifiers ?? {}), ...roles },\n });\n }\n\n const roots: string[] = [];\n for (const kind of kinds.values()) {\n if (kind.parent === null) {\n roots.push(kind.name);\n } else if (!kinds.has(kind.parent)) {\n throw new RegistryError(`kind ${kind.name} has unknown parent ${kind.parent}`);\n }\n for (const facet of kind.facets ?? []) {\n if (!facets.has(facet)) {\n throw new RegistryError(`kind ${kind.name} declares unknown facet ${facet}`);\n }\n }\n }\n const root = roots[0];\n if (root === undefined || roots.length !== 1) {\n throw new RegistryError(`expected exactly one root kind, found: ${roots.join(\", \")}`);\n }\n for (const kind of kinds.values()) {\n const seen = new Set<string>([kind.name]);\n let current = kind.parent;\n while (current !== null) {\n if (seen.has(current)) {\n throw new RegistryError(`kind cycle through ${current}`);\n }\n seen.add(current);\n current = kinds.get(current)?.parent ?? null;\n }\n }\n\n for (const reference of input.namedReferences ?? []) {\n if (!relations.has(reference.relation)) {\n throw new RegistryError(`named reference ${reference.attribute} draws unknown relation kind ${reference.relation}`);\n }\n if (!kinds.has(reference.toKind)) {\n throw new RegistryError(`named reference ${reference.attribute} names unknown kind ${reference.toKind}`);\n }\n }\n\n this.kinds = kinds;\n this.relations = this.inherit(relations);\n this.facets = facets;\n // A qualifier or a role with the name of an attribute of each relation (name, from, to) replaces it with no error\n if (relations.size > 0) {\n const inherited = this.effectiveShape(RELATION_ROOT);\n for (const relation of relations.values()) {\n for (const [what, names] of [\n [\"qualifier\", Object.keys(relation.qualifiers ?? {})],\n [\"role\", Object.keys(relation.roles ?? {})],\n ] as const) {\n for (const name of names) {\n if (name in inherited) {\n throw new RegistryError(\n `relation kind ${relation.name} declares ${what} ${name}, which every relation instance already has`,\n );\n }\n }\n }\n }\n }\n for (const deadline of input.deadlines ?? []) {\n if (!kinds.has(deadline.kind)) {\n throw new RegistryError(`deadline ${deadline.attribute} is on unknown kind ${deadline.kind}`);\n }\n // A time after a check counts calendar days, so it is a whole number of days\n if (deadline.after !== undefined) {\n const why = whyNotConvertible(deadline.after.unit, \"d\");\n const days = why === undefined ? valueIn(deadline.after, \"d\") : Number.NaN;\n if (!Number.isInteger(days)) {\n throw new RegistryError(\n `deadline ${deadline.attribute} on ${deadline.kind}: after must be whole days${why === undefined ? \"\" : ` (${why})`}`,\n );\n }\n }\n }\n this.namedReferences = input.namedReferences ?? [];\n this.deadlines = input.deadlines ?? [];\n this.rootKind = root;\n }\n\n /**\n * This method gives each relation kind with the parts that it gets from the kinds that it narrows. A child makes\n * the ends of its parent narrower, and it adds qualifiers and roles. It does not declare a part of its parent again.\n * It gets the key, the symmetry and the transitivity of its parent when it does not declare them.\n */\n private inherit(declared: ReadonlyMap<string, RelationKindDef>): Map<string, RelationKindDef> {\n const merged = new Map<string, RelationKindDef>();\n const resolve = (name: string): RelationKindDef => {\n const done = merged.get(name);\n if (done !== undefined) return done;\n const own = declared.get(name);\n if (own === undefined) throw new RegistryError(`unknown relation kind: ${name}`);\n let effective = own;\n if (own.parent !== undefined) {\n const parent = resolve(own.parent);\n for (const [end, mine, theirs] of [\n [\"from\", own.from, parent.from],\n [\"to\", own.to, parent.to],\n ] as const) {\n for (const kind of mine) {\n if (!theirs.some((wider) => this.isSubkindOf(kind, wider))) {\n throw new RegistryError(\n `relation kind ${name}: ${end} kind ${kind} is wider than ${own.parent} allows (${theirs.join(\"|\")})`,\n );\n }\n }\n }\n const fields = [...Object.keys(parent.qualifiers ?? {}), ...Object.keys(parent.roles ?? {})];\n for (const field of [...Object.keys(own.qualifiers ?? {}), ...Object.keys(own.roles ?? {})]) {\n if (fields.includes(field)) {\n throw new RegistryError(`relation kind ${name} redeclares ${field}, which it has from ${own.parent}`);\n }\n }\n const qualifiers = { ...(parent.qualifiers ?? {}), ...(own.qualifiers ?? {}) };\n const roles = { ...(parent.roles ?? {}), ...(own.roles ?? {}) };\n const key = own.key ?? parent.key;\n const symmetric = own.symmetric ?? parent.symmetric;\n const transitive = own.transitive ?? parent.transitive;\n effective = {\n ...own,\n ...(Object.keys(qualifiers).length > 0 ? { qualifiers } : {}),\n ...(Object.keys(roles).length > 0 ? { roles } : {}),\n ...(key !== undefined ? { key } : {}),\n ...(symmetric !== undefined ? { symmetric } : {}),\n ...(transitive !== undefined ? { transitive } : {}),\n };\n }\n // A key part is a part that a relation has one of: an end, a role with one filler, a qualifier\n const key = effective.key ?? ENDS_KEY;\n if (key.length === 0 || new Set(key).size !== key.length) {\n throw new RegistryError(`relation kind ${name}: a key names each part once`);\n }\n for (const part of key) {\n const role = effective.roles?.[part];\n const keyable =\n part === \"from\" ||\n part === \"to\" ||\n Object.keys(effective.qualifiers ?? {}).includes(part) ||\n (role !== undefined && role.many !== true);\n if (!keyable) {\n throw new RegistryError(`relation kind ${name}: key part ${part} is not an end, a single role or a qualifier`);\n }\n }\n merged.set(name, effective);\n return effective;\n };\n for (const name of declared.keys()) resolve(name);\n return merged;\n }\n\n /**\n * This method gives the kinds from the root to the kind, in that order.\n *\n * @throws RegistryError when a kind is not known\n */\n ancestry(kindName: string): readonly KindDef[] {\n const chain: KindDef[] = [];\n let current: string | null = kindName;\n while (current !== null) {\n const kind = this.kinds.get(current);\n if (kind === undefined) {\n throw new RegistryError(`unknown kind: ${current}`);\n }\n chain.unshift(kind);\n current = kind.parent;\n }\n return chain;\n }\n\n /** This method tells if a kind is the ancestor kind or a subkind of it. */\n isSubkindOf(kindName: string, ancestorName: string): boolean {\n return this.ancestry(kindName).some((kind) => kind.name === ancestorName);\n }\n\n /**\n * This method gives the kind and each of its subkinds.\n *\n * @throws RegistryError when the kind is not known\n */\n subkindClosure(kindName: string): ReadonlySet<string> {\n const cached = this.closureCache.get(kindName);\n if (cached !== undefined) return cached;\n if (!this.kinds.has(kindName)) {\n throw new RegistryError(`unknown kind: ${kindName}`);\n }\n const closure = new Set<string>();\n for (const kind of this.kinds.keys()) {\n if (this.isSubkindOf(kind, kindName)) {\n closure.add(kind);\n }\n }\n this.closureCache.set(kindName, closure);\n return closure;\n }\n\n /** This method gives the ladder of a kind: its own ladder, or the ladder of the nearest kind above it. */\n ladderOf(kindName: string): string | undefined {\n const chain = this.ancestry(kindName);\n for (let at = chain.length - 1; at >= 0; at -= 1) {\n const ladder = chain[at]?.ladder;\n if (ladder !== undefined) return ladder;\n }\n return undefined;\n }\n\n /** This method gives the type of option of a kind: its own type, or the type of the nearest kind above it. */\n optionOf(kindName: string): string | undefined {\n const chain = this.ancestry(kindName);\n for (let at = chain.length - 1; at >= 0; at -= 1) {\n const option = chain[at]?.option;\n if (option !== undefined) return option;\n }\n return undefined;\n }\n\n /** This method gives each attribute of a kind: the attributes of its ancestors and their facets, then its own. */\n effectiveShape(kindName: string): AttrShape {\n const shape: Record<string, z.ZodType> = {};\n for (const kind of this.ancestry(kindName)) {\n for (const facetName of kind.facets ?? []) {\n const facet = this.facets.get(facetName);\n if (facet !== undefined) {\n Object.assign(shape, facet.attributes);\n }\n }\n Object.assign(shape, kind.attributes);\n }\n return shape;\n }\n\n /** This method gives the strict schema of the attributes of a kind. */\n effectiveSchema(kindName: string): z.ZodType {\n const cached = this.schemaCache.get(kindName);\n if (cached !== undefined) return cached;\n const schema = z.strictObject(this.effectiveShape(kindName));\n this.schemaCache.set(kindName, schema);\n return schema;\n }\n\n /**\n * This method checks an entity and gives it with its parsed attributes. An entity with no scope gets the default\n * scope of its kind.\n *\n * @throws RegistryError when the entity is not correct\n */\n validateEntity(raw: unknown): Entity {\n const parsed = entitySchema.safeParse(raw);\n if (!parsed.success) {\n throw new RegistryError(\"invalid entity\", zodIssues(\"entity\", parsed.error));\n }\n const entity = parsed.data;\n if (!this.kinds.has(entity.kind)) {\n throw new RegistryError(`entity ${entity.id} has unknown kind ${entity.kind}`);\n }\n const attrs = this.effectiveSchema(entity.kind).safeParse(entity.attrs);\n if (!attrs.success) {\n throw new RegistryError(`invalid attrs for ${entity.id}`, zodIssues(entity.id, attrs.error));\n }\n // The id of a relation instance comes from its kind and its ends, and only a relation instance has such an id\n const relation = this.relations.get(entity.kind);\n if (relation !== undefined) {\n const data = attrs.data as Record<string, unknown> & { from: string; to: string };\n const roles = Object.fromEntries(\n Object.keys(relation.roles ?? {})\n .filter((role) => data[role] !== undefined)\n .map((role) => [role, data[role] as string | readonly string[]]),\n );\n const id = this.relationIdOf({ type: entity.kind, from: data.from, to: data.to, roles, qualifiers: data });\n if (entity.id !== id) {\n throw new RegistryError(`${entity.id}: a ${entity.kind} from ${data.from} to ${data.to} is ${id}`);\n }\n } else if (isRelationId(entity.id)) {\n throw new RegistryError(`${entity.id}: rel. ids belong to relation instances, not a ${entity.kind}`);\n }\n const defaultScope = this.kinds.get(entity.kind)?.defaultScope;\n const envelope =\n defaultScope !== undefined && entity.envelope[\"scope\"] === undefined\n ? { ...entity.envelope, scope: defaultScope }\n : entity.envelope;\n return { ...entity, envelope, attrs: attrs.data as Record<string, unknown> };\n }\n\n /**\n * This method gives the id of a relation from the key of its kind. A symmetric kind sorts its two ends, so the two\n * orders give the same id. A key with only the two ends gives the id of `relationId`.\n *\n * @throws RegistryError when the relation kind is not known\n */\n relationIdOf(edge: RelationLike): string {\n const relation = this.relations.get(edge.type);\n if (relation === undefined) throw new RegistryError(`unknown relation kind: ${edge.type}`);\n const symmetric = relation.symmetric === true;\n const [a, b] = symmetric && edge.to < edge.from ? [edge.to, edge.from] : [edge.from, edge.to];\n const parts: Array<readonly [string, unknown]> = [];\n for (const part of relation.key ?? ENDS_KEY) {\n const value =\n part === \"from\"\n ? a\n : part === \"to\"\n ? b\n : relation.roles?.[part] !== undefined\n ? edge.roles?.[part]\n : edge.qualifiers?.[part];\n if (value !== undefined) parts.push([part, value]);\n }\n const ends = parts.length === 2 && parts[0]?.[0] === \"from\" && parts[1]?.[0] === \"to\";\n return ends ? relationId(edge.type, edge.from, edge.to, symmetric) : keyedRelationId(edge.type, parts);\n }\n\n /**\n * This method checks an edge: its kind, the kinds of its ends and its role fillers, and its qualifiers. It gives\n * the edge with its id.\n *\n * @param kindOf - This function gives the kind of an entity id, or `undefined` for an id with no entity.\n * @throws RegistryError when the edge is not correct\n */\n validateEdge(raw: unknown, kindOf: (id: string) => string | undefined): Edge {\n const parsed = edgeSchema.safeParse(raw);\n if (!parsed.success) {\n throw new RegistryError(\"invalid edge\", zodIssues(\"edge\", parsed.error));\n }\n const input = parsed.data;\n const relation = this.relations.get(input.type);\n if (relation === undefined) {\n throw new RegistryError(`unknown relation kind: ${input.type}`);\n }\n const label = `${input.from} -${input.type}-> ${input.to}`;\n if (relation.abstract === true) {\n const narrower = [...this.relations.values()]\n .filter((candidate) => candidate.parent === input.type)\n .map((candidate) => candidate.name)\n .sort();\n throw new RegistryError(\n `${label}: ${input.type} is abstract, a family with no instances of its own: say which, ${narrower.join(\" or \")}`,\n );\n }\n const check = (part: string, endId: string, allowed: readonly string[]): void => {\n const kind = kindOf(endId);\n if (kind === undefined) {\n throw new RegistryError(`${label}: ${part} entity ${endId} not found`);\n }\n if (allowed.length === 0) {\n throw new RegistryError(`${label}: ${input.type} allows no ${part} kind yet: an add-on extends it`);\n }\n if (!allowed.some((ancestor) => this.isSubkindOf(kind, ancestor))) {\n throw new RegistryError(`${label}: ${part} kind ${kind} not allowed (expected ${allowed.join(\"|\")})`);\n }\n };\n check(\"from\", input.from, relation.from);\n check(\"to\", input.to, relation.to);\n const roles = input.roles ?? {};\n for (const [role, fillers] of Object.entries(roles)) {\n const def = relation.roles?.[role];\n if (def === undefined) {\n throw new RegistryError(`${label}: relation kind ${input.type} has no role ${role}`);\n }\n const many = def.many === true;\n if (many !== Array.isArray(fillers)) {\n throw new RegistryError(`${label}: role ${role} takes ${many ? \"a list of entities\" : \"one entity\"}`);\n }\n const list: readonly string[] = typeof fillers === \"string\" ? [fillers] : fillers;\n if (list.length === 0 || new Set(list).size !== list.length) {\n throw new RegistryError(`${label}: role ${role} lists each filler once, and at least one`);\n }\n for (const filler of list) check(`role ${role}`, filler, def.kinds);\n }\n let qualifiers = input.qualifiers;\n if (relation.qualifiers !== undefined) {\n const checked = z.strictObject(relation.qualifiers).safeParse(input.qualifiers);\n if (!checked.success) {\n throw new RegistryError(`invalid qualifiers for ${label}`, zodIssues(label, checked.error));\n }\n qualifiers = checked.data as Record<string, unknown>;\n } else if (Object.keys(input.qualifiers).length > 0) {\n throw new RegistryError(`${label}: relation kind ${input.type} declares no qualifiers`);\n }\n // The registry calculates the id. An id that is not the id of the key is an edit by hand\n const hasRoles = Object.keys(roles).length > 0;\n const id = this.relationIdOf({ ...input, roles, qualifiers });\n if (input.id !== undefined && input.id !== id) {\n throw new RegistryError(`${label}: id ${input.id} is not this relation's (${id})`);\n }\n return {\n id,\n from: input.from,\n type: input.type,\n to: input.to,\n ...(hasRoles ? { roles } : {}),\n qualifiers,\n envelope: input.envelope,\n };\n }\n\n /**\n * This method gives the registry as data: an entity for each kind and each facet. Each parent gives an edge\n * `subkind-of`, and each facet of a kind gives an edge `has-facet`.\n */\n toGraph(): { entities: Entity[]; edges: EdgeInput[] } {\n const entities: Entity[] = [];\n const edges: EdgeInput[] = [];\n for (const facet of this.facets.values()) {\n entities.push({\n id: `ontology.facet.${facet.name}`,\n kind: \"facet\",\n attrs: { name: facet.name, description: facet.description },\n envelope: {},\n });\n }\n for (const kind of this.kinds.values()) {\n const relation = this.relations.get(kind.name);\n entities.push({\n id: `ontology.kind.${kind.name}`,\n kind: \"kind\",\n attrs: {\n name: kind.name,\n mode: kind.mode,\n description: kind.description,\n ...(relation !== undefined\n ? {\n from_kinds: [...relation.from],\n to_kinds: [...relation.to],\n ...(relation.symmetric === true ? { symmetric: true } : {}),\n ...(relation.transitive === true ? { transitive: true } : {}),\n ...(relation.roles !== undefined ? { roles: Object.keys(relation.roles) } : {}),\n ...(relation.key !== undefined ? { key: [...relation.key] } : {}),\n }\n : {}),\n },\n envelope: {},\n });\n if (kind.parent !== null) {\n edges.push({\n from: `ontology.kind.${kind.name}`,\n type: \"subkind-of\",\n to: `ontology.kind.${kind.parent}`,\n qualifiers: {},\n envelope: {},\n });\n }\n for (const facetName of kind.facets ?? []) {\n edges.push({\n from: `ontology.kind.${kind.name}`,\n type: \"has-facet\",\n to: `ontology.facet.${facetName}`,\n qualifiers: {},\n envelope: {},\n });\n }\n }\n return { entities, edges };\n }\n}\n","import { isQuantitySchema } from \"@mark1russell7/quantity/schema\";\nimport type { z } from \"zod\";\n\n/** The column shape of an attribute in a view of a store. */\nexport type ColumnShape =\n | { readonly kind: \"text\" }\n | { readonly kind: \"number\" }\n | { readonly kind: \"boolean\" }\n | { readonly kind: \"array\"; readonly element: \"text\" | \"number\" | \"json\" }\n /** A quantity `{ value, unit }` becomes a number column and a unit column. */\n | { readonly kind: \"quantity\" }\n | { readonly kind: \"json\" };\n\ninterface AnyDef {\n readonly type: string;\n readonly innerType?: z.ZodType;\n readonly element?: z.ZodType;\n}\n\nconst defOf = (schema: z.ZodType): AnyDef => (schema as unknown as { def: AnyDef }).def;\n\nconst WRAPPERS = new Set([\"optional\", \"nullable\", \"default\", \"readonly\", \"nonoptional\"]);\n\nconst unwrap = (schema: z.ZodType): AnyDef => {\n let def = defOf(schema);\n while (WRAPPERS.has(def.type) && def.innerType !== undefined) {\n def = defOf(def.innerType);\n }\n return def;\n};\n\nconst scalar = (def: AnyDef): \"text\" | \"number\" | \"boolean\" | \"json\" => {\n switch (def.type) {\n case \"string\":\n case \"enum\":\n case \"literal\":\n return \"text\";\n case \"number\":\n case \"int\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n default:\n return \"json\";\n }\n};\n\n/** This function gives the column shape of the schema of an attribute. */\nexport const columnShape = (schema: z.ZodType): ColumnShape => {\n if (isQuantitySchema(schema)) return { kind: \"quantity\" };\n const def = unwrap(schema);\n if (def.type === \"array\" && def.element !== undefined) {\n const element = scalar(unwrap(def.element));\n return { kind: \"array\", element: element === \"boolean\" ? \"json\" : element };\n }\n const kind = scalar(def);\n return kind === \"json\" ? { kind: \"json\" } : { kind };\n};\n","/** The options of a generator of a store. */\nexport interface GenerateOptions {\n /** The first line of each generated SQL file. An add-on names its own command here. */\n readonly header?: string;\n}\n\n/** The default first line of each generated SQL file. */\nexport const DEFAULT_HEADER = \"-- Generated by @mark1russell7/ontology from the kinds of a registry. Do not edit by hand.\";\n\n/** This function gives the header line of a generated SQL file, with its line end. */\nexport const headerOf = (options: GenerateOptions | undefined): string => `${options?.header ?? DEFAULT_HEADER}\\n`;\n","import { RegistryError } from \"../registry.ts\";\nimport type { Registry } from \"../registry.ts\";\nimport type { ColumnShape } from \"./columns.ts\";\nimport { columnShape } from \"./columns.ts\";\nimport type { GenerateOptions } from \"./header.ts\";\nimport { headerOf } from \"./header.ts\";\n\nconst BASE_TABLES = `CREATE TABLE IF NOT EXISTS entities (\n id VARCHAR PRIMARY KEY,\n kind VARCHAR NOT NULL,\n attrs JSON NOT NULL DEFAULT '{}',\n envelope JSON NOT NULL DEFAULT '{}'\n);\n\nCREATE TABLE IF NOT EXISTS edges (\n id VARCHAR NOT NULL,\n from_id VARCHAR NOT NULL,\n type VARCHAR NOT NULL,\n to_id VARCHAR NOT NULL,\n roles JSON NOT NULL DEFAULT '{}',\n qualifiers JSON NOT NULL DEFAULT '{}',\n envelope JSON NOT NULL DEFAULT '{}',\n inverse BOOLEAN NOT NULL DEFAULT FALSE,\n PRIMARY KEY (id, from_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_entities_kind ON entities (kind);\nCREATE INDEX IF NOT EXISTS idx_edges_from ON edges (from_id);\nCREATE INDEX IF NOT EXISTS idx_edges_to ON edges (to_id);\nCREATE INDEX IF NOT EXISTS idx_edges_type ON edges (type);\n`;\n\nconst identifier = (name: string): string => name.replace(/-/g, \"_\");\n\n// SQL reserves the names of the two ends of a relation (from, to), so each attribute column has quotes\nconst column = (key: string): string => `\"${identifier(key)}\"`;\n\nconst attrColumn = (key: string, shape: ColumnShape): string => {\n switch (shape.kind) {\n case \"text\":\n return `attrs->>'${key}' AS ${column(key)}`;\n case \"number\":\n return `CAST(attrs->>'${key}' AS DOUBLE) AS ${column(key)}`;\n case \"boolean\":\n return `CAST(attrs->>'${key}' AS BOOLEAN) AS ${column(key)}`;\n case \"array\":\n if (shape.element === \"text\") {\n return `CAST(attrs->'${key}' AS VARCHAR[]) AS ${column(key)}`;\n }\n if (shape.element === \"number\") {\n return `CAST(attrs->'${key}' AS DOUBLE[]) AS ${column(key)}`;\n }\n return `attrs->'${key}' AS ${column(key)}`;\n case \"json\":\n return `attrs->'${key}' AS ${column(key)}`;\n case \"quantity\":\n // The amount is a number that a query can add, and its unit is the next column. An infinite amount is NULL\n return `TRY_CAST(attrs->'${key}'->>'value' AS DOUBLE) AS ${column(key)},\\n attrs->'${key}'->>'unit' AS ${column(`${key}_unit`)}`;\n }\n};\n\n/** This function gives the view columns of an attribute. A quantity has two columns. */\nconst columnNames = (key: string, shape: ColumnShape): string[] =>\n shape.kind === \"quantity\" ? [key, `${key}_unit`] : [key];\n\nconst ENVELOPE_COLUMNS = [\n \"envelope->>'scope' AS scope\",\n \"envelope->>'valid_from' AS valid_from\",\n \"envelope->>'valid_to' AS valid_to\",\n \"envelope->>'observed_at' AS observed_at\",\n];\n\n// An attribute with the name of one of these columns hides the column in the view, so the generator refuses it\nconst RESERVED_COLUMNS = new Set([\n \"id\",\n \"kind\",\n ...ENVELOPE_COLUMNS.map((line) => line.slice(line.lastIndexOf(\" AS \") + 4)),\n]);\n\n/**\n * This function gives the DuckDB tables of a store of entities and edges, and one view for each kind. The view of a\n * kind has a column for each attribute, and it shows the entities of the kind and of each of its subkinds.\n *\n * @throws RegistryError when an attribute has the name of a fixed column, or two attributes give the same column\n */\nexport const generateDuckDbDdl = (registry: Registry, options?: GenerateOptions): string => {\n const sections: string[] = [headerOf(options), BASE_TABLES];\n for (const kind of registry.kinds.values()) {\n const closure = [...registry.subkindClosure(kind.name)].sort();\n const kindList = closure.map((name) => `'${name}'`).join(\", \");\n const columns = [\"id\", \"kind\"];\n const taken = new Set<string>();\n for (const [key, schema] of Object.entries(registry.effectiveShape(kind.name))) {\n if (RESERVED_COLUMNS.has(key)) {\n throw new RegistryError(\n `kind ${kind.name}: attribute ${key} has the name of a fixed view column (id, kind or an envelope column)`,\n );\n }\n const shape = columnShape(schema);\n for (const name of columnNames(key, shape)) {\n if (taken.has(identifier(name))) {\n throw new RegistryError(\n `kind ${kind.name} has two view columns named ${identifier(name)}: the unit column of a quantity is <attribute>_unit`,\n );\n }\n taken.add(identifier(name));\n }\n columns.push(attrColumn(key, shape));\n }\n columns.push(...ENVELOPE_COLUMNS);\n sections.push(\n `CREATE OR REPLACE VIEW v_${identifier(kind.name)} AS\\nSELECT\\n ${columns.join(\",\\n \")}\\nFROM entities\\nWHERE kind IN (${kindList});\\n`,\n );\n }\n return sections.join(\"\\n\");\n};\n","import type { Registry } from \"../registry.ts\";\nimport type { GenerateOptions } from \"./header.ts\";\nimport { headerOf } from \"./header.ts\";\n\n/**\n * This function gives the SQLite tables of a store of entities and edges. The tables are the same for each\n * registry: a kind is a value of the column `kind`, and the attributes are JSON.\n */\nexport const generateSqliteDdl = (_registry: Registry, options?: GenerateOptions): string => `${headerOf(options)}\nCREATE TABLE IF NOT EXISTS entities (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL,\n attrs TEXT NOT NULL DEFAULT '{}',\n envelope TEXT NOT NULL DEFAULT '{}'\n);\n\nCREATE TABLE IF NOT EXISTS edges (\n id TEXT NOT NULL,\n from_id TEXT NOT NULL,\n type TEXT NOT NULL,\n to_id TEXT NOT NULL,\n roles TEXT NOT NULL DEFAULT '{}',\n qualifiers TEXT NOT NULL DEFAULT '{}',\n envelope TEXT NOT NULL DEFAULT '{}',\n inverse INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (id, from_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_entities_kind ON entities (kind);\nCREATE INDEX IF NOT EXISTS idx_edges_from ON edges (from_id);\nCREATE INDEX IF NOT EXISTS idx_edges_to ON edges (to_id);\nCREATE INDEX IF NOT EXISTS idx_edges_type ON edges (type);\n`;\n","import { z } from \"zod\";\nimport type { KindDef, RelationKindDef } from \"../grammar.ts\";\nimport { edgeSchema, entitySchema } from \"../grammar.ts\";\nimport type { Registry } from \"../registry.ts\";\n\n/** One kind as data: the JSON Schema of its attributes and of the attributes of its facets. */\nexport interface KindJson {\n readonly name: string;\n readonly parent: string | null;\n readonly mode: string;\n readonly description: string;\n /** The attributes of its facets, then its own attributes. The attributes of a parent come through `parent`. */\n readonly attributes: Record<string, unknown>;\n /** Its facets. Their attributes are in `attributes`. */\n readonly facets?: string[];\n readonly defaultScope?: string;\n readonly staleAfterDays?: number;\n}\n\n/** One relation kind as data: the JSON Schema of its qualifiers, and its roles. */\nexport interface RelationJson {\n readonly name: string;\n /** The relation kind that it narrows. */\n readonly parent?: string;\n readonly description: string;\n readonly from: string[];\n readonly to: string[];\n readonly qualifiers?: Record<string, unknown>;\n readonly symmetric?: boolean;\n readonly transitive?: boolean;\n readonly abstract?: boolean;\n readonly roles?: Readonly<\n Record<string, { readonly description: string; readonly kinds: string[]; readonly many?: boolean }>\n >;\n readonly key?: string[];\n}\n\n/** A registry as data. */\nexport interface RegistryJson {\n readonly kinds: readonly KindJson[];\n /** Each relation kind. Each relation kind is also in `kinds`, with the mode `relation`. */\n readonly relations: readonly RelationJson[];\n}\n\n/** The JSON Schemas of a registry: an entity, an edge, and the attributes of each kind. */\nexport interface JsonSchemas {\n readonly entity: Record<string, unknown>;\n readonly edge: Record<string, unknown>;\n readonly kinds: Record<string, Record<string, unknown>>;\n}\n\n/** This function gives one kind as data. The schema includes the attributes of the facets of the kind. */\nexport const kindJson = (registry: Registry, kind: KindDef): KindJson => {\n const facets = kind.facets ?? [];\n const shape = Object.assign(\n {},\n ...facets.map((name) => registry.facets.get(name)?.attributes ?? {}),\n kind.attributes,\n ) as Record<string, z.ZodType>;\n return {\n name: kind.name,\n parent: kind.parent,\n mode: kind.mode,\n description: kind.description,\n attributes: z.toJSONSchema(z.strictObject(shape)) as Record<string, unknown>,\n ...(facets.length > 0 ? { facets: [...facets] } : {}),\n ...(kind.defaultScope !== undefined ? { defaultScope: kind.defaultScope } : {}),\n ...(kind.staleAfterDays !== undefined ? { staleAfterDays: kind.staleAfterDays } : {}),\n };\n};\n\n/** This function gives one relation kind as data. */\nexport const relationJson = (relation: RelationKindDef): RelationJson => ({\n name: relation.name,\n ...(relation.parent !== undefined ? { parent: relation.parent } : {}),\n description: relation.description,\n from: [...relation.from],\n to: [...relation.to],\n ...(relation.qualifiers !== undefined\n ? { qualifiers: z.toJSONSchema(z.strictObject(relation.qualifiers)) as Record<string, unknown> }\n : {}),\n ...(relation.symmetric !== undefined ? { symmetric: relation.symmetric } : {}),\n ...(relation.transitive !== undefined ? { transitive: relation.transitive } : {}),\n ...(relation.abstract === true ? { abstract: true } : {}),\n ...(relation.roles !== undefined\n ? {\n roles: Object.fromEntries(\n Object.entries(relation.roles).map(([role, def]) => [\n role,\n { description: def.description, kinds: [...def.kinds], ...(def.many === true ? { many: true } : {}) },\n ]),\n ),\n }\n : {}),\n ...(relation.key !== undefined ? { key: [...relation.key] } : {}),\n});\n\n/** This function gives a registry as data: each kind and each relation kind. */\nexport const registryJson = (registry: Registry): RegistryJson => ({\n kinds: [...registry.kinds.values()].map((kind) => kindJson(registry, kind)),\n relations: [...registry.relations.values()].map(relationJson),\n});\n\n/** This function gives the JSON Schemas of an entity, an edge, and the full attributes of each kind. */\nexport const generateJsonSchemas = (registry: Registry): JsonSchemas => ({\n entity: z.toJSONSchema(entitySchema) as Record<string, unknown>,\n edge: z.toJSONSchema(edgeSchema) as Record<string, unknown>,\n kinds: Object.fromEntries(\n [...registry.kinds.keys()].map((name) => [\n name,\n z.toJSONSchema(z.strictObject(registry.effectiveShape(name))) as Record<string, unknown>,\n ]),\n ),\n});\n","import { generateDuckDbDdl } from \"./codegen/duckdb.ts\";\nimport type { GenerateOptions } from \"./codegen/header.ts\";\nimport { generateJsonSchemas, registryJson } from \"./codegen/jsonschema.ts\";\nimport { generateSqliteDdl } from \"./codegen/sqlite.ts\";\nimport type { Registry } from \"./registry.ts\";\n\n/** The generated files of a registry, by file name. */\nexport interface GeneratedFiles {\n readonly \"duckdb.sql\": string;\n readonly \"sqlite.sql\": string;\n readonly \"registry.json\": string;\n readonly \"jsonschema.json\": string;\n}\n\n/** This function gives each generated file of a registry: the SQL of two stores, the registry and the JSON Schemas. */\nexport const generateAll = (registry: Registry, options?: GenerateOptions): GeneratedFiles => ({\n \"duckdb.sql\": generateDuckDbDdl(registry, options),\n \"sqlite.sql\": generateSqliteDdl(registry, options),\n \"registry.json\": `${JSON.stringify(registryJson(registry), null, 2)}\\n`,\n \"jsonschema.json\": `${JSON.stringify(generateJsonSchemas(registry), null, 2)}\\n`,\n});\n"],"mappings":";;;;;AASA,MAAa,QAAyB;CAAC;CAAO;CAAc;CAAa;CAAY;CAAe;AAAU;;AAG9G,MAAa,SAAS;CAAC;CAAU;CAAU;CAAW;AAAU;;AAMhE,MAAa,cAA8C,EAAE,KAAK,MAAM;;;;;AAMxE,MAAM,aAA8C;CAAE,QAAQ;CAAG,QAAQ;CAAG,SAAS;CAAG,UAAU;AAAE;;AAGpG,MAAa,aAAa,UAAyB,WAAW;;AAG9D,MAAa,YAAY,GAAU,MAAqB,WAAW,MAAM,WAAW,KAAK,IAAI;;AAG7F,MAAa,aAAa,OAAc,aAA6B,WAAW,UAAU,WAAW;;AAGrG,MAAa,eAAuB;;AAGpC,MAAa,oBAA4B;;AAGzC,MAAa,iBAA8B,EAAE,OAAO,CAAC,CAAC,MAAM,iBAAiB;AAE7E,MAAM,cAAc,EAAE,IAAI,SAAS,EAAE,QAAQ,KAAK,CAAC;;AA6CnD,MAAa,UAAU,WAAiD;CACtE,MAAM,OAAO,OAAO,MAAM;CAC1B,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO;AAClD;;AAmDA,MAAM,WAAW,SAAyB;CACxC,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,GAAG;EACjD,QAAQ,OAAO,IAAI;EACnB,OAAQ,OAAO,iBAAkB;CACnC;CACA,OAAO,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,IAAI,GAAG;AAC3C;;;;;;;;;AAUA,MAA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