From a0390170bf8dd57ddb178f93283ed2970f8bed98 Mon Sep 17 00:00:00 2001 From: Christopher Raquet Date: Tue, 1 Dec 2026 09:44:52 +0100 Subject: [PATCH 1/6] feat: implement revised type system in primitives --- AGENTS.md | 3 +- LICENSE | 2 +- README.md | 4 + .../scripts/generate-creep-profiles.mjs | 4 +- packages/examples/src/localTestingBackend.ts | 2 +- packages/primitives/README.md | 6 +- .../primitives/src/impl/ConcreteFDORecord.ts | 266 ---------- .../primitives/src/impl/ConcreteProfile.ts | 32 -- .../primitives/src/impl/DefaultFDORecord.ts | 365 ++++++++++++++ ...lFDORecord.ts => DefaultLocalFDORecord.ts} | 11 +- packages/primitives/src/impl/LocalFDOGraph.ts | 9 +- .../primitives/src/impl/PublishedFDOGraph.ts | 12 +- packages/primitives/src/impl/index.ts | 5 +- packages/primitives/src/impl/markers.ts | 3 +- .../primitives/src/interfaces/Attribute.ts | 279 +++++++++- .../primitives/src/interfaces/FDOContext.ts | 13 + .../primitives/src/interfaces/FDOGraph.ts | 5 +- .../primitives/src/interfaces/FDORecord.ts | 166 ++++-- packages/primitives/src/interfaces/Profile.ts | 36 +- .../src/interfaces/ProfileDefinition.ts | 30 -- .../src/interfaces/PublishAdapter.ts | 6 +- packages/primitives/src/interfaces/README.md | 48 ++ .../src/interfaces/ResolveAdapter.ts | 4 +- packages/primitives/src/interfaces/index.ts | 1 - .../primitives/src/type-system/attributes.ts | 53 ++ .../primitives/src/type-system/profiles.ts | 10 + packages/primitives/src/types.ts | 32 +- packages/primitives/src/utils.ts | 8 +- packages/primitives/tests/FDORecord.test.ts | 476 +++++++++--------- .../primitives/tests/LocalFDOGraph.test.ts | 88 ++-- packages/primitives/tests/Profile.test.ts | 240 +++++++-- .../tests/PublishedFDOGraph.test.ts | 18 +- packages/simple-types/README.md | 2 +- 33 files changed, 1445 insertions(+), 794 deletions(-) delete mode 100644 packages/primitives/src/impl/ConcreteFDORecord.ts delete mode 100644 packages/primitives/src/impl/ConcreteProfile.ts create mode 100644 packages/primitives/src/impl/DefaultFDORecord.ts rename packages/primitives/src/impl/{ConcreteLocalFDORecord.ts => DefaultLocalFDORecord.ts} (75%) create mode 100644 packages/primitives/src/interfaces/FDOContext.ts delete mode 100644 packages/primitives/src/interfaces/ProfileDefinition.ts create mode 100644 packages/primitives/src/interfaces/README.md create mode 100644 packages/primitives/src/type-system/attributes.ts create mode 100644 packages/primitives/src/type-system/profiles.ts diff --git a/AGENTS.md b/AGENTS.md index c381d56..6522a3f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ Inside a package, `pnpm build` is `tsc --noEmit` then `tsdown`, emitting a singl - TS is strict with `verbatimModuleSyntax`/`isolatedModules`: type-only imports MUST use `import type`. - Relative imports must end in `.js` even though files are `.ts` (node16/nodenext resolution), e.g. `../types.js`. -- Public surface is `src/index.ts`. Interfaces have no prefix (`FDORecord`, `FDOGraph`, `Profile`, `ProfileDefinition`); implementations are `Concrete`-prefixed classes in `src/impl/` (`ConcreteLocalFDORecord`, `ConcreteProfile`), except the graph implementation, which is named after its strategy (`LocalFDOGraph`). +- Public surface is `src/index.ts`. Interfaces have no prefix (`FDORecord`, `FDOGraph`, `Profile`, `ProfileDefinition`); implementations are `Concrete`-prefixed classes in `src/impl/` (`ConcreteLocalFDORecord`, `DefaultProfile`), except the graph implementation, which is named after its strategy (`LocalFDOGraph`). - Core types (`PID`, `LocalID`, `RecordValue`, ...) live in `src/types.ts`. ## Documentation @@ -44,3 +44,4 @@ To document another package: add `src/.ts`, add it to `entryPoints`, ad - Vitest tests live in `tests/*.test.ts` (node environment) and import from `../src/...` directly (never from `dist`). - Coverage currently reports 100%; no threshold is enforced, but keep touched code covered. +- Never use type casts (`as`) or `@ts-ignore`/`@ts-expect-error` in tests — they hide real type issues. If a test case cannot be expressed with the current types, fix the source types instead of silencing the error. The only exception is mocking: constructing a test double that the type system cannot represent honestly (e.g. a published record fixture). diff --git a/LICENSE b/LICENSE index 261eeb9..e6df1a4 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2026 Karlsruhe Institute of Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index 0d90451..01de912 100644 --- a/README.md +++ b/README.md @@ -197,3 +197,7 @@ pnpm test:stream # same as test, with interleaved output pnpm --filter @fdo-sdk/primitives test pnpm --filter @fdo-sdk/playground dev ``` +# Attributions + +The packages of this repository are built on the basis of the [FAIR Digital Objects Architecture Specification](https://fairdo-org.github.io/fdo-architecture-spec/) (CC-BY 4.0 License) and may use excerpts of the specification in method and parameter descriptions. These excerpts may be +adapted to read properly in their specific context. This package is not endorsed by the FDO Forum. \ No newline at end of file diff --git a/packages/examples/scripts/generate-creep-profiles.mjs b/packages/examples/scripts/generate-creep-profiles.mjs index dd58a2a..235a431 100644 --- a/packages/examples/scripts/generate-creep-profiles.mjs +++ b/packages/examples/scripts/generate-creep-profiles.mjs @@ -48,7 +48,7 @@ out += "/generate-creep-profiles.mjs. Do not edit manually. */\n" out += 'import type { Attribute, ProfileDefinition, RecordValue } from "@fdo-sdk/primitives"\n' -out += 'import { ConcreteProfile } from "@fdo-sdk/primitives"\n' +out += 'import { DefaultProfile } from "@fdo-sdk/primitives"\n' out += "\n" for (const { name, pid, props } of profiles) { @@ -96,7 +96,7 @@ for (const { name, pid, props } of profiles) { out += "export const " + name + - "Profile = new ConcreteProfile(" + + "Profile = new DefaultProfile(" + name + "ProfileDefinition)\n\n" } diff --git a/packages/examples/src/localTestingBackend.ts b/packages/examples/src/localTestingBackend.ts index 65b9db5..f9723cc 100644 --- a/packages/examples/src/localTestingBackend.ts +++ b/packages/examples/src/localTestingBackend.ts @@ -23,7 +23,7 @@ * `FDORecord`, `Profile`, ...) so the example would work unchanged with a * different context or backend implementation. The only concrete classes used * are `ConcreteMappingContext` (constructed, then consumed as - * `MappingContext`), `ConcreteProfile` (the standard way to define a + * `MappingContext`), `DefaultProfile` (the standard way to define a * profile) and `LocalTestingBackend` itself — the latter also exposes * `resetStore()` as a static method that no interface covers. */ diff --git a/packages/primitives/README.md b/packages/primitives/README.md index 7f2ced5..8daaea4 100644 --- a/packages/primitives/README.md +++ b/packages/primitives/README.md @@ -38,12 +38,12 @@ mandatory. Attribute values are still stored under their PIDs. ```ts import { ConcreteLocalFDORecord, - ConcreteProfile, + DefaultProfile, reference, skip, } from "@fdo-sdk/primitives" -const publicationProfile = new ConcreteProfile({ +const publicationProfile = new DefaultProfile({ pid: "PROFILE/PUBLICATION", readableName: "Publication", profileAttributePID: "attr/profiles", @@ -145,7 +145,7 @@ experiments. Production backends implement the same interfaces. | `PublishedFDOGraph` | Read-only graph of published records | | `ConcreteLocalFDORecord` | Record with a local ID | | `ConcreteFDORecord` | Base record, optionally with a PID | -| `ConcreteProfile` | Implementation of `Profile` | +| `DefaultProfile` | Implementation of `Profile` | | `keep`, `skip`, `reference`, `referenceBidi` | Markers and references for `addProfile()` | | `FDORecord`, `FDOGraph`, `Profile`, ... | Interfaces for custom implementations | | `LocalID`, `PID`, `RecordValue`, ... | Core types | diff --git a/packages/primitives/src/impl/ConcreteFDORecord.ts b/packages/primitives/src/impl/ConcreteFDORecord.ts deleted file mode 100644 index 5980bf2..0000000 --- a/packages/primitives/src/impl/ConcreteFDORecord.ts +++ /dev/null @@ -1,266 +0,0 @@ -import type { - Attribute, - FDORecord, - IdentifiableFDORecord, - PublishedFDORecord, -} from "../interfaces/index.js" -import { - type WithMarkers, - type LocalID, - type PID, - type ProfileAttributes, - type RecordValue, - type ReferenceDeclaration, -} from "../types.js" -import { toArray } from "../utils.js" -import type { Profile } from "../interfaces/Profile.js" -import { isKeep, isReference, isSkip } from "./markers.js" - -/** - * Base implementation of the {@link FDORecord} interface. Can hold a PID to be - * a {@link PublishedFDORecord} (use {@link isPublished} to check). - * - * Consider using {@link ConcreteLocalFDORecord} if you are creating FDOs - */ -export class ConcreteFDORecord implements FDORecord { - readonly PID: PID | undefined - - protected attributes: Map = new Map() - protected references: ReferenceDeclaration[] = [] - protected conformsToProfiles: PID[] = [] - - constructor(pid?: PID) { - this.PID = pid - } - - addRecord(record: FDORecord): void { - const recordMap = record.getAll() - this.addMap(recordMap) - } - - protected addMap(map: Map) { - for (const [key, value] of map) { - if (this.attributes.has(key)) { - const currentValue = this.attributes.get(key)! - const newValue = toArray(currentValue) - newValue.push(...toArray(value)) - this.attributes.set(key, newValue) - } else { - this.attributes.set(key, value) - } - } - } - - addAttribute>( - attribute: Attr | PID, - value: Attr extends Attribute ? T : RecordValue, - ): void { - this.addMap(new Map([[this.getPIDFromAttributOrPID(attribute), value]])) - } - - addProfile

>( - profile: P, - attributes: P extends Profile ? WithMarkers : never, - ): void { - this.conformsToProfiles.push(profile.def.pid) - - // If the profile defines a profileAttributePID, we mark this profile as active in that profile marker attribute - if (profile.def.profileAttributePID) { - const existingProfileMarker = this.get( - profile.def.profileAttributePID, - ) - - // If the profile marker attribute doesn't exist yet or doesn't contain this specific profile yet, we add it - if ( - !existingProfileMarker || - !toArray(existingProfileMarker).some( - (profilePID) => profilePID === profile.def.pid, - ) - ) { - this.addAttribute( - profile.def.profileAttributePID, - profile.def.pid, - ) - } - } - - const mapped = new Map() - for (const [attributeName, value] of Object.entries(attributes)) { - const attributePID = profile.mapAttributeNameToPID(attributeName) - - if (isKeep(value)) { - const existingValue = this.get(attributePID) - if (existingValue === undefined) { - throw new Error( - `Cannot add profile ${profile.def.readableName} because attribute ${attributeName} (PID: ${attributePID}) was specified as "keep", but is not present in this record`, - ) - } - } else if (isSkip(value)) { - // continue - } else if (isReference(value)) { - this.addReferenceDirect(attributePID, value.ref) - } else if ( - Array.isArray(value) && - value.some((element) => isReference(element)) - ) { - const references = value.filter((element) => - isReference(element), - ) - const primitives = value.filter( - (element) => typeof element !== "object", - ) - - for (const reference of references) { - this.addReferenceDirect(attributePID, reference.ref) - } - - mapped.set(attributePID, primitives) - } else { - if ( - (Array.isArray(value) && - value.some((element) => typeof element === "object")) || - (typeof value === "object" && !Array.isArray(value)) - ) { - console.error( - "Profile instance contains illegal value of type object. This might be an internal error.", - attributes, - attributePID, - value, - ) - throw new Error( - "Profile instance contains illegal value of type object. This might be an internal error.", - ) - } - - mapped.set(attributePID, value as RecordValue) - } - } - this.addMap(mapped as Map) - } - - protected addReferenceDirect( - fromAttribute: PID, - reference: - | Omit - | Omit< - ReferenceDeclaration & { direction: "bidi" }, - "fromAttribute" - >, - ): void { - this.references.push({ ...reference, fromAttribute }) - this.addAttribute(fromAttribute, reference.toRecord) - } - - addReference( - fromAttribute: PID | Attribute, - toRecord: PID | LocalID | IdentifiableFDORecord, - ): void { - const target = - typeof toRecord === "object" - ? (toRecord.PID ?? - ("localID" in toRecord ? toRecord.localID : undefined)) - : toRecord - - if (target === undefined) - throw new Error( - "Cannot add reference to target because target has no PID and no LocalID", - ) - - this.references.push({ - direction: "uni", - fromAttribute: this.getPIDFromAttributOrPID(fromAttribute), - toRecord: target, - }) - this.addAttribute(fromAttribute, target) - } - - addReferenceBidi( - fromAttribute: PID | Attribute, - inverseAttribute: PID | Attribute, - toRecord: PID | LocalID | IdentifiableFDORecord, - ): void { - const target = - typeof toRecord === "object" - ? (toRecord.PID ?? - ("localID" in toRecord ? toRecord.localID : undefined)) - : toRecord - - if (target === undefined) - throw new Error( - "Cannot add reference to target because target has no PID and no LocalID", - ) - - this.references.push({ - direction: "bidi", - fromAttribute: this.getPIDFromAttributOrPID(fromAttribute), - inverseAttribute: this.getPIDFromAttributOrPID(inverseAttribute), - toRecord: target, - }) - this.addAttribute(fromAttribute, target) - } - - get(attribute: PID | Attribute): RecordValue | undefined { - return structuredClone( - this.attributes.get(this.getPIDFromAttributOrPID(attribute)), - ) - } - - getAll(): Map { - return structuredClone(this.attributes) - } - - getReferences(): ReferenceDeclaration[] { - return structuredClone(this.references) - } - - getProfiles(): PID[] { - return this.conformsToProfiles - } - - has(attribute: PID | Attribute): boolean { - return this.attributes.has(this.getPIDFromAttributOrPID(attribute)) - } - - set(attribute: Attribute, value: T): void - set(attribute: PID, value: RecordValue): void - set( - attribute: PID | Attribute, - value: T, - ): void { - this.attributes.set(this.getPIDFromAttributOrPID(attribute), value) - this.removeReferencesFrom(this.getPIDFromAttributOrPID(attribute)) - } - - protected getPIDFromAttributOrPID(attributeOrPID: PID | Attribute) { - return typeof attributeOrPID === "string" - ? attributeOrPID - : attributeOrPID.pid - } - - protected removeReferencesFrom(from: PID) { - this.references = this.references.filter( - (ref) => ref.fromAttribute !== from, - ) - } - - remove(attribute: PID) { - this.attributes.delete(attribute) - } - - toJSON(): Record { - return Object.fromEntries(this.attributes) - } - - toString(): string { - return JSON.stringify( - { - PID: this.PID, - profiles: this.conformsToProfiles.join(", "), - attributes: Object.fromEntries(this.attributes), - references: this.references, - }, - null, - 2, - ) - } -} diff --git a/packages/primitives/src/impl/ConcreteProfile.ts b/packages/primitives/src/impl/ConcreteProfile.ts deleted file mode 100644 index d953d68..0000000 --- a/packages/primitives/src/impl/ConcreteProfile.ts +++ /dev/null @@ -1,32 +0,0 @@ -import type { ProfileDefinition } from "../interfaces/index.js" -import type { Profile } from "../interfaces/Profile.js" -import type { PID, ProfileAttributes } from "../types.js" - -export class ConcreteProfile< - A extends ProfileAttributes, -> implements Profile { - readonly def: ProfileDefinition - - constructor(def: ProfileDefinition) { - this.def = def - } - - mapPIDToAttributeName(pid: PID): string { - const mapping = Object.entries(this.def.mapping) - const match = mapping.find(([, p]) => p === pid) - if (!match) - throw new Error( - `mapPIDToAttributeName: No attribute with the PID ${pid} is defined in the profile ${this.def.readableName}`, - ) - return match[0] - } - - mapAttributeNameToPID(attributeName: string): PID { - const pid = this.def.mapping[attributeName] - if (!pid) - throw new Error( - `mapAttributeNameToPID: No attribute with the name ${attributeName} is defined in the profile ${this.def.readableName}`, - ) - return pid - } -} diff --git a/packages/primitives/src/impl/DefaultFDORecord.ts b/packages/primitives/src/impl/DefaultFDORecord.ts new file mode 100644 index 0000000..e909bba --- /dev/null +++ b/packages/primitives/src/impl/DefaultFDORecord.ts @@ -0,0 +1,365 @@ +import type { + FDORecord, + IdentifiableFDORecord, + CompleteFDORecord, +} from "../interfaces/index.js" +import { + type LocalID, + type PID, + type ReferenceDeclaration, + type WithMarkers, +} from "../types.js" +import { toArray } from "../utils.js" +import { isKeep, isReference, isSkip } from "./markers.js" +import type { + AttributeAnyType, + AttributeDef, + AttrsToObj, + AttrTypeWithCardinality, + CardinalityType, + DefaultAttributeDef, + Simplify, +} from "../interfaces/index.js" +import type { ProfileDef } from "../interfaces/Profile.js" +import { + DataAttribute, + ProfileAttribute, + TypeAttribute, +} from "../type-system/attributes.js" +/** + * Base implementation of the {@link FDORecord} interface. Can hold a PID to be + * a {@link CompleteFDORecord} (use {@link isPublished} to check). + * + * Consider using {@link DefaultLocalFDORecord} if you are creating FDOs + */ +export class DefaultFDORecord implements FDORecord { + readonly PID: PID | undefined + + protected attributes: Map< + PID, + AttrTypeWithCardinality + > = new Map() + protected references: ReferenceDeclaration[] = [] + + constructor(pid?: PID) { + this.PID = pid + } + + addRecord(record: FDORecord): void { + const recordMap = record.getAll() + this.addMap(recordMap) + } + + protected addMap( + map: Map>, + ) { + for (const [key, value] of map) { + if (this.attributes.has(key)) { + const currentValue = this.attributes.get(key)! + const newValue = toArray(currentValue) + newValue.push(...toArray(value)) + this.attributes.set(key, newValue) + } else { + this.attributes.set(key, value) + } + } + } + + addAttribute( + attribute: Attr | PID, + value: Attr extends DefaultAttributeDef + ? AttrTypeWithCardinality + : AttrTypeWithCardinality, + ): void { + this.addMap(new Map([[this.getPIDFromAttributOrPID(attribute), value]])) + } + + addData( + attribute: PID, + value?: AttrTypeWithCardinality, + ): void + addData( + attribute: Attr, + value?: AttrTypeWithCardinality, + ): void + addData( + attribute: DefaultAttributeDef | PID, + value?: AttrTypeWithCardinality, + ) { + if (!value) { + if (!this.attributes.has(this.getPIDFromAttributOrPID(attribute))) { + throw new Error( + `Cannot declare ${typeof attribute === "string" ? "attribute" : attribute.name} (${this.getPIDFromAttributOrPID(attribute)}) as data attribute because it is not present on this record ${this.getDebugIdentifier()}`, + ) + } + } else { + if (typeof attribute === "string") { + this.addAttribute(attribute, value) + } else { + this.addAttribute(attribute, value) + } + } + + this.addAttribute( + DataAttribute, + this.getPIDFromAttributOrPID(attribute), + ) + } + + addType( + attribute: PID, + value?: AttrTypeWithCardinality, + ): void + addType( + attribute: Attr, + value?: AttrTypeWithCardinality, + ): void + addType( + attribute: DefaultAttributeDef | PID, + value?: AttrTypeWithCardinality, + ) { + if (!value) { + if (!this.attributes.has(this.getPIDFromAttributOrPID(attribute))) { + throw new Error( + `Cannot declare ${typeof attribute === "string" ? "attribute" : attribute.name} (${this.getPIDFromAttributOrPID(attribute)}) as type attribute because it is not present on this record ${this.getDebugIdentifier()}`, + ) + } + } else { + this.addAttribute(attribute, value) + } + + this.addAttribute( + TypeAttribute, + this.getPIDFromAttributOrPID(attribute), + ) + } + + addProfile

>( + profile: P, + attributes: P extends ProfileDef + ? Simplify>> + : never, + ): void { + this.addAttribute(ProfileAttribute, profile.pid) + + const mapped = new Map< + PID, + AttrTypeWithCardinality + >() + for (const [attributeName, value] of Object.entries(attributes)) { + const attribute = profile.attributes.find( + (attr) => attr.name === attributeName, + )! + + if (isKeep(value)) { + const existingValue = this.get(attribute) + if (existingValue === undefined) { + throw new Error( + `Cannot add profile ${profile.name} ${profile.pid} because attribute ${attributeName} (PID: ${attribute.pid}) was specified as "keep", but is not present in this record ${this.getDebugIdentifier()}`, + ) + } + } else if (isSkip(value)) { + // continue + } else if (isReference(value)) { + this.addReferenceDirect(attribute.pid, value.ref) + } else if ( + Array.isArray(value) && + value.some((element) => isReference(element)) + ) { + const references = value.filter((element) => + isReference(element), + ) + const primitives = value.filter( + (element) => typeof element !== "object", + ) + + for (const reference of references) { + this.addReferenceDirect(attribute.pid, reference.ref) + } + + mapped.set(attribute.pid, primitives) + } else { + if ( + (Array.isArray(value) && + value.some((element) => typeof element === "object")) || + (typeof value === "object" && !Array.isArray(value)) + ) { + console.error( + "Profile instance contains illegal value of type object. This might be an internal error.", + attributes, + attribute, + value, + ) + throw new Error( + `Profile instance contains illegal value of type object. This might be an internal error. ${this.getDebugIdentifier()}`, + ) + } + + mapped.set(attribute.pid, value) + } + } + this.addMap(mapped) + } + + protected addReferenceDirect( + fromAttribute: PID, + reference: + | Omit + | Omit< + ReferenceDeclaration & { direction: "bidi" }, + "fromAttribute" + >, + ): void { + this.references.push({ ...reference, fromAttribute }) + this.addAttribute(fromAttribute, reference.toRecord) + } + + addReference( + fromAttribute: PID | AttributeDef, + toRecord: PID | LocalID | IdentifiableFDORecord, + ): void { + const target = + typeof toRecord === "object" + ? (toRecord.PID ?? + ("localID" in toRecord ? toRecord.localID : undefined)) + : toRecord + + if (target === undefined) + throw new Error( + `Cannot add reference to target because target has no PID and no LocalID ${this.getDebugIdentifier()}`, + ) + + this.references.push({ + direction: "uni", + fromAttribute: this.getPIDFromAttributOrPID(fromAttribute), + toRecord: target, + }) + this.addAttribute(fromAttribute, target) + } + + addReferenceBidi( + fromAttribute: PID | AttributeDef, + inverseAttribute: PID | AttributeDef, + toRecord: PID | LocalID | IdentifiableFDORecord, + ): void { + const target = + typeof toRecord === "object" + ? (toRecord.PID ?? + ("localID" in toRecord ? toRecord.localID : undefined)) + : toRecord + + if (target === undefined) + throw new Error( + `Cannot add reference to target because target has no PID and no LocalID ${this.getDebugIdentifier()}`, + ) + + this.references.push({ + direction: "bidi", + fromAttribute: this.getPIDFromAttributOrPID(fromAttribute), + inverseAttribute: this.getPIDFromAttributOrPID(inverseAttribute), + toRecord: target, + }) + this.addAttribute(fromAttribute, target) + } + + get(attribute: PID): AttributeAnyType | undefined + get( + attribute: A, + ): AttrTypeWithCardinality | undefined + get( + attribute: PID | DefaultAttributeDef, + ): AttrTypeWithCardinality | undefined { + return structuredClone( + this.attributes.get(this.getPIDFromAttributOrPID(attribute)), + ) + } + + getAll(): Map> { + return structuredClone(this.attributes) + } + + getType(): AttrTypeWithCardinality | undefined { + return this.get(TypeAttribute) + } + + getData(): AttrTypeWithCardinality | undefined { + return this.get(DataAttribute) + } + + getProfile(): AttrTypeWithCardinality | undefined { + return this.get(ProfileAttribute) + } + + getReferences(): ReferenceDeclaration[] { + return structuredClone(this.references) + } + + has(attribute: PID | DefaultAttributeDef): boolean { + return this.attributes.has(this.getPIDFromAttributOrPID(attribute)) + } + + set( + attribute: PID, + value: AttrTypeWithCardinality, + ): void + set( + attribute: A, + value: AttrTypeWithCardinality, + ): void + set( + attribute: PID | DefaultAttributeDef, + value: AttrTypeWithCardinality, + ): void { + this.attributes.set(this.getPIDFromAttributOrPID(attribute), value) + this.removeReferencesFrom(this.getPIDFromAttributOrPID(attribute)) + } + + protected getPIDFromAttributOrPID( + attributeOrPID: PID | DefaultAttributeDef, + ) { + return typeof attributeOrPID === "string" + ? attributeOrPID + : attributeOrPID.pid + } + + protected removeReferencesFrom(from: PID) { + this.references = this.references.filter( + (ref) => ref.fromAttribute !== from, + ) + } + + remove(attribute: PID | DefaultAttributeDef) { + const pid = this.getPIDFromAttributOrPID(attribute) + if ( + pid === TypeAttribute.pid || + pid === DataAttribute.pid || + pid === ProfileAttribute.pid + ) { + throw new Error( + `Cannot remove mandatory attributes FDO_Profile, FDO_Type and FDO_Data ${this.getDebugIdentifier()}`, + ) + } + this.attributes.delete(pid) + this.removeReferencesFrom(pid) + } + + protected getDebugIdentifier() { + return `(on PID: ${this.PID})` + } + + toJSON(): Record> { + return Object.fromEntries(this.attributes) + } + + toString(): string { + return JSON.stringify( + { + PID: this.PID, + attributes: Object.fromEntries(this.attributes), + references: this.references, + }, + null, + 2, + ) + } +} diff --git a/packages/primitives/src/impl/ConcreteLocalFDORecord.ts b/packages/primitives/src/impl/DefaultLocalFDORecord.ts similarity index 75% rename from packages/primitives/src/impl/ConcreteLocalFDORecord.ts rename to packages/primitives/src/impl/DefaultLocalFDORecord.ts index 17fc870..e8dcb9a 100644 --- a/packages/primitives/src/impl/ConcreteLocalFDORecord.ts +++ b/packages/primitives/src/impl/DefaultLocalFDORecord.ts @@ -1,13 +1,13 @@ import type { LocalFDORecord } from "../interfaces/index.js" import { type LocalID, type PID } from "../types.js" -import { ConcreteFDORecord } from "./ConcreteFDORecord.js" +import { DefaultFDORecord } from "./DefaultFDORecord.js" /** * {@link FDORecord} implementation that can hold a local ID. The local ID * will be replaced by the publisher service with a PID. */ -export class ConcreteLocalFDORecord - extends ConcreteFDORecord +export class DefaultLocalFDORecord + extends DefaultFDORecord implements LocalFDORecord { readonly localID: LocalID @@ -17,12 +17,15 @@ export class ConcreteLocalFDORecord this.localID = localID } + protected getDebugIdentifier(): string { + return `(localID: ${this.localID}, PID: ${this.PID})` + } + toString(): string { return JSON.stringify( { localID: this.localID, PID: this.PID, - profiles: this.conformsToProfiles.join(", "), attributes: Object.fromEntries(this.attributes), references: this.references, }, diff --git a/packages/primitives/src/impl/LocalFDOGraph.ts b/packages/primitives/src/impl/LocalFDOGraph.ts index 06f0e7a..4921b0d 100644 --- a/packages/primitives/src/impl/LocalFDOGraph.ts +++ b/packages/primitives/src/impl/LocalFDOGraph.ts @@ -1,10 +1,11 @@ import type { + AttributeAnyType, FDOGraph, FDOGraphAddRecordOptions, LocalFDORecord, } from "../interfaces/index.js" -import type { LocalID, PID, RecordValue } from "../types.js" -import { ConcreteLocalFDORecord } from "./ConcreteLocalFDORecord.js" +import type { LocalID, PID } from "../types.js" +import { DefaultLocalFDORecord } from "./DefaultLocalFDORecord.js" /** * A graph of locally created FDO records than can be used without PIDs @@ -39,7 +40,7 @@ export class LocalFDOGraph implements FDOGraph { localID: LocalID, options?: FDOGraphAddRecordOptions, ): LocalFDORecord { - const record = new ConcreteLocalFDORecord(localID) + const record = new DefaultLocalFDORecord(localID) this.addRecord(record, options) return record } @@ -102,7 +103,7 @@ export class LocalFDOGraph implements FDOGraph { .join("\n") } - toJSON(): Record>[] { + toJSON(): Record>[] { const entries = this.getRecords().map((record) => [ `${record.localID} - ${record.PID || "unpublished"}`, record.toJSON(), diff --git a/packages/primitives/src/impl/PublishedFDOGraph.ts b/packages/primitives/src/impl/PublishedFDOGraph.ts index 006eae3..1db0c72 100644 --- a/packages/primitives/src/impl/PublishedFDOGraph.ts +++ b/packages/primitives/src/impl/PublishedFDOGraph.ts @@ -1,15 +1,15 @@ -import type { ReadOnlyFDOGraph } from "../interfaces/index.js" -import type { PublishedFDORecord } from "../interfaces/index.js" -import type { LocalID, PID, RecordValue } from "../types.js" +import type { AttributeAnyType, ReadOnlyFDOGraph } from "../interfaces/index.js" +import type { CompleteFDORecord } from "../interfaces/index.js" +import type { LocalID, PID } from "../types.js" /** - * A graph of published FDO records. The records are identified by their + * A graph of published (and therefore complete) FDO records. The records are identified by their * {@link PID}. In contrast to the {@link LocalFDOGraph}, the records of a * published graph do not need a local ID: a published record is globally * identified by its PID. */ export class PublishedFDOGraph< - RecordType extends PublishedFDORecord = PublishedFDORecord, + RecordType extends CompleteFDORecord = CompleteFDORecord, > implements ReadOnlyFDOGraph { private readonly records = new Map() private readonly recordsByLocalID = new Map() @@ -38,7 +38,7 @@ export class PublishedFDOGraph< return this.getRecords().find(predicate) } - toJSON(): Record>[] { + toJSON(): Record>[] { const entries = this.getRecords().map((record) => [ this.labelOf(record), record.toJSON(), diff --git a/packages/primitives/src/impl/index.ts b/packages/primitives/src/impl/index.ts index cb3d4e1..ea5223a 100644 --- a/packages/primitives/src/impl/index.ts +++ b/packages/primitives/src/impl/index.ts @@ -1,6 +1,5 @@ -export { ConcreteLocalFDORecord } from "./ConcreteLocalFDORecord.js" -export { ConcreteFDORecord } from "./ConcreteFDORecord.js" -export { ConcreteProfile } from "./ConcreteProfile.js" +export { DefaultLocalFDORecord } from "./DefaultLocalFDORecord.js" +export { DefaultFDORecord } from "./DefaultFDORecord.js" export { LocalFDOGraph } from "./LocalFDOGraph.js" export { PublishedFDOGraph } from "./PublishedFDOGraph.js" export * from "./markers.js" diff --git a/packages/primitives/src/impl/markers.ts b/packages/primitives/src/impl/markers.ts index 600e8de..bebbc81 100644 --- a/packages/primitives/src/impl/markers.ts +++ b/packages/primitives/src/impl/markers.ts @@ -7,6 +7,7 @@ import type { } from "../types.js" import type { Attribute, IdentifiableFDORecord } from "../interfaces/index.js" import { getRecordIdentifier } from "../utils.js" +import type { DefaultAttributeDef } from "../interfaces/Attribute.js" /** * To be used in {@link FDORecord.addProfile}. Marks a mandatory attribute as skipped, meaning it won't be added to the record. @@ -53,7 +54,7 @@ export function reference( * @param targetRecord The referenced record, or the {@link PID} or local identifier of the referenced record */ export function referenceBidi( - inverseAttribute: PID | Attribute, + inverseAttribute: PID | DefaultAttributeDef, targetRecord: LocalID | PID | IdentifiableFDORecord, ): ReferenceMarker { return { diff --git a/packages/primitives/src/interfaces/Attribute.ts b/packages/primitives/src/interfaces/Attribute.ts index 93bd961..0c8f053 100644 --- a/packages/primitives/src/interfaces/Attribute.ts +++ b/packages/primitives/src/interfaces/Attribute.ts @@ -1,6 +1,279 @@ -import type { PID, RecordValue } from "../types.js" +import type { PID, ReferenceMarker } from "../types.js" -export interface Attribute { +export type AttributeDefTypes = + | "base" + | "syntax" + | "profileRef" + | "attrRef" + | "combination" + | "union" + | "vocabulary" + +export type CardinalityType = `${number}..${number | "*"}` + +export type AttributeAnyType = + string | boolean | number | Record + +export interface AttributeDef< + N extends string, + Type extends AttributeAnyType, + Cardinality extends CardinalityType, +> { + readonly defType: AttributeDefTypes + readonly "~type": Type readonly pid: PID - readonly readableName: string + readonly name: N + readonly cardinality: Cardinality + readonly description?: string | string[] + readonly validationStrategyForCombination?: "anyof" | "allof" +} + +export type DefaultAttributeDef = AttributeDef< + string, + AttributeAnyType, + CardinalityType +> + +export interface AttributeDefSyntax< + N extends string, + Cardinality extends CardinalityType, + PrimitiveType extends "string" | "number" | "integer" | "boolean", + Whitelist extends string | string[] | undefined = undefined, +> extends AttributeDef< + N, + Whitelist extends string | string[] + ? Whitelist extends string[] + ? Whitelist[number] + : Whitelist + : PrimitiveType extends "string" + ? string + : PrimitiveType extends "number" + ? number + : PrimitiveType extends "integer" + ? number + : PrimitiveType extends "boolean" + ? boolean + : string, + Cardinality +> { + readonly defType: "syntax" + readonly primitiveDataType?: PrimitiveType + readonly regex?: string + readonly numericInterval?: `${"[" | "("}${number}, ${number}${"]" | ")"}` + readonly whitelist?: Whitelist + readonly blacklist?: string | string[] +} + +export interface AttributeDefProfileRef< + N extends string, + Cardinality extends CardinalityType, +> extends AttributeDef { + readonly defType: "profileRef" + readonly allowedProfiles?: string | string[] +} + +export interface AttributeDefAttrRef< + N extends string, + Cardinality extends CardinalityType, +> extends AttributeDef { + readonly defType: "attrRef" + readonly allowedAttributes?: string | string[] + readonly allowedPlainNames?: string | string[] +} + +export interface AttributeDefCombination< + N extends string, + Cardinality extends CardinalityType, + AttributesInComb extends AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], + Type extends AttributeAnyType = Simplify>, +> extends AttributeDef { + readonly defType: "combination" + readonly allowedAttributesInCombination?: AttributesInComb +} + +export interface AttributeDefUnion< + N extends string, + Cardinality extends CardinalityType, + AttributesInUnion extends AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], + Type extends AttributeAnyType = AttributesInUnion[number]["~type"], +> extends AttributeDef { + readonly defType: "union" + readonly allowedAttributesInUnion?: AttributesInUnion +} + +export interface AttributeDefVocabularyRef< + N extends string, + Cardinality extends CardinalityType, +> extends AttributeDef { + readonly defType: "vocabulary" + readonly importVocabulary: PID + readonly SPARQLCheck?: string +} + +export type RequiredAttr = A extends OptionalAttr ? never : A +export type MultiValueAttr = A extends SingleValueAttr ? never : A +export type SingleValueAttr = + A extends AttributeDef ? A : never +export type OptionalAttr = + A extends AttributeDef + ? A + : never +export type AttrTypeWithCardinality< + A extends AttributeDef, +> = A extends MultiValueAttr ? A["~type"] | A["~type"][] : A["~type"] + +export type AttrsToObj< + AttributeList extends readonly AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], +> = { + [ + Attribute in RequiredAttr as Attribute["name"] + ]: AttrTypeWithCardinality +} & { + [ + Attribute in OptionalAttr as Attribute["name"] + ]+?: AttrTypeWithCardinality +} + +export type Simplify = { [K in keyof T]: T[K] } & {} + +function withPhantomType( + obj: Obj, +): Obj & { "~type": Type } { + return obj as Obj & { "~type": Type } +} + +export const Attribute = { + makeBase( + details: Simplify< + Omit, "~type" | "defType"> + >, + ): AttributeDef { + return withPhantomType({ + defType: "base", + ...details, + }) + }, + + makeSyntax< + N extends string, + Cardinality extends CardinalityType, + PrimitiveType extends "string" | "number" | "integer" | "boolean", + Whitelist extends string | string[] | undefined = undefined, + >( + details: Simplify< + Omit< + AttributeDefSyntax, + "~type" | "defType" + > + >, + ): AttributeDefSyntax { + return withPhantomType({ + defType: "syntax", + ...details, + }) + }, + + makeAttrRef( + details: Simplify< + Omit, "~type" | "defType"> + >, + ): AttributeDefAttrRef { + return withPhantomType({ + defType: "attrRef", + ...details, + }) + }, + + makeProfileRef( + details: Simplify< + Omit, "~type" | "defType"> + >, + ): AttributeDefProfileRef { + return withPhantomType({ + defType: "profileRef", + ...details, + }) + }, + + makeCombination< + N extends string, + Cardinality extends CardinalityType, + AttributesInComb extends AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], + Type extends AttributeAnyType = Simplify>, + >( + details: Simplify< + Omit< + AttributeDefCombination, + "~type" | "defType" + > + >, + ): AttributeDefCombination { + return withPhantomType({ + defType: "combination", + ...details, + }) + }, + + makeUnion< + N extends string, + Cardinality extends CardinalityType, + AttributesInUnion extends AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], + Type extends AttributeAnyType = AttributesInUnion[number]["~type"], + >( + details: Simplify< + Omit< + AttributeDefUnion, + "~type" | "defType" + > + >, + ): AttributeDefUnion { + return withPhantomType({ + defType: "union", + ...details, + }) + }, + + makeVocabulary( + details: Simplify< + Omit, "~type" | "defType"> + >, + ): AttributeDefVocabularyRef { + return withPhantomType({ + defType: "vocabulary", + ...details, + }) + }, + + makeRefined< + A extends AttributeDef, + NewCardinality extends CardinalityType, + >( + attribute: A, + newCardinality: NewCardinality, + ): AttributeDef { + return { + ...attribute, + cardinality: newCardinality, + } + }, } diff --git a/packages/primitives/src/interfaces/FDOContext.ts b/packages/primitives/src/interfaces/FDOContext.ts new file mode 100644 index 0000000..0b0cc1c --- /dev/null +++ b/packages/primitives/src/interfaces/FDOContext.ts @@ -0,0 +1,13 @@ +import type { DefaultAttributeDef } from "./Attribute.js" +import type { PID } from "../types.js" +import type { ProfileDef } from "./Profile.js" + +export interface FDOContext { + readonly attributes: Map + readonly profiles: Map> + + registerAttribute(attribute: DefaultAttributeDef): void + registerProfile(profile: ProfileDef): void + lookupAttribute(pid: PID): DefaultAttributeDef | undefined + lookupProfile(pid: PID): ProfileDef | undefined +} diff --git a/packages/primitives/src/interfaces/FDOGraph.ts b/packages/primitives/src/interfaces/FDOGraph.ts index 99fde56..3899490 100644 --- a/packages/primitives/src/interfaces/FDOGraph.ts +++ b/packages/primitives/src/interfaces/FDOGraph.ts @@ -1,5 +1,6 @@ import type { FDORecord, ReadOnlyFDORecord } from "./FDORecord.js" -import type { LocalID, PID, RecordValue } from "../types.js" +import type { LocalID, PID } from "../types.js" +import type { AttributeAnyType } from "./Attribute.js" export type FDOGraphAddRecordOptions = Partial<{ /** @@ -67,7 +68,7 @@ export interface ReadOnlyFDOGraph< * Returns the contents of this graph in a plain format, to be used with * {@link JSON.stringify} */ - toJSON(): Record>[] + toJSON(): Record>[] /** * Returns the content of this graph as a string, mainly useful for diff --git a/packages/primitives/src/interfaces/FDORecord.ts b/packages/primitives/src/interfaces/FDORecord.ts index 358ab98..4ea18d0 100644 --- a/packages/primitives/src/interfaces/FDORecord.ts +++ b/packages/primitives/src/interfaces/FDORecord.ts @@ -1,18 +1,30 @@ import type { - WithMarkers, LocalID, PID, - ProfileAttributes, - RecordValue, ReferenceDeclaration, + WithMarkers, } from "../types.js" -import type { Profile } from "./Profile.js" import type { Attribute } from "./Attribute.js" +import type { + AttributeAnyType, + AttributeDef, + AttrsToObj, + AttrTypeWithCardinality, + CardinalityType, + DefaultAttributeDef, + Simplify, +} from "./Attribute.js" +import type { ProfileDef } from "./Profile.js" +import { + DataAttribute, + ProfileAttribute, + TypeAttribute, +} from "../type-system/attributes.js" /** - * Either a {@link LocalFDORecord} or a {@link PublishedFDORecord} + * Either a {@link LocalFDORecord} or a {@link CompleteFDORecord} */ -export type IdentifiableFDORecord = LocalFDORecord | PublishedFDORecord +export type IdentifiableFDORecord = LocalFDORecord | CompleteFDORecord /** * Represents a single FDO record that has a {@link LocalID} and is optionally associated with a registered {@link PID}. @@ -29,20 +41,45 @@ export interface LocalFDORecord extends FDORecord { } /** - * Represents a single FDO record that has a registered {@link PID} + * Represents a single FDO record that has a registered {@link PID} and all required + * attributes. * * A record consists of attributes, each with one or more values. Each attribute * is uniquely identified by its {@link PID}. */ -export interface PublishedFDORecord extends FDORecord { +export interface CompleteFDORecord extends FDORecord { /** * The globally unique and registered identifier of this record. */ readonly PID: PID + + /** + * The FDO type gives a hint to a machine how the identified resource may be processed. It points to the attribute that further specifies the FDO type. + */ + getType(): AttrTypeWithCardinality + + /** + * This attribute is the entry point to find the data associated with an FDO. If the identified resource is physical or conceptual, the string "self" is used. If the resource it digital, this attribute points to the Attribute that references the digital resource. + */ + getData(): AttrTypeWithCardinality + + /** + * Get the PIDs of profiles this record conforms to. Can be used for validation. + */ + getProfile(): AttrTypeWithCardinality } -export interface PublishedLocalFDORecord - extends Omit, PublishedFDORecord {} +/** + * Represents a single FDO record that has a registered {@link PID} + * and a localID {@link LocalID}. + * + * A record consists of attributes, each with one or more values. Each attribute + * is uniquely identified by its {@link PID}. + */ +export interface CompleteLocalFDORecord + extends + Omit, + CompleteFDORecord {} /** * Represents a single FDO record that is optionally associated with a registered {@link PID}. @@ -55,25 +92,23 @@ export interface FDORecord extends ReadOnlyFDORecord { * Set the value of the specified attribute. Will add the attribute to the record * if it does not exist yet. Will replace (all) existing value(s) of this attribute * with the specified value. - * @param attribute {@link PID} of the attribute. - * @param value New value of the attribute. Can be an array to add multiple values, if allowed by the attribute. - */ - set(attribute: PID, value: RecordValue): void - - /** - * Set the value of the specified attribute. Will add the attribute to the record - * if it does not exist yet. Will replace (all) existing value(s) of this attribute - * with the specified value. - * @param attribute {@link Attribute} instance of the attribute. + * @param attribute {@link PID} of the attribute or {@link AttributeDef} attribute definition. * @param value New value of the attribute. Can be an array to add multiple values, if allowed by the attribute. */ - set(attribute: Attribute, value: T): void + set( + attribute: PID, + value: AttrTypeWithCardinality, + ): void + set( + attribute: A, + value: AttrTypeWithCardinality, + ): void /** * Remove the attribute and all its values from the record * @param attribute {@link PID} or {@link Attribute} instance of the attribute */ - remove(attribute: PID | Attribute): void + remove(attribute: PID | DefaultAttributeDef): void /** * Add the contents of another record to this record. This method does not @@ -88,28 +123,48 @@ export interface FDORecord extends ReadOnlyFDORecord { * @param attribute {@link PID} of the attribute * @param value New value of the attribute. Can be an array to add multiple values, if allowed by the attribute. */ - addAttribute(attribute: PID, value: RecordValue): void + addAttribute(attribute: PID, value: AttributeAnyType): void /** - * Add an attribute to the record. This method does not override existing - * data. + * Add a non-data attribute to the record. This method does not override existing + * values. * @param attribute {@link Attribute} instance of the attribute * @param value New value of the attribute. Can be an array to add multiple values, if allowed by the attribute. */ - addAttribute>( + addAttribute( attribute: Attr, - value: Attr extends Attribute ? T : never, + value: AttrTypeWithCardinality, ): void /** - * Mark this record as conformant to the specified profile and add at least - * the required attributes of the profile. - * @param profile The profile to conform to - * @param attributes An object containing at least all required attributes of the profile. May also contain optional attributes. You may use {@link reference}, {@link keep} and {@link skip}. + * Add a data attribute to the record. This method does not override existing + * values. + * @param attribute {@link Attribute} instance of the attribute + * @param value New value of the attribute. Can be an array to add multiple values, if allowed by the attribute. Can be left empty if the attribute is already present. */ - addProfile

>( - profile: P, - attributes: P extends Profile ? WithMarkers : never, + addData( + attribute: Attr | PID, + value?: Attr extends DefaultAttributeDef + ? AttrTypeWithCardinality + : AttrTypeWithCardinality, + ): void + + /** + * Add a type attribute to the record. This method does not override existing + * values. + * @param attribute {@link Attribute} instance of the attribute + * @param value New value of the attribute. Can be an array to add multiple values, if allowed by the attribute. Can be left empty if the attribute is already present. + */ + addType( + attribute: Attr, + value?: AttrTypeWithCardinality, + ): void + + addProfile>( + profile: UsedProfile, + attributes: UsedProfile extends ProfileDef + ? Simplify>> + : never, ): void /** @@ -121,7 +176,7 @@ export interface FDORecord extends ReadOnlyFDORecord { * @see {@link FDORecord.addReferenceBidi} for bidirectional references */ addReference( - fromAttribute: PID | Attribute, + fromAttribute: PID | AttributeDef, toRecord: PID | LocalID | IdentifiableFDORecord, ): void @@ -130,14 +185,14 @@ export interface FDORecord extends ReadOnlyFDORecord { * The target record must be in the current local or remote graph in order to * create the back-reference * @param fromAttribute The attribute of this record where the reference will be placed - * @param toAttribute The attribute of the target record where the back-reference will be placed + * @param inverseAttribute The attribute of the target record where the back-reference will be placed * @param toRecord the record that should be referenced, or a local ID ({@link LocalID}) or {@link PID} of the referenced record. Must either * be known locally or be resolvable via its PID * @see {@link FDORecord.addReference} for unidirectional references */ addReferenceBidi( - fromAttribute: PID | Attribute, - toAttribute: PID | Attribute, + fromAttribute: PID | AttributeDef, + inverseAttribute: PID | AttributeDef, toRecord: PID | LocalID | IdentifiableFDORecord, ): void } @@ -160,37 +215,52 @@ export interface ReadOnlyFDORecord { * @param attribute {@link PID} or {@link Attribute} instance of the attribute * @returns the value of the attribute, or undefined if the attribute is not present on this record */ - get(attribute: PID | Attribute): RecordValue | undefined + get(attribute: PID): AttributeAnyType | undefined + get( + attribute: A, + ): AttrTypeWithCardinality | undefined /** * Get a map of all attributes present on this record * @returns a map of attribute PIDs to attribute values */ - getAll(): Map + getAll(): Map> /** - * Get a list of outgoing references from this record to other records. Locally - * used to realize bidirectional references when the FDO Graph is published. + * The FDO type gives a hint to a machine how the identified resource may be processed. It points to the attribute that further specifies the FDO type. */ - getReferences(): ReferenceDeclaration[] + getType(): AttrTypeWithCardinality | undefined + + /** + * This attribute is the entry point to find the data associated with an FDO. If the identified resource is physical or conceptual, the string "self" is used. If the resource it digital, this attribute points to the Attribute that references the digital resource. + */ + getData(): AttrTypeWithCardinality | undefined /** - * Get a list of profiles this record conforms to. Can be used for validation. - * Each profile is globally identified by its PID. + * Get the PIDs of profiles this record conforms to. Can be used for validation. */ - getProfiles(): PID[] + getProfile(): AttrTypeWithCardinality | undefined + + /** + * Get a list of outgoing references from this record to other records. Locally + * used to realize bidirectional references when the FDO Graph is published. + * + * Only contains references that were added to this record using {@link addReference} + * or {@link addReferenceBidi} or similar + */ + getReferences(): ReferenceDeclaration[] /** * Check whether a specific attribute is present on this record * @param attribute {@link PID} or {@link Attribute} instance of the attribute */ - has(attribute: PID | Attribute): boolean + has(attribute: PID | DefaultAttributeDef): boolean /** * Returns the contents of this record in a plain format, to be used with * {@link JSON.stringify} */ - toJSON(): Record + toJSON(): Record> /** * Returns the content of this record as a string, mainly useful for diff --git a/packages/primitives/src/interfaces/Profile.ts b/packages/primitives/src/interfaces/Profile.ts index f85a4cb..4971bca 100644 --- a/packages/primitives/src/interfaces/Profile.ts +++ b/packages/primitives/src/interfaces/Profile.ts @@ -1,9 +1,33 @@ -import type { ProfileDefinition } from "./ProfileDefinition.js" -import type { PID, ProfileAttributes } from "../types.js" +import { + type AttributeAnyType, + type AttributeDef, + type CardinalityType, +} from "./Attribute.js" +import type { PID } from "../types.js" -export interface Profile { - readonly def: ProfileDefinition +export interface ProfileDef< + Attributes extends readonly AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], +> { + pid: PID + attributes: Attributes + name?: string | string[] + description?: string | string[] + denyAdditionalAttributes?: boolean +} - mapPIDToAttributeName(pid: PID): string - mapAttributeNameToPID(attributeName: string): PID +export const Profile = { + make< + Attributes extends readonly AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], + UsedProfile extends ProfileDef, + >(details: UsedProfile): UsedProfile { + return details + }, } diff --git a/packages/primitives/src/interfaces/ProfileDefinition.ts b/packages/primitives/src/interfaces/ProfileDefinition.ts deleted file mode 100644 index c6a3192..0000000 --- a/packages/primitives/src/interfaces/ProfileDefinition.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { AttributeToPID, PID, ProfileAttributes } from "../types.js" - -export interface ProfileDefinition { - /** - * The PID of this profile - */ - readonly pid: PID - - /** - * The human-readable name of this profile - */ - readonly readableName: string - - /** - * The PID of the attribute that is used to mark this profile as active for records that use it. - * When left undefined, no attribute will be used to mark this profile as active. - * - * @example - * // profileAttributePID: "0.SIMPLE/PROFILE" - * - * myRecord.addProfile(MY_PROFILE, { ... }) - * // -> attribute "0.SIMPLE/PROFILE" on myRecord is set to MY_PROFILE.pid - */ - readonly profileAttributePID?: PID - - /** - * Maps the readable name of an attribute to its PID - */ - readonly mapping: AttributeToPID -} diff --git a/packages/primitives/src/interfaces/PublishAdapter.ts b/packages/primitives/src/interfaces/PublishAdapter.ts index dab8ea5..d15b1a1 100644 --- a/packages/primitives/src/interfaces/PublishAdapter.ts +++ b/packages/primitives/src/interfaces/PublishAdapter.ts @@ -1,5 +1,5 @@ import type { ReadOnlyFDOGraph } from "./FDOGraph.js" -import type { FDORecord, PublishedFDORecord } from "./FDORecord.js" +import type { FDORecord, CompleteFDORecord } from "./FDORecord.js" /** * Publishes records to a backend that assigns PIDs. @@ -19,9 +19,9 @@ export interface PublishAdapter { */ publishGraph( graph: ReadOnlyFDOGraph, - ): Promise> + ): Promise> /** * Publishes a single record and returns it with its PID. */ - publishRecord(record: FDORecord): Promise + publishRecord(record: FDORecord): Promise } diff --git a/packages/primitives/src/interfaces/README.md b/packages/primitives/src/interfaces/README.md new file mode 100644 index 0000000..ba59fb3 --- /dev/null +++ b/packages/primitives/src/interfaces/README.md @@ -0,0 +1,48 @@ +## Class Structure + +```mermaid +classDiagram + class ReadOnlyFDORecord { + PID: string | undefined + FDO_Type: string | undefined + FDO_Data: string | undefined + FDO_Profile: string | undefined + } + + class FDORecord { + + } + + class LocalFDORecord { + localID: string + } + + class CompleteFDORecord { + PID: string + FDO_Type: string + FDO_Data: string + FDO_Profile: string + } + + namespace IdentifiableFDORecord { + class LocalFDORecord + class CompleteFDORecord + class LocalCompleteFDORecord + } + + class LocalCompleteFDORecord { + PID: string + localID: string + FDO_Type: string + FDO_Data: string + FDO_Profile: string + } + + + ReadOnlyFDORecord <|-- FDORecord + FDORecord <|-- LocalFDORecord + FDORecord <|-- CompleteFDORecord + LocalFDORecord <|-- LocalCompleteFDORecord + CompleteFDORecord <|-- LocalCompleteFDORecord +``` + diff --git a/packages/primitives/src/interfaces/ResolveAdapter.ts b/packages/primitives/src/interfaces/ResolveAdapter.ts index 43c1c2e..a9c9a97 100644 --- a/packages/primitives/src/interfaces/ResolveAdapter.ts +++ b/packages/primitives/src/interfaces/ResolveAdapter.ts @@ -1,4 +1,4 @@ -import type { PID, PublishedFDORecord } from "../index.js" +import type { PID, CompleteFDORecord } from "../index.js" /** * Resolves published records from a backend. @@ -16,5 +16,5 @@ export interface ResolveAdapter { * Resolves a record by its PID, or returns `undefined` if no record with * that PID exists. */ - resolveRecord(recordPID: PID): Promise + resolveRecord(recordPID: PID): Promise } diff --git a/packages/primitives/src/interfaces/index.ts b/packages/primitives/src/interfaces/index.ts index 86a8211..3f10fc4 100644 --- a/packages/primitives/src/interfaces/index.ts +++ b/packages/primitives/src/interfaces/index.ts @@ -1,6 +1,5 @@ export * from "./FDORecord.js" export * from "./FDOGraph.js" -export * from "./ProfileDefinition.js" export * from "./Attribute.js" export * from "./Profile.js" export * from "./PublishAdapter.js" diff --git a/packages/primitives/src/type-system/attributes.ts b/packages/primitives/src/type-system/attributes.ts new file mode 100644 index 0000000..797fcf2 --- /dev/null +++ b/packages/primitives/src/type-system/attributes.ts @@ -0,0 +1,53 @@ +import { Attribute } from "../interfaces/Attribute.js" + +export const TypeAttribute = Attribute.makeAttrRef({ + name: "FDO_type", + pid: "0.FDO/Type", + description: + "The FDO type gives a hint to a machine how the identified resource may be processed. It points to the attribute that further specifies the FDO type.", + cardinality: "1..*", +}) + +export const ProfileAttribute = Attribute.makeProfileRef({ + name: "FDO_profile", + pid: "0.FDO/Profile", + description: + "This attribute points to a FDO profile. The FDO profile is a template for any FDO record instantiating this profile.", + cardinality: "1..*", + allowedProfiles: "0.FDO/ProfileDef", +}) + +export const MetadataAttribute = Attribute.makeAttrRef({ + name: "FDO_metadata", + pid: "0.FDO/Metadata", + description: + "The 0.FDO/Metadata attribute is the entry point to find metadata files associated with an FDO.", + cardinality: "0..*", +}) + +export const DataAsSelfAttribute = Attribute.makeSyntax({ + name: "FDO_data_as_self", + pid: "0.FDO/DataAsSelf", + description: + 'If identified resource is physical or conceptual, the string "self" is used as the value of 0.FDO/Data.', + cardinality: "0..1", + primitiveDataType: "string", + whitelist: "self", +}) + +export const DataAsAttrRef = Attribute.makeAttrRef({ + name: "FDO_data_as_attr_ref", + pid: "0.FDO/DataAsAttrRef", + cardinality: "0..1", + description: + "If the identified resource it digital, 0.FDO/Data points to the attribute that references the digital resource.", +}) + +export const DataAttribute = Attribute.makeUnion({ + name: "FDO_data", + pid: "0.FDO/Data", + description: + 'The 0.FDO/Data attribute is the entry point to find the data associated with an FDO. If the identified resource is physical or conceptual, the string "self" is used. If the resource it digital, 0.FDO/Data points to the Attribute that references the digital resource.', + cardinality: "1..*", + allowedAttributesInUnion: [DataAsSelfAttribute, DataAsAttrRef], +}) diff --git a/packages/primitives/src/type-system/profiles.ts b/packages/primitives/src/type-system/profiles.ts new file mode 100644 index 0000000..874873c --- /dev/null +++ b/packages/primitives/src/type-system/profiles.ts @@ -0,0 +1,10 @@ +import { DataAttribute, ProfileAttribute, TypeAttribute } from "./attributes.js" +import { Profile } from "../interfaces/Profile.js" + +export const RootProfile = Profile.make({ + pid: "0.FDO/Root", + attributes: [TypeAttribute, ProfileAttribute, DataAttribute], + name: "FDO_root_profile", + description: + "This FDO defines the root profile. Any FDO must be valid against the root profile. The root profile requires three attributes: 0.FDO/Type, 0.FDO/Profile, 0.FDO/Data.These three attributes must be used in any FDO. The root profile can and should be extended by other profiles.", +}) diff --git a/packages/primitives/src/types.ts b/packages/primitives/src/types.ts index 5e493c6..4a653f8 100644 --- a/packages/primitives/src/types.ts +++ b/packages/primitives/src/types.ts @@ -3,7 +3,7 @@ * Care must be taken to ensure the local identifier is always unique and always the same for each * thing that will be represented as an FDO record. */ -export type LocalID = `LOCAL/${string}` | `EXTERNAL/${string}` +export type LocalID = `LOCAL/${string}` /** * The PID is the globally unique and persistent identifier of a published FDO record. Its structure @@ -11,15 +11,6 @@ export type LocalID = `LOCAL/${string}` | `EXTERNAL/${string}` */ export type PID = string -/** - * Possible values of attributes within an FDO record - */ -export type RecordValue = string | string[] - -export type ProfileAttributes = { - [key: string]: RecordValue -} - export type KeepMarker = { mark: "keep" } export type SkipMarker = { mark: "skip" } export type ReferenceMarker = { @@ -29,34 +20,18 @@ export type ReferenceMarker = { | Omit } -/** - * Attribute markers are used in {@link FDORecord.addProfile} to allow declaring - * skipped (see {@link skip}), kept (see {@link keep}) or referenced (see {@link reference}) attribute inline in the profile attribute - * definition. - */ -export type AttributeMarker = KeepMarker | SkipMarker | ReferenceMarker - /** * @internal */ -type AddMarker = T extends (infer InnerType)[] - ? AttributeMarker | (InnerType | ReferenceMarker)[] - : T | AttributeMarker +type AddMarker = T | KeepMarker | SkipMarker /** * @internal */ -export type WithMarkers

= { +export type WithMarkers

= { [key in keyof P]: AddMarker } -/** - * @internal - */ -export type AttributeToPID

= { - -readonly [key in keyof P]-?: PID -} - export type UniReferenceDeclaration = { direction: "uni" /** @@ -68,6 +43,7 @@ export type UniReferenceDeclaration = { */ toRecord: LocalID | PID } + export type BidiReferenceDeclaration = { direction: "bidi" /** diff --git a/packages/primitives/src/utils.ts b/packages/primitives/src/utils.ts index 935e432..d47d0b6 100644 --- a/packages/primitives/src/utils.ts +++ b/packages/primitives/src/utils.ts @@ -2,8 +2,8 @@ import type { FDORecord, IdentifiableFDORecord, LocalFDORecord, - PublishedFDORecord, - PublishedLocalFDORecord, + CompleteFDORecord, + CompleteLocalFDORecord, } from "./interfaces/index.js" export function toArray(val: T | T[]): T[] { @@ -18,13 +18,13 @@ export function isLocal(record: FDORecord): record is LocalFDORecord { return "localID" in record } -export function isPublished(record: FDORecord): record is PublishedFDORecord { +export function isPublished(record: FDORecord): record is CompleteFDORecord { return record.PID !== undefined } export function isPublishedMapped( record: FDORecord, -): record is PublishedLocalFDORecord { +): record is CompleteLocalFDORecord { return isLocal(record) && isPublished(record) } diff --git a/packages/primitives/tests/FDORecord.test.ts b/packages/primitives/tests/FDORecord.test.ts index 37caf17..4991a56 100644 --- a/packages/primitives/tests/FDORecord.test.ts +++ b/packages/primitives/tests/FDORecord.test.ts @@ -1,118 +1,157 @@ import { describe, it, expect } from "vitest" import { + Attribute, type FDORecord, - keep, type LocalFDORecord, + keep, + Profile, reference, referenceBidi, skip, + DefaultFDORecord, + DefaultLocalFDORecord, } from "../src/index.js" -import type { ProfileDefinition } from "../src/index.js" -import { ConcreteLocalFDORecord, ConcreteProfile } from "../src/index.js" -import type { Attribute } from "../src/index.js" +import { + DataAttribute, + ProfileAttribute, + TypeAttribute, +} from "../src/type-system/attributes.js" +import { RootProfile } from "../src/type-system/profiles.js" + +const datasetNameAttr = Attribute.makeSyntax({ + name: "datasetName", + pid: "some/pid1", + cardinality: "1..1", + primitiveDataType: "string", +}) -type HMCProfileAttributes = { - datasetName: string - authors: string | string[] - dateCreated?: string -} +const authorsAttr = Attribute.makeSyntax({ + name: "authors", + pid: "some/pid2", + cardinality: "0..*", + primitiveDataType: "string", +}) -const def: ProfileDefinition = { - pid: "profile/pid", - readableName: "HMC Profile", - mapping: { - datasetName: "some/pid1", - authors: "some/pid2", - dateCreated: "some/pid3", - }, -} - -const defWithAttributeMarker: ProfileDefinition = { - ...def, - profileAttributePID: "some/profile", -} - -const testAttr: Attribute = { +const dateCreatedAttr = Attribute.makeSyntax({ + name: "dateCreated", + pid: "some/pid3", + cardinality: "0..1", + primitiveDataType: "string", +}) + +const testAttr = Attribute.makeSyntax({ + name: "testAttr", pid: "TEST/testAttr", - readableName: "testAttr", -} + cardinality: "0..*", + primitiveDataType: "string", +}) -const srcAttr: Attribute = { +const srcAttr = Attribute.makeAttrRef({ + name: "srcAttr", pid: "TEST/srcAttr", - readableName: "srcAttr", -} + cardinality: "0..*", +}) -const fromAttr: Attribute = { +const fromAttr = Attribute.makeAttrRef({ + name: "from", pid: "TEST/from", - readableName: "from", -} + cardinality: "0..*", +}) -const toAttr: Attribute = { +const toAttr = Attribute.makeAttrRef({ + name: "to", pid: "TEST/to", - readableName: "to", -} + cardinality: "0..*", +}) -describe("FDORecord (via ConcreteMappedFDORecord)", () => { +const typeIdentifierAttr = Attribute.makeAttrRef({ + name: "typeIdentifier", + pid: "TEST/typeIdentifier", + cardinality: "0..1", +}) + +const conformsToAttr = Attribute.makeProfileRef({ + name: "conformsTo", + pid: "some/pid4", + cardinality: "0..*", +}) + +const HMCProfile = Profile.make({ + pid: "profile/pid", + name: "HMC Profile", + attributes: [datasetNameAttr, authorsAttr, dateCreatedAttr, conformsToAttr], +}) + +describe("FDORecord (via DefaultLocalFDORecord)", () => { describe("construction", () => { it("sets localID and leaves PID undefined when no PID is given", () => { - const r: ConcreteLocalFDORecord = new ConcreteLocalFDORecord( - "LOCAL/1", - ) + const r = new DefaultLocalFDORecord("LOCAL/1") expect(r.localID).toBe("LOCAL/1") expect(r.PID).toBeUndefined() }) it("sets PID when one is provided", () => { - const r: FDORecord = new ConcreteLocalFDORecord( - "LOCAL/1", - "rec/pid", - ) + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/pid") expect(r.PID).toBe("rec/pid") }) + + it("can be used without a local ID", () => { + const r = new DefaultFDORecord() + expect(r.PID).toBeUndefined() + }) }) describe("set / get / has", () => { it("get returns undefined for a missing attribute", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") expect(r.get("missing/pid")).toBeUndefined() }) it("has returns false for missing and true for present attributes", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") expect(r.has("a/pid")).toBe(false) r.set("a/pid", "v") expect(r.has("a/pid")).toBe(true) }) it("set stores a string value retrievable by get", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set("a/pid", "value") expect(r.get("a/pid")).toBe("value") }) it("set stores an array value retrievable by get", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set("a/pid", ["x", "y"]) expect(r.get("a/pid")).toEqual(["x", "y"]) }) it("set overwrites an existing value without concatenating", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set("a/pid", "first") r.set("a/pid", "second") expect(r.get("a/pid")).toBe("second") }) + it("works with attribute definitions", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.set(datasetNameAttr, "value") + expect(r.get(datasetNameAttr)).toBe("value") + expect(r.get("some/pid1")).toBe("value") + }) + it("get returns a deep clone (mutating the result does not affect the record)", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - r.set("a/pid", ["x", "y"]) - const val = r.get("a/pid") as string[] - val.push("z") - expect(r.get("a/pid")).toEqual(["x", "y"]) + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.set(testAttr, ["x", "y"]) + const val = r.get(testAttr) + if (Array.isArray(val)) { + val.push("z") + } + expect(r.get(testAttr)).toEqual(["x", "y"]) }) it("set removes all reference declarations", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReference(srcAttr, "LOCAL/2") expect(r.get(srcAttr)).toBe("LOCAL/2") expect(r.getReferences()).toHaveLength(1) @@ -122,7 +161,7 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { }) it("removes elements on remove", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set("a/pid", ["x", "y"]) r.set("b/pid", ["x", "y"]) expect(r.getAll().size).toBe(2) @@ -133,16 +172,29 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { expect(r.get("a/pid")).toBeUndefined() expect(r.get("b/pid")).not.toBeUndefined() }) + + it("throws when removing mandatory attributes", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + expect(() => r.remove(TypeAttribute)).toThrow( + /Cannot remove mandatory attributes/, + ) + expect(() => r.remove(DataAttribute)).toThrow( + /Cannot remove mandatory attributes/, + ) + expect(() => r.remove(ProfileAttribute)).toThrow( + /Cannot remove mandatory attributes/, + ) + }) }) describe("getAll", () => { it("returns an empty map for a fresh record", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") expect(r.getAll().size).toBe(0) }) it("returns all set attributes", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set("a/1", "v1") r.set("a/2", "v2") const all = r.getAll() @@ -152,7 +204,7 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { }) it("returns a clone (mutating the map does not affect the record)", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set("a/1", "v1") const all = r.getAll() all.set("a/2", "injected") @@ -164,21 +216,21 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { describe("addAttribute", () => { it("adds an attribute", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addAttribute(testAttr, "test") expect(r.get(testAttr)).toBe("test") expect(r.get(testAttr.pid)).toBe("test") }) it("concatenates values when adding a tuple for an existing PID", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set(testAttr, "first") r.addAttribute(testAttr, "second") expect(r.get(testAttr)).toEqual(["first", "second"]) }) it("concatenates into an existing array value", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set(testAttr, ["x"]) r.addAttribute(testAttr, "y") expect(r.get(testAttr)).toEqual(["x", "y"]) @@ -187,19 +239,19 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { describe("addRecord", () => { it("merges all attributes from another record", () => { - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1") a.set("a/1", "v1") a.set("a/2", "v2") - const b: FDORecord = new ConcreteLocalFDORecord("LOCAL/2") + const b: FDORecord = new DefaultLocalFDORecord("LOCAL/2") b.addRecord(a) expect(b.get("a/1")).toBe("v1") expect(b.get("a/2")).toBe("v2") }) it("concatenates values for overlapping PIDs when merging records", () => { - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1") a.set("shared/pid", "fromA") - const b: FDORecord = new ConcreteLocalFDORecord("LOCAL/2") + const b: FDORecord = new DefaultLocalFDORecord("LOCAL/2") b.set("shared/pid", "fromB") b.addRecord(a) expect(b.get("shared/pid")).toEqual(["fromB", "fromA"]) @@ -208,36 +260,36 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { describe("addReference", () => { it("adds a reference attribute pointing at a PID target", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReference(fromAttr, "target/pid") expect(r.get(fromAttr)).toBe("target/pid") }) it("adds a reference attribute pointing at a LocalID target", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReference(fromAttr, "LOCAL/2") expect(r.get(fromAttr)).toBe("LOCAL/2") }) it("uses the record's PID as target when given a record with a PID", () => { - const target: LocalFDORecord = new ConcreteLocalFDORecord( + const target: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/2", "target/pid", ) - const r: LocalFDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: LocalFDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReference(fromAttr, target) expect(r.get(fromAttr)).toBe("target/pid") }) it("falls back to localID when the target record has no PID", () => { - const target: LocalFDORecord = new ConcreteLocalFDORecord("LOCAL/2") - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const target: LocalFDORecord = new DefaultLocalFDORecord("LOCAL/2") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReference(fromAttr, target) expect(r.get(fromAttr)).toBe("LOCAL/2") }) it("concatenates with an existing value for the from-attribute", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set(fromAttr, "existing") r.addReference(fromAttr, "target/pid") expect(r.get(fromAttr)).toEqual(["existing", "target/pid"]) @@ -246,269 +298,225 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { describe("addReferenceBidi", () => { it("adds a reference attribute pointing at a PID target", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReferenceBidi(fromAttr, toAttr, "target/pid") expect(r.get(fromAttr)).toBe("target/pid") }) it("adds a reference attribute pointing at a LocalID target", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReferenceBidi(fromAttr, toAttr, "LOCAL/2") expect(r.get(fromAttr)).toBe("LOCAL/2") }) it("uses the record's PID as target when given a record with a PID", () => { - const target: LocalFDORecord = new ConcreteLocalFDORecord( + const target: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/2", "target/pid", ) - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReferenceBidi(fromAttr, toAttr, target) expect(r.get(fromAttr)).toBe("target/pid") }) it("falls back to localID when the target record has no PID", () => { - const target: LocalFDORecord = new ConcreteLocalFDORecord("LOCAL/2") - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const target: LocalFDORecord = new DefaultLocalFDORecord("LOCAL/2") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.addReferenceBidi(fromAttr, toAttr, target) expect(r.get(fromAttr)).toBe("LOCAL/2") }) it("concatenates with an existing value for the from-attribute", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set(fromAttr, "existing") r.addReferenceBidi(fromAttr, toAttr, "target/pid") expect(r.get(fromAttr)).toEqual(["existing", "target/pid"]) }) }) + describe("addData / getData", () => { + it("adds the data attribute and points 0.FDO/Data at it", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addData(datasetNameAttr, "myData") + expect(r.get(datasetNameAttr)).toBe("myData") + expect(r.getData()).toBe("some/pid1") + }) + + it("points 0.FDO/Data at an existing attribute when no value is given", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.set("data/pid", "value") + r.addData("data/pid") + expect(r.getData()).toBe("data/pid") + }) + + it("supports the string 'self' for physical or conceptual resources", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addData("some/pid", "self") + expect(r.getData()).toBe("some/pid") + }) + + it("throws when declaring a missing attribute as data without a value", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + expect(() => r.addData("missing/pid")).toThrow(/Cannot declare/) + }) + }) + + describe("addType / getType", () => { + it("adds the type attribute and points 0.FDO/Type at it", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addType(typeIdentifierAttr, "0.TYPES/creep-experiment") + expect(r.get(typeIdentifierAttr)).toBe("0.TYPES/creep-experiment") + expect(r.getType()).toBe("TEST/typeIdentifier") + }) + + it("throws when declaring a missing attribute as type without a value", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + expect(() => r.addType(typeIdentifierAttr)).toThrow( + /Cannot declare/, + ) + }) + }) + describe("addProfile", () => { - it("maps profile attributes to PIDs and adds them to the record", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(def) - r.addProfile(profile, { + it("maps profile attribute names to PIDs and adds them to the record", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addProfile(HMCProfile, { datasetName: "My Dataset", authors: ["a1", "a2"], }) expect(r.get("some/pid1")).toBe("My Dataset") expect(r.get("some/pid2")).toEqual(["a1", "a2"]) - expect(r.getProfiles()).toEqual([profile.def.pid]) + expect(r.getProfile()).toBe("profile/pid") }) it("only adds provided attributes (optional ones are omitted)", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(def) - r.addProfile(profile, { datasetName: "DS", authors: "a1" }) + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addProfile(HMCProfile, { datasetName: "DS", authors: "a1" }) expect(r.has("some/pid3")).toBe(false) }) it("concatenates with existing values for overlapping PIDs", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set("some/pid1", "existing") - const profile = new ConcreteProfile(def) - r.addProfile(profile, { datasetName: "new", authors: "a1" }) + r.addProfile(HMCProfile, { datasetName: "new", authors: "a1" }) expect(r.get("some/pid1")).toEqual(["existing", "new"]) }) it("does not add skipped values", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(def) - r.addProfile(profile, { datasetName: skip(), authors: "a1" }) - expect(r.get("some/pid1")).toEqual(undefined) + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addProfile(HMCProfile, { datasetName: skip(), authors: "a1" }) + expect(r.get("some/pid1")).toBeUndefined() }) - it("does not override or add to existing values when keep is used", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(def) + it("does not override existing values when keep is used", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") r.set("some/pid1", "existing") - r.addProfile(profile, { datasetName: keep(), authors: "a1" }) - expect(r.get("some/pid1")).toEqual("existing") + r.addProfile(HMCProfile, { datasetName: keep(), authors: "a1" }) + expect(r.get("some/pid1")).toBe("existing") }) it("throws when keep is used but no value exists", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(def) + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") expect(() => - r.addProfile(profile, { datasetName: keep(), authors: "a1" }), + r.addProfile(HMCProfile, { + datasetName: keep(), + authors: "a1", + }), ).toThrow( - 'Cannot add profile HMC Profile because attribute datasetName (PID: some/pid1) was specified as "keep", but is not present in this record', + /was specified as "keep", but is not present in this record/, ) }) - it("adds single references", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(def) - - r.addProfile(profile, { - datasetName: reference("LOCAL/target"), + it("adds single references on attributes that allow them", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addProfile(HMCProfile, { + datasetName: "DS", authors: "a1", + conformsTo: reference("LOCAL/target"), }) - expect(r.get("some/pid1")).toEqual("LOCAL/target") + expect(r.get("some/pid4")).toBe("LOCAL/target") expect(r.getReferences()).toEqual([ { direction: "uni", - fromAttribute: "some/pid1", + fromAttribute: "some/pid4", toRecord: "LOCAL/target", }, ]) }) - it("adds multiple references", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(def) - - r.addProfile(profile, { - authors: [ + it("adds multiple references and keeps primitive values", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addProfile(HMCProfile, { + datasetName: "Test Dataset", + conformsTo: [ reference("LOCAL/target1"), referenceBidi("some/pid5", "LOCAL/target2"), - "orcid...", + "plain", referenceBidi(testAttr, "LOCAL/target3"), ], - datasetName: "Test Dataset", }) - expect(r.get("some/pid2")).toEqual([ + expect(r.get("some/pid4")).toEqual([ "LOCAL/target1", "LOCAL/target2", "LOCAL/target3", - "orcid...", + "plain", ]) expect(r.getReferences()).toEqual([ { direction: "uni", - fromAttribute: "some/pid2", + fromAttribute: "some/pid4", toRecord: "LOCAL/target1", }, { direction: "bidi", - fromAttribute: "some/pid2", + fromAttribute: "some/pid4", inverseAttribute: "some/pid5", toRecord: "LOCAL/target2", }, { direction: "bidi", - fromAttribute: "some/pid2", + fromAttribute: "some/pid4", inverseAttribute: testAttr.pid, toRecord: "LOCAL/target3", }, ]) }) - it("catches and throws unknown markers", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(def) - - expect(() => - r.addProfile(profile, { - // @ts-ignore - datasetName: { mark: "test" }, - authors: "a1", - }), - ).toThrow( - "Profile instance contains illegal value of type object. This might be an internal error.", - ) - - expect(() => - r.addProfile(profile, { - // @ts-ignore - datasetName: ["test", { mark: "test" }], - authors: "a1", - }), - ).toThrow( - "Profile instance contains illegal value of type object. This might be an internal error.", - ) - }) - - it("adds the profile marker attribute when it doesn't exist", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(defWithAttributeMarker) - - expect(r.get("some/profile")).toBeUndefined() - r.addProfile(profile, { - authors: ["me", "you"], - datasetName: "test", - dateCreated: "today", + it("appends each profile PID to the FDO_Profile attribute", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + const secondHMCProfile = Profile.make({ + pid: "profile/pid2", + name: "HMC Profile 2", + attributes: [datasetNameAttr, authorsAttr], }) - expect(r.get("some/profile")).toBe("profile/pid") - }) - it("adds the profile to the marker attribute", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(defWithAttributeMarker) - const secondDefWithAttributeMarker: ProfileDefinition = - { - ...defWithAttributeMarker, - pid: "profile/pid2", - } - const secondProfile = new ConcreteProfile( - secondDefWithAttributeMarker, - ) - - expect(r.get("some/profile")).toBeUndefined() - r.addProfile(profile, { + r.addProfile(HMCProfile, { + datasetName: "first", authors: ["me", "you"], - datasetName: "test", - dateCreated: "today", }) - expect(r.get("some/profile")).toBe("profile/pid") - r.addProfile(secondProfile, { + r.addProfile(secondHMCProfile, { + datasetName: "second", authors: ["ada", "grace"], - datasetName: "another test", - dateCreated: "tomorrow", }) - expect(r.get("some/profile")).toEqual([ - "profile/pid", - "profile/pid2", - ]) + expect(r.getProfile()).toEqual(["profile/pid", "profile/pid2"]) }) - it("adds each profile only once to the marker attribute", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const profile = new ConcreteProfile(defWithAttributeMarker) - const secondDefWithAttributeMarker: ProfileDefinition = - { - ...defWithAttributeMarker, - pid: "profile/pid2", - } - const secondProfile = new ConcreteProfile( - secondDefWithAttributeMarker, - ) - - expect(r.get("some/profile")).toBeUndefined() - r.addProfile(profile, { - authors: ["me", "you"], - datasetName: "test", - dateCreated: "today", + it("can instantiate the root profile from the type-system", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addProfile(RootProfile, { + FDO_type: TypeAttribute.pid, + FDO_profile: RootProfile.pid, + FDO_data: "self", }) - r.addProfile(profile, { - authors: ["me", "you"], - datasetName: "test", - dateCreated: "today", - }) - expect(r.get("some/profile")).toBe("profile/pid") - r.addProfile(secondProfile, { - authors: ["ada", "grace"], - datasetName: "another test", - dateCreated: "tomorrow", - }) - expect(r.get("some/profile")).toEqual([ - "profile/pid", - "profile/pid2", - ]) - r.addProfile(profile, { - authors: ["me", "you"], - datasetName: "test", - dateCreated: "today", - }) - expect(r.get("some/profile")).toEqual([ - "profile/pid", - "profile/pid2", - ]) + expect(r.getType()).toBe(TypeAttribute.pid) + expect(r.getData()).toBe("self") + expect(r.getProfile()).toContain(RootProfile.pid) }) }) describe("toString", () => { it("includes localID, PID and attributes", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") r.set("some/pid", "value") const str = r.toString() expect(str).toContain("LOCAL/1") @@ -516,9 +524,9 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { expect(str).toContain('"some/pid": "value"') }) - it("lists the readable names of conforming profiles", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - r.addProfile(new ConcreteProfile(def), { + it("lists the PIDs of conforming profiles", () => { + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + r.addProfile(HMCProfile, { datasetName: "DS", authors: "a1", }) @@ -526,14 +534,14 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { }) it("prints an empty record without failing", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") expect(r.toString()).toContain("LOCAL/1") }) }) describe("toJSON", () => { it("returns the attributes as a plain pid -> value object", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") r.set("a/pid", "value") r.set("b/pid", ["x", "y"]) expect(r.toJSON()).toEqual({ @@ -543,12 +551,12 @@ describe("FDORecord (via ConcreteMappedFDORecord)", () => { }) it("returns an empty object for a record without attributes", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") expect(r.toJSON()).toEqual({}) }) it("is used automatically by JSON.stringify", () => { - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") r.set("a/pid", "value") expect(JSON.stringify(r)).toBe('{"a/pid":"value"}') }) diff --git a/packages/primitives/tests/LocalFDOGraph.test.ts b/packages/primitives/tests/LocalFDOGraph.test.ts index c347e36..56d77d0 100644 --- a/packages/primitives/tests/LocalFDOGraph.test.ts +++ b/packages/primitives/tests/LocalFDOGraph.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from "vitest" import type { FDOGraph, LocalFDORecord } from "../src/index.js" import type { FDORecord } from "../src/index.js" -import { LocalFDOGraph, ConcreteLocalFDORecord } from "../src/index.js" +import { LocalFDOGraph, DefaultLocalFDORecord } from "../src/index.js" describe("LocalFDOGraph", () => { describe("construction", () => { @@ -14,8 +14,8 @@ describe("LocalFDOGraph", () => { describe("addRecord / getRecords", () => { it("returns all added records", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") - const b: FDORecord = new ConcreteLocalFDORecord("LOCAL/2") + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") + const b: FDORecord = new DefaultLocalFDORecord("LOCAL/2") graph.addRecord(a) graph.addRecord(b) expect(graph.getRecords()).toEqual([a, b]) @@ -23,7 +23,7 @@ describe("LocalFDOGraph", () => { it("returns a new array each time (mutating it does not affect the graph)", () => { const graph: FDOGraph = new LocalFDOGraph() - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1")) + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1")) const records = graph.getRecords() records.pop() expect(graph.getRecords()).toHaveLength(1) @@ -31,9 +31,9 @@ describe("LocalFDOGraph", () => { it("throws when a record with the same id already exists", () => { const graph: FDOGraph = new LocalFDOGraph() - const original = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") + const original = new DefaultLocalFDORecord("LOCAL/1", "rec/a") graph.addRecord(original) - const replacement: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const replacement: FDORecord = new DefaultLocalFDORecord("LOCAL/1") expect(() => graph.addRecord(replacement)).toThrow() expect(graph.getRecords()).toEqual([original]) expect(graph.getRecord("LOCAL/1")).toBe(original) @@ -42,8 +42,8 @@ describe("LocalFDOGraph", () => { it("replaces an existing record with the same localID when overwrite is true", () => { const graph: FDOGraph = new LocalFDOGraph() - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1", "rec/a")) - const replacement: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1", "rec/a")) + const replacement: FDORecord = new DefaultLocalFDORecord("LOCAL/1") graph.addRecord(replacement, { overwrite: true }) expect(graph.getRecords()).toEqual([replacement]) expect(graph.getRecord("LOCAL/1")).toBe(replacement) @@ -52,9 +52,9 @@ describe("LocalFDOGraph", () => { it("does not re-index the PID when a record with the same localID is replaced and overwrite is false", () => { const graph: LocalFDOGraph = new LocalFDOGraph() - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1", "rec/a")) + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1", "rec/a")) expect(() => - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1", "rec/b")), + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1", "rec/b")), ).toThrow() expect(graph.getRecord("rec/a")?.localID).toBe("LOCAL/1") expect(graph.getRecord("rec/b")).toBeUndefined() @@ -62,8 +62,8 @@ describe("LocalFDOGraph", () => { it("re-indexes the PID when a record with the same localID is replaced and overwrite is true", () => { const graph: LocalFDOGraph = new LocalFDOGraph() - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1", "rec/a")) - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1", "rec/b"), { + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1", "rec/a")) + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1", "rec/b"), { overwrite: true, }) expect(graph.getRecord("rec/a")).toBeUndefined() @@ -94,28 +94,28 @@ describe("LocalFDOGraph", () => { describe("getRecord", () => { it("finds a record by localID", () => { const graph: FDOGraph = new LocalFDOGraph() - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") graph.addRecord(r) expect(graph.getRecord("LOCAL/1")).toBe(r) }) it("finds a record by PID", () => { const graph: FDOGraph = new LocalFDOGraph() - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") graph.addRecord(r) expect(graph.getRecord("rec/a")).toBe(r) }) it("finds a PID-less record by localID", () => { const graph: FDOGraph = new LocalFDOGraph() - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") graph.addRecord(r) expect(graph.getRecord("LOCAL/1")).toBe(r) }) it("returns undefined for an unknown id", () => { const graph: FDOGraph = new LocalFDOGraph() - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1", "rec/a")) + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1", "rec/a")) expect(graph.getRecord("LOCAL/missing")).toBeUndefined() expect(graph.getRecord("rec/missing")).toBeUndefined() }) @@ -124,14 +124,14 @@ describe("LocalFDOGraph", () => { describe("removeRecord", () => { it("removes a PID-less record by localID", () => { const graph: FDOGraph = new LocalFDOGraph() - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1")) + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1")) graph.removeRecord("LOCAL/1") expect(graph.getRecords()).toEqual([]) }) it("removes a record by PID and clears both lookups", () => { const graph: FDOGraph = new LocalFDOGraph() - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1", "rec/a")) + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1", "rec/a")) graph.removeRecord("rec/a") expect(graph.getRecords()).toEqual([]) expect(graph.getRecord("LOCAL/1")).toBeUndefined() @@ -140,11 +140,11 @@ describe("LocalFDOGraph", () => { it("only removes the matching record when multiple exist", () => { const graph: FDOGraph = new LocalFDOGraph() - const keep: FDORecord = new ConcreteLocalFDORecord( + const keep: FDORecord = new DefaultLocalFDORecord( "LOCAL/2", "rec/b", ) - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1", "rec/a")) + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1", "rec/a")) graph.addRecord(keep) graph.removeRecord("LOCAL/1") expect(graph.getRecords()).toEqual([keep]) @@ -152,7 +152,7 @@ describe("LocalFDOGraph", () => { it("does nothing for an unknown id", () => { const graph: FDOGraph = new LocalFDOGraph() - const r: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") + const r: FDORecord = new DefaultLocalFDORecord("LOCAL/1") graph.addRecord(r) expect(() => graph.removeRecord("rec/missing")).not.toThrow() expect(graph.getRecords()).toEqual([r]) @@ -162,8 +162,8 @@ describe("LocalFDOGraph", () => { describe("findRecord", () => { it("returns the first record matching the predicate", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") - const b: FDORecord = new ConcreteLocalFDORecord("LOCAL/2", "rec/b") + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") + const b: FDORecord = new DefaultLocalFDORecord("LOCAL/2", "rec/b") graph.addRecord(a) graph.addRecord(b) expect(graph.findRecord((r) => r.PID === "rec/b")).toBe(b) @@ -171,7 +171,7 @@ describe("LocalFDOGraph", () => { it("returns undefined when no record matches", () => { const graph: FDOGraph = new LocalFDOGraph() - graph.addRecord(new ConcreteLocalFDORecord("LOCAL/1")) + graph.addRecord(new DefaultLocalFDORecord("LOCAL/1")) expect(graph.findRecord(() => false)).toBeUndefined() }) }) @@ -179,11 +179,11 @@ describe("LocalFDOGraph", () => { describe("build", () => { it("adds a back-reference via the toAttribute on the target record", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: LocalFDORecord = new ConcreteLocalFDORecord( + const a: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/1", "rec/a", ) - const b: LocalFDORecord = new ConcreteLocalFDORecord( + const b: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/2", "rec/b", ) @@ -199,8 +199,8 @@ describe("LocalFDOGraph", () => { it("uses the source record's localID as back-reference when it has no PID", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: LocalFDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const b: LocalFDORecord = new ConcreteLocalFDORecord( + const a: LocalFDORecord = new DefaultLocalFDORecord("LOCAL/1") + const b: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/2", "rec/b", ) @@ -216,11 +216,11 @@ describe("LocalFDOGraph", () => { it("resolves the target by localID", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: LocalFDORecord = new ConcreteLocalFDORecord( + const a: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/1", "rec/a", ) - const b: LocalFDORecord = new ConcreteLocalFDORecord("LOCAL/2") + const b: LocalFDORecord = new DefaultLocalFDORecord("LOCAL/2") graph.addRecord(a) graph.addRecord(b) @@ -233,11 +233,11 @@ describe("LocalFDOGraph", () => { it("leaves the forward reference in place on the source record", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: LocalFDORecord = new ConcreteLocalFDORecord( + const a: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/1", "rec/a", ) - const b: LocalFDORecord = new ConcreteLocalFDORecord( + const b: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/2", "rec/b", ) @@ -254,9 +254,9 @@ describe("LocalFDOGraph", () => { it("concatenates back-references from multiple sources", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") - const c: FDORecord = new ConcreteLocalFDORecord("LOCAL/3", "rec/c") - const b: LocalFDORecord = new ConcreteLocalFDORecord( + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") + const c: FDORecord = new DefaultLocalFDORecord("LOCAL/3", "rec/c") + const b: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/2", "rec/b", ) @@ -274,9 +274,9 @@ describe("LocalFDOGraph", () => { it("does not add back-references for unidirectional references", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") - const c: FDORecord = new ConcreteLocalFDORecord("LOCAL/3", "rec/c") - const b: LocalFDORecord = new ConcreteLocalFDORecord( + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") + const c: FDORecord = new DefaultLocalFDORecord("LOCAL/3", "rec/c") + const b: LocalFDORecord = new DefaultLocalFDORecord( "LOCAL/2", "rec/b", ) @@ -295,7 +295,7 @@ describe("LocalFDOGraph", () => { it("throws on bidirectional references to records that are not in the local graph", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") graph.addRecord(a) a.addReferenceBidi("has/data", "is/dataFor", "LOCAL/missing") @@ -306,7 +306,7 @@ describe("LocalFDOGraph", () => { it("throws when built twice or more", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") graph.addRecord(a) a.addReference("has/data", "LOCAL/missing") @@ -320,8 +320,8 @@ describe("LocalFDOGraph", () => { describe("toString", () => { it("prints all record toStrings separated by newlines", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1", "rec/a") - const b: FDORecord = new ConcreteLocalFDORecord("LOCAL/2") + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1", "rec/a") + const b: FDORecord = new DefaultLocalFDORecord("LOCAL/2") graph.addRecord(a) graph.addRecord(b) expect(graph.toString()).toBe(`${a.toString()}\n${b.toString()}`) @@ -336,8 +336,8 @@ describe("LocalFDOGraph", () => { describe("toJSON", () => { it("returns an array of the record JSON objects", () => { const graph: FDOGraph = new LocalFDOGraph() - const a: FDORecord = new ConcreteLocalFDORecord("LOCAL/1") - const b: FDORecord = new ConcreteLocalFDORecord("LOCAL/2") + const a: FDORecord = new DefaultLocalFDORecord("LOCAL/1") + const b: FDORecord = new DefaultLocalFDORecord("LOCAL/2") a.set("a/pid", "value-a") b.set("b/pid", "value-b") graph.addRecord(a) diff --git a/packages/primitives/tests/Profile.test.ts b/packages/primitives/tests/Profile.test.ts index 4ad3407..7ecd323 100644 --- a/packages/primitives/tests/Profile.test.ts +++ b/packages/primitives/tests/Profile.test.ts @@ -1,59 +1,189 @@ import { describe, it, expect } from "vitest" -import type { Profile } from "../src/index.js" -import type { ProfileDefinition } from "../src/index.js" -import { ConcreteProfile } from "../src/index.js" - -type HMCProfileAttributes = { - datasetName: string - authors: string | string[] - dateCreated?: string -} - -const def: ProfileDefinition = { - pid: "profile/pid", - readableName: "HMC Profile", - mapping: { - datasetName: "some/pid1", - authors: "some/pid2", - dateCreated: "some/pid3", - }, -} - -describe("Profile (via ConcreteProfile)", () => { - it("exposes the definition via readonly def", () => { - const profile: Profile = new ConcreteProfile(def) - expect(profile.def).toBe(def) - expect(profile.def.pid).toBe("profile/pid") - expect(profile.def.mapping.datasetName).toBe("some/pid1") - }) - - describe("mapPIDToAttributeName", () => { - it("maps a single PID to its attribute name", () => { - const profile = new ConcreteProfile(def) - const mapped = profile.mapPIDToAttributeName("some/pid1") - expect(mapped).toBe("datasetName") - }) - - it("throws when an attribute has no mapping", () => { - const profile = new ConcreteProfile(def) - expect(() => profile.mapPIDToAttributeName("not/known")).toThrow( - "mapPIDToAttributeName: No attribute with the PID not/known is defined in the profile HMC Profile", - ) - }) - }) - - describe("mapAttributeNameToPID", () => { - it("maps a single string attribute name to its PID", () => { - const profile = new ConcreteProfile(def) - const mapped = profile.mapAttributeNameToPID("datasetName") - expect(mapped).toBe("some/pid1") - }) - - it("throws when an attribute has no mapping", () => { - const profile = new ConcreteProfile(def) - expect(() => profile.mapAttributeNameToPID("unknown")).toThrow( - "mapAttributeNameToPID: No attribute with the name unknown is defined in the profile HMC Profile", - ) +import { Attribute, Profile, reference } from "../src/index.js" +import { + DataAsAttrRef, + DataAsSelfAttribute, + DataAttribute, + MetadataAttribute, + ProfileAttribute, + TypeAttribute, +} from "../src/type-system/attributes.js" +import { RootProfile } from "../src/type-system/profiles.js" + +describe("Attribute factories", () => { + it("makeSyntax creates a syntax attribute definition", () => { + const attr = Attribute.makeSyntax({ + name: "title", + pid: "TEST/title", + cardinality: "1..1", + primitiveDataType: "string", + }) + expect(attr.defType).toBe("syntax") + expect(attr.pid).toBe("TEST/title") + expect(attr.name).toBe("title") + expect(attr.cardinality).toBe("1..1") + }) + + it("makeAttrRef creates an attribute reference definition", () => { + const attr = Attribute.makeAttrRef({ + name: "related", + pid: "TEST/related", + cardinality: "0..*", + }) + expect(attr.defType).toBe("attrRef") + }) + + it("makeProfileRef creates a profile reference definition", () => { + const attr = Attribute.makeProfileRef({ + name: "conformsTo", + pid: "TEST/conformsTo", + cardinality: "0..*", + allowedProfiles: "0.FDO/ProfileDef", + }) + expect(attr.defType).toBe("profileRef") + expect(attr.allowedProfiles).toBe("0.FDO/ProfileDef") + }) + + it("profileRef attributes allow reference markers in their value type", () => { + const attr = Attribute.makeProfileRef({ + name: "conformsTo", + pid: "TEST/conformsTo", + cardinality: "0..*", + }) + const value: (typeof attr)["~type"] = reference("LOCAL/target") + expect(value.mark).toBe("reference") + }) + + it("makeVocabulary creates a vocabulary reference definition", () => { + const attr = Attribute.makeVocabulary({ + name: "species", + pid: "TEST/species", + cardinality: "0..1", + importVocabulary: "0.VOCAB/species", + }) + expect(attr.defType).toBe("vocabulary") + expect(attr.importVocabulary).toBe("0.VOCAB/species") + }) + + it("makeCombination creates a combination definition", () => { + const left = Attribute.makeSyntax({ + name: "left", + pid: "TEST/left", + cardinality: "1..1", + primitiveDataType: "number", + }) + const right = Attribute.makeSyntax({ + name: "right", + pid: "TEST/right", + cardinality: "1..1", + primitiveDataType: "number", + }) + const combo = Attribute.makeCombination({ + name: "coordinates", + pid: "TEST/coordinates", + cardinality: "1..1", + allowedAttributesInCombination: [left, right], + }) + expect(combo.defType).toBe("combination") + expect(combo.allowedAttributesInCombination).toEqual([left, right]) + }) + + it("makeUnion creates a union definition", () => { + const union = Attribute.makeUnion({ + name: "data", + pid: "TEST/data", + cardinality: "1..1", + allowedAttributesInUnion: [DataAsSelfAttribute, DataAsAttrRef], }) + expect(union.defType).toBe("union") + expect(union.allowedAttributesInUnion).toEqual([ + DataAsSelfAttribute, + DataAsAttrRef, + ]) + }) + + it("makeRefined adjusts the cardinality whilst keeping the other properties", () => { + const base = Attribute.makeSyntax({ + name: "title", + pid: "TEST/title", + cardinality: "0..*", + primitiveDataType: "string", + }) + const refined = Attribute.makeRefined(base, "1..1") + expect(refined.cardinality).toBe("1..1") + expect(refined.pid).toBe("TEST/title") + expect(refined.name).toBe("title") + expect(refined.defType).toBe("syntax") + }) + + it("syntax definitions narrow the value type through the whitelist", () => { + const selfAttr = Attribute.makeSyntax({ + name: "asSelf", + pid: "TEST/asSelf", + cardinality: "0..1", + primitiveDataType: "string", + whitelist: "self", + }) + const value: (typeof selfAttr)["~type"] = "self" + expect(value).toBe("self") + }) +}) + +describe("Profile", () => { + it("make keeps the passed definition unchanged", () => { + const profile = Profile.make({ pid: "profile/pid", attributes: [] }) + expect(profile).toEqual({ pid: "profile/pid", attributes: [] }) + }) + + it("carries the attribute definitions it was created with", () => { + const titleAttr = Attribute.makeSyntax({ + name: "title", + pid: "TEST/title", + cardinality: "1..1", + primitiveDataType: "string", + }) + const profile = Profile.make({ + pid: "profile/title", + name: "Title Profile", + description: "A profile with a single title attribute", + attributes: [titleAttr], + }) + expect(profile.pid).toBe("profile/title") + expect(profile.name).toBe("Title Profile") + expect(profile.attributes).toEqual([titleAttr]) + }) +}) + +describe("standard type-system attributes and the root profile", () => { + it("defines the FDO type, profile, metadata and data attributes", () => { + expect(TypeAttribute.pid).toBe("0.FDO/Type") + expect(TypeAttribute.name).toBe("FDO_type") + expect(TypeAttribute.defType).toBe("attrRef") + + expect(ProfileAttribute.pid).toBe("0.FDO/Profile") + expect(ProfileAttribute.name).toBe("FDO_profile") + expect(ProfileAttribute.defType).toBe("profileRef") + expect(ProfileAttribute.allowedProfiles).toBe("0.FDO/ProfileDef") + + expect(MetadataAttribute.pid).toBe("0.FDO/Metadata") + expect(MetadataAttribute.name).toBe("FDO_metadata") + + expect(DataAttribute.pid).toBe("0.FDO/Data") + expect(DataAttribute.name).toBe("FDO_data") + expect(DataAttribute.defType).toBe("union") + expect(DataAttribute.allowedAttributesInUnion).toEqual([ + DataAsSelfAttribute, + DataAsAttrRef, + ]) + }) + + it("defines a root profile that every FDO must conform to", () => { + expect(RootProfile.pid).toBe("0.FDO/Root") + expect(RootProfile.name).toBe("FDO_root_profile") + expect(RootProfile.attributes).toEqual([ + TypeAttribute, + ProfileAttribute, + DataAttribute, + ]) }) }) diff --git a/packages/primitives/tests/PublishedFDOGraph.test.ts b/packages/primitives/tests/PublishedFDOGraph.test.ts index 6972650..42fe8e4 100644 --- a/packages/primitives/tests/PublishedFDOGraph.test.ts +++ b/packages/primitives/tests/PublishedFDOGraph.test.ts @@ -1,22 +1,22 @@ import { describe, it, expect } from "vitest" -import type { LocalID, PublishedFDORecord } from "../src/index.js" +import type { LocalID, CompleteFDORecord } from "../src/index.js" import { - ConcreteFDORecord, - ConcreteLocalFDORecord, + DefaultFDORecord, + DefaultLocalFDORecord, PublishedFDOGraph, } from "../src/index.js" -function publishedRecord(pid: string): PublishedFDORecord { - const record = new ConcreteFDORecord(pid) - return record as PublishedFDORecord +function publishedRecord(pid: string): CompleteFDORecord { + const record = new DefaultFDORecord(pid) + return record as CompleteFDORecord } function publishedMappedRecord( localID: LocalID, pid: string, -): PublishedFDORecord { - const record = new ConcreteLocalFDORecord(localID, pid) - return record as PublishedFDORecord +): CompleteFDORecord { + const record = new DefaultLocalFDORecord(localID, pid) + return record as CompleteFDORecord } describe("PublishedFDOGraph", () => { diff --git a/packages/simple-types/README.md b/packages/simple-types/README.md index b37981b..44b7d3d 100644 --- a/packages/simple-types/README.md +++ b/packages/simple-types/README.md @@ -81,5 +81,5 @@ attributes). ## Writing your own types For real data, define your own `ProfileDefinition` and instantiate it with -`ConcreteProfile` from `@fdo-sdk/primitives`. The simple types are a model for +`DefaultProfile` from `@fdo-sdk/primitives`. The simple types are a model for how to do that, not a fixed vocabulary. From 43a6814e8be36fe630b2123db824a838ddd9a2bb Mon Sep 17 00:00:00 2001 From: Christopher Raquet Date: Tue, 1 Dec 2026 09:50:38 +0100 Subject: [PATCH 2/6] fix: corrections --- packages/primitives/src/impl/markers.ts | 2 +- packages/primitives/src/index.ts | 1 + packages/primitives/src/type-system/index.ts | 2 ++ packages/primitives/src/utils.ts | 13 +++++++++---- 4 files changed, 13 insertions(+), 5 deletions(-) create mode 100644 packages/primitives/src/type-system/index.ts diff --git a/packages/primitives/src/impl/markers.ts b/packages/primitives/src/impl/markers.ts index bebbc81..d5da97b 100644 --- a/packages/primitives/src/impl/markers.ts +++ b/packages/primitives/src/impl/markers.ts @@ -7,7 +7,7 @@ import type { } from "../types.js" import type { Attribute, IdentifiableFDORecord } from "../interfaces/index.js" import { getRecordIdentifier } from "../utils.js" -import type { DefaultAttributeDef } from "../interfaces/Attribute.js" +import type { DefaultAttributeDef } from "../interfaces/index.js" /** * To be used in {@link FDORecord.addProfile}. Marks a mandatory attribute as skipped, meaning it won't be added to the record. diff --git a/packages/primitives/src/index.ts b/packages/primitives/src/index.ts index cf976f5..5ebef56 100644 --- a/packages/primitives/src/index.ts +++ b/packages/primitives/src/index.ts @@ -1,3 +1,4 @@ export * from "./types.js" export * from "./interfaces/index.js" export * from "./impl/index.js" +export * from "./type-system/index.js" diff --git a/packages/primitives/src/type-system/index.ts b/packages/primitives/src/type-system/index.ts new file mode 100644 index 0000000..79e6f48 --- /dev/null +++ b/packages/primitives/src/type-system/index.ts @@ -0,0 +1,2 @@ +export * from "./attributes.js" +export * from "./profiles.js" diff --git a/packages/primitives/src/utils.ts b/packages/primitives/src/utils.ts index d47d0b6..501792c 100644 --- a/packages/primitives/src/utils.ts +++ b/packages/primitives/src/utils.ts @@ -18,14 +18,19 @@ export function isLocal(record: FDORecord): record is LocalFDORecord { return "localID" in record } -export function isPublished(record: FDORecord): record is CompleteFDORecord { - return record.PID !== undefined +export function isComplete(record: FDORecord): record is CompleteFDORecord { + return ( + record.PID !== undefined && + record.getType() !== undefined && + record.getData() !== undefined && + record.getProfile() !== undefined + ) } -export function isPublishedMapped( +export function isCompleteLocal( record: FDORecord, ): record is CompleteLocalFDORecord { - return isLocal(record) && isPublished(record) + return isLocal(record) && isComplete(record) } export function getRecordIdentifier(record: IdentifiableFDORecord): string { From 5afccc142c37b276bd371c74173d955a969182da Mon Sep 17 00:00:00 2001 From: Christopher Raquet Date: Tue, 1 Dec 2026 15:38:20 +0100 Subject: [PATCH 3/6] fix: adapt packages to new type system --- packages/examples/.gitignore | 1 - .../examples/assets/creep-experiments.json | 107 --- .../examples/assets/creep-profiles/Base.json | 101 --- .../creep-profiles/CreepExperiment.json | 123 ---- .../assets/creep-profiles/DataResource.json | 65 -- .../assets/creep-profiles/Helmholtz.json | 45 -- .../assets/creep-profiles/Material.json | 75 --- .../examples/assets/creep-profiles/NFDI.json | 48 -- .../assets/creep-profiles/Publication.json | 74 -- .../assets/creep-profiles/Versionable.json | 67 -- packages/examples/package.json | 25 - .../scripts/generate-creep-profiles.mjs | 119 ---- packages/examples/src/example.ts | 76 --- .../examples/src/generated/creepProfiles.ts | 414 ------------ packages/examples/src/localTestingBackend.ts | 636 ------------------ packages/examples/tsconfig.json | 43 -- .../src/impl/ContinuousMappingContext.ts | 16 +- .../src/impl/backends/LocalTestingBackend.ts | 72 +- .../src/impl/clients/typid/TypidClient.ts | 88 --- .../src/impl/resolvers/TypidResolver.ts | 65 -- .../interfaces/ContinuousResolveAdapter.ts | 4 +- packages/mapping/src/types.ts | 4 +- .../tests/ConcreteMappingContext.test.ts | 50 +- .../mapping/tests/LocalTestingBackend.test.ts | 220 +++--- .../playground/src/components/RecordList.tsx | 15 +- packages/playground/src/examples/examples.ts | 3 +- .../src/runner/playground-backend.ts | 10 +- packages/playground/src/runner/snapshot.ts | 16 +- .../tests/playground-backend.test.ts | 20 +- packages/playground/tests/sandbox.test.ts | 12 +- packages/playground/tests/snapshot.test.ts | 47 +- packages/playground/tests/ts-project.test.ts | 14 +- .../primitives/src/impl/DefaultFDORecord.ts | 5 +- packages/primitives/src/index.ts | 1 + .../primitives/src/interfaces/Attribute.ts | 136 +++- .../primitives/src/interfaces/FDORecord.ts | 4 +- packages/primitives/src/interfaces/Profile.ts | 8 + packages/simple-types/README.md | 87 ++- packages/simple-types/src/attributes.ts | 275 +++++--- packages/simple-types/src/identifiers.ts | 37 - packages/simple-types/src/index.ts | 1 - packages/simple-types/src/profiles.ts | 138 ++-- .../simple-types/tests/attributes.test.ts | 89 ++- packages/simple-types/tests/profiles.test.ts | 128 +++- pnpm-lock.yaml | 120 +--- 45 files changed, 904 insertions(+), 2800 deletions(-) delete mode 100644 packages/examples/.gitignore delete mode 100644 packages/examples/assets/creep-experiments.json delete mode 100644 packages/examples/assets/creep-profiles/Base.json delete mode 100644 packages/examples/assets/creep-profiles/CreepExperiment.json delete mode 100644 packages/examples/assets/creep-profiles/DataResource.json delete mode 100644 packages/examples/assets/creep-profiles/Helmholtz.json delete mode 100644 packages/examples/assets/creep-profiles/Material.json delete mode 100644 packages/examples/assets/creep-profiles/NFDI.json delete mode 100644 packages/examples/assets/creep-profiles/Publication.json delete mode 100644 packages/examples/assets/creep-profiles/Versionable.json delete mode 100644 packages/examples/package.json delete mode 100644 packages/examples/scripts/generate-creep-profiles.mjs delete mode 100644 packages/examples/src/example.ts delete mode 100644 packages/examples/src/generated/creepProfiles.ts delete mode 100644 packages/examples/src/localTestingBackend.ts delete mode 100644 packages/examples/tsconfig.json delete mode 100644 packages/mapping/src/impl/clients/typid/TypidClient.ts delete mode 100644 packages/mapping/src/impl/resolvers/TypidResolver.ts delete mode 100644 packages/simple-types/src/identifiers.ts diff --git a/packages/examples/.gitignore b/packages/examples/.gitignore deleted file mode 100644 index 4985073..0000000 --- a/packages/examples/.gitignore +++ /dev/null @@ -1 +0,0 @@ -result.json \ No newline at end of file diff --git a/packages/examples/assets/creep-experiments.json b/packages/examples/assets/creep-experiments.json deleted file mode 100644 index 34d7af1..0000000 --- a/packages/examples/assets/creep-experiments.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "creepExperiments": [ - { - "id": "creep-exp-001", - "FDO_profile": [ - "21.T11969/077fe9c54ed5ed26fa54", - "21.T11969/222fb86c0b3bece35729" - ], - "creator": ["https://orcid.org/0009-0005-2800-4833"], - "creatorAffiliation": ["https://ror.org/04cdgtt98"], - "dateCreated": "2026-06-22T16:38:31.467Z", - "dateModified": "2026-07-20T10:12:00.000Z", - "keyword": ["creep", "high-temperature", "nickel-alloy"], - "name": "Creep test of Inconel 718 at 650°C", - "description": "Stress rupture test of Inconel 718 under a sustained load of 200 MPa at 650 °C according to DIN EN ISO 204.", - "applicableStandard": ["DIN EN ISO 204:2023-10"], - "testID": "CC-2026-001", - "specifiedTemperature": "650", - "initialStress": "200", - "testDuration": "P120D", - "percentageCreepExtension": "0.042", - "SingleCrystalOrientation": "45", - "usesMaterial": ["21.T11969/d8169782b57c7a9e9f01"], - "dataResources": [ - { - "id": "creep-exp-001/raw-data.csv", - "mimeType": "text/csv", - "dataObjectLocation": [ - "https://data.example.org/creep-exp-001/raw-data.csv" - ], - "spdxLicense": ["https://spdx.org/licenses/CC-BY-4.0"], - "checksum": [ - "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" - ] - }, - { - "id": "creep-exp-001/creep-curve.png", - "mimeType": "image/png", - "dataObjectLocation": [ - "https://data.example.org/creep-exp-001/creep-curve.png" - ], - "spdxLicense": ["https://spdx.org/licenses/CC-BY-4.0"], - "checksum": [ - "sha256:fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210" - ] - }, - { - "id": "creep-exp-001/measurement-log.json", - "mimeType": "application/json", - "dataObjectLocation": [ - "https://data.example.org/creep-exp-001/measurement-log.json" - ], - "spdxLicense": ["https://spdx.org/licenses/CC-BY-4.0"], - "checksum": [ - "sha256:1111111111111111111111111111111111111111111111111111111111111111" - ] - } - ] - }, - { - "id": "creep-exp-002", - "FDO_profile": [ - "21.T11969/077fe9c54ed5ed26fa54", - "21.T11969/222fb86c0b3bece35729" - ], - "creator": ["https://orcid.org/0009-0005-2800-4833"], - "creatorAffiliation": ["https://ror.org/04cdgtt98"], - "dateCreated": "2026-07-01T09:00:00.000Z", - "dateModified": "2026-07-30T16:45:00.000Z", - "keyword": ["creep", "steel", "CM247LC"], - "name": "Creep test of CM247LC at 850°C", - "description": "Creep test of the single-crystal superalloy CM247LC at 850 °C and 300 MPa.", - "applicableStandard": ["DIN EN ISO 204:2023-10"], - "testID": "CC-2026-002", - "specifiedTemperature": "850", - "initialStress": "300", - "testDuration": "P60D", - "percentageCreepExtension": "0.087", - "SingleCrystalOrientation": "0", - "usesMaterial": ["21.T11969/d8169782b57c7a9e9f01"], - "dataResources": [ - { - "id": "creep-exp-002/raw-data.csv", - "mimeType": "text/csv", - "dataObjectLocation": [ - "https://data.example.org/creep-exp-002/raw-data.csv" - ], - "spdxLicense": ["https://spdx.org/licenses/CC-BY-4.0"], - "checksum": [ - "sha256:2222222222222222222222222222222222222222222222222222222222222222" - ] - }, - { - "id": "creep-exp-002/creep-curve.png", - "mimeType": "image/png", - "dataObjectLocation": [ - "https://data.example.org/creep-exp-002/creep-curve.png" - ], - "spdxLicense": ["https://spdx.org/licenses/CC-BY-4.0"], - "checksum": [ - "sha256:3333333333333333333333333333333333333333333333333333333333333333" - ] - } - ] - } - ] -} diff --git a/packages/examples/assets/creep-profiles/Base.json b/packages/examples/assets/creep-profiles/Base.json deleted file mode 100644 index 7f7423b..0000000 --- a/packages/examples/assets/creep-profiles/Base.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "Identifier": "21.T11969/077fe9c54ed5ed26fa54", - "name": "Base", - "description": "Base profile containing fundamental metadata attributes for any FAIR Digital Object. Provides essential provenance, identification, and descriptive information.", - "versioning": { - "version": "0.0.1" - }, - "provenance": { - "contributors": [ - { - "Name": "Maximilian Inckmann", - "ORCID": "https://orcid.org/0009-0005-2800-4833" - } - ], - "creationDate": "2026-06-22T16:38:31.467Z", - "lastModificationDate": "2026-07-06T16:37:16.746Z" - }, - "ExpectedUse": "Foundation profile for all FAIR Digital Objects, ensuring consistent core metadata across diverse research outputs including datasets, software, publications, and experimental records.", - "References": [], - "Aliases": [ - "Foundation Profile", - "Minimal Metadata Profile" - ], - "Schema": { - "Type": "Object", - "Properties": [ - { - "Name": "FDO_profile", - "Title": "FDO profile", - "Description": "Handle identifier(s) pointing to the FDO profiles that defines the record structure for a FAIR Digital Object.", - "Type": "21.T11969/01e3f7ccb897f9c724dd", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "creator", - "Title": "Creator", - "Description": "ORCID URL(s) identifying the creator(s) or author(s) of a research output, dataset, or digital object.", - "Type": "21.T11969/7c67083a5d218e544063", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "creatorAffiliation", - "Title": "Creator Affiliation", - "Description": "ROR (Research Organization Registry) identifier(s) for the institutional affiliation(s) of creators and contributors.", - "Type": "21.T11969/ea9f6b3d78c6608fe801", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "dateCreated", - "Title": "Date Created", - "Description": "ISO 8601 datetime stamp indicating when a resource, dataset, or digital object was originally created.", - "Type": "21.T11969/29f92bd203dd3eaa5a1f", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "dateModified", - "Title": "Date Modified", - "Description": "ISO 8601 datetime stamp indicating when a resource, dataset, or digital object was last modified or updated.", - "Type": "21.T11969/397d831aa3a9d18eb52c", - "Properties": { - "Cardinality": "0 - 1" - } - }, - { - "Name": "keyword", - "Title": "Keyword", - "Description": "Subject keyword or phrase describing the topical content of a resource for discovery and classification purposes.", - "Type": "21.T11969/793ff5c33c3aeb32907a", - "Properties": { - "Cardinality": "0 - n" - } - }, - { - "Name": "name", - "Title": "Name", - "Description": "Human-readable name or title assigned to a resource for identification and display purposes.", - "Type": "21.T11969/bd3e9fb9b606d2198c9e", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "description", - "Title": "Description", - "Description": "Free-text description providing contextual information about a resource's content, purpose, or characteristics.", - "Type": "21.T11969/880724416f5857987e70", - "Properties": { - "Cardinality": "0 - n" - } - } - ] - } -} \ No newline at end of file diff --git a/packages/examples/assets/creep-profiles/CreepExperiment.json b/packages/examples/assets/creep-profiles/CreepExperiment.json deleted file mode 100644 index 7e13567..0000000 --- a/packages/examples/assets/creep-profiles/CreepExperiment.json +++ /dev/null @@ -1,123 +0,0 @@ -{ - "Identifier": "21.T11969/222fb86c0b3bece35729", - "name": "CreepExperiment", - "description": "Profile for creep testing experiments per DIN EN ISO 204:2023-10, capturing test conditions, parameters, and relationships to materials and data.", - "versioning": { - "version": "0.0.1" - }, - "provenance": { - "contributors": [ - { - "Name": "Maximilian Inckmann", - "ORCID": "https://orcid.org/0009-0005-2800-4833" - } - ], - "creationDate": "2026-06-22T16:39:29.497Z", - "lastModificationDate": "2026-06-22T16:39:29.497Z" - }, - "ExpectedUse": "Comprehensive metadata for high-temperature creep tests on metallic materials, including stress rupture testing and time-dependent deformation measurements under sustained load.", - "References": [ - "https://dx.doi.org/10.31030/3485273", - "https://www.dinmedia.de/en/standard/din-en-iso-204/371676068" - ], - "Aliases": [ - "Creep Test Profile", - "Stress Rupture Test Profile", - "High-Temperature Testing Profile" - ], - "Schema": { - "Type": "Object", - "Properties": [ - { - "Name": "applicableStandard", - "Title": "Applicable Standard", - "Description": "Identifier or designation of a technical standard, specification, or protocol governing a procedure, test, or data format.", - "Type": "21.T11969/dda596702b20205cba36", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "testID", - "Title": "Test ID", - "Description": "Unique identifier assigned to a specific test, experiment, or measurement procedure instance.", - "Type": "21.T11969/1a34a6966f91cc341f58", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "specifiedTemperature", - "Title": "Specified Temperature", - "Description": "Test temperature value in degrees Celsius (°C) for experimental conditions or material testing procedures.", - "Type": "21.T11969/ac4a911ffb09772718e3", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "initialStress", - "Title": "Initial Stress", - "Description": "Applied mechanical stress value in megapascals (MPa) at the start of a materials testing experiment.", - "Type": "21.T11969/8bd53487030550ee2e94", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "testDuration", - "Title": "Test Duration", - "Description": "Duration of an experiment or test procedure expressed in ISO 8601 duration format.", - "Type": "21.T11969/7e84faadd49ac88d02b8", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "percentageCreepExtension", - "Title": "Percentage Creep Extension", - "Description": "Creep strain expressed as a dimensionless ratio (0-1) representing the relative elongation of a material under sustained load.", - "Type": "21.T11969/4be978cac878da94105e", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "SingleCrystalOrientation", - "Title": "Single Crystal Orientation", - "Description": "Crystallographic orientation angle in degrees (0-360) specifying the angular position of a single crystal relative to a reference axis.", - "Type": "21.T11969/4597cf0db467d7e365a9", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "hasData", - "Title": "Has Data", - "Description": "Handle identifier(s) for data resources associated with or derived from this resource.", - "Type": "21.T11969/cc230f978e8add2e2520", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "hasMetadata", - "Title": "Has Metadata", - "Description": "Handle identifier(s) for metadata resources describing or accompanying this resource.", - "Type": "21.T11969/d0773859091aeb451528", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "usesMaterial", - "Title": "Uses Material", - "Description": "Handle identifier(s) for material samples or substances used in an experiment or process.", - "Type": "21.T11969/2dced98076fda9cbf0ef", - "Properties": { - "Cardinality": "1 - n" - } - } - ] - } -} \ No newline at end of file diff --git a/packages/examples/assets/creep-profiles/DataResource.json b/packages/examples/assets/creep-profiles/DataResource.json deleted file mode 100644 index a4f1d34..0000000 --- a/packages/examples/assets/creep-profiles/DataResource.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "Identifier": "21.T11969/0738c2ef35faef0fb552", - "name": "DataResource", - "description": "Profile for digital data resources specifying format, location, licensing, and integrity verification information.", - "versioning": { - "version": "0.0.1" - }, - "provenance": { - "contributors": [ - { - "Name": "Maximilian Inckmann", - "ORCID": "https://orcid.org/0009-0005-2800-4833" - } - ], - "creationDate": "2026-06-22T16:40:34.448Z", - "lastModificationDate": "2026-06-22T16:40:34.448Z" - }, - "ExpectedUse": "Metadata for downloadable data files, bitstreams, and digital objects requiring format specification, access locations, license terms, and integrity verification.", - "References": [], - "Aliases": [ - "Bitstream Metadata Profile", - "Data File Profile" - ], - "Schema": { - "Type": "Object", - "Properties": [ - { - "Name": "mimeType", - "Title": "Media Type", - "Description": "Media type (MIME type) identifier specifying the format of a digital resource or bitstream.", - "Type": "21.T11969/3313b863118ed5eb0ded", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "dataObjectLocation", - "Title": "Data Object Location", - "Description": "URL(s) pointing to the location(s) where the actual digital object bitstream or data file can be accessed or downloaded.", - "Type": "21.T11969/479febb2bbe8400da547", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "spdxLicense", - "Title": "SPDX License", - "Description": "SPDX license URL(s) specifying the license terms under which a resource is distributed.", - "Type": "21.T11969/623654b1072ae7b88202", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "checksum", - "Title": "Checksum", - "Description": "Cryptographic checksum value for verifying data integrity and detecting file corruption or tampering.", - "Type": "21.T11969/a80ed2ef79e22f1d8af8", - "Properties": { - "Cardinality": "1 - n" - } - } - ] - } -} \ No newline at end of file diff --git a/packages/examples/assets/creep-profiles/Helmholtz.json b/packages/examples/assets/creep-profiles/Helmholtz.json deleted file mode 100644 index 8c97d44..0000000 --- a/packages/examples/assets/creep-profiles/Helmholtz.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "Identifier": "21.T11969/4f19ada2a020aaa8a14a", - "name": "Helmholtz", - "description": "Helmholtz Association-specific metadata profile for classifying research outputs according to strategic research areas and program-oriented funding structures.", - "versioning": { - "version": "0.0.1" - }, - "provenance": { - "contributors": [ - { - "Name": "Maximilian Inckmann", - "ORCID": "https://orcid.org/0009-0005-2800-4833" - } - ], - "creationDate": "2026-06-22T16:41:14.348Z", - "lastModificationDate": "2026-06-22T16:41:14.348Z" - }, - "ExpectedUse": "Metadata enrichment for Helmholtz Association research outputs, enabling portfolio analysis, strategic reporting, and alignment with institutional research classification schemes.", - "References": [ - "https://www.helmholtz.de/en/research/" - ], - "Schema": { - "Type": "Object", - "Properties": [ - { - "Name": "helmholtzResearchArea", - "Title": "Helmholtz Research Area", - "Description": "Helmholtz Association research area classification from the predefined set of six strategic research fields.", - "Type": "21.T11969/ed4732b6dc70be0f1b22", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "helmholtzPoFStructure", - "Title": "Program-Oriented Funding Structure", - "Description": "Helmholtz Program-Oriented Funding (PoF) structure identifier indicating the hierarchical research program classification.", - "Type": "21.T11969/e5cb2389246c17ee0503", - "Properties": { - "Cardinality": "1 - n" - } - } - ] - } -} \ No newline at end of file diff --git a/packages/examples/assets/creep-profiles/Material.json b/packages/examples/assets/creep-profiles/Material.json deleted file mode 100644 index b84190d..0000000 --- a/packages/examples/assets/creep-profiles/Material.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "Identifier": "21.T11969/d8169782b57c7a9e9f01", - "name": "Material", - "description": "Profile for material samples documenting identification, visual characterization, composition, and thermal processing history.", - "versioning": { - "version": "0.0.1" - }, - "provenance": { - "contributors": [ - { - "Name": "Maximilian Inckmann", - "ORCID": "https://orcid.org/0009-0005-2800-4833" - } - ], - "creationDate": "2026-06-22T16:42:11.552Z", - "lastModificationDate": "2026-06-22T16:42:11.552Z" - }, - "ExpectedUse": "Metadata for physical material specimens, alloy batches, and reference materials in materials science workflows, linking samples to characterization data and experimental use.", - "References": [], - "Aliases": [ - "Material Sample Profile", - "Specimen Metadata Profile", - "Alloy Characterization Profile" - ], - "Schema": { - "Type": "Object", - "Properties": [ - { - "Name": "materialID", - "Title": "Material ID", - "Description": "Unique identifier assigned to a specific material sample, alloy batch, or substance.", - "Type": "21.T11969/716805eef0349802dc9a", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "previewImage", - "Title": "Preview Image", - "Description": "URL(s) to thumbnail or preview images providing visual representation of a resource's content.", - "Type": "21.T11969/925e3f9925a88476ffba", - "Properties": { - "Cardinality": "0 - n" - } - }, - { - "Name": "semImage", - "Title": "SEM Image", - "Description": "Handle identifier for a scanning electron microscopy (SEM) image associated with a material sample or experiment.", - "Type": "21.T11969/19a94f596420bb274408", - "Properties": { - "Cardinality": "0 - n" - } - }, - { - "Name": "hasChemicalComposition", - "Title": "Has Chemical Composition", - "Description": "Handle identifier for a resource containing the chemical composition data of a material sample.", - "Type": "21.T11969/e32cfb93d7fc61ce3ca5", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "hasHeatTreatment", - "Title": "Has Heat Treatment", - "Description": "Handle identifier for a resource documenting the heat treatment process applied to a material sample.", - "Type": "21.T11969/766ae14d72b49cfb5273", - "Properties": { - "Cardinality": "0 - n" - } - } - ] - } -} \ No newline at end of file diff --git a/packages/examples/assets/creep-profiles/NFDI.json b/packages/examples/assets/creep-profiles/NFDI.json deleted file mode 100644 index be7b15d..0000000 --- a/packages/examples/assets/creep-profiles/NFDI.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "Identifier": "21.T11969/175a75397933f1b370af", - "name": "NFDI", - "description": "National Research Data Infrastructure (NFDI) profile for recording consortium affiliations and grant funding information.", - "versioning": { - "version": "0.0.1" - }, - "provenance": { - "contributors": [ - { - "Name": "Maximilian Inckmann", - "ORCID": "https://orcid.org/0009-0005-2800-4833" - } - ], - "creationDate": "2026-06-22T16:42:43.726Z", - "lastModificationDate": "2026-06-22T16:42:43.726Z" - }, - "ExpectedUse": "Documentation of NFDI consortium involvement and funding acknowledgments for German research data infrastructure initiatives.", - "References": [ - "https://www.nfdi.de/" - ], - "Aliases": [ - "NFDI Consortium Profile" - ], - "Schema": { - "Type": "Object", - "Properties": [ - { - "Name": "nfdiConsortia", - "Title": "NFDI Consortium", - "Description": "NFDI (National Research Data Infrastructure) consortium name or identifier indicating membership or affiliation.", - "Type": "21.T11969/3b01aa9a09f0fab04265", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "grantNumber", - "Title": "Grant Number", - "Description": "Grant award number or identifier assigned by a funding organization to a research project.", - "Type": "21.T11969/1c25f48eb6a47b22a9cc", - "Properties": { - "Cardinality": "1 - n" - } - } - ] - } -} \ No newline at end of file diff --git a/packages/examples/assets/creep-profiles/Publication.json b/packages/examples/assets/creep-profiles/Publication.json deleted file mode 100644 index 23c726e..0000000 --- a/packages/examples/assets/creep-profiles/Publication.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "Identifier": "21.T11969/e00441c49bf6cb62a4a5", - "name": "Publication", - "description": "Profile for scholarly publications and citable research outputs with persistent identifiers, publication metadata, and attribution information.", - "versioning": { - "version": "0.0.1" - }, - "provenance": { - "contributors": [ - { - "Name": "Maximilian Inckmann", - "ORCID": "https://orcid.org/0009-0005-2800-4833" - } - ], - "creationDate": "2026-06-22T16:43:59.590Z", - "lastModificationDate": "2026-06-22T16:43:59.590Z" - }, - "ExpectedUse": "Metadata for journal articles, conference papers, preprints, datasets with DOIs, software publications, and other formally published research outputs requiring citation metadata.", - "Aliases": [ - "Scholarly Publication Profile", - "Citable Resource Profile", - "DOI Publication Profile" - ], - "Schema": { - "Type": "Object", - "Properties": [ - { - "Name": "doi", - "Title": "DOI", - "Description": "DOI (Digital Object Identifier) providing a persistent, resolvable identifier for a digital object.", - "Type": "21.T11969/48e563f148dc04d8b31c", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "dataCitePublicationType", - "Title": "Publication Type", - "Description": "DataCite ResourceTypeGeneral term indicating the broad category of a registered resource.", - "Type": "21.T11969/48dbf6a89f9748ae4ead", - "Properties": { - "Cardinality": "1 - n" - } - }, - { - "Name": "publisher", - "Title": "Publisher", - "Description": "Name of the organization or entity responsible for making a resource available.", - "Type": "21.T11969/cdd96207a7dfbcc0db93", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "datePublished", - "Title": "Date Published", - "Description": "ISO 8601 datetime stamp indicating when a resource was formally published or made publicly available.", - "Type": "21.T11969/0c9b86e828976a85d4f2", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "creator", - "Title": "Creator", - "Description": "ORCID URL(s) identifying the creator(s) or author(s) of a research output, dataset, or digital object.", - "Type": "21.T11969/7c67083a5d218e544063", - "Properties": { - "Cardinality": "1 - n" - } - } - ] - } -} \ No newline at end of file diff --git a/packages/examples/assets/creep-profiles/Versionable.json b/packages/examples/assets/creep-profiles/Versionable.json deleted file mode 100644 index 2a36d09..0000000 --- a/packages/examples/assets/creep-profiles/Versionable.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "Identifier": "21.T11969/6c663a0695a411803d70", - "name": "Versionable", - "description": "Versioning profile enabling tracking of version chains, release sequences, and relationships between iterations of evolving resources.", - "versioning": { - "version": "0.0.1" - }, - "provenance": { - "contributors": [ - { - "Name": "Maximilian Inckmann", - "ORCID": "https://orcid.org/0009-0005-2800-4833" - } - ], - "creationDate": "2026-06-22T16:44:44.652Z", - "lastModificationDate": "2026-06-22T16:44:44.652Z" - }, - "ExpectedUse": "Version management for software releases, dataset updates, iterative publications, and any digital objects undergoing sequential development with explicit version relationships.", - "References": [ - "https://semver.org" - ], - "Aliases": [ - "Version Control Profile", - "Release Chain Profile" - ], - "Schema": { - "Type": "Object", - "Properties": [ - { - "Name": "version", - "Title": "Version", - "Description": "Semantic version identifier for a specific iteration or release of a resource.", - "Type": "21.T11969/be1ae3492b235faad933", - "Properties": { - "Cardinality": "1" - } - }, - { - "Name": "nextVersion", - "Title": "Next Version", - "Description": "Handle identifier pointing to a newer version of the same resource.", - "Type": "21.T11969/7f1a6afddcfeefbf195b", - "Properties": { - "Cardinality": "0 - 1" - } - }, - { - "Name": "previousVersion", - "Title": "Previous Version", - "Description": "Handle identifier pointing to an earlier version of the same resource.", - "Type": "21.T11969/7c97f00a2a95826c1a8f", - "Properties": { - "Cardinality": "0 - 1" - } - }, - { - "Name": "latestVersion", - "Title": "Latest Version", - "Description": "Handle identifier pointing to the most current published version of a resource.", - "Type": "21.T11969/2b4d6ceda80ddd63f7a9", - "Properties": { - "Cardinality": "0 - 1" - } - } - ] - } -} \ No newline at end of file diff --git a/packages/examples/package.json b/packages/examples/package.json deleted file mode 100644 index b7373fc..0000000 --- a/packages/examples/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "@fdo-sdk/examples", - "version": "0.1.0", - "description": "", - "main": "index.js", - "scripts": { - "build": "tsc", - "build-and-run": "pnpm run build && pnpm run run", - "run": "node ./dist/example.js", - "run:mapping": "node ./dist/localTestingBackend.js", - "build-and-run:mapping": "pnpm run build && pnpm run run:mapping" - }, - "keywords": [], - "author": "", - "license": "ISC", - "type": "module", - "devDependencies": { - "@types/node": "^26.2.0", - "typescript": "^6.0.3" - }, - "dependencies": { - "@fdo-sdk/mapping": "workspace:*", - "@fdo-sdk/primitives": "workspace:*" - } -} diff --git a/packages/examples/scripts/generate-creep-profiles.mjs b/packages/examples/scripts/generate-creep-profiles.mjs deleted file mode 100644 index 235a431..0000000 --- a/packages/examples/scripts/generate-creep-profiles.mjs +++ /dev/null @@ -1,119 +0,0 @@ -import { readdir, readFile, writeFile } from "node:fs/promises" -import { dirname, join } from "node:path" -import { fileURLToPath } from "node:url" - -const here = dirname(fileURLToPath(import.meta.url)) - -const profilesDir = join(here, "..", "assets", "creep-profiles") -const outFile = join(here, "..", "src", "generated", "creepProfiles.ts") - -const files = (await readdir(profilesDir)) - .filter((f) => f.endsWith(".json")) - .sort() - -const typeFor = (cardinality) => { - const multi = cardinality.includes("n") - const optional = cardinality.startsWith("0") - const base = multi ? "string | string[]" : "string" - return { base, optional } -} - -const profiles = [] -for (const file of files) { - const json = JSON.parse(await readFile(join(profilesDir, file), "utf8")) - const name = json.name ?? file.replace(/\.json$/, "") - const props = [] - for (const prop of json.Schema.Properties) { - const { base, optional } = typeFor(prop.Properties?.Cardinality ?? "1") - props.push({ - key: prop.Name, - comment: prop.Description, - title: prop.Title ?? prop.Name, - base, - optional, - pid: prop.Type, - }) - } - profiles.push({ name, pid: json.Identifier, props }) -} - -const key = (name) => - /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name) -const camel = (name) => name.charAt(0).toLowerCase() + name.slice(1) - -let out = "" -out += - "/* Generated by " + - here.split("/").pop() + - "/generate-creep-profiles.mjs. Do not edit manually. */\n" -out += - 'import type { Attribute, ProfileDefinition, RecordValue } from "@fdo-sdk/primitives"\n' -out += 'import { DefaultProfile } from "@fdo-sdk/primitives"\n' -out += "\n" - -for (const { name, pid, props } of profiles) { - out += "export type " + name + "ProfileAttributes = {\n" - for (const prop of props) { - out += " /** " + prop.comment + " */\n" - out += - " " + - key(prop.key) + - (prop.optional ? "?" : "") + - ": " + - prop.base + - "\n" - } - out += "}\n\n" - - out += "export const " + camel(name) + "Attributes = {\n" - for (const prop of props) { - out += " " + key(prop.key) + ": {\n" - out += ' pid: "' + prop.pid + '",\n' - out += ' readableName: "' + prop.title + '",\n' - out += " },\n" - } - out += - "} as const satisfies Record>\n\n" - - out += - "export const " + - name + - "ProfileDefinition: ProfileDefinition<" + - name + - "ProfileAttributes> = {\n" - out += ' pid: "' + pid + '",\n' - out += ' readableName: "' + name + '",\n' - out += " mapping: {\n" - for (const prop of props) { - out += - " " + key(prop.key) + ": " + JSON.stringify(prop.pid) + ",\n" - } - out += " },\n" - out += "}\n\n" - - out += - "export const " + - name + - "Profile = new DefaultProfile(" + - name + - "ProfileDefinition)\n\n" -} - -out += "export const creepProfiles = {\n" -for (const { name } of profiles) { - out += " " + key(name) + ": " + name + "Profile,\n" -} -out += "}\n" - -await writeFile(outFile, out) - -console.log("Wrote " + outFile) -console.log( - "Profiles: " + - profiles.map((p) => p.name).join(", ") + - " (" + - profiles.length + - " total)", -) diff --git a/packages/examples/src/example.ts b/packages/examples/src/example.ts deleted file mode 100644 index eeb8676..0000000 --- a/packages/examples/src/example.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { - BaseProfile, - CreepExperimentProfile, - DataResourceProfile, - creepExperimentAttributes, -} from "./generated/creepProfiles.js" -import { ContinuousMappingContext, type MappingContext } from "@fdo-sdk/mapping" -import { type FDORecord, skip, referenceBidi } from "@fdo-sdk/primitives" -import experimentsData from "../assets/creep-experiments.json" with { type: "json" } -import * as fs from "node:fs" -type Experiment = (typeof experimentsData)["creepExperiments"][number] -type DataFile = Experiment["dataResources"][number] - -const mappingPID = "TEST/creep-experiments" -const context: MappingContext = new ContinuousMappingContext(mappingPID) - -function addDataResource(record: FDORecord, file: DataFile) { - record.addProfile(DataResourceProfile, { - mimeType: file.mimeType, - dataObjectLocation: file.dataObjectLocation, - spdxLicense: file.spdxLicense, - checksum: file.checksum, - }) -} - -function addCreepExperiment(record: FDORecord, experiment: Experiment) { - record.addProfile(BaseProfile, { - FDO_profile: experiment.FDO_profile, - creator: experiment.creator, - creatorAffiliation: experiment.creatorAffiliation, - dateCreated: experiment.dateCreated, - dateModified: experiment.dateModified, - keyword: experiment.keyword, - name: experiment.name, - description: experiment.description, - }) - - record.addProfile(CreepExperimentProfile, { - applicableStandard: experiment.applicableStandard, - testID: experiment.testID, - specifiedTemperature: experiment.specifiedTemperature, - initialStress: experiment.initialStress, - testDuration: experiment.testDuration, - percentageCreepExtension: experiment.percentageCreepExtension, - SingleCrystalOrientation: experiment.SingleCrystalOrientation, - hasData: experiment.dataResources.map((file) => - referenceBidi( - creepExperimentAttributes.hasMetadata, - `LOCAL/${file.id}`, - ), - ), - hasMetadata: skip(), - usesMaterial: experiment.usesMaterial, - }) -} - -for (const experiment of experimentsData.creepExperiments) { - for (const file of experiment.dataResources) { - addDataResource(context.newRecord(`LOCAL/${file.id}`), file) - } - - addCreepExperiment(context.newRecord(`LOCAL/${experiment.id}`), experiment) -} - -// The graph is built before it is published: building realizes the -// bidirectional references, the result of the build is the mapping result. -// The result holds the records that are created by the mapping and the records -// that are updated by it. -const result = context.build() - -fs.writeFile( - "./result.json", - JSON.stringify({ create: result.create, update: result.update }, null, 2), - () => {}, -) -console.log("Resulting graph was written to result.json") diff --git a/packages/examples/src/generated/creepProfiles.ts b/packages/examples/src/generated/creepProfiles.ts deleted file mode 100644 index ce20a4a..0000000 --- a/packages/examples/src/generated/creepProfiles.ts +++ /dev/null @@ -1,414 +0,0 @@ -/* Generated by scripts/generate-creep-profiles.mjs. Do not edit manually. */ -import type { Attribute, ProfileDefinition, RecordValue } from "@fdo-sdk/primitives" -import { ConcreteProfile } from "@fdo-sdk/primitives" - -export type BaseProfileAttributes = { - /** Handle identifier(s) pointing to the FDO profiles that defines the record structure for a FAIR Digital Object. */ - FDO_profile: string | string[] - /** ORCID URL(s) identifying the creator(s) or author(s) of a research output, dataset, or digital object. */ - creator: string | string[] - /** ROR (Research Organization Registry) identifier(s) for the institutional affiliation(s) of creators and contributors. */ - creatorAffiliation: string | string[] - /** ISO 8601 datetime stamp indicating when a resource, dataset, or digital object was originally created. */ - dateCreated: string - /** ISO 8601 datetime stamp indicating when a resource, dataset, or digital object was last modified or updated. */ - dateModified?: string - /** Subject keyword or phrase describing the topical content of a resource for discovery and classification purposes. */ - keyword?: string | string[] - /** Human-readable name or title assigned to a resource for identification and display purposes. */ - name: string | string[] - /** Free-text description providing contextual information about a resource's content, purpose, or characteristics. */ - description?: string | string[] -} - -export const baseAttributes = { - FDO_profile: { - pid: "21.T11969/01e3f7ccb897f9c724dd", - readableName: "FDO profile", - }, - creator: { - pid: "21.T11969/7c67083a5d218e544063", - readableName: "Creator", - }, - creatorAffiliation: { - pid: "21.T11969/ea9f6b3d78c6608fe801", - readableName: "Creator Affiliation", - }, - dateCreated: { - pid: "21.T11969/29f92bd203dd3eaa5a1f", - readableName: "Date Created", - }, - dateModified: { - pid: "21.T11969/397d831aa3a9d18eb52c", - readableName: "Date Modified", - }, - keyword: { - pid: "21.T11969/793ff5c33c3aeb32907a", - readableName: "Keyword", - }, - name: { - pid: "21.T11969/bd3e9fb9b606d2198c9e", - readableName: "Name", - }, - description: { - pid: "21.T11969/880724416f5857987e70", - readableName: "Description", - }, -} as const satisfies Record> - -export const BaseProfileDefinition: ProfileDefinition = { - pid: "21.T11969/077fe9c54ed5ed26fa54", - readableName: "Base", - mapping: { - FDO_profile: "21.T11969/01e3f7ccb897f9c724dd", - creator: "21.T11969/7c67083a5d218e544063", - creatorAffiliation: "21.T11969/ea9f6b3d78c6608fe801", - dateCreated: "21.T11969/29f92bd203dd3eaa5a1f", - dateModified: "21.T11969/397d831aa3a9d18eb52c", - keyword: "21.T11969/793ff5c33c3aeb32907a", - name: "21.T11969/bd3e9fb9b606d2198c9e", - description: "21.T11969/880724416f5857987e70", - }, -} - -export const BaseProfile = new ConcreteProfile(BaseProfileDefinition) - -export type CreepExperimentProfileAttributes = { - /** Identifier or designation of a technical standard, specification, or protocol governing a procedure, test, or data format. */ - applicableStandard: string | string[] - /** Unique identifier assigned to a specific test, experiment, or measurement procedure instance. */ - testID: string - /** Test temperature value in degrees Celsius (°C) for experimental conditions or material testing procedures. */ - specifiedTemperature: string - /** Applied mechanical stress value in megapascals (MPa) at the start of a materials testing experiment. */ - initialStress: string - /** Duration of an experiment or test procedure expressed in ISO 8601 duration format. */ - testDuration: string - /** Creep strain expressed as a dimensionless ratio (0-1) representing the relative elongation of a material under sustained load. */ - percentageCreepExtension: string - /** Crystallographic orientation angle in degrees (0-360) specifying the angular position of a single crystal relative to a reference axis. */ - SingleCrystalOrientation: string - /** Handle identifier(s) for data resources associated with or derived from this resource. */ - hasData: string | string[] - /** Handle identifier(s) for metadata resources describing or accompanying this resource. */ - hasMetadata: string | string[] - /** Handle identifier(s) for material samples or substances used in an experiment or process. */ - usesMaterial: string | string[] -} - -export const creepExperimentAttributes = { - applicableStandard: { - pid: "21.T11969/dda596702b20205cba36", - readableName: "Applicable Standard", - }, - testID: { - pid: "21.T11969/1a34a6966f91cc341f58", - readableName: "Test ID", - }, - specifiedTemperature: { - pid: "21.T11969/ac4a911ffb09772718e3", - readableName: "Specified Temperature", - }, - initialStress: { - pid: "21.T11969/8bd53487030550ee2e94", - readableName: "Initial Stress", - }, - testDuration: { - pid: "21.T11969/7e84faadd49ac88d02b8", - readableName: "Test Duration", - }, - percentageCreepExtension: { - pid: "21.T11969/4be978cac878da94105e", - readableName: "Percentage Creep Extension", - }, - SingleCrystalOrientation: { - pid: "21.T11969/4597cf0db467d7e365a9", - readableName: "Single Crystal Orientation", - }, - hasData: { - pid: "21.T11969/cc230f978e8add2e2520", - readableName: "Has Data", - }, - hasMetadata: { - pid: "21.T11969/d0773859091aeb451528", - readableName: "Has Metadata", - }, - usesMaterial: { - pid: "21.T11969/2dced98076fda9cbf0ef", - readableName: "Uses Material", - }, -} as const satisfies Record> - -export const CreepExperimentProfileDefinition: ProfileDefinition = { - pid: "21.T11969/222fb86c0b3bece35729", - readableName: "CreepExperiment", - mapping: { - applicableStandard: "21.T11969/dda596702b20205cba36", - testID: "21.T11969/1a34a6966f91cc341f58", - specifiedTemperature: "21.T11969/ac4a911ffb09772718e3", - initialStress: "21.T11969/8bd53487030550ee2e94", - testDuration: "21.T11969/7e84faadd49ac88d02b8", - percentageCreepExtension: "21.T11969/4be978cac878da94105e", - SingleCrystalOrientation: "21.T11969/4597cf0db467d7e365a9", - hasData: "21.T11969/cc230f978e8add2e2520", - hasMetadata: "21.T11969/d0773859091aeb451528", - usesMaterial: "21.T11969/2dced98076fda9cbf0ef", - }, -} - -export const CreepExperimentProfile = new ConcreteProfile(CreepExperimentProfileDefinition) - -export type DataResourceProfileAttributes = { - /** Media type (MIME type) identifier specifying the format of a digital resource or bitstream. */ - mimeType: string - /** URL(s) pointing to the location(s) where the actual digital object bitstream or data file can be accessed or downloaded. */ - dataObjectLocation: string | string[] - /** SPDX license URL(s) specifying the license terms under which a resource is distributed. */ - spdxLicense: string | string[] - /** Cryptographic checksum value for verifying data integrity and detecting file corruption or tampering. */ - checksum: string | string[] -} - -export const dataResourceAttributes = { - mimeType: { - pid: "21.T11969/3313b863118ed5eb0ded", - readableName: "Media Type", - }, - dataObjectLocation: { - pid: "21.T11969/479febb2bbe8400da547", - readableName: "Data Object Location", - }, - spdxLicense: { - pid: "21.T11969/623654b1072ae7b88202", - readableName: "SPDX License", - }, - checksum: { - pid: "21.T11969/a80ed2ef79e22f1d8af8", - readableName: "Checksum", - }, -} as const satisfies Record> - -export const DataResourceProfileDefinition: ProfileDefinition = { - pid: "21.T11969/0738c2ef35faef0fb552", - readableName: "DataResource", - mapping: { - mimeType: "21.T11969/3313b863118ed5eb0ded", - dataObjectLocation: "21.T11969/479febb2bbe8400da547", - spdxLicense: "21.T11969/623654b1072ae7b88202", - checksum: "21.T11969/a80ed2ef79e22f1d8af8", - }, -} - -export const DataResourceProfile = new ConcreteProfile(DataResourceProfileDefinition) - -export type HelmholtzProfileAttributes = { - /** Helmholtz Association research area classification from the predefined set of six strategic research fields. */ - helmholtzResearchArea: string | string[] - /** Helmholtz Program-Oriented Funding (PoF) structure identifier indicating the hierarchical research program classification. */ - helmholtzPoFStructure: string | string[] -} - -export const helmholtzAttributes = { - helmholtzResearchArea: { - pid: "21.T11969/ed4732b6dc70be0f1b22", - readableName: "Helmholtz Research Area", - }, - helmholtzPoFStructure: { - pid: "21.T11969/e5cb2389246c17ee0503", - readableName: "Program-Oriented Funding Structure", - }, -} as const satisfies Record> - -export const HelmholtzProfileDefinition: ProfileDefinition = { - pid: "21.T11969/4f19ada2a020aaa8a14a", - readableName: "Helmholtz", - mapping: { - helmholtzResearchArea: "21.T11969/ed4732b6dc70be0f1b22", - helmholtzPoFStructure: "21.T11969/e5cb2389246c17ee0503", - }, -} - -export const HelmholtzProfile = new ConcreteProfile(HelmholtzProfileDefinition) - -export type MaterialProfileAttributes = { - /** Unique identifier assigned to a specific material sample, alloy batch, or substance. */ - materialID: string - /** URL(s) to thumbnail or preview images providing visual representation of a resource's content. */ - previewImage?: string | string[] - /** Handle identifier for a scanning electron microscopy (SEM) image associated with a material sample or experiment. */ - semImage?: string | string[] - /** Handle identifier for a resource containing the chemical composition data of a material sample. */ - hasChemicalComposition: string - /** Handle identifier for a resource documenting the heat treatment process applied to a material sample. */ - hasHeatTreatment?: string | string[] -} - -export const materialAttributes = { - materialID: { - pid: "21.T11969/716805eef0349802dc9a", - readableName: "Material ID", - }, - previewImage: { - pid: "21.T11969/925e3f9925a88476ffba", - readableName: "Preview Image", - }, - semImage: { - pid: "21.T11969/19a94f596420bb274408", - readableName: "SEM Image", - }, - hasChemicalComposition: { - pid: "21.T11969/e32cfb93d7fc61ce3ca5", - readableName: "Has Chemical Composition", - }, - hasHeatTreatment: { - pid: "21.T11969/766ae14d72b49cfb5273", - readableName: "Has Heat Treatment", - }, -} as const satisfies Record> - -export const MaterialProfileDefinition: ProfileDefinition = { - pid: "21.T11969/d8169782b57c7a9e9f01", - readableName: "Material", - mapping: { - materialID: "21.T11969/716805eef0349802dc9a", - previewImage: "21.T11969/925e3f9925a88476ffba", - semImage: "21.T11969/19a94f596420bb274408", - hasChemicalComposition: "21.T11969/e32cfb93d7fc61ce3ca5", - hasHeatTreatment: "21.T11969/766ae14d72b49cfb5273", - }, -} - -export const MaterialProfile = new ConcreteProfile(MaterialProfileDefinition) - -export type NFDIProfileAttributes = { - /** NFDI (National Research Data Infrastructure) consortium name or identifier indicating membership or affiliation. */ - nfdiConsortia: string | string[] - /** Grant award number or identifier assigned by a funding organization to a research project. */ - grantNumber: string | string[] -} - -export const nFDIAttributes = { - nfdiConsortia: { - pid: "21.T11969/3b01aa9a09f0fab04265", - readableName: "NFDI Consortium", - }, - grantNumber: { - pid: "21.T11969/1c25f48eb6a47b22a9cc", - readableName: "Grant Number", - }, -} as const satisfies Record> - -export const NFDIProfileDefinition: ProfileDefinition = { - pid: "21.T11969/175a75397933f1b370af", - readableName: "NFDI", - mapping: { - nfdiConsortia: "21.T11969/3b01aa9a09f0fab04265", - grantNumber: "21.T11969/1c25f48eb6a47b22a9cc", - }, -} - -export const NFDIProfile = new ConcreteProfile(NFDIProfileDefinition) - -export type PublicationProfileAttributes = { - /** DOI (Digital Object Identifier) providing a persistent, resolvable identifier for a digital object. */ - doi: string - /** DataCite ResourceTypeGeneral term indicating the broad category of a registered resource. */ - dataCitePublicationType: string | string[] - /** Name of the organization or entity responsible for making a resource available. */ - publisher: string - /** ISO 8601 datetime stamp indicating when a resource was formally published or made publicly available. */ - datePublished: string - /** ORCID URL(s) identifying the creator(s) or author(s) of a research output, dataset, or digital object. */ - creator: string | string[] -} - -export const publicationAttributes = { - doi: { - pid: "21.T11969/48e563f148dc04d8b31c", - readableName: "DOI", - }, - dataCitePublicationType: { - pid: "21.T11969/48dbf6a89f9748ae4ead", - readableName: "Publication Type", - }, - publisher: { - pid: "21.T11969/cdd96207a7dfbcc0db93", - readableName: "Publisher", - }, - datePublished: { - pid: "21.T11969/0c9b86e828976a85d4f2", - readableName: "Date Published", - }, - creator: { - pid: "21.T11969/7c67083a5d218e544063", - readableName: "Creator", - }, -} as const satisfies Record> - -export const PublicationProfileDefinition: ProfileDefinition = { - pid: "21.T11969/e00441c49bf6cb62a4a5", - readableName: "Publication", - mapping: { - doi: "21.T11969/48e563f148dc04d8b31c", - dataCitePublicationType: "21.T11969/48dbf6a89f9748ae4ead", - publisher: "21.T11969/cdd96207a7dfbcc0db93", - datePublished: "21.T11969/0c9b86e828976a85d4f2", - creator: "21.T11969/7c67083a5d218e544063", - }, -} - -export const PublicationProfile = new ConcreteProfile(PublicationProfileDefinition) - -export type VersionableProfileAttributes = { - /** Semantic version identifier for a specific iteration or release of a resource. */ - version: string - /** Handle identifier pointing to a newer version of the same resource. */ - nextVersion?: string - /** Handle identifier pointing to an earlier version of the same resource. */ - previousVersion?: string - /** Handle identifier pointing to the most current published version of a resource. */ - latestVersion?: string -} - -export const versionableAttributes = { - version: { - pid: "21.T11969/be1ae3492b235faad933", - readableName: "Version", - }, - nextVersion: { - pid: "21.T11969/7f1a6afddcfeefbf195b", - readableName: "Next Version", - }, - previousVersion: { - pid: "21.T11969/7c97f00a2a95826c1a8f", - readableName: "Previous Version", - }, - latestVersion: { - pid: "21.T11969/2b4d6ceda80ddd63f7a9", - readableName: "Latest Version", - }, -} as const satisfies Record> - -export const VersionableProfileDefinition: ProfileDefinition = { - pid: "21.T11969/6c663a0695a411803d70", - readableName: "Versionable", - mapping: { - version: "21.T11969/be1ae3492b235faad933", - nextVersion: "21.T11969/7f1a6afddcfeefbf195b", - previousVersion: "21.T11969/7c97f00a2a95826c1a8f", - latestVersion: "21.T11969/2b4d6ceda80ddd63f7a9", - }, -} - -export const VersionableProfile = new ConcreteProfile(VersionableProfileDefinition) - -export const creepProfiles = { - Base: BaseProfile, - CreepExperiment: CreepExperimentProfile, - DataResource: DataResourceProfile, - Helmholtz: HelmholtzProfile, - Material: MaterialProfile, - NFDI: NFDIProfile, - Publication: PublicationProfile, - Versionable: VersionableProfile, -} diff --git a/packages/examples/src/localTestingBackend.ts b/packages/examples/src/localTestingBackend.ts deleted file mode 100644 index f9723cc..0000000 --- a/packages/examples/src/localTestingBackend.ts +++ /dev/null @@ -1,636 +0,0 @@ -/** - * A comprehensive example for `LocalTestingBackend`, the in-memory backend - * that stands in for a real PID service during local testing. - * - * The example walks through the full lifecycle of a mapping: - * - * 1. Building a local graph of FDO records from two profiles - * 2. Realizing bidirectional references via `MappingContext.build()` - * 3. Publishing the built mapping result through a `PublishAdapter` - * 4. Resolving records again through a `ResolveAdapter` - * 5. The high level FDO record of the mapping and the published records, - * which hold no local IDs except their own - * 6. Snapshot semantics of resolved records - * 7. An update cycle (the same mapping procedure runs a second time on - * changed source data: modify, add and delete records, republish, PIDs - * stay stable) - * 8. Isolation between mappings (scoped graphs, shared store) - * 9. Publishing without a mapping (a single record or a whole graph) - * 10. Resetting the store between test runs - * - * Everything is typed against the interfaces (`MappingContext`, - * `MappingResult`, `ContinuousPublishAdapter`, `ResolveAdapter`, `FDOGraph`, - * `FDORecord`, `Profile`, ...) so the example would work unchanged with a - * different context or backend implementation. The only concrete classes used - * are `ConcreteMappingContext` (constructed, then consumed as - * `MappingContext`), `DefaultProfile` (the standard way to define a - * profile) and `LocalTestingBackend` itself — the latter also exposes - * `resetStore()` as a static method that no interface covers. - */ -import { - ConcreteProfile, - keep, - reference, - referenceBidi, - skip, - type Attribute, - type LocalID, - type PID, - type Profile, - type ProfileDefinition, - type PublishedLocalFDORecord, - type ReadOnlyFDOGraph, -} from "@fdo-sdk/primitives" -import { - ContinuousMappingContext, - LocalTestingBackend, - type ContinuousPublishAdapter, - type ContinuousPublishResult, - type ContinuousResolveAdapter, - type MappingContext, - type MappingResult, -} from "@fdo-sdk/mapping" - -// --------------------------------------------------------------------------- -// The domain: a small self-contained "dataset publishing" mapping with -// dataset records, author records and supplement records. -// --------------------------------------------------------------------------- - -const mappingPID: PID = "TEST/mapping-example" -const otherMappingPID: PID = "TEST/mapping-other" - -// Attribute definitions, shared by the profiles and the example code below. -const nameAttr: Attribute = { pid: "attr/name", readableName: "name" } -const descriptionAttr: Attribute = { - pid: "attr/description", - readableName: "description", -} -const keywordAttr: Attribute = { - pid: "attr/keyword", - readableName: "keyword", -} -const licenseAttr: Attribute = { - pid: "attr/license", - readableName: "license", -} -const hasAuthorAttr: Attribute = { - pid: "attr/hasAuthor", - readableName: "hasAuthor", -} -const hasPartAttr: Attribute = { - pid: "attr/hasPart", - readableName: "hasPart", -} -const affiliationAttr: Attribute = { - pid: "attr/affiliation", - readableName: "affiliation", -} -const authoredDatasetsAttr: Attribute = { - pid: "attr/authoredDatasets", - readableName: "authoredDatasets", -} -const titleAttr: Attribute = { - pid: "attr/title", - readableName: "title", -} -const formatAttr: Attribute = { - pid: "attr/format", - readableName: "format", -} - -type DatasetAttributes = { - name: string - description: string - keyword: string[] - license: string - hasAuthor: string[] - hasPart: string[] -} - -type AuthorAttributes = { - name: string - affiliation: string - /** Back-reference, filled in by `MappingContext.build()` — see `skip()` below */ - authoredDatasets: string[] -} - -const datasetDef: ProfileDefinition = { - pid: "profile/dataset", - readableName: "Dataset Profile", - mapping: { - name: nameAttr.pid, - description: descriptionAttr.pid, - keyword: keywordAttr.pid, - license: licenseAttr.pid, - hasAuthor: hasAuthorAttr.pid, - hasPart: hasPartAttr.pid, - }, -} - -const authorDef: ProfileDefinition = { - pid: "profile/author", - readableName: "Author Profile", - mapping: { - name: nameAttr.pid, - affiliation: affiliationAttr.pid, - authoredDatasets: authoredDatasetsAttr.pid, - }, -} - -// Profiles are consumed through the `Profile` interface, so the concrete -// implementation behind them can be swapped without touching any consumer. -const DatasetProfile: Profile = new ConcreteProfile( - datasetDef, -) -const AuthorProfile: Profile = new ConcreteProfile(authorDef) - -// --------------------------------------------------------------------------- -// The source data: the input of the mapping procedure. The mapping is a pure -// function of this data, so running it again with changed data is what the -// update cycle in section 6 does. -// --------------------------------------------------------------------------- - -type Supplement = { - localID: LocalID - title: string - format: string -} - -type SourceData = { - datasetName: string - supplements: Supplement[] -} - -const initialSourceData: SourceData = { - datasetName: "Climate Index 2026", - supplements: [ - { - localID: "LOCAL/supplement/code", - title: "Companion analysis code", - format: "text/x-python", - }, - ], -} - -const updatedSourceData: SourceData = { - datasetName: "Climate Index 2026 (final)", - supplements: [ - { - localID: "LOCAL/supplement/notes", - title: "Analysis notes", - format: "text/markdown", - }, - ], -} - -// --------------------------------------------------------------------------- -// Helpers that only depend on interfaces -// --------------------------------------------------------------------------- - -function section(title: string): void { - console.log(`\n${"=".repeat(72)}`) - console.log(title) - console.log("=".repeat(72)) -} - -function show(label: string, value: unknown): void { - const rendered = - typeof value === "string" ? value : JSON.stringify(value, null, 2) - console.log(`${label}: ${rendered}`) -} - -/** - * The mapping procedure: it maps the source data onto FDO records in the - * local graph of the given context. It does not depend on the state of the - * context, so it can be run as often as needed — every run fills a fresh - * local graph. - */ -function mapping(context: MappingContext, source: SourceData): void { - // Authors: the mandatory `authoredDatasets` back-reference is skipped here — - // it will be filled in by `context.build()` once the datasets declare their - // bidirectional references. - const ada = context.newRecord("LOCAL/author/ada") - ada.addProfile(AuthorProfile, { - name: "Ada Lovelace", - affiliation: "Analytical Engines Lab", - authoredDatasets: skip(), - }) - - const grace = context.newRecord("LOCAL/author/grace") - grace.addProfile(AuthorProfile, { - name: "Grace Hopper", - affiliation: "Naval Computing Lab", - authoredDatasets: skip(), - }) - - // Supplements do not conform to any profile — plain attributes are fine too. - for (const supplement of source.supplements) { - const record = context.newRecord(supplement.localID) - record.set(titleAttr, supplement.title) - record.set(formatAttr, supplement.format) - } - - // The dataset profile is filled from "source data": the description is set - // first and then declared as `keep()`, the authors are declared as - // bidirectional references and the supplements as unidirectional ones. - const dataset = context.newRecord("LOCAL/dataset/climate-index") - dataset.set( - descriptionAttr, - "A curated collection of yearly climate index measurements.", - ) - dataset.addProfile(DatasetProfile, { - name: source.datasetName, - description: keep(), // already present on the record, see above - keyword: ["climate", "index"], - license: "CC-BY-4.0", - hasAuthor: [ - referenceBidi(authoredDatasetsAttr, "LOCAL/author/ada"), - referenceBidi(authoredDatasetsAttr, "LOCAL/author/grace"), - ], - hasPart: source.supplements.map((supplement) => - reference(supplement.localID), - ), - }) -} - -/** - * Build the local graph of the context and publish the result. This is the - * regular workflow of a mapping: the graph is built first, so that all - * references are resolved, and only the built result is published. - */ -async function publishMapping( - publisher: ContinuousPublishAdapter, - context: MappingContext, -): Promise { - const result = context.build() - return await publisher.publishContinuous(result) -} - -async function resolveMapping( - resolver: ContinuousResolveAdapter, - mappingPID: PID, -): Promise> { - return await resolver.resolveMappingRecords(mappingPID) -} - -function summarize(graph: ReadOnlyFDOGraph): unknown { - return graph - .getRecords() - .map((record) => ({ localID: record.localID, PID: record.PID })) -} - -// --------------------------------------------------------------------------- -// 1. Setup: a mapping context plus a backend used through its two adapters -// --------------------------------------------------------------------------- - -section("1. Setup") - -const context: MappingContext = new ContinuousMappingContext(mappingPID) - -// LocalTestingBackend is the concrete class under test, but everything below -// only ever talks to it through the ContinuousPublishAdapter / ResolveAdapter -// interfaces. -// The backend is not bound to a single mapping: the mapping is determined by -// the mapping result that is published, so one backend can serve any number -// of mappings (see section 8). -const backend: ContinuousPublishAdapter & ContinuousResolveAdapter = - new LocalTestingBackend() -const publisher: ContinuousPublishAdapter = backend -const resolver: ContinuousResolveAdapter = backend - -show("Mapping PID", mappingPID) -show("Fresh local graph records", context.localGraph.getRecords()) - -// --------------------------------------------------------------------------- -// 2. Build the local graph -// --------------------------------------------------------------------------- - -section("2. Build the local graph") - -mapping(context, initialSourceData) - -show("Local graph (records with attributes)", context.localGraph.toJSON()) - -// --------------------------------------------------------------------------- -// 3. Realize bidirectional references -// --------------------------------------------------------------------------- - -section("3. context.build() realizes the back-references") - -// `build()` must run before the first publish: back-references are written as -// `record.PID ?? record.localID`, and at this point no record has a PID yet, -// so both directions consistently reference local IDs. -// -// The result of the build is the mapping result: the graph that is to be -// published, plus the PIDs of the records that are not part of the mapping -// anymore. Nothing was published before, so the latter list is empty. -const result: MappingResult = context.build() - -show("Local graph (built)", context.localGraph.toJSON()) -show("Deleted records", result.delete) -show( - "ada.get(authoredDatasetsAttr)", - context.localGraph.getRecord("LOCAL/author/ada")?.get(authoredDatasetsAttr), -) -show( - "grace.get(authoredDatasetsAttr)", - context.localGraph - .getRecord("LOCAL/author/grace") - ?.get(authoredDatasetsAttr), -) -show( - "dataset.get(hasAuthorAttr)", - context.localGraph - .getRecord("LOCAL/dataset/climate-index") - ?.get(hasAuthorAttr), -) - -// --------------------------------------------------------------------------- -// 4. Publish the mapping result through the PublishAdapter -// --------------------------------------------------------------------------- - -section("4. Publish the mapping result") - -const dataset = context.localGraph.getRecord("LOCAL/dataset/climate-index")! - -show("dataset.PID before publish", dataset.PID) - -// `publishContinuous` publishes the result of a continuous mapping: the -// records of the mapping are published, the records that are not part of the -// mapping anymore are deleted, and the high level FDO record of the mapping -// is created or updated. -const publishResult: ContinuousPublishResult = - await publisher.publishContinuous(result) - -show("dataset.PID after publish", dataset.PID) -show( - "ada.PID after publish", - context.localGraph.getRecord("LOCAL/author/ada")?.PID, -) -show("PID of the mapping", publishResult.mappingPID) -show("Published records of the mapping", summarize(publishResult.graph)) -show("Deleted records", publishResult.deleted) - -// --------------------------------------------------------------------------- -// 5. Resolve through the ResolveAdapter -// --------------------------------------------------------------------------- - -section("5. Resolve the mapping records") - -const published = await resolveMapping(resolver, mappingPID) -show("Resolved records", summarize(published)) - -// The mapping itself is a high level FDO record with the PID of the mapping. -// It references all the records that are part of the mapping, and every one -// of them points back to it. -const mappingRecord = await resolver.resolveRecord(mappingPID) -show("Mapping record (high level FDO record)", mappingRecord?.toJSON()) -show( - "Records point back to the mapping record", - published.getRecords().map((record) => ({ - localID: record.localID, - partOfMapping: record.get("attr/partOfMapping"), - })), -) - -// The published records contain no local IDs: the backend assigned a PID to -// every record and fixed up the references, so the references of the published -// records point to PIDs. The only local ID a published record holds is its own -// — in `0.SIMPLE/LOCAL_ID`, where it identifies the record for the mapping that -// published it. -show( - "Local IDs left in the published records", - published.getRecords().flatMap((record) => - Object.entries(record.toJSON()).flatMap(([attribute, value]) => - (Array.isArray(value) ? value : [value]) - .filter( - (entry) => - typeof entry === "string" && entry.startsWith("LOCAL/"), - ) - .map((entry) => ({ - attribute, - localID: entry, - ownLocalID: record.localID, - })), - ), - ), -) - -// Resolved records are addressable by local ID... -const resolvedDataset = published.getRecord("LOCAL/dataset/climate-index") -show("Resolved dataset (by localID)", resolvedDataset) - -// ...as well as by PID. -show( - "Same record by PID", - published.getRecord(dataset.PID!) === resolvedDataset, -) - -// `resolveRecord` fetches a single record from the shared store, independent -// of any mapping. It returns undefined for unknown PIDs. -const single = await resolver.resolveRecord(dataset.PID!) -show("resolveRecord(dataset.PID)", single?.toJSON()) -show( - "resolveRecord(unknown PID)", - await resolver.resolveRecord("TEST/does-not-exist"), -) - -// --------------------------------------------------------------------------- -// 6. Resolved records are snapshots -// --------------------------------------------------------------------------- - -section("6. Resolved records are snapshots") - -dataset.set(nameAttr, "Climate Index 2026 (draft revision)") -show("local record after change", dataset.get(nameAttr)) - -const stale = await resolver.resolveRecord(dataset.PID!) -show("resolved record without republishing (unchanged)", stale?.get(nameAttr)) - -// --------------------------------------------------------------------------- -// 7. Update cycle: the same mapping procedure runs a second time -// --------------------------------------------------------------------------- - -section("7. Update cycle") - -// The update cycle is a second run of the very same mapping procedure: the -// published records are resolved again and become the remote graph of a new -// context. The mapping is run again on changed source data, the new context -// is built and the new mapping result is published. -// -// The backend keeps the PID of a record stable as long as it is published -// under the same local ID, so the dataset keeps its PID even though it is -// mapped from scratch. -const updateContext: MappingContext = new ContinuousMappingContext(mappingPID) - -await updateContext.resolveRemoteGraph(resolver) - -mapping(updateContext, updatedSourceData) - -const updateResult = updateContext.build() - -// The supplement of the first run is not part of the mapping anymore, so the -// context reports its PID as deleted. -show("Deleted records", updateResult.delete) - -await publisher.publishContinuous(updateResult) - -show( - "Mapping record after update", - (await resolver.resolveRecord(mappingPID))?.toJSON(), -) - -const updated = await resolveMapping(resolver, mappingPID) -show("Resolved records after update", summarize(updated)) -show( - "PID of the dataset is stable", - updated.getRecord("LOCAL/dataset/climate-index")?.PID === dataset.PID, -) -show( - "Updated attribute value", - updated.getRecord("LOCAL/dataset/climate-index")?.get(nameAttr), -) -show( - "New supplement record", - updated.getRecord("LOCAL/supplement/notes")?.toJSON(), -) -show( - "Supplement that is not part of the mapping anymore", - updated.getRecord("LOCAL/supplement/code"), -) -show( - "hasPart now references the new supplement", - updated.getRecord("LOCAL/dataset/climate-index")?.get(hasPartAttr), -) - -// --------------------------------------------------------------------------- -// 8. Mapping isolation: scoped graphs over a shared store -// --------------------------------------------------------------------------- - -section("8. Mapping isolation") - -// A second, independent mapping, published through the very same backend: the -// backend is not bound to a single mapping. All backend instances share one -// store, so the records of the other mapping are visible to the first mapping -// as well. -const otherContext: MappingContext = new ContinuousMappingContext( - otherMappingPID, -) - -const release = otherContext.newRecord("LOCAL/release/v1") -release.set(titleAttr, "Climate Index 2026 release announcement") -await publishMapping(publisher, otherContext) - -const otherPublished = await resolveMapping(resolver, otherMappingPID) -show("Records of the other mapping", summarize(otherPublished)) -show( - "Mapping record of the other mapping", - (await resolver.resolveRecord(otherMappingPID))?.toJSON(), -) -show( - "The other mapping does not see this mapping's records", - otherPublished.getRecord("LOCAL/dataset/climate-index") === undefined, -) -show( - "This mapping does not see the other mapping's records", - published.getRecord("LOCAL/release/v1") === undefined, -) -show( - "resolveRecord is not mapping-scoped (shared store)", - (await resolver.resolveRecord(dataset.PID!))?.PID, -) - -// --------------------------------------------------------------------------- -// 9. Publishing without a mapping -// --------------------------------------------------------------------------- - -section("9. Publishing without a mapping") - -// Not every published record belongs to a mapping: a single record or a whole -// graph can be published on its own. `publishRecord` and `publishGraph` do not -// create a high level FDO record of a mapping, and the published records do -// not point back to one. They are published all the same: they get a PID, they -// are stored and they can be resolved. - -const noticeContext: MappingContext = new ContinuousMappingContext( - "TEST/notice", -) -const notice = noticeContext.newRecord("LOCAL/notice") -notice.set(titleAttr, "Climate Index 2026 release announcement") - -const publishedNotice = await publisher.publishRecord(notice) - -show("Published record", publishedNotice.toJSON()) -show("PID of the published record", publishedNotice.PID) -show( - "The record keeps its own local ID", - publishedNotice.get("0.SIMPLE/LOCAL_ID"), -) -show( - "The record does not point back to a mapping", - publishedNotice.get("attr/partOfMapping"), -) - -// A whole graph, published on its own. The dataset references the part, and -// the reference is fixed up to the PID the part was published with. -// -// TODO: this is not what happens yet: the example never creates a record for -// "LOCAL/graph/part", so there is no published target to fix the reference up -// to, and the published record keeps the local ID of the reference. Either add -// a part record to the graph, or reword this comment and the labels below. -const graphContext: MappingContext = new ContinuousMappingContext("TEST/graph") -const graphDataset = graphContext.newRecord("LOCAL/graph/dataset") -graphDataset.addReference(hasPartAttr, "LOCAL/graph/part") - -const publishedGraph = await publisher.publishGraph(graphContext.localGraph) - -show( - "Published graph", - publishedGraph.getRecords().map((record) => ({ - PID: record.PID, - attributes: record.toJSON(), - })), -) -show( - "The reference of the graph is fixed up to a PID", - publishedGraph.getRecord(graphDataset.PID!)?.get(hasPartAttr), -) - -// The published records are not part of any mapping: the mapping of the -// example does not contain them, and there is no high level FDO record for -// them. -show( - "The published records are not part of the mapping", - (await resolveMapping(resolver, mappingPID)).getRecord("LOCAL/notice") === - undefined, -) -show( - "There is no high level FDO record for them", - await resolver.resolveRecord("TEST/notice"), -) -show( - "The published record is resolvable all the same", - (await resolver.resolveRecord(publishedNotice.PID))?.get(titleAttr), -) - -// --------------------------------------------------------------------------- -// 10. Reset the store between test runs -// --------------------------------------------------------------------------- - -section("10. Reset the store") - -// `resetStore` is a static method on the class — the one piece of the API not -// covered by the PublishAdapter / ResolveAdapter interfaces. -LocalTestingBackend.resetStore() - -try { - await resolveMapping(resolver, mappingPID) -} catch (error) { - show( - "resolveMappingRecords after reset", - error instanceof Error ? error.message : String(error), - ) -} -show("resolveRecord after reset", await resolver.resolveRecord(dataset.PID!)) - -console.log("\nDone.") diff --git a/packages/examples/tsconfig.json b/packages/examples/tsconfig.json deleted file mode 100644 index fbe0cdd..0000000 --- a/packages/examples/tsconfig.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - // Visit https://aka.ms/tsconfig to read more about this file - "compilerOptions": { - // File Layout - "rootDir": "./src", - "outDir": "./dist", - - // Environment Settings - // See also https://aka.ms/tsconfig/module - "module": "nodenext", - "target": "esnext", - // For nodejs: - // "lib": ["esnext"], - "types": ["node"], - // and npm install -D @types/node - - // Other Outputs - "sourceMap": true, - "declaration": true, - "declarationMap": true, - - // Stricter Typechecking Options - "noUncheckedIndexedAccess": true, - "exactOptionalPropertyTypes": true, - - // Style Options - // "noImplicitReturns": true, - // "noImplicitOverride": true, - // "noUnusedLocals": true, - // "noUnusedParameters": true, - // "noFallthroughCasesInSwitch": true, - // "noPropertyAccessFromIndexSignature": true, - - // Recommended Options - "strict": true, - "jsx": "react-jsx", - "verbatimModuleSyntax": true, - "isolatedModules": true, - "noUncheckedSideEffectImports": true, - "moduleDetection": "force", - "skipLibCheck": true - } -} diff --git a/packages/mapping/src/impl/ContinuousMappingContext.ts b/packages/mapping/src/impl/ContinuousMappingContext.ts index 440cc28..f266a33 100644 --- a/packages/mapping/src/impl/ContinuousMappingContext.ts +++ b/packages/mapping/src/impl/ContinuousMappingContext.ts @@ -7,20 +7,20 @@ import type { FDOGraph, LocalFDORecord, PID, - PublishedLocalFDORecord, + CompleteLocalFDORecord, ReadOnlyFDOGraph, } from "@fdo-sdk/primitives" import { - ConcreteLocalFDORecord, type FDORecord, LocalFDOGraph, type LocalID, } from "@fdo-sdk/primitives" import { PublishedFDOGraph } from "@fdo-sdk/primitives" +import { DefaultLocalFDORecord } from "@fdo-sdk/primitives" export class ContinuousMappingContext implements MappingContext { readonly #localGraph = new LocalFDOGraph() - #remoteGraph: ReadOnlyFDOGraph = + #remoteGraph: ReadOnlyFDOGraph = new PublishedFDOGraph() #hasResolvedRemoteGraph = false @@ -34,8 +34,12 @@ export class ContinuousMappingContext implements MappingContext { return this.#localGraph } - get remoteGraph(): ReadOnlyFDOGraph { - return structuredClone(this.#remoteGraph) + get remoteGraph(): ReadOnlyFDOGraph { + const copy = new PublishedFDOGraph() + for (const record of this.#remoteGraph.getRecords()) { + copy.addRecord(record) + } + return copy } async resolveRemoteGraph(resolver: ContinuousResolveAdapter) { @@ -46,7 +50,7 @@ export class ContinuousMappingContext implements MappingContext { } newRecord(localID: LocalID): FDORecord { - const record = new ConcreteLocalFDORecord(localID) + const record = new DefaultLocalFDORecord(localID) this.#localGraph.addRecord(record) return record } diff --git a/packages/mapping/src/impl/backends/LocalTestingBackend.ts b/packages/mapping/src/impl/backends/LocalTestingBackend.ts index 7b323a2..d03d1e6 100644 --- a/packages/mapping/src/impl/backends/LocalTestingBackend.ts +++ b/packages/mapping/src/impl/backends/LocalTestingBackend.ts @@ -1,27 +1,27 @@ import type { ContinuousPublishAdapter } from "../../interfaces/index.js" import type { MappingResult, ContinuousPublishResult } from "../../types.js" import { - ConcreteFDORecord, + DefaultFDORecord, + PublishedFDOGraph, + type AttrTypeWithCardinality, + type CompleteFDORecord, + type CompleteLocalFDORecord, + type DefaultAttributeDef, type FDORecord, type LocalID, type PID, - type PublishedFDORecord, type ReadOnlyFDOGraph, - type RecordValue, type ReferenceDeclaration, } from "@fdo-sdk/primitives" import type { ResolveAdapter } from "@fdo-sdk/primitives" -import { - PublishedFDOGraph, - type PublishedLocalFDORecord, -} from "@fdo-sdk/primitives" + +type AttributeValue = AttrTypeWithCardinality type StoredRecord = { pid: PID localID: LocalID | undefined - attributes: Map + attributes: Map references: ReferenceDeclaration[] - profiles: PID[] } const pidPrefix = "TEST" @@ -50,9 +50,10 @@ const partOfMappingAttribute: PID = "attr/partOfMapping" * can restore the local ID a record was published with when it resolves the * record, so references expressed in terms of local IDs can be resolved again. * - * The PID itself mirrors `FDO_TYPES.LOCAL_ID` of `@fdo-sdk/simple-types`, - * which is where consumers of the simple types find it. It is spelled out - * here because `@fdo-sdk/mapping` does not depend on that package. + * The PID itself mirrors the `0.SIMPLE/LOCAL_ID` attribute of + * `@fdo-sdk/simple-types`, which is where consumers of the simple types find + * it. It is spelled out here because `@fdo-sdk/mapping` does not depend on that + * package. */ const localIdAttribute: PID = "0.SIMPLE/LOCAL_ID" @@ -66,7 +67,7 @@ const store: { mappings: new Map(), } -class RestoredFDORecord extends ConcreteFDORecord { +class RestoredFDORecord extends DefaultFDORecord { readonly localID: LocalID | undefined constructor(stored: StoredRecord) { @@ -74,7 +75,6 @@ class RestoredFDORecord extends ConcreteFDORecord { this.localID = stored.localID this.attributes = new Map(stored.attributes) this.references = [...stored.references] - this.conformsToProfiles = [...stored.profiles] } } @@ -193,7 +193,7 @@ export class LocalTestingBackend */ async publishGraph( graph: ReadOnlyFDOGraph, - ): Promise> { + ): Promise> { const published = this.publishRecords(graph.getRecords(), undefined) const result = new PublishedFDOGraph() @@ -206,14 +206,14 @@ export class LocalTestingBackend /** * Publishes a single record, without a mapping. */ - async publishRecord(record: FDORecord): Promise { + async publishRecord(record: FDORecord): Promise { const published = this.publishRecords([record], undefined) return this.restoredRecord(published[0]!.pid) } async resolveMappingRecords( mappingPID: PID, - ): Promise> { + ): Promise> { const recordPIDs = store.mappings.get(mappingPID) if (!recordPIDs) { throw new Error(`Mapping record not found: ${mappingPID}`) @@ -224,10 +224,10 @@ export class LocalTestingBackend async resolveRecord( recordPID: PID, - ): Promise { + ): Promise { const stored = store.records.get(recordPID) if (!stored) return undefined - return new RestoredFDORecord(stored) as PublishedFDORecord + return new RestoredFDORecord(stored) as CompleteFDORecord } static resetStore(): void { @@ -241,7 +241,7 @@ export class LocalTestingBackend * mapping that references all the records that are part of the mapping. */ private storeMappingRecord(mappingPID: PID, recordPIDs: PID[]): void { - const attributes = new Map() + const attributes = new Map() attributes.set(hasMappingRecordAttribute, recordPIDs) const references: ReferenceDeclaration[] = recordPIDs.map((pid) => ({ @@ -256,7 +256,6 @@ export class LocalTestingBackend localID: undefined, attributes, references, - profiles: [], }) } @@ -353,7 +352,6 @@ export class LocalTestingBackend pidsByLocalID.get(reference.toRecord) ?? reference.toRecord, })), - profiles: [...record.getProfiles()], }) if (mappingPID !== undefined) { @@ -378,21 +376,21 @@ export class LocalTestingBackend */ private publishedGraph( scope: Set, - ): PublishedFDOGraph { - const graph = new PublishedFDOGraph() + ): PublishedFDOGraph { + const graph = new PublishedFDOGraph() for (const pid of scope) { const stored = store.records.get(pid)! graph.addRecord( - new RestoredFDORecord(stored) as PublishedLocalFDORecord, + new RestoredFDORecord(stored) as CompleteLocalFDORecord, ) } return graph } - private restoredRecord(pid: PID): PublishedFDORecord { + private restoredRecord(pid: PID): CompleteFDORecord { return new RestoredFDORecord( store.records.get(pid)!, - ) as PublishedFDORecord + ) as CompleteFDORecord } private localIDOf(record: FDORecord): LocalID | undefined { @@ -411,16 +409,24 @@ export class LocalTestingBackend * was referenced by before it was published. */ private resolvePlaceholders( - value: RecordValue, + value: AttributeValue, pidsByLocalID: Map, - ): RecordValue { - return typeof value === "string" - ? (pidsByLocalID.get(value) ?? value) - : value.map((entry) => pidsByLocalID.get(entry) ?? entry) + ): AttributeValue { + if (typeof value === "string") { + return pidsByLocalID.get(value) ?? value + } + if (Array.isArray(value)) { + return value.map((entry) => + typeof entry === "string" + ? (pidsByLocalID.get(entry) ?? entry) + : entry, + ) + } + return value } private addValue( - attributes: Map, + attributes: Map, attribute: PID, value: string, ): void { diff --git a/packages/mapping/src/impl/clients/typid/TypidClient.ts b/packages/mapping/src/impl/clients/typid/TypidClient.ts deleted file mode 100644 index 4489475..0000000 --- a/packages/mapping/src/impl/clients/typid/TypidClient.ts +++ /dev/null @@ -1,88 +0,0 @@ -const baseUrl = "https://typed-pid-maker.datamanager.kit.edu/preview" - -export type TypidRecord = { - pid: string - entries: { - [key: string]: { - key: string - name: string - value: string - }[] - } -} - -export class TypidClient { - async fetchRecord(pid: string) { - let req - try { - req = await fetch(`${baseUrl}/api/v1/pit/pid/${pid}`) - } catch (error) { - throw new Error("Unable to reach Typed PID Maker", { cause: error }) - } - - let data - if (req.ok) { - try { - data = (await req.json()) as TypidRecord - } catch (error) { - throw new Error("Unable to fetch record, malformed response", { - cause: error, - }) - } - } else if (req.status === 404) { - return undefined - } else - throw new Error( - `Unable to fetch record, unknown status code ${req.status}`, - ) - - return data - } - - async createRecord( - entries: TypidRecord["entries"], - dryrun: boolean = false, - ) { - let req - try { - req = await fetch( - `${baseUrl}/api/v1/pit/pid/${dryrun ? "?dryrun=true" : ""}`, - { - method: "POST", - body: JSON.stringify(entries), - headers: { "Content-Type": "application/json" }, - }, - ) - } catch (error) { - throw new Error("Unable to reach Typed PID Maker", { cause: error }) - } - - let data - if (req.ok) { - try { - data = (await req.json()) as TypidRecord - } catch (error) { - throw new Error("Unable to create record, malformed response", { - cause: error, - }) - } - } else if (req.status === 400) { - let details - try { - details = await req.json() - console.error( - "Unable to create record, validation failed.", - details, - ) - } catch (_) {} - throw new Error("Unable to create record, validation failed.", { - cause: details, - }) - } else - throw new Error( - `Unable to create record, unknown status code ${req.status}`, - ) - - return data - } -} diff --git a/packages/mapping/src/impl/resolvers/TypidResolver.ts b/packages/mapping/src/impl/resolvers/TypidResolver.ts deleted file mode 100644 index f9386b6..0000000 --- a/packages/mapping/src/impl/resolvers/TypidResolver.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { - ConcreteFDORecord, - PublishedFDOGraph, - type PID, - type PublishedFDORecord, - type PublishedLocalFDORecord, - type ReadOnlyFDOGraph, - type ResolveAdapter, -} from "@fdo-sdk/primitives" -import { TypidClient, type TypidRecord } from "../clients/typid/TypidClient.js" - -const typidClient = new TypidClient() - -export class TypidResolver implements ResolveAdapter { - async resolveMappingRecords( - mappingPID: PID, - ): Promise> { - const graph = new PublishedFDOGraph() - - const rootRecord = await this.resolveRecord(mappingPID) - if (!rootRecord) { - throw new Error("Mapping record not found") - } - - return graph - } - - async resolveRecord( - recordPID: PID, - ): Promise { - let typidRecord - try { - typidRecord = await typidClient.fetchRecord(recordPID) - } catch (e) { - throw new Error("Could not fetch record", { cause: e }) - } - - if (typidRecord) { - return this.typidRecordToPIDRecord(typidRecord) - } else { - return undefined - } - } - - private typidRecordToPIDRecord( - typidRecord: TypidRecord, - ): PublishedFDORecord { - const record = new ConcreteFDORecord( - typidRecord.pid, - ) as PublishedFDORecord - - const attributes = Object.values(typidRecord.entries) - .filter((entry) => entry.length > 0) - .map((entry) => { - const values = entry.map((value) => value.value) - return { key: entry[0]!.key, value: values } - }) - - for (const attribute of attributes) { - record.addAttribute(attribute.key, attribute.value) - } - - return record - } -} diff --git a/packages/mapping/src/interfaces/ContinuousResolveAdapter.ts b/packages/mapping/src/interfaces/ContinuousResolveAdapter.ts index 5c43512..1a37a41 100644 --- a/packages/mapping/src/interfaces/ContinuousResolveAdapter.ts +++ b/packages/mapping/src/interfaces/ContinuousResolveAdapter.ts @@ -2,7 +2,7 @@ import type { ResolveAdapter, PID, ReadOnlyFDOGraph, - PublishedLocalFDORecord, + CompleteLocalFDORecord, } from "@fdo-sdk/primitives" /** @@ -21,5 +21,5 @@ export interface ContinuousResolveAdapter extends ResolveAdapter { */ resolveMappingRecords( mappingPID: PID, - ): Promise> + ): Promise> } diff --git a/packages/mapping/src/types.ts b/packages/mapping/src/types.ts index 0ac7db5..029e6b3 100644 --- a/packages/mapping/src/types.ts +++ b/packages/mapping/src/types.ts @@ -1,8 +1,8 @@ import type { LocalFDORecord, PID, - PublishedLocalFDORecord, ReadOnlyFDOGraph, + CompleteLocalFDORecord, } from "@fdo-sdk/primitives" /** @@ -25,6 +25,6 @@ export type ContinuousPublishResult = { * the high level FDO record that represents the mapping. */ mappingPID: PID - graph: ReadOnlyFDOGraph + graph: ReadOnlyFDOGraph deleted: PID[] } diff --git a/packages/mapping/tests/ConcreteMappingContext.test.ts b/packages/mapping/tests/ConcreteMappingContext.test.ts index ff2598d..f5c3477 100644 --- a/packages/mapping/tests/ConcreteMappingContext.test.ts +++ b/packages/mapping/tests/ConcreteMappingContext.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest" import { - ConcreteLocalFDORecord, + DefaultLocalFDORecord, PublishedFDOGraph, - type PublishedLocalFDORecord, + type CompleteLocalFDORecord, } from "@fdo-sdk/primitives" import { ContinuousMappingContext } from "../src/index.js" import type { ContinuousResolveAdapter } from "../src/index.js" @@ -10,11 +10,11 @@ import type { ContinuousResolveAdapter } from "../src/index.js" const mappingPID = "TEST/mapping" function remoteGraphWith( - ...records: ConcreteLocalFDORecord[] -): PublishedFDOGraph { - const graph = new PublishedFDOGraph() + ...records: DefaultLocalFDORecord[] +): PublishedFDOGraph { + const graph = new PublishedFDOGraph() for (const record of records) { - graph.addRecord(record as PublishedLocalFDORecord) + graph.addRecord(record as CompleteLocalFDORecord) } return graph } @@ -34,8 +34,8 @@ describe("ContinuousMappingContext", () => { it("reports the PIDs of the remote records that are not part of the mapping anymore", async () => { const remote = remoteGraphWith( - new ConcreteLocalFDORecord("LOCAL/1", "TEST/1"), - new ConcreteLocalFDORecord("LOCAL/2", "TEST/2"), + new DefaultLocalFDORecord("LOCAL/1", "TEST/1"), + new DefaultLocalFDORecord("LOCAL/2", "TEST/2"), ) const context = new ContinuousMappingContext(mappingPID) const resolver: ContinuousResolveAdapter = { @@ -70,4 +70,38 @@ describe("ContinuousMappingContext", () => { ).toBe("LOCAL/source") }) }) + + describe("resolveRemoteGraph and remoteGraph", () => { + const emptyResolver: ContinuousResolveAdapter = { + resolveMappingRecords: async () => + remoteGraphWith(), + resolveRecord: async () => undefined, + } + + it("reports whether the remote graph has been resolved", async () => { + const context = new ContinuousMappingContext(mappingPID) + + expect(context.hasResolvedRemoteGraph).toBe(false) + + await context.resolveRemoteGraph(emptyResolver) + + expect(context.hasResolvedRemoteGraph).toBe(true) + }) + + it("exposes the resolved remote graph", async () => { + const context = new ContinuousMappingContext(mappingPID) + const resolver: ContinuousResolveAdapter = { + resolveMappingRecords: async () => + remoteGraphWith( + new DefaultLocalFDORecord("LOCAL/1", "TEST/1"), + ), + resolveRecord: async () => undefined, + } + await context.resolveRemoteGraph(resolver) + + expect(context.remoteGraph.getRecord("LOCAL/1")?.PID).toBe( + "TEST/1", + ) + }) + }) }) diff --git a/packages/mapping/tests/LocalTestingBackend.test.ts b/packages/mapping/tests/LocalTestingBackend.test.ts index cebb1ce..d122636 100644 --- a/packages/mapping/tests/LocalTestingBackend.test.ts +++ b/packages/mapping/tests/LocalTestingBackend.test.ts @@ -1,12 +1,12 @@ import { beforeEach, describe, expect, it } from "vitest" import { - ConcreteFDORecord, - ConcreteLocalFDORecord, - ConcreteProfile, + Attribute, + DefaultFDORecord, + DefaultLocalFDORecord, LocalFDOGraph, - type Attribute, + Profile, + type LocalFDORecord, type PID, - type ProfileDefinition, } from "@fdo-sdk/primitives" import { ContinuousMappingContext, @@ -14,34 +14,42 @@ import { type MappingResult, } from "../src/index.js" -type TestProfileAttributes = { - datasetName: string - authors: string | string[] -} +const datasetNameAttr = Attribute.makeSyntax({ + name: "datasetName", + pid: "attr/datasetName", + cardinality: "1..1", + primitiveDataType: "string", +}) -const def: ProfileDefinition = { +const authorsAttr = Attribute.makeSyntax({ + name: "authors", + pid: "attr/authors", + cardinality: "0..*", + primitiveDataType: "string", +}) + +const testProfile = Profile.make({ pid: "profile/test", - readableName: "Test Profile", - mapping: { - datasetName: "attr/datasetName", - authors: "attr/authors", - }, -} + name: "Test Profile", + attributes: [datasetNameAttr, authorsAttr], +}) -const fromAttr: Attribute = { +const fromAttr = Attribute.makeAttrRef({ + name: "from", pid: "attr/from", - readableName: "from", -} + cardinality: "0..*", +}) -const toAttr: Attribute = { +const toAttr = Attribute.makeAttrRef({ + name: "to", pid: "attr/to", - readableName: "to", -} + cardinality: "0..*", +}) const mappingPID = "TEST/mapping" function newGraphWithRecords( - ...records: ConcreteLocalFDORecord[] + ...records: LocalFDORecord[] ): LocalFDOGraph { const graph = new LocalFDOGraph() for (const record of records) graph.addRecord(record) @@ -53,7 +61,7 @@ function newGraphWithRecords( * created by the mapping, the given PIDs are deleted by the mapping. */ function newMappingResult( - records: ConcreteLocalFDORecord[] = [], + records: LocalFDORecord[] = [], deleted: PID[] = [], pid: PID = mappingPID, ): MappingResult { @@ -67,7 +75,7 @@ function newMappingResult( async function publishAll( backend: LocalTestingBackend, - ...records: ConcreteLocalFDORecord[] + ...records: LocalFDORecord[] ): Promise { await publishFor(backend, mappingPID, ...records) } @@ -75,7 +83,7 @@ async function publishAll( async function publishFor( backend: LocalTestingBackend, pid: PID, - ...records: ConcreteLocalFDORecord[] + ...records: LocalFDORecord[] ): Promise { await backend.publishContinuous(newMappingResult(records, [], pid)) } @@ -88,8 +96,8 @@ describe("LocalTestingBackend", () => { describe("publishContinuous", () => { it("assigns fresh unique PIDs to records without a PID", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/1") - const recordB = new ConcreteLocalFDORecord("LOCAL/2") + const recordA = new DefaultLocalFDORecord("LOCAL/1") + const recordB = new DefaultLocalFDORecord("LOCAL/2") await publishAll(backend, recordA, recordB) @@ -100,7 +108,7 @@ describe("LocalTestingBackend", () => { it("keeps the PID of records that already have one", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1", "existing/pid") + const record = new DefaultLocalFDORecord("LOCAL/1", "existing/pid") await publishAll(backend, record) @@ -110,11 +118,11 @@ describe("LocalTestingBackend", () => { it("publishes plain records without a localID", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteFDORecord() + const record = new DefaultFDORecord() record.set("attr/a", "value") await backend.publishContinuous( - newMappingResult([record as unknown as ConcreteLocalFDORecord]), + newMappingResult([record as unknown as LocalFDORecord]), ) const resolved = await backend.resolveRecord(record.PID!) @@ -124,7 +132,7 @@ describe("LocalTestingBackend", () => { it("updates the stored snapshot when a record is published again", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") record.set("attr/a", "v1") await publishAll(backend, record) const firstPID = record.PID! @@ -163,10 +171,10 @@ describe("LocalTestingBackend", () => { it("does not reuse the PID of a record of another mapping", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/1") + const recordA = new DefaultLocalFDORecord("LOCAL/1") await publishAll(backend, recordA) - const recordB = new ConcreteLocalFDORecord("LOCAL/1") + const recordB = new DefaultLocalFDORecord("LOCAL/1") await publishFor(backend, "TEST/other-mapping", recordB) expect(recordB.PID).not.toBe(recordA.PID) @@ -174,7 +182,7 @@ describe("LocalTestingBackend", () => { it("deletes the records that are not part of the mapping result anymore", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") await publishAll(backend, record) const pid = record.PID! @@ -196,8 +204,8 @@ describe("LocalTestingBackend", () => { it("returns the published records of the mapping", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/1") - const recordB = new ConcreteLocalFDORecord("LOCAL/2") + const recordA = new DefaultLocalFDORecord("LOCAL/1") + const recordB = new DefaultLocalFDORecord("LOCAL/2") await publishAll(backend, recordA, recordB) const result = await backend.publishContinuous( @@ -211,7 +219,7 @@ describe("LocalTestingBackend", () => { it("returns the PIDs of the deleted records", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") await publishAll(backend, record) const pid = record.PID! @@ -260,8 +268,8 @@ describe("LocalTestingBackend", () => { describe("publishGraph", () => { it("publishes all the records of the graph", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/a") - const recordB = new ConcreteLocalFDORecord("LOCAL/b") + const recordA = new DefaultLocalFDORecord("LOCAL/a") + const recordB = new DefaultLocalFDORecord("LOCAL/b") const published = await backend.publishGraph( newGraphWithRecords(recordA, recordB), @@ -274,7 +282,7 @@ describe("LocalTestingBackend", () => { it("returns the published records with their PIDs", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") record.set("attr/a", "value") const published = await backend.publishGraph( @@ -290,7 +298,7 @@ describe("LocalTestingBackend", () => { const backend = new LocalTestingBackend() await backend.publishGraph( - newGraphWithRecords(new ConcreteLocalFDORecord("LOCAL/a")), + newGraphWithRecords(new DefaultLocalFDORecord("LOCAL/a")), ) expect(await backend.resolveRecord(mappingPID)).toBeUndefined() @@ -298,7 +306,7 @@ describe("LocalTestingBackend", () => { it("does not reference a mapping from the published records", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") const published = await backend.publishGraph( newGraphWithRecords(record), @@ -311,7 +319,7 @@ describe("LocalTestingBackend", () => { it("keeps the own local ID of the published records", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") const published = await backend.publishGraph( newGraphWithRecords(record), @@ -324,8 +332,8 @@ describe("LocalTestingBackend", () => { it("fixes up the references between the published records", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/a") - const recordB = new ConcreteLocalFDORecord("LOCAL/b") + const recordA = new DefaultLocalFDORecord("LOCAL/a") + const recordB = new DefaultLocalFDORecord("LOCAL/b") recordA.addReference(fromAttr, "LOCAL/b") const published = await backend.publishGraph( @@ -339,9 +347,9 @@ describe("LocalTestingBackend", () => { it("publishes records without a local ID", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteFDORecord() + const record = new DefaultFDORecord() const graph = new LocalFDOGraph() - graph.addRecord(record as unknown as ConcreteLocalFDORecord) + graph.addRecord(record as unknown as LocalFDORecord) const published = await backend.publishGraph(graph) @@ -351,11 +359,11 @@ describe("LocalTestingBackend", () => { it("assigns a new PID to a record that is published again", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") await backend.publishGraph(newGraphWithRecords(record)) const firstPID = record.PID! - const secondRun = new ConcreteLocalFDORecord("LOCAL/a") + const secondRun = new DefaultLocalFDORecord("LOCAL/a") await backend.publishGraph(newGraphWithRecords(secondRun)) expect(secondRun.PID).not.toBe(firstPID) @@ -363,10 +371,10 @@ describe("LocalTestingBackend", () => { it("does not reuse the PID of a record of a mapping", async () => { const backend = new LocalTestingBackend() - const mapped = new ConcreteLocalFDORecord("LOCAL/a") + const mapped = new DefaultLocalFDORecord("LOCAL/a") await publishAll(backend, mapped) - const unmapped = new ConcreteLocalFDORecord("LOCAL/a") + const unmapped = new DefaultLocalFDORecord("LOCAL/a") await backend.publishGraph(newGraphWithRecords(unmapped)) expect(unmapped.PID).not.toBe(mapped.PID) @@ -376,7 +384,7 @@ describe("LocalTestingBackend", () => { describe("publishRecord", () => { it("assigns a PID to the record", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") const published = await backend.publishRecord(record) @@ -386,7 +394,7 @@ describe("LocalTestingBackend", () => { it("publishes the record so that it can be resolved", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") record.set("attr/a", "value") const published = await backend.publishRecord(record) @@ -397,7 +405,7 @@ describe("LocalTestingBackend", () => { it("keeps the own local ID of the record", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") const published = await backend.publishRecord(record) @@ -406,7 +414,7 @@ describe("LocalTestingBackend", () => { it("does not reference a mapping from the published record", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") const published = await backend.publishRecord(record) @@ -415,7 +423,7 @@ describe("LocalTestingBackend", () => { it("publishes a record without a local ID", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteFDORecord() + const record = new DefaultFDORecord() const published = await backend.publishRecord(record) @@ -425,11 +433,11 @@ describe("LocalTestingBackend", () => { it("assigns a new PID to a record that is published again", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") await backend.publishRecord(record) const firstPID = record.PID! - const secondRun = new ConcreteLocalFDORecord("LOCAL/a") + const secondRun = new DefaultLocalFDORecord("LOCAL/a") await backend.publishRecord(secondRun) expect(secondRun.PID).not.toBe(firstPID) @@ -437,7 +445,7 @@ describe("LocalTestingBackend", () => { it("keeps the back-reference to the mapping of the record", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") await publishAll(backend, record) const published = await backend.publishRecord(record) @@ -449,8 +457,8 @@ describe("LocalTestingBackend", () => { describe("the references of the published records", () => { it("are fixed up to the PIDs of the records of the mapping", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/a") - const recordB = new ConcreteLocalFDORecord("LOCAL/b") + const recordA = new DefaultLocalFDORecord("LOCAL/a") + const recordB = new DefaultLocalFDORecord("LOCAL/b") recordA.addReference(fromAttr, "LOCAL/b") await publishAll(backend, recordA, recordB) @@ -468,16 +476,16 @@ describe("LocalTestingBackend", () => { it("are fixed up to the PIDs of the fresh records of a later run", async () => { const backend = new LocalTestingBackend() - const firstRun = new ConcreteLocalFDORecord("LOCAL/a") - const target = new ConcreteLocalFDORecord("LOCAL/b") + const firstRun = new DefaultLocalFDORecord("LOCAL/a") + const target = new DefaultLocalFDORecord("LOCAL/b") firstRun.addReference(fromAttr, "LOCAL/b") await publishAll(backend, firstRun, target) // The second run of the same mapping publishes new records: they // receive fresh PIDs, and the references are fixed up to those // PIDs. - const secondRun = new ConcreteLocalFDORecord("LOCAL/a") - const secondTarget = new ConcreteLocalFDORecord("LOCAL/b") + const secondRun = new DefaultLocalFDORecord("LOCAL/a") + const secondTarget = new DefaultLocalFDORecord("LOCAL/b") secondRun.addReference(fromAttr, "LOCAL/b") await publishAll(backend, secondRun, secondTarget) @@ -504,7 +512,7 @@ describe("LocalTestingBackend", () => { it("keep the reference to a record that is not part of the mapping", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") record.addReference(fromAttr, "LOCAL/unknown") await publishAll(backend, record) @@ -522,7 +530,7 @@ describe("LocalTestingBackend", () => { it("leave the local ID in attributes that do not hold references", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") record.set("attr/sourceId", "LOCAL/a") record.set("attr/relatedIds", ["LOCAL/a", "LOCAL/b"]) await publishAll(backend, record) @@ -535,12 +543,44 @@ describe("LocalTestingBackend", () => { "LOCAL/b", ]) }) + + it("leave non-string values in reference attributes unchanged", async () => { + const backend = new LocalTestingBackend() + // The attribute becomes a reference attribute because another + // record of the mapping declares a reference on it. + const referenceOwner = new DefaultLocalFDORecord("LOCAL/owner") + referenceOwner.addReference(fromAttr, "LOCAL/target") + + const withPlainValue = new DefaultLocalFDORecord("LOCAL/plain") + withPlainValue.set("attr/from", true) + const withMixedArray = new DefaultLocalFDORecord("LOCAL/mixed") + withMixedArray.set("attr/from", [true, "LOCAL/target"]) + + await publishAll( + backend, + referenceOwner, + withPlainValue, + withMixedArray, + ) + + const resolvedPlain = await backend.resolveRecord( + withPlainValue.PID!, + ) + expect(resolvedPlain?.get("attr/from")).toBe(true) + const resolvedMixed = await backend.resolveRecord( + withMixedArray.PID!, + ) + expect(resolvedMixed?.get("attr/from")).toEqual([ + true, + "LOCAL/target", + ]) + }) }) describe("the own local ID of a published record", () => { it("is kept in the attribute of the record", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") await publishAll(backend, record) const resolved = await backend.resolveRecord(record.PID!) @@ -550,8 +590,8 @@ describe("LocalTestingBackend", () => { it("is the only local ID of the published record", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/a") - const recordB = new ConcreteLocalFDORecord("LOCAL/b") + const recordA = new DefaultLocalFDORecord("LOCAL/a") + const recordB = new DefaultLocalFDORecord("LOCAL/b") recordA.addReference(fromAttr, "LOCAL/b") await publishAll(backend, recordA, recordB) @@ -572,10 +612,10 @@ describe("LocalTestingBackend", () => { it("is not added to a record without a local ID", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteFDORecord() + const record = new DefaultFDORecord() await backend.publishContinuous( - newMappingResult([record as unknown as ConcreteLocalFDORecord]), + newMappingResult([record as unknown as LocalFDORecord]), ) const resolved = await backend.resolveRecord(record.PID!) @@ -586,7 +626,7 @@ describe("LocalTestingBackend", () => { describe("the high level FDO record of the mapping", () => { it("is a record with the PID of the mapping", async () => { const backend = new LocalTestingBackend() - await publishAll(backend, new ConcreteLocalFDORecord("LOCAL/1")) + await publishAll(backend, new DefaultLocalFDORecord("LOCAL/1")) const mappingRecord = await backend.resolveRecord(mappingPID) @@ -596,8 +636,8 @@ describe("LocalTestingBackend", () => { it("references all the records that are part of the mapping", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/1") - const recordB = new ConcreteLocalFDORecord("LOCAL/2") + const recordA = new DefaultLocalFDORecord("LOCAL/1") + const recordB = new DefaultLocalFDORecord("LOCAL/2") await publishAll(backend, recordA, recordB) const mappingRecord = await backend.resolveRecord(mappingPID) @@ -624,7 +664,7 @@ describe("LocalTestingBackend", () => { it("is referenced back by every record of the mapping", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") await publishAll(backend, record) const resolved = await backend.resolveRecord(record.PID!) @@ -634,7 +674,7 @@ describe("LocalTestingBackend", () => { it("keeps an already existing back-reference of a record", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") record.set("attr/partOfMapping", "existing/mapping") await publishAll(backend, record) @@ -648,7 +688,7 @@ describe("LocalTestingBackend", () => { it("keeps the already existing back-references of a record", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") record.set("attr/partOfMapping", [ "existing/mapping-1", "existing/mapping-2", @@ -666,7 +706,7 @@ describe("LocalTestingBackend", () => { it("does not contain the records of another mapping", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") await publishAll(backend, record) const otherMappingRecord = @@ -677,10 +717,10 @@ describe("LocalTestingBackend", () => { it("is updated when the mapping is published again", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") await publishAll(backend, record) - const secondRun = new ConcreteLocalFDORecord("LOCAL/2") + const secondRun = new DefaultLocalFDORecord("LOCAL/2") await publishAll(backend, secondRun) const mappingRecord = await backend.resolveRecord(mappingPID) @@ -694,8 +734,8 @@ describe("LocalTestingBackend", () => { describe("resolveRecord", () => { it("returns a record with the same PID, attributes, references and profiles", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") - record.addProfile(new ConcreteProfile(def), { + const record = new DefaultLocalFDORecord("LOCAL/1") + record.addProfile(testProfile, { datasetName: "My Dataset", authors: ["a1", "a2"], }) @@ -723,7 +763,7 @@ describe("LocalTestingBackend", () => { toRecord: "LOCAL/target2", }, ]) - expect(resolved?.getProfiles()).toEqual(["profile/test"]) + expect(resolved?.getProfile()).toBe("profile/test") }) it("returns undefined for an unknown PID", async () => { @@ -733,7 +773,7 @@ describe("LocalTestingBackend", () => { it("returns a snapshot that is unaffected by later changes to the published record", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") record.set("attr/a", "before") await publishAll(backend, record) @@ -746,7 +786,7 @@ describe("LocalTestingBackend", () => { it("resolves records from any mapping published through any backend", async () => { const backendA = new LocalTestingBackend() const backendB = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/a") + const recordA = new DefaultLocalFDORecord("LOCAL/a") await publishAll(backendA, recordA) expect(await backendB.resolveRecord(recordA.PID!)).toBeDefined() @@ -786,8 +826,8 @@ describe("LocalTestingBackend", () => { it("resolves the records of each mapping independently", async () => { const backend = new LocalTestingBackend() - const recordA = new ConcreteLocalFDORecord("LOCAL/a") - const recordB = new ConcreteLocalFDORecord("LOCAL/b") + const recordA = new DefaultLocalFDORecord("LOCAL/a") + const recordB = new DefaultLocalFDORecord("LOCAL/b") await publishFor(backend, "TEST/mapping-a", recordA) await publishFor(backend, "TEST/mapping-b", recordB) @@ -811,7 +851,7 @@ describe("LocalTestingBackend", () => { describe("resetStore", () => { it("clears all published records and PID assignments", async () => { const backend = new LocalTestingBackend() - const record = new ConcreteLocalFDORecord("LOCAL/1") + const record = new DefaultLocalFDORecord("LOCAL/1") await publishAll(backend, record) LocalTestingBackend.resetStore() diff --git a/packages/playground/src/components/RecordList.tsx b/packages/playground/src/components/RecordList.tsx index b00dcff..e83d2ad 100644 --- a/packages/playground/src/components/RecordList.tsx +++ b/packages/playground/src/components/RecordList.tsx @@ -1,7 +1,18 @@ +import type { AttributeAnyType } from "@fdo-sdk/primitives" import type { RecordSnapshot } from "../runner/snapshot.js" -function formatAttributeValue(value: string | string[]): string { - return Array.isArray(value) ? value.join(", ") : value +function formatValue(value: AttributeAnyType): string { + if (typeof value === "string") return value + if (typeof value === "object") return JSON.stringify(value) + return String(value) +} + +function formatAttributeValue( + value: AttributeAnyType | AttributeAnyType[], +): string { + return Array.isArray(value) + ? value.map(formatValue).join(", ") + : formatValue(value) } export function RecordCard({ record }: { record: RecordSnapshot }) { diff --git a/packages/playground/src/examples/examples.ts b/packages/playground/src/examples/examples.ts index cad3c20..297ae32 100644 --- a/packages/playground/src/examples/examples.ts +++ b/packages/playground/src/examples/examples.ts @@ -17,7 +17,6 @@ export const EXAMPLES: Example[] = [ // graph on the right shows the current state of the store after every // publish. import { - ConcreteLocalFDORecord, LocalFDOGraph, keep, referenceBidi, @@ -212,7 +211,7 @@ await backend.publishContinuous(updateResult) source: `// Records do not need profiles: plain attributes and references are // enough. This example shows the raw record API of the primitives package // with the attributes of @fdo-sdk/simple-types. -import { ConcreteLocalFDORecord, LocalFDOGraph } from "@fdo-sdk/primitives" +import { LocalFDOGraph } from "@fdo-sdk/primitives" import { SIMPLE_ATTRIBUTES } from "@fdo-sdk/simple-types" import { PlaygroundBackend } from "@fdo-sdk/playground" diff --git a/packages/playground/src/runner/playground-backend.ts b/packages/playground/src/runner/playground-backend.ts index 63e6da6..398855d 100644 --- a/packages/playground/src/runner/playground-backend.ts +++ b/packages/playground/src/runner/playground-backend.ts @@ -1,8 +1,8 @@ import type { + CompleteFDORecord, FDORecord, LocalID, PID, - PublishedFDORecord, ReadOnlyFDOGraph, } from "@fdo-sdk/primitives" import { @@ -107,7 +107,7 @@ export class PlaygroundBackend extends LocalTestingBackend { override async publishGraph( graph: ReadOnlyFDOGraph, - ): Promise> { + ): Promise> { const pending: PendingPublish[] = graph.getRecords().map((record) => ({ record, kind: record.PID ? ("updated" as const) : ("created" as const), @@ -121,7 +121,7 @@ export class PlaygroundBackend extends LocalTestingBackend { override async publishRecord( record: FDORecord, - ): Promise { + ): Promise { const kind: "created" | "updated" = record.PID ? "updated" : "created" const published = await super.publishRecord(record) @@ -135,12 +135,12 @@ export class PlaygroundBackend extends LocalTestingBackend { * through this class. This is the state the playground shows as the * published graph. */ - async getAllRecords(): Promise { + async getAllRecords(): Promise { const resolved = await Promise.all( [...PlaygroundBackend.#pids].map((pid) => this.resolveRecord(pid)), ) return resolved.filter( - (record): record is PublishedFDORecord => record !== undefined, + (record): record is CompleteFDORecord => record !== undefined, ) } diff --git a/packages/playground/src/runner/snapshot.ts b/packages/playground/src/runner/snapshot.ts index 2aee3b3..b4213cb 100644 --- a/packages/playground/src/runner/snapshot.ts +++ b/packages/playground/src/runner/snapshot.ts @@ -1,10 +1,14 @@ import type { + AttributeAnyType, ReadOnlyFDOGraph, ReadOnlyFDORecord, ReferenceDeclaration, } from "@fdo-sdk/primitives" -export type AttributeSnapshot = { pid: string; value: string | string[] } +export type AttributeSnapshot = { + pid: string + value: AttributeAnyType | AttributeAnyType[] +} export type ReferenceSnapshot = { attribute: string @@ -43,6 +47,14 @@ function recordId(record: ReadOnlyFDORecord, index: number): string { return record.PID ?? localIDOf(record) ?? `record-${index}` } +function profilesOf(record: ReadOnlyFDORecord): string[] { + const profile = record.getProfile() + if (profile === undefined) return [] + return (Array.isArray(profile) ? profile : [profile]).filter( + (entry): entry is string => typeof entry === "string", + ) +} + export function snapshotGraph( graph: ReadOnlyFDOGraph, label: string, @@ -76,7 +88,7 @@ export function snapshotRecords( id: recordId(record, index), pid: record.PID, localID: localIDOf(record), - profiles: [...record.getProfiles()], + profiles: profilesOf(record), attributes: [...record.getAll()].map(([pid, value]) => ({ pid, value, diff --git a/packages/playground/tests/playground-backend.test.ts b/packages/playground/tests/playground-backend.test.ts index 404f491..ada4546 100644 --- a/packages/playground/tests/playground-backend.test.ts +++ b/packages/playground/tests/playground-backend.test.ts @@ -1,8 +1,9 @@ import { beforeEach, describe, expect, it } from "vitest" import { - ConcreteLocalFDORecord, - ConcreteProfile, + Attribute, + DefaultLocalFDORecord, LocalFDOGraph, + Profile, type LocalID, } from "@fdo-sdk/primitives" import { ContinuousMappingContext } from "@fdo-sdk/mapping" @@ -11,16 +12,21 @@ import { type StoreEvent, } from "../src/runner/playground-backend.js" -const nameAttr = { pid: "attr/name", readableName: "name" } +const nameAttr = Attribute.makeSyntax({ + name: "name", + pid: "attr/name", + cardinality: "1..1", + primitiveDataType: "string", +}) -const authorProfile = new ConcreteProfile({ +const authorProfile = Profile.make({ pid: "profile/author", - readableName: "Author", - mapping: { name: nameAttr.pid }, + name: "Author", + attributes: [nameAttr], }) function makeRecord(localID: LocalID, name: string) { - const record = new ConcreteLocalFDORecord(localID) + const record = new DefaultLocalFDORecord(localID) record.addProfile(authorProfile, { name }) return record } diff --git a/packages/playground/tests/sandbox.test.ts b/packages/playground/tests/sandbox.test.ts index 4eb1aba..1e2c9a4 100644 --- a/packages/playground/tests/sandbox.test.ts +++ b/packages/playground/tests/sandbox.test.ts @@ -204,9 +204,9 @@ describe("runScript", () => { it("exposes @fdo-sdk/simple-types to user scripts", async () => { const outcome = await runScript( [ - 'import { ConcreteLocalFDORecord } from "@fdo-sdk/primitives"', + 'import { DefaultLocalFDORecord } from "@fdo-sdk/primitives"', 'import { SIMPLE_ATTRIBUTES, SIMPLE_PROFILES } from "@fdo-sdk/simple-types"', - 'const record = new ConcreteLocalFDORecord("LOCAL/one")', + 'const record = new DefaultLocalFDORecord("LOCAL/one")', "record.addProfile(SIMPLE_PROFILES.DATA_OBJECT, {", ' dataObjectLocation: "https://example.org/data/one.nc",', ' dataObjectLicense: "CC-BY-4.0",', @@ -228,10 +228,10 @@ describe("runScript", () => { const snapshots: GraphSnapshot[] = [] const outcome = await runScript( [ - 'import { ConcreteLocalFDORecord, LocalFDOGraph } from "@fdo-sdk/primitives"', + 'import { DefaultLocalFDORecord, LocalFDOGraph } from "@fdo-sdk/primitives"', 'import { PlaygroundBackend } from "@fdo-sdk/playground"', "const backend = PlaygroundBackend.getInstance()", - 'const record = new ConcreteLocalFDORecord("LOCAL/one")', + 'const record = new DefaultLocalFDORecord("LOCAL/one")', 'record.set("attr/name", "one")', "const graph = new LocalFDOGraph()", "graph.addRecord(record)", @@ -259,10 +259,10 @@ describe("runScript", () => { PlaygroundBackend.resetStore() const outcome = await runScript( [ - 'import { ConcreteLocalFDORecord, LocalFDOGraph } from "@fdo-sdk/primitives"', + 'import { DefaultLocalFDORecord, LocalFDOGraph } from "@fdo-sdk/primitives"', 'import { PlaygroundBackend } from "@fdo-sdk/playground"', "const backend = PlaygroundBackend.getInstance()", - 'const record = new ConcreteLocalFDORecord("LOCAL/one")', + 'const record = new DefaultLocalFDORecord("LOCAL/one")', 'record.set("attr/name", "one")', "const graph = new LocalFDOGraph()", "graph.addRecord(record)", diff --git a/packages/playground/tests/snapshot.test.ts b/packages/playground/tests/snapshot.test.ts index 8a6df66..47250a1 100644 --- a/packages/playground/tests/snapshot.test.ts +++ b/packages/playground/tests/snapshot.test.ts @@ -1,32 +1,43 @@ import { describe, expect, it } from "vitest" import { - ConcreteLocalFDORecord, - ConcreteProfile, + Attribute, + DefaultLocalFDORecord, LocalFDOGraph, + Profile, } from "@fdo-sdk/primitives" import { LocalTestingBackend } from "@fdo-sdk/mapping" import { snapshotGraph, snapshotRecords } from "../src/runner/snapshot.js" -const nameAttr = { pid: "attr/name", readableName: "name" } -const hasAuthorAttr = { pid: "attr/hasAuthor", readableName: "hasAuthor" } -const authoredAttr = { +const nameAttr = Attribute.makeSyntax({ + name: "name", + pid: "attr/name", + cardinality: "1..1", + primitiveDataType: "string", +}) +const hasAuthorAttr = Attribute.makeAttrRef({ + name: "hasAuthor", + pid: "attr/hasAuthor", + cardinality: "0..*", +}) +const authoredAttr = Attribute.makeAttrRef({ + name: "authoredDatasets", pid: "attr/authoredDatasets", - readableName: "authoredDatasets", -} + cardinality: "0..*", +}) -const authorProfile = new ConcreteProfile({ +const authorProfile = Profile.make({ pid: "profile/author", - readableName: "Author", - mapping: { name: nameAttr.pid }, + name: "Author", + attributes: [nameAttr], }) function buildGraph(): LocalFDOGraph { const graph = new LocalFDOGraph() - const ada = new ConcreteLocalFDORecord("LOCAL/ada") + const ada = new DefaultLocalFDORecord("LOCAL/ada") ada.addProfile(authorProfile, { name: "Ada" }) - const grace = new ConcreteLocalFDORecord("LOCAL/grace") + const grace = new DefaultLocalFDORecord("LOCAL/grace") grace.addProfile(authorProfile, { name: "Grace" }) - const dataset = new ConcreteLocalFDORecord("LOCAL/dataset") + const dataset = new DefaultLocalFDORecord("LOCAL/dataset") dataset.addProfile(authorProfile, { name: "Dataset" }) dataset.addReferenceBidi(hasAuthorAttr, authoredAttr, "LOCAL/ada") dataset.addReference(hasAuthorAttr, "LOCAL/grace") @@ -118,9 +129,9 @@ describe("snapshotGraph", () => { describe("snapshotRecords", () => { it("snapshots an arbitrary list of records", () => { - const a = new ConcreteLocalFDORecord("LOCAL/a") + const a = new DefaultLocalFDORecord("LOCAL/a") a.set(nameAttr.pid, "A") - const b = new ConcreteLocalFDORecord("LOCAL/b") + const b = new DefaultLocalFDORecord("LOCAL/b") b.set(nameAttr.pid, "B") const snapshot = snapshotRecords([a, b], "Published graph") @@ -142,8 +153,8 @@ describe("snapshotRecords", () => { }) it("does not duplicate a bidirectional reference that both records declare", () => { - const a = new ConcreteLocalFDORecord("LOCAL/a") - const b = new ConcreteLocalFDORecord("LOCAL/b") + const a = new DefaultLocalFDORecord("LOCAL/a") + const b = new DefaultLocalFDORecord("LOCAL/b") a.addReferenceBidi(hasAuthorAttr, authoredAttr, "LOCAL/b") b.addReferenceBidi(authoredAttr, hasAuthorAttr, "LOCAL/a") @@ -159,7 +170,7 @@ describe("snapshotRecords", () => { }) it("keeps a bidirectional reference to a record outside the snapshot", () => { - const record = new ConcreteLocalFDORecord("LOCAL/a") + const record = new DefaultLocalFDORecord("LOCAL/a") record.addReferenceBidi(hasAuthorAttr, authoredAttr, "LOCAL/outside") const snapshot = snapshotRecords([record], "Local") diff --git a/packages/playground/tests/ts-project.test.ts b/packages/playground/tests/ts-project.test.ts index 7f8e18a..647c210 100644 --- a/packages/playground/tests/ts-project.test.ts +++ b/packages/playground/tests/ts-project.test.ts @@ -75,7 +75,7 @@ describe("createProject completions", () => { const project = makeProject() const names = completeNames( project, - 'import { ConcreteLocalFDORecord } from "@fdo-sdk/primitives"\nconst record = new ConcreteLocalFDORecord("LOCAL/1")\nrecord.', + 'import { DefaultLocalFDORecord } from "@fdo-sdk/primitives"\nconst record = new DefaultLocalFDORecord("LOCAL/1")\nrecord.', ) expect(names).toContain("addProfile") @@ -168,10 +168,10 @@ describe("createProject completions", () => { const names = completeNames( project, [ - 'import { ConcreteLocalFDORecord } from "@fdo-sdk/primitives"', + 'import { DefaultLocalFDORecord } from "@fdo-sdk/primitives"', 'import { PlaygroundBackend } from "@fdo-sdk/playground"', "const backend = PlaygroundBackend.getInstance()", - 'const record = new ConcreteLocalFDORecord("LOCAL/1")', + 'const record = new DefaultLocalFDORecord("LOCAL/1")', "record.addProfile", "const published = await backend.publishGraph(record)", "published.", @@ -255,7 +255,7 @@ describe("createProject diagnostics", () => { it("warns about a non-existent member", () => { const project = makeProject() project.update( - 'import { ConcreteLocalFDORecord } from "@fdo-sdk/primitives"\nconst record = new ConcreteLocalFDORecord("LOCAL/1")\nrecord.build()', + 'import { DefaultLocalFDORecord } from "@fdo-sdk/primitives"\nconst record = new DefaultLocalFDORecord("LOCAL/1")\nrecord.build()', ) const diagnostics = project.diagnostics() @@ -282,7 +282,7 @@ describe("createProject diagnostics", () => { it("does not report unused variables", () => { const project = makeProject() project.update( - 'import { ConcreteLocalFDORecord } from "@fdo-sdk/primitives"\nconst unused = new ConcreteLocalFDORecord("LOCAL/1")', + 'import { DefaultLocalFDORecord } from "@fdo-sdk/primitives"\nconst unused = new DefaultLocalFDORecord("LOCAL/1")', ) expect(project.diagnostics()).toEqual([]) @@ -292,7 +292,7 @@ describe("createProject diagnostics", () => { const project = makeProject() project.update( [ - 'import { ConcreteLocalFDORecord, LocalFDOGraph } from "@fdo-sdk/primitives"', + 'import { DefaultLocalFDORecord, LocalFDOGraph } from "@fdo-sdk/primitives"', 'import { ContinuousMappingContext } from "@fdo-sdk/mapping"', 'import { PlaygroundBackend } from "@fdo-sdk/playground"', "", @@ -301,7 +301,7 @@ describe("createProject diagnostics", () => { 'const context = new ContinuousMappingContext("TEST/mapping")', 'const record = context.newRecord("LOCAL/1")', 'record.set("attr/name", "x")', - 'const local = new ConcreteLocalFDORecord("LOCAL/2")', + 'const local = new DefaultLocalFDORecord("LOCAL/2")', "const graph = new LocalFDOGraph()", "graph.addRecord(local)", "graph.build()", diff --git a/packages/primitives/src/impl/DefaultFDORecord.ts b/packages/primitives/src/impl/DefaultFDORecord.ts index e909bba..e1f5907 100644 --- a/packages/primitives/src/impl/DefaultFDORecord.ts +++ b/packages/primitives/src/impl/DefaultFDORecord.ts @@ -9,7 +9,7 @@ import { type ReferenceDeclaration, type WithMarkers, } from "../types.js" -import { toArray } from "../utils.js" +import { isComplete, toArray } from "../utils.js" import { isKeep, isReference, isSkip } from "./markers.js" import type { AttributeAnyType, @@ -26,9 +26,10 @@ import { ProfileAttribute, TypeAttribute, } from "../type-system/attributes.js" + /** * Base implementation of the {@link FDORecord} interface. Can hold a PID to be - * a {@link CompleteFDORecord} (use {@link isPublished} to check). + * a {@link CompleteFDORecord} (use {@link isComplete} to check). * * Consider using {@link DefaultLocalFDORecord} if you are creating FDOs */ diff --git a/packages/primitives/src/index.ts b/packages/primitives/src/index.ts index 5ebef56..8267003 100644 --- a/packages/primitives/src/index.ts +++ b/packages/primitives/src/index.ts @@ -2,3 +2,4 @@ export * from "./types.js" export * from "./interfaces/index.js" export * from "./impl/index.js" export * from "./type-system/index.js" +export * from "./utils.js" diff --git a/packages/primitives/src/interfaces/Attribute.ts b/packages/primitives/src/interfaces/Attribute.ts index 0c8f053..b30b3c2 100644 --- a/packages/primitives/src/interfaces/Attribute.ts +++ b/packages/primitives/src/interfaces/Attribute.ts @@ -14,6 +14,11 @@ export type CardinalityType = `${number}..${number | "*"}` export type AttributeAnyType = string | boolean | number | Record +/** + * Base interface for an attribute definition that all attribute definitions + * must extend. An attribute has a name (N), allowed value types (Type) and a + * cardinality (Cardinality, either "0..1", "1..1", "1..*", "0..*") + */ export interface AttributeDef< N extends string, Type extends AttributeAnyType, @@ -28,12 +33,54 @@ export interface AttributeDef< readonly validationStrategyForCombination?: "anyof" | "allof" } +/** + * Default type signature for an attribute definition, can be used to express + * any attribute + */ export type DefaultAttributeDef = AttributeDef< string, AttributeAnyType, CardinalityType > +type PrimitiveValue< + PrimitiveType extends "string" | "number" | "integer" | "boolean", +> = PrimitiveType extends "string" + ? string + : PrimitiveType extends "number" + ? number + : PrimitiveType extends "integer" + ? number + : PrimitiveType extends "boolean" + ? boolean + : string + +/** + * The value type of a syntax attribute: the primitive type, narrowed to the + * whitelist values when a whitelist is given. The `[Whitelist] extends + * [undefined]` guard exists because under `strictNullChecks: false` (the + * playground's language service) `undefined extends string[]` is true, which + * would otherwise index into `undefined` and collapse the whole conditional + * to `unknown`, breaking assignability to the attribute base types. + */ +type SyntaxValueType< + PrimitiveType extends "string" | "number" | "integer" | "boolean", + Whitelist, +> = [Whitelist] extends [undefined] // only undefined extends undefined + ? PrimitiveValue + : Whitelist extends string | string[] + ? Whitelist extends string[] + ? Whitelist[number] + : Whitelist + : PrimitiveValue + +/** + * This interface defines an attribute whose value dictates a specific syntax. + * It has a specific primitive type (string, number, integer, boolean) and + * can specify a whitelist, blacklist, regex or a numeric interval. + * + * In case of a string, the numeric interval describes the length of the string. + */ export interface AttributeDefSyntax< N extends string, Cardinality extends CardinalityType, @@ -41,19 +88,7 @@ export interface AttributeDefSyntax< Whitelist extends string | string[] | undefined = undefined, > extends AttributeDef< N, - Whitelist extends string | string[] - ? Whitelist extends string[] - ? Whitelist[number] - : Whitelist - : PrimitiveType extends "string" - ? string - : PrimitiveType extends "number" - ? number - : PrimitiveType extends "integer" - ? number - : PrimitiveType extends "boolean" - ? boolean - : string, + SyntaxValueType, Cardinality > { readonly defType: "syntax" @@ -64,6 +99,11 @@ export interface AttributeDefSyntax< readonly blacklist?: string | string[] } +/** + * This interface defines an attribute whose value is a reference to another + * FDO Record. It may restrict which profiles the referenced FDO Record must + * be conforming to. + */ export interface AttributeDefProfileRef< N extends string, Cardinality extends CardinalityType, @@ -72,6 +112,11 @@ export interface AttributeDefProfileRef< readonly allowedProfiles?: string | string[] } +/** + * This interface defines an attribute whose value is the PID of another + * attribute. The reference attribute must also be present on the same record + * where this attribute is present. + */ export interface AttributeDefAttrRef< N extends string, Cardinality extends CardinalityType, @@ -81,6 +126,11 @@ export interface AttributeDefAttrRef< readonly allowedPlainNames?: string | string[] } +/** + * This interface defines an attribute that is a combination of two or more + * other attributes. The value of such a combination attribute is a + * JSON Object in the : form. + */ export interface AttributeDefCombination< N extends string, Cardinality extends CardinalityType, @@ -95,6 +145,11 @@ export interface AttributeDefCombination< readonly allowedAttributesInCombination?: AttributesInComb } +/** + * This interface defines an attribute that is a union of two or more + * other attributes. Allowed values of this attribute are a union + * of the types of attributes in the union. + */ export interface AttributeDefUnion< N extends string, Cardinality extends CardinalityType, @@ -109,6 +164,10 @@ export interface AttributeDefUnion< readonly allowedAttributesInUnion?: AttributesInUnion } +/** + * This interface defines an attribute whose values must come from a specific + * vocabulary. + */ export interface AttributeDefVocabularyRef< N extends string, Cardinality extends CardinalityType, @@ -130,6 +189,11 @@ export type AttrTypeWithCardinality< A extends AttributeDef, > = A extends MultiValueAttr ? A["~type"] | A["~type"][] : A["~type"] +/** + * @internal + * Turns an array of attribute definitions into an object in the form + * : + */ export type AttrsToObj< AttributeList extends readonly AttributeDef< string, @@ -148,6 +212,10 @@ export type AttrsToObj< export type Simplify = { [K in keyof T]: T[K] } & {} +/** + * Add the `~type` property to the given object on the type layer + * @param obj + */ function withPhantomType( obj: Obj, ): Obj & { "~type": Type } { @@ -155,6 +223,12 @@ function withPhantomType( } export const Attribute = { + /** + * Make an attribute with no specific value checking. The value of this + * attribute is expected to be a string. + * @param details + * @see AttributeDef + */ makeBase( details: Simplify< Omit, "~type" | "defType"> @@ -166,6 +240,11 @@ export const Attribute = { }) }, + /** + * Make a syntax attribute + * @param details + * @see AttributeDefSyntax + */ makeSyntax< N extends string, Cardinality extends CardinalityType, @@ -185,6 +264,11 @@ export const Attribute = { }) }, + /** + * Make an attribute reference attribute + * @param details + * @see AttributeDefAttrRef + */ makeAttrRef( details: Simplify< Omit, "~type" | "defType"> @@ -196,6 +280,11 @@ export const Attribute = { }) }, + /** + * Make a profile reference attribute + * @param details + * @see AttributeDefProfileRef + */ makeProfileRef( details: Simplify< Omit, "~type" | "defType"> @@ -207,6 +296,11 @@ export const Attribute = { }) }, + /** + * Make a combination attribute consisting of multiple other attributes + * @param details + * @see AttributeDefCombination + */ makeCombination< N extends string, Cardinality extends CardinalityType, @@ -230,6 +324,11 @@ export const Attribute = { }) }, + /** + * Make an attribute that is the union of multiple other attributes + * @param details + * @see AttributeDefUnion + */ makeUnion< N extends string, Cardinality extends CardinalityType, @@ -253,6 +352,11 @@ export const Attribute = { }) }, + /** + * Make a vocabulary attribute + * @param details + * @see AttributeDefVocabularyRef + */ makeVocabulary( details: Simplify< Omit, "~type" | "defType"> @@ -264,6 +368,12 @@ export const Attribute = { }) }, + /** + * Make a refined version of an existing attribute, where the cardinality + * is changed. + * @param attribute + * @param newCardinality + */ makeRefined< A extends AttributeDef, NewCardinality extends CardinalityType, diff --git a/packages/primitives/src/interfaces/FDORecord.ts b/packages/primitives/src/interfaces/FDORecord.ts index 4ea18d0..843b061 100644 --- a/packages/primitives/src/interfaces/FDORecord.ts +++ b/packages/primitives/src/interfaces/FDORecord.ts @@ -245,8 +245,8 @@ export interface ReadOnlyFDORecord { * Get a list of outgoing references from this record to other records. Locally * used to realize bidirectional references when the FDO Graph is published. * - * Only contains references that were added to this record using {@link addReference} - * or {@link addReferenceBidi} or similar + * Only contains references that were added to this record using {@link FDORecord.addReference} + * or {@link FDORecord.addReferenceBidi} or similar */ getReferences(): ReferenceDeclaration[] diff --git a/packages/primitives/src/interfaces/Profile.ts b/packages/primitives/src/interfaces/Profile.ts index 4971bca..3f9c790 100644 --- a/packages/primitives/src/interfaces/Profile.ts +++ b/packages/primitives/src/interfaces/Profile.ts @@ -5,6 +5,10 @@ import { } from "./Attribute.js" import type { PID } from "../types.js" +/** + * This interface defines an FDO Profile. It consists of the PID of the profile, + * and the expected attributes. + */ export interface ProfileDef< Attributes extends readonly AttributeDef< string, @@ -20,6 +24,10 @@ export interface ProfileDef< } export const Profile = { + /** + * @see ProfileDef + * @param details + */ make< Attributes extends readonly AttributeDef< string, diff --git a/packages/simple-types/README.md b/packages/simple-types/README.md index 44b7d3d..6846901 100644 --- a/packages/simple-types/README.md +++ b/packages/simple-types/README.md @@ -34,8 +34,11 @@ data.addProfile(SIMPLE_PROFILES.DATA_OBJECT, { data.get(SIMPLE_ATTRIBUTES.MIME_TYPE) // "application/netcdf" ``` -The attribute constants can be used anywhere a PID or `Attribute` is -expected, e.g. `record.get(SIMPLE_ATTRIBUTES.DOI)`. +Applying a profile writes every attribute under its PID and records the +profile PID at `0.FDO/Profile`, readable via `record.getProfile()`. +`SIMPLE_ATTRIBUTES` entries are attribute definitions and can be used +anywhere a PID or `AttributeDef` is expected, e.g. +`record.get(SIMPLE_ATTRIBUTES.DOI)`. ## Profiles @@ -46,40 +49,58 @@ expected, e.g. `record.get(SIMPLE_ATTRIBUTES.DOI)`. | `SIMPLE_PROFILES.DATA_OBJECT` | `dataObjectLocation`, `dataObjectLicense`, `mimeType` | `isPartOf`, `createdWithSoftware` | | `SIMPLE_PROFILES.PUBLICATION` | `doi`, `publicationTitle`, `publicationCreator` | `hasPart` | -Every profile uses `0.SIMPLE/PROFILE` as its profile marker attribute, so -`addProfile()` writes the profile PID there and into `getProfiles()`. +Attributes that point at other FDO records (`isPartOf`, `hasPart`, +`createdWithSoftware`) are declared as profile references, so they accept a +profile PID or a `reference()` marker — `reference(software)` above adds a +reference from the `createdWithSoftware` attribute to the software record. +The `PROFILE` attribute is restricted to the four simple profiles. ## Attributes -| Constant | PID | -| -------------------------------------------- | ----------------------------------- | -| `SIMPLE_ATTRIBUTES.OWNER` | `0.SIMPLE/OWNER` | -| `SIMPLE_ATTRIBUTES.HELMHOLTZ_RESEARCH_FIELD` | `0.SIMPLE/HELMHOLTZ_RESEARCH_FIELD` | -| `SIMPLE_ATTRIBUTES.PROFILE` | `0.SIMPLE/PROFILE` | -| `SIMPLE_ATTRIBUTES.SOFTWARE_REPOSITORY_TYPE` | `0.SIMPLE/SOFTWARE_REPOSITORY_TYPE` | -| `SIMPLE_ATTRIBUTES.SOFTWARE_LOCATION` | `0.SIMPLE/SOFTWARE_LOCATION` | -| `SIMPLE_ATTRIBUTES.SOFTWARE_LICENSE` | `0.SIMPLE/SOFTWARE_LICENSE` | -| `SIMPLE_ATTRIBUTES.README_LOCATION` | `0.SIMPLE/README_LOCATION` | -| `SIMPLE_ATTRIBUTES.DATA_OBJECT_LOCATION` | `0.SIMPLE/DATA_OBJECT_LOCATION` | -| `SIMPLE_ATTRIBUTES.DATA_OBJECT_LICENSE` | `0.SIMPLE/DATA_OBJECT_LICENSE` | -| `SIMPLE_ATTRIBUTES.MIME_TYPE` | `0.SIMPLE/MIME_TYPE` | -| `SIMPLE_ATTRIBUTES.DOI` | `0.SIMPLE/DOI` | -| `SIMPLE_ATTRIBUTES.PUBLICATION_TITLE` | `0.SIMPLE/PUBLICATION_TITLE` | -| `SIMPLE_ATTRIBUTES.PUBLICATION_CREATOR` | `0.SIMPLE/PUBLICATION_CREATOR` | -| `SIMPLE_ATTRIBUTES.VERSION` | `0.SIMPLE/VERSION` | -| `SIMPLE_ATTRIBUTES.PUBLICATION_DATE` | `0.SIMPLE/PUBLICATION_DATE` | -| `SIMPLE_ATTRIBUTES.CREATION_DATE` | `0.SIMPLE/CREATION_DATE` | -| `SIMPLE_ATTRIBUTES.IS_PART_OF` | `0.SIMPLE/IS_PART_OF` | -| `SIMPLE_ATTRIBUTES.HAS_PART` | `0.SIMPLE/HAS_PART` | -| `SIMPLE_ATTRIBUTES.CREATED_WITH_SOFTWARE` | `0.SIMPLE/CREATED_WITH_SOFTWARE` | -| `SIMPLE_ATTRIBUTES.LOCAL_ID` | `0.SIMPLE/LOCAL_ID` | - -The raw identifier objects are exported too: `FDO_TYPES` (attributes), -`FDO_PROFILES` (profiles) and `LEGACY_TYPE_KEYS` (the legacy version and date -attributes). +| Constant | PID | Cardinality | +| -------------------------------------------- | ----------------------------------- | ------------ | +| `SIMPLE_ATTRIBUTES.OWNER` | `0.SIMPLE/OWNER` | `1..1` | +| `SIMPLE_ATTRIBUTES.HELMHOLTZ_RESEARCH_FIELD` | `0.SIMPLE/HELMHOLTZ_RESEARCH_FIELD` | `1..1` | +| `SIMPLE_ATTRIBUTES.PROFILE` | `0.SIMPLE/PROFILE` | `0..1` | +| `SIMPLE_ATTRIBUTES.SOFTWARE_REPOSITORY_TYPE` | `0.SIMPLE/SOFTWARE_REPOSITORY_TYPE` | `1..1` | +| `SIMPLE_ATTRIBUTES.SOFTWARE_LOCATION` | `0.SIMPLE/SOFTWARE_LOCATION` | `1..1` | +| `SIMPLE_ATTRIBUTES.SOFTWARE_LICENSE` | `0.SIMPLE/SOFTWARE_LICENSE` | `1..1` | +| `SIMPLE_ATTRIBUTES.README_LOCATION` | `0.SIMPLE/README_LOCATION` | `0..1` | +| `SIMPLE_ATTRIBUTES.DATA_OBJECT_LOCATION` | `0.SIMPLE/DATA_OBJECT_LOCATION` | `1..1` | +| `SIMPLE_ATTRIBUTES.DATA_OBJECT_LICENSE` | `0.SIMPLE/DATA_OBJECT_LICENSE` | `1..1` | +| `SIMPLE_ATTRIBUTES.MIME_TYPE` | `0.SIMPLE/MIME_TYPE` | `1..1` | +| `SIMPLE_ATTRIBUTES.DOI` | `0.SIMPLE/DOI` | `1..1` | +| `SIMPLE_ATTRIBUTES.PUBLICATION_TITLE` | `0.SIMPLE/PUBLICATION_TITLE` | `1..1` | +| `SIMPLE_ATTRIBUTES.PUBLICATION_CREATOR` | `0.SIMPLE/PUBLICATION_CREATOR` | `1..*` | +| `SIMPLE_ATTRIBUTES.VERSION` | `0.SIMPLE/VERSION` | `0..1` | +| `SIMPLE_ATTRIBUTES.PUBLICATION_DATE` | `0.SIMPLE/PUBLICATION_DATE` | `0..1` | +| `SIMPLE_ATTRIBUTES.CREATION_DATE` | `0.SIMPLE/CREATION_DATE` | `0..1` | +| `SIMPLE_ATTRIBUTES.IS_PART_OF` | `0.SIMPLE/IS_PART_OF` | `0..*` | +| `SIMPLE_ATTRIBUTES.HAS_PART` | `0.SIMPLE/HAS_PART` | `0..1` | +| `SIMPLE_ATTRIBUTES.CREATED_WITH_SOFTWARE` | `0.SIMPLE/CREATED_WITH_SOFTWARE` | `0..*` | +| `SIMPLE_ATTRIBUTES.LOCAL_ID` | `0.SIMPLE/LOCAL_ID` | `0..1` | ## Writing your own types -For real data, define your own `ProfileDefinition` and instantiate it with -`DefaultProfile` from `@fdo-sdk/primitives`. The simple types are a model for -how to do that, not a fixed vocabulary. +For real data, define your own attributes with `Attribute.makeSyntax` (or the +other factories) and combine them with `Profile.make`. The simple types are a +model for how to do that, not a fixed vocabulary. + +```ts +import { Attribute, Profile } from "@fdo-sdk/primitives" + +const TitleAttribute = Attribute.makeSyntax({ + name: "title", + pid: "0.MYAPP/TITLE", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const PublicationProfile = Profile.make({ + pid: "0.MYAPP/PUBLICATION", + name: "My Publication Profile", + attributes: [TitleAttribute], +}) + +record.addProfile(PublicationProfile, { title: "FDOs in practice" }) +``` diff --git a/packages/simple-types/src/attributes.ts b/packages/simple-types/src/attributes.ts index a439cdb..65bfbb9 100644 --- a/packages/simple-types/src/attributes.ts +++ b/packages/simple-types/src/attributes.ts @@ -1,91 +1,186 @@ -import type { Attribute } from "@fdo-sdk/primitives" -import { FDO_TYPES, LEGACY_TYPE_KEYS } from "./identifiers.js" - -export const SIMPLE_ATTRIBUTES: { - readonly OWNER: Attribute - readonly HELMHOLTZ_RESEARCH_FIELD: Attribute - readonly PROFILE: Attribute - readonly SOFTWARE_REPOSITORY_TYPE: Attribute - readonly SOFTWARE_LOCATION: Attribute - readonly SOFTWARE_LICENSE: Attribute - readonly README_LOCATION: Attribute - readonly DATA_OBJECT_LOCATION: Attribute - readonly DATA_OBJECT_LICENSE: Attribute - readonly MIME_TYPE: Attribute - readonly DOI: Attribute - readonly PUBLICATION_TITLE: Attribute - readonly PUBLICATION_CREATOR: Attribute - readonly VERSION: Attribute - readonly PUBLICATION_DATE: Attribute - readonly CREATION_DATE: Attribute - readonly IS_PART_OF: Attribute - readonly HAS_PART: Attribute - readonly CREATED_WITH_SOFTWARE: Attribute - readonly LOCAL_ID: Attribute -} = { - OWNER: { pid: FDO_TYPES.OWNER, readableName: "Owner" }, - HELMHOLTZ_RESEARCH_FIELD: { - pid: FDO_TYPES.HELMHOLTZ_RESEARCH_FIELD, - readableName: "Helmholtz Research Field", - }, - PROFILE: { pid: FDO_TYPES.PROFILE, readableName: "Profile" }, - SOFTWARE_REPOSITORY_TYPE: { - pid: FDO_TYPES.SOFTWARE_REPOSITORY_TYPE, - readableName: "Software Repository Type", - }, - SOFTWARE_LOCATION: { - pid: FDO_TYPES.SOFTWARE_LOCATION, - readableName: "Software Location", - }, - SOFTWARE_LICENSE: { - pid: FDO_TYPES.SOFTWARE_LICENSE, - readableName: "Software License", - }, - README_LOCATION: { - pid: FDO_TYPES.README_LOCATION, - readableName: "README Location", - }, - DATA_OBJECT_LOCATION: { - pid: FDO_TYPES.DATA_OBJECT_LOCATION, - readableName: "Data Object Location", - }, - DATA_OBJECT_LICENSE: { - pid: FDO_TYPES.DATA_OBJECT_LICENSE, - readableName: "Data Object License", - }, - MIME_TYPE: { pid: FDO_TYPES.MIME_TYPE, readableName: "MIME Type" }, - DOI: { pid: FDO_TYPES.DOI, readableName: "DOI" }, - PUBLICATION_TITLE: { - pid: FDO_TYPES.PUBLICATION_TITLE, - readableName: "Publication Title", - }, - PUBLICATION_CREATOR: { - pid: FDO_TYPES.PUBLICATION_CREATOR, - readableName: "Publication Creator", - }, - VERSION: { pid: LEGACY_TYPE_KEYS.VERSION, readableName: "Version" }, - PUBLICATION_DATE: { - pid: LEGACY_TYPE_KEYS.PUBLICATION_DATE, - readableName: "Publication Date", - }, - CREATION_DATE: { - pid: LEGACY_TYPE_KEYS.CREATION_DATE, - readableName: "Creation Date", - }, - IS_PART_OF: { - pid: FDO_TYPES.IS_PART_OF, - readableName: "Is Part Of", - }, - HAS_PART: { - pid: FDO_TYPES.HAS_PART, - readableName: "Has Part", - }, - CREATED_WITH_SOFTWARE: { - pid: FDO_TYPES.CREATED_WITH_SOFTWARE, - readableName: "Created with Software", - }, - LOCAL_ID: { - pid: FDO_TYPES.LOCAL_ID, - readableName: "Local ID", - }, +import { Attribute } from "@fdo-sdk/primitives" + +const OWNER = Attribute.makeSyntax({ + name: "owner", + pid: "0.SIMPLE/OWNER", + description: "The person or organisation responsible for the FDO.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const HELMHOLTZ_RESEARCH_FIELD = Attribute.makeSyntax({ + name: "helmholtzResearchField", + pid: "0.SIMPLE/HELMHOLTZ_RESEARCH_FIELD", + description: "The Helmholtz research field the resource belongs to.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const PROFILE = Attribute.makeProfileRef({ + name: "profile", + pid: "0.SIMPLE/PROFILE", + description: + "The simple profile this record conforms to. Profile membership is usually recorded automatically through 0.FDO/Profile when a profile is applied.", + cardinality: "0..1", + allowedProfiles: [ + "0.SIMPLE/CORE", + "0.SIMPLE/DATA_OBJECT", + "0.SIMPLE/SOFTWARE", + "0.SIMPLE/PUBLICATION", + ], +}) + +const SOFTWARE_REPOSITORY_TYPE = Attribute.makeSyntax({ + name: "softwareRepositoryType", + pid: "0.SIMPLE/SOFTWARE_REPOSITORY_TYPE", + description: 'The type of the software repository, e.g. "git".', + cardinality: "1..1", + primitiveDataType: "string", +}) + +const SOFTWARE_LOCATION = Attribute.makeSyntax({ + name: "softwareLocation", + pid: "0.SIMPLE/SOFTWARE_LOCATION", + description: "The location where the software is stored.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const SOFTWARE_LICENSE = Attribute.makeSyntax({ + name: "softwareLicense", + pid: "0.SIMPLE/SOFTWARE_LICENSE", + description: "The license the software is published under.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const README_LOCATION = Attribute.makeSyntax({ + name: "readmeLocation", + pid: "0.SIMPLE/README_LOCATION", + description: "The location of the README file.", + cardinality: "0..1", + primitiveDataType: "string", +}) + +const DATA_OBJECT_LOCATION = Attribute.makeSyntax({ + name: "dataObjectLocation", + pid: "0.SIMPLE/DATA_OBJECT_LOCATION", + description: "The location where the data object is stored.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const DATA_OBJECT_LICENSE = Attribute.makeSyntax({ + name: "dataObjectLicense", + pid: "0.SIMPLE/DATA_OBJECT_LICENSE", + description: "The license the data object is published under.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const MIME_TYPE = Attribute.makeSyntax({ + name: "mimeType", + pid: "0.SIMPLE/MIME_TYPE", + description: "The MIME type of the data object.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const DOI = Attribute.makeSyntax({ + name: "doi", + pid: "0.SIMPLE/DOI", + description: "The Digital Object Identifier of the publication.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const PUBLICATION_TITLE = Attribute.makeSyntax({ + name: "publicationTitle", + pid: "0.SIMPLE/PUBLICATION_TITLE", + description: "The title of the publication.", + cardinality: "1..1", + primitiveDataType: "string", +}) + +const PUBLICATION_CREATOR = Attribute.makeProfileRef({ + name: "publicationCreator", + pid: "0.SIMPLE/PUBLICATION_CREATOR", + description: "The creator(s) of the publication.", + cardinality: "1..*", +}) + +const VERSION = Attribute.makeSyntax({ + name: "version", + pid: "0.SIMPLE/VERSION", + description: "The version of the resource.", + cardinality: "0..1", + primitiveDataType: "string", +}) + +const PUBLICATION_DATE = Attribute.makeSyntax({ + name: "publicationDate", + pid: "0.SIMPLE/PUBLICATION_DATE", + description: "The date the publication was published.", + cardinality: "0..1", + primitiveDataType: "string", +}) + +const CREATION_DATE = Attribute.makeSyntax({ + name: "creationDate", + pid: "0.SIMPLE/CREATION_DATE", + description: "The date the resource was created.", + cardinality: "0..1", + primitiveDataType: "string", +}) + +const IS_PART_OF = Attribute.makeProfileRef({ + name: "isPartOf", + pid: "0.SIMPLE/IS_PART_OF", + description: "The FDO record this record is part of.", + cardinality: "0..*", +}) + +const HAS_PART = Attribute.makeProfileRef({ + name: "hasPart", + pid: "0.SIMPLE/HAS_PART", + description: "An FDO record that is part of this record.", + cardinality: "0..*", +}) + +const CREATED_WITH_SOFTWARE = Attribute.makeProfileRef({ + name: "createdWithSoftware", + pid: "0.SIMPLE/CREATED_WITH_SOFTWARE", + description: "The software that was used to create this record.", + cardinality: "0..*", +}) + +const LOCAL_ID = Attribute.makeSyntax({ + name: "localId", + pid: "0.SIMPLE/LOCAL_ID", + description: "The local identifier of the FDO record.", + cardinality: "0..1", + primitiveDataType: "string", +}) + +export const SIMPLE_ATTRIBUTES = { + OWNER, + HELMHOLTZ_RESEARCH_FIELD, + PROFILE, + SOFTWARE_REPOSITORY_TYPE, + SOFTWARE_LOCATION, + SOFTWARE_LICENSE, + README_LOCATION, + DATA_OBJECT_LOCATION, + DATA_OBJECT_LICENSE, + MIME_TYPE, + DOI, + PUBLICATION_TITLE, + PUBLICATION_CREATOR, + VERSION, + PUBLICATION_DATE, + CREATION_DATE, + IS_PART_OF, + HAS_PART, + CREATED_WITH_SOFTWARE, + LOCAL_ID, } diff --git a/packages/simple-types/src/identifiers.ts b/packages/simple-types/src/identifiers.ts deleted file mode 100644 index 3d80203..0000000 --- a/packages/simple-types/src/identifiers.ts +++ /dev/null @@ -1,37 +0,0 @@ -export const FDO_TYPES = { - OWNER: "0.SIMPLE/OWNER", - HELMHOLTZ_RESEARCH_FIELD: "0.SIMPLE/HELMHOLTZ_RESEARCH_FIELD", - PROFILE: "0.SIMPLE/PROFILE", - SOFTWARE_REPOSITORY_TYPE: "0.SIMPLE/SOFTWARE_REPOSITORY_TYPE", - SOFTWARE_LOCATION: "0.SIMPLE/SOFTWARE_LOCATION", - SOFTWARE_LICENSE: "0.SIMPLE/SOFTWARE_LICENSE", - README_LOCATION: "0.SIMPLE/README_LOCATION", - DATA_OBJECT_LOCATION: "0.SIMPLE/DATA_OBJECT_LOCATION", - DATA_OBJECT_LICENSE: "0.SIMPLE/DATA_OBJECT_LICENSE", - MIME_TYPE: "0.SIMPLE/MIME_TYPE", - DOI: "0.SIMPLE/DOI", - PUBLICATION_TITLE: "0.SIMPLE/PUBLICATION_TITLE", - PUBLICATION_CREATOR: "0.SIMPLE/PUBLICATION_CREATOR", - IS_PART_OF: "0.SIMPLE/IS_PART_OF", - HAS_PART: "0.SIMPLE/HAS_PART", - CREATED_WITH_SOFTWARE: "0.SIMPLE/CREATED_WITH_SOFTWARE", - LOCAL_ID: "0.SIMPLE/LOCAL_ID", -} as const - -export const FDO_PROFILES = { - CORE: "0.SIMPLE/CORE", - DATA_OBJECT: "0.SIMPLE/DATA_OBJECT", - SOFTWARE: "0.SIMPLE/SOFTWARE", - PUBLICATION: "0.SIMPLE/PUBLICATION", -} as const - -export const LEGACY_TYPE_KEYS = { - VERSION: "0.SIMPLE/VERSION", - PUBLICATION_DATE: "0.SIMPLE/PUBLICATION_DATE", - CREATION_DATE: "0.SIMPLE/CREATION_DATE", -} as const - -export type FdoTypeIdentifier = - | (typeof FDO_TYPES)[keyof typeof FDO_TYPES] - | (typeof FDO_PROFILES)[keyof typeof FDO_PROFILES] - | (typeof LEGACY_TYPE_KEYS)[keyof typeof LEGACY_TYPE_KEYS] diff --git a/packages/simple-types/src/index.ts b/packages/simple-types/src/index.ts index 868c579..79e6f48 100644 --- a/packages/simple-types/src/index.ts +++ b/packages/simple-types/src/index.ts @@ -1,3 +1,2 @@ -export * from "./identifiers.js" export * from "./attributes.js" export * from "./profiles.js" diff --git a/packages/simple-types/src/profiles.ts b/packages/simple-types/src/profiles.ts index 1dbb438..a18febe 100644 --- a/packages/simple-types/src/profiles.ts +++ b/packages/simple-types/src/profiles.ts @@ -1,92 +1,48 @@ -import { ConcreteProfile } from "@fdo-sdk/primitives" -import type { Profile, ProfileDefinition } from "@fdo-sdk/primitives" -import { FDO_PROFILES, FDO_TYPES } from "./identifiers.js" - -export type CoreProfileAttributes = { - owner: string - helmholtzResearchField: string -} - -export type DataObjectProfileAttributes = { - dataObjectLocation: string - dataObjectLicense: string - mimeType: string - isPartOf?: string | string[] - createdWithSoftware?: string | string[] -} - -export type SoftwareProfileAttributes = { - softwareRepositoryType: string - softwareLocation: string - softwareLicense: string - readmeLocation?: string -} - -export type PublicationProfileAttributes = { - doi: string - publicationTitle: string - publicationCreator: string | string[] - hasPart?: string | string[] -} - -const coreProfileDefinition: ProfileDefinition = { - pid: FDO_PROFILES.CORE, - readableName: "Simple Core Profile", - profileAttributePID: FDO_TYPES.PROFILE, - mapping: { - owner: FDO_TYPES.OWNER, - helmholtzResearchField: FDO_TYPES.HELMHOLTZ_RESEARCH_FIELD, - }, -} - -const dataObjectProfileDefinition: ProfileDefinition = - { - pid: FDO_PROFILES.DATA_OBJECT, - readableName: "Simple Data Object Profile", - profileAttributePID: FDO_TYPES.PROFILE, - mapping: { - dataObjectLocation: FDO_TYPES.DATA_OBJECT_LOCATION, - dataObjectLicense: FDO_TYPES.DATA_OBJECT_LICENSE, - mimeType: FDO_TYPES.MIME_TYPE, - createdWithSoftware: FDO_TYPES.CREATED_WITH_SOFTWARE, - isPartOf: FDO_TYPES.IS_PART_OF, - }, - } - -const softwareProfileDefinition: ProfileDefinition = - { - pid: FDO_PROFILES.SOFTWARE, - readableName: "Simple Software Profile", - profileAttributePID: FDO_TYPES.PROFILE, - mapping: { - softwareRepositoryType: FDO_TYPES.SOFTWARE_REPOSITORY_TYPE, - softwareLocation: FDO_TYPES.SOFTWARE_LOCATION, - softwareLicense: FDO_TYPES.SOFTWARE_LICENSE, - readmeLocation: FDO_TYPES.README_LOCATION, - }, - } - -const publicationProfileDefinition: ProfileDefinition = - { - pid: FDO_PROFILES.PUBLICATION, - readableName: "Simple Publication Profile", - profileAttributePID: FDO_TYPES.PROFILE, - mapping: { - doi: FDO_TYPES.DOI, - publicationTitle: FDO_TYPES.PUBLICATION_TITLE, - publicationCreator: FDO_TYPES.PUBLICATION_CREATOR, - hasPart: FDO_TYPES.HAS_PART, - }, - } - -export const SIMPLE_PROFILES: { - readonly CORE: Profile - readonly DATA_OBJECT: Profile - readonly SOFTWARE: Profile - readonly PUBLICATION: Profile -} = { - CORE: new ConcreteProfile(coreProfileDefinition), - DATA_OBJECT: new ConcreteProfile(dataObjectProfileDefinition), - SOFTWARE: new ConcreteProfile(softwareProfileDefinition), - PUBLICATION: new ConcreteProfile(publicationProfileDefinition), +import { Profile } from "@fdo-sdk/primitives" +import { SIMPLE_ATTRIBUTES } from "./attributes.js" + +export const SIMPLE_PROFILES = { + CORE: Profile.make({ + pid: "0.SIMPLE/CORE", + name: "Simple Core Profile", + description: "The minimal profile all simple FDO records conform to.", + attributes: [ + SIMPLE_ATTRIBUTES.OWNER, + SIMPLE_ATTRIBUTES.HELMHOLTZ_RESEARCH_FIELD, + ], + }), + DATA_OBJECT: Profile.make({ + pid: "0.SIMPLE/DATA_OBJECT", + name: "Simple Data Object Profile", + description: "Describes a data object.", + attributes: [ + SIMPLE_ATTRIBUTES.DATA_OBJECT_LOCATION, + SIMPLE_ATTRIBUTES.DATA_OBJECT_LICENSE, + SIMPLE_ATTRIBUTES.MIME_TYPE, + SIMPLE_ATTRIBUTES.IS_PART_OF, + SIMPLE_ATTRIBUTES.CREATED_WITH_SOFTWARE, + ], + }), + SOFTWARE: Profile.make({ + pid: "0.SIMPLE/SOFTWARE", + name: "Simple Software Profile", + description: "Describes a software package.", + attributes: [ + SIMPLE_ATTRIBUTES.SOFTWARE_REPOSITORY_TYPE, + SIMPLE_ATTRIBUTES.SOFTWARE_LOCATION, + SIMPLE_ATTRIBUTES.SOFTWARE_LICENSE, + SIMPLE_ATTRIBUTES.README_LOCATION, + ], + }), + PUBLICATION: Profile.make({ + pid: "0.SIMPLE/PUBLICATION", + name: "Simple Publication Profile", + description: "Describes a publication.", + attributes: [ + SIMPLE_ATTRIBUTES.DOI, + SIMPLE_ATTRIBUTES.PUBLICATION_TITLE, + SIMPLE_ATTRIBUTES.PUBLICATION_CREATOR, + SIMPLE_ATTRIBUTES.HAS_PART, + ], + }), } diff --git a/packages/simple-types/tests/attributes.test.ts b/packages/simple-types/tests/attributes.test.ts index 4cb923c..7e2af32 100644 --- a/packages/simple-types/tests/attributes.test.ts +++ b/packages/simple-types/tests/attributes.test.ts @@ -1,37 +1,50 @@ import { describe, expect, it } from "vitest" -import { ConcreteFDORecord } from "@fdo-sdk/primitives" -import { FDO_TYPES, LEGACY_TYPE_KEYS, SIMPLE_ATTRIBUTES } from "../src/index.js" +import { DefaultFDORecord, reference } from "@fdo-sdk/primitives" +import { SIMPLE_ATTRIBUTES } from "../src/index.js" + +const ATTRIBUTE_PIDS: Record = { + OWNER: "0.SIMPLE/OWNER", + HELMHOLTZ_RESEARCH_FIELD: "0.SIMPLE/HELMHOLTZ_RESEARCH_FIELD", + PROFILE: "0.SIMPLE/PROFILE", + SOFTWARE_REPOSITORY_TYPE: "0.SIMPLE/SOFTWARE_REPOSITORY_TYPE", + SOFTWARE_LOCATION: "0.SIMPLE/SOFTWARE_LOCATION", + SOFTWARE_LICENSE: "0.SIMPLE/SOFTWARE_LICENSE", + README_LOCATION: "0.SIMPLE/README_LOCATION", + DATA_OBJECT_LOCATION: "0.SIMPLE/DATA_OBJECT_LOCATION", + DATA_OBJECT_LICENSE: "0.SIMPLE/DATA_OBJECT_LICENSE", + MIME_TYPE: "0.SIMPLE/MIME_TYPE", + DOI: "0.SIMPLE/DOI", + PUBLICATION_TITLE: "0.SIMPLE/PUBLICATION_TITLE", + PUBLICATION_CREATOR: "0.SIMPLE/PUBLICATION_CREATOR", + VERSION: "0.SIMPLE/VERSION", + PUBLICATION_DATE: "0.SIMPLE/PUBLICATION_DATE", + CREATION_DATE: "0.SIMPLE/CREATION_DATE", + IS_PART_OF: "0.SIMPLE/IS_PART_OF", + HAS_PART: "0.SIMPLE/HAS_PART", + CREATED_WITH_SOFTWARE: "0.SIMPLE/CREATED_WITH_SOFTWARE", + LOCAL_ID: "0.SIMPLE/LOCAL_ID", +} describe("SIMPLE_ATTRIBUTES", () => { - it("covers every type identifier", () => { + it("covers every simple type with its expected PID", () => { expect(Object.keys(SIMPLE_ATTRIBUTES)).toEqual( - expect.arrayContaining([ - ...Object.keys(FDO_TYPES), - ...Object.keys(LEGACY_TYPE_KEYS), - ]), + Object.keys(ATTRIBUTE_PIDS), ) - }) - - it("uses the identifier PIDs with non-empty readable names", () => { - for (const identifiers of [FDO_TYPES, LEGACY_TYPE_KEYS]) { - for (const [key, pid] of Object.entries(identifiers)) { - const attribute = - SIMPLE_ATTRIBUTES[key as keyof typeof SIMPLE_ATTRIBUTES] - expect(attribute.pid).toBe(pid) - expect(attribute.readableName.length).toBeGreaterThan(0) - } + for (const [key, attribute] of Object.entries(SIMPLE_ATTRIBUTES)) { + expect(attribute.pid).toBe(ATTRIBUTE_PIDS[key]) + expect(attribute.name.length).toBeGreaterThan(0) } }) it("can be set and read on FDO records", () => { - const record = new ConcreteFDORecord() + const record = new DefaultFDORecord() record.set(SIMPLE_ATTRIBUTES.OWNER, "0000-0002-1825-0097") expect(record.get(SIMPLE_ATTRIBUTES.OWNER)).toBe("0000-0002-1825-0097") - expect(record.get(FDO_TYPES.OWNER)).toBe("0000-0002-1825-0097") + expect(record.get("0.SIMPLE/OWNER")).toBe("0000-0002-1825-0097") }) it("supports array values for multi-valued attributes", () => { - const record = new ConcreteFDORecord() + const record = new DefaultFDORecord() record.set(SIMPLE_ATTRIBUTES.PUBLICATION_CREATOR, [ "0000-0002-1825-0097", "0000-0003-4045-3566", @@ -41,4 +54,40 @@ describe("SIMPLE_ATTRIBUTES", () => { "0000-0003-4045-3566", ]) }) + + it("labels relations to other FDO records as profile references", () => { + expect(SIMPLE_ATTRIBUTES.PROFILE.defType).toBe("profileRef") + expect(SIMPLE_ATTRIBUTES.IS_PART_OF.defType).toBe("profileRef") + expect(SIMPLE_ATTRIBUTES.HAS_PART.defType).toBe("profileRef") + expect(SIMPLE_ATTRIBUTES.CREATED_WITH_SOFTWARE.defType).toBe( + "profileRef", + ) + }) + + it("restricts the profile attribute to the simple profiles", () => { + expect(SIMPLE_ATTRIBUTES.PROFILE.allowedProfiles).toEqual([ + "0.SIMPLE/CORE", + "0.SIMPLE/DATA_OBJECT", + "0.SIMPLE/SOFTWARE", + "0.SIMPLE/PUBLICATION", + ]) + }) + + it("accepts reference markers where the value type allows them", () => { + const record = new DefaultFDORecord() + record.set( + SIMPLE_ATTRIBUTES.CREATED_WITH_SOFTWARE, + reference("LOCAL/software/tools"), + ) + expect(record.get(SIMPLE_ATTRIBUTES.CREATED_WITH_SOFTWARE)).toEqual({ + mark: "reference", + ref: { direction: "uni", toRecord: "LOCAL/software/tools" }, + }) + }) + + it("accepts plain identifiers on the profile attribute", () => { + const record = new DefaultFDORecord() + record.set(SIMPLE_ATTRIBUTES.PROFILE, "0.SIMPLE/SOFTWARE") + expect(record.get(SIMPLE_ATTRIBUTES.PROFILE)).toBe("0.SIMPLE/SOFTWARE") + }) }) diff --git a/packages/simple-types/tests/profiles.test.ts b/packages/simple-types/tests/profiles.test.ts index 97ea8e3..a7f1fc0 100644 --- a/packages/simple-types/tests/profiles.test.ts +++ b/packages/simple-types/tests/profiles.test.ts @@ -1,69 +1,125 @@ import { describe, expect, it } from "vitest" -import { ConcreteFDORecord } from "@fdo-sdk/primitives" import { - FDO_PROFILES, - FDO_TYPES, - SIMPLE_ATTRIBUTES, - SIMPLE_PROFILES, -} from "../src/index.js" + DefaultFDORecord, + DefaultLocalFDORecord, + reference, +} from "@fdo-sdk/primitives" +import { SIMPLE_ATTRIBUTES, SIMPLE_PROFILES } from "../src/index.js" + +const PROFILE_PIDS: Record = { + CORE: "0.SIMPLE/CORE", + DATA_OBJECT: "0.SIMPLE/DATA_OBJECT", + SOFTWARE: "0.SIMPLE/SOFTWARE", + PUBLICATION: "0.SIMPLE/PUBLICATION", +} describe("SIMPLE_PROFILES", () => { - it("uses the profile identifiers", () => { - for (const [key, pid] of Object.entries(FDO_PROFILES)) { - expect( - SIMPLE_PROFILES[key as keyof typeof SIMPLE_PROFILES].def.pid, - ).toBe(pid) + it("uses the simple profile PIDs", () => { + expect(Object.keys(SIMPLE_PROFILES)).toEqual(Object.keys(PROFILE_PIDS)) + for (const [key, profile] of Object.entries(SIMPLE_PROFILES)) { + expect(profile.pid).toBe(PROFILE_PIDS[key]) } }) - it("maps every attribute to an existing attribute PID", () => { + it("declares every profile attribute as a simple-type attribute", () => { const attributePIDs = new Set( Object.values(SIMPLE_ATTRIBUTES).map((attribute) => attribute.pid), ) for (const profile of Object.values(SIMPLE_PROFILES)) { - for (const attributeName of Object.keys(profile.def.mapping)) { - const pid = profile.mapAttributeNameToPID(attributeName) - expect(attributePIDs.has(pid)).toBe(true) + for (const attribute of profile.attributes) { + expect(attributePIDs.has(attribute.pid)).toBe(true) } } }) - it("resolves attribute names back from PIDs", () => { + it("uses attribute definitions whose names match the SIMPLE_ATTRIBUTES entries", () => { for (const profile of Object.values(SIMPLE_PROFILES)) { - for (const [attributeName, pid] of Object.entries( - profile.def.mapping, - )) { - expect(profile.mapPIDToAttributeName(pid)).toBe(attributeName) + for (const attribute of profile.attributes) { + const matching = Object.values(SIMPLE_ATTRIBUTES).find( + (candidate) => candidate.pid === attribute.pid, + ) + expect(matching?.name).toBe(attribute.name) } } }) - it("throws for unknown PIDs and attribute names", () => { - const profile = SIMPLE_PROFILES.CORE - expect(() => profile.mapPIDToAttributeName("unknown/pid")).toThrow() - expect(() => profile.mapAttributeNameToPID("unknown")).toThrow() + it("can be applied to FDO records and registers the profile PID at 0.FDO/Profile", () => { + const record = new DefaultFDORecord() + record.addProfile(SIMPLE_PROFILES.SOFTWARE, { + softwareRepositoryType: "git", + softwareLocation: "https://github.com/example/example", + softwareLicense: "MIT", + readmeLocation: "https://example.com/README.md", + }) + expect(record.getProfile()).toBe("0.SIMPLE/SOFTWARE") + expect(record.get(SIMPLE_ATTRIBUTES.SOFTWARE_LOCATION)).toBe( + "https://github.com/example/example", + ) + expect(record.get("0.SIMPLE/SOFTWARE_LOCATION")).toBe( + "https://github.com/example/example", + ) }) - it("includes the PROFILE attribute in every profile (as profileAttributePID)", () => { - for (const profile of Object.values(SIMPLE_PROFILES)) { - expect(profile.def.profileAttributePID).toBe(FDO_TYPES.PROFILE) - } + it("leaves optional attributes out when they are not provided", () => { + const record = new DefaultFDORecord() + record.addProfile(SIMPLE_PROFILES.DATA_OBJECT, { + dataObjectLocation: "https://example.org/data/measurements.nc", + dataObjectLicense: "CC-BY-4.0", + mimeType: "application/netcdf", + }) + expect(record.get("0.SIMPLE/MIME_TYPE")).toBe("application/netcdf") + expect(record.has("0.SIMPLE/IS_PART_OF")).toBe(false) + expect(record.has("0.SIMPLE/CREATED_WITH_SOFTWARE")).toBe(false) }) - it("can be applied to FDO records", () => { - const record = new ConcreteFDORecord() + it("appends the profile PID when multiple profiles are applied", () => { + const record = new DefaultFDORecord() + record.addProfile(SIMPLE_PROFILES.CORE, { + owner: "Jane Doe", + helmholtzResearchField: "Earth and Environment", + }) record.addProfile(SIMPLE_PROFILES.SOFTWARE, { - softwareRepositoryType: "GitHub", + softwareRepositoryType: "git", softwareLocation: "https://github.com/example/example", softwareLicense: "MIT", - readmeLocation: "https://example.com/README.md", }) - expect(record.getProfiles()).toEqual([FDO_PROFILES.SOFTWARE]) - expect(record.get(SIMPLE_ATTRIBUTES.PROFILE)).toBe( - FDO_PROFILES.SOFTWARE, + expect(record.getProfile()).toEqual([ + "0.SIMPLE/CORE", + "0.SIMPLE/SOFTWARE", + ]) + }) + + it("adds references to other records through profile reference attributes", () => { + const software = new DefaultLocalFDORecord("LOCAL/software/tools") + const data = new DefaultLocalFDORecord("LOCAL/data-object/measurements") + data.addProfile(SIMPLE_PROFILES.DATA_OBJECT, { + dataObjectLocation: "https://example.org/data/measurements.nc", + dataObjectLicense: "CC-BY-4.0", + mimeType: "application/netcdf", + createdWithSoftware: reference(software), + }) + expect(data.get(SIMPLE_ATTRIBUTES.CREATED_WITH_SOFTWARE)).toBe( + "LOCAL/software/tools", ) + expect(data.getReferences()).toEqual([ + { + direction: "uni", + fromAttribute: "0.SIMPLE/CREATED_WITH_SOFTWARE", + toRecord: "LOCAL/software/tools", + }, + ]) + }) + + it("can be applied to an FDO record in a graph", () => { + const record = new DefaultLocalFDORecord("LOCAL/software/climate-tools") + record.addProfile(SIMPLE_PROFILES.SOFTWARE, { + softwareRepositoryType: "git", + softwareLocation: "https://github.com/example/climate-tools", + softwareLicense: "MIT", + }) + expect(record.getProfile()).toBe("0.SIMPLE/SOFTWARE") expect(record.get(SIMPLE_ATTRIBUTES.SOFTWARE_LOCATION)).toBe( - "https://github.com/example/example", + "https://github.com/example/climate-tools", ) }) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 251c15f..0a36e8c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -206,22 +206,6 @@ importers: specifier: ^4.14.1 version: 4.14.1(typedoc@0.28.20(typescript@6.0.3)) - packages/examples: - dependencies: - '@fdo-sdk/mapping': - specifier: workspace:* - version: link:../mapping - '@fdo-sdk/primitives': - specifier: workspace:* - version: link:../primitives - devDependencies: - '@types/node': - specifier: ^26.2.0 - version: 26.2.0 - typescript: - specifier: ^6.0.3 - version: 6.0.3 - packages/mapping: dependencies: '@fdo-sdk/primitives': @@ -248,7 +232,7 @@ importers: version: 6.0.3 vitest: specifier: ^4.1.10 - version: 4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0)) + version: 4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@7.3.7(@types/node@26.2.0)(lightningcss@1.33.0)(yaml@2.9.0)) packages/playground: dependencies: @@ -333,7 +317,7 @@ importers: version: 6.0.3 vitest: specifier: ^4.1.10 - version: 4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0)) + version: 4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@7.3.7(@types/node@26.2.0)(lightningcss@1.33.0)(yaml@2.9.0)) packages/simple-types: dependencies: @@ -355,7 +339,7 @@ importers: version: 6.0.3 vitest: specifier: ^4.1.10 - version: 4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0)) + version: 4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@7.3.7(@types/node@26.2.0)(lightningcss@1.33.0)(yaml@2.9.0)) packages: @@ -3453,49 +3437,6 @@ packages: yaml: optional: true - vite@8.2.1: - resolution: {integrity: sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - peerDependencies: - '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.4.0 - esbuild: ^0.27.0 || ^0.28.0 - jiti: '>=1.21.0' - less: ^4.0.0 - sass: ^1.70.0 - sass-embedded: ^1.70.0 - stylus: '>=0.54.8' - sugarss: ^5.0.0 - terser: ^5.16.0 - tsx: ^4.8.1 - yaml: ^2.4.2 - peerDependenciesMeta: - '@types/node': - optional: true - '@vitejs/devtools': - optional: true - esbuild: - optional: true - jiti: - optional: true - less: - optional: true - sass: - optional: true - sass-embedded: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - tsx: - optional: true - yaml: - optional: true - vitest@4.1.10: resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==} engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} @@ -4749,7 +4690,7 @@ snapshots: obug: 2.1.4 std-env: 4.2.0 tinyrainbow: 3.1.1 - vitest: 4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0)) + vitest: 4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@7.3.7(@types/node@26.2.0)(lightningcss@1.33.0)(yaml@2.9.0)) '@vitest/expect@4.1.10': dependencies: @@ -4768,14 +4709,6 @@ snapshots: optionalDependencies: vite: 7.3.7(@types/node@26.2.0)(lightningcss@1.33.0)(yaml@2.9.0) - '@vitest/mocker@4.1.10(vite@8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0))': - dependencies: - '@vitest/spy': 4.1.10 - estree-walker: 3.0.3 - magic-string: 0.30.21 - optionalDependencies: - vite: 8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0) - '@vitest/pretty-format@4.1.10': dependencies: tinyrainbow: 3.1.1 @@ -5218,7 +5151,8 @@ snapshots: defu@6.1.7: {} - detect-libc@2.1.2: {} + detect-libc@2.1.2: + optional: true diff@8.0.4: {} @@ -5748,6 +5682,7 @@ snapshots: lightningcss-linux-x64-musl: 1.33.0 lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 + optional: true lines-and-columns@1.2.4: {} @@ -6712,19 +6647,6 @@ snapshots: lightningcss: 1.33.0 yaml: 2.9.0 - vite@8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0): - dependencies: - lightningcss: 1.33.0 - picomatch: 4.0.5 - postcss: 8.5.26 - rolldown: 1.2.1 - tinyglobby: 0.2.17 - optionalDependencies: - '@types/node': 26.2.0 - esbuild: 0.28.2 - fsevents: 2.3.3 - yaml: 2.9.0 - vitest@4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@7.3.7(@types/node@26.2.0)(lightningcss@1.33.0)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.10 @@ -6753,34 +6675,6 @@ snapshots: transitivePeerDependencies: - msw - vitest@4.1.10(@types/node@26.2.0)(@vitest/coverage-v8@4.1.10)(vite@8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0)): - dependencies: - '@vitest/expect': 4.1.10 - '@vitest/mocker': 4.1.10(vite@8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0)) - '@vitest/pretty-format': 4.1.10 - '@vitest/runner': 4.1.10 - '@vitest/snapshot': 4.1.10 - '@vitest/spy': 4.1.10 - '@vitest/utils': 4.1.10 - es-module-lexer: 2.3.1 - expect-type: 1.4.0 - magic-string: 0.30.21 - obug: 2.1.4 - pathe: 2.0.3 - picomatch: 4.0.5 - std-env: 4.2.0 - tinybench: 2.9.0 - tinyexec: 1.3.0 - tinyglobby: 0.2.17 - tinyrainbow: 3.1.1 - vite: 8.2.1(@types/node@26.2.0)(esbuild@0.28.2)(yaml@2.9.0) - why-is-node-running: 2.3.0 - optionalDependencies: - '@types/node': 26.2.0 - '@vitest/coverage-v8': 4.1.10(vitest@4.1.10) - transitivePeerDependencies: - - msw - w3c-keyname@2.2.8: {} walk-up-path@4.0.0: {} From e9e158ddc065e027c6b9f2eb40bb25420018c62b Mon Sep 17 00:00:00 2001 From: Christopher Raquet Date: Tue, 1 Dec 2026 15:45:45 +0100 Subject: [PATCH 4/6] fix: adapt packages to new type system --- packages/primitives/src/impl/Attribute.ts | 189 ++++++++++++++++++ packages/primitives/src/impl/index.ts | 1 + packages/primitives/src/impl/markers.ts | 2 +- .../{Attribute.ts => AttributeDef.ts} | 178 +---------------- .../primitives/src/interfaces/FDOContext.ts | 2 +- .../primitives/src/interfaces/FDOGraph.ts | 2 +- .../primitives/src/interfaces/FDORecord.ts | 4 +- packages/primitives/src/interfaces/Profile.ts | 2 +- packages/primitives/src/interfaces/index.ts | 2 +- .../primitives/src/type-system/attributes.ts | 2 +- 10 files changed, 199 insertions(+), 185 deletions(-) create mode 100644 packages/primitives/src/impl/Attribute.ts rename packages/primitives/src/interfaces/{Attribute.ts => AttributeDef.ts} (58%) diff --git a/packages/primitives/src/impl/Attribute.ts b/packages/primitives/src/impl/Attribute.ts new file mode 100644 index 0000000..369195f --- /dev/null +++ b/packages/primitives/src/impl/Attribute.ts @@ -0,0 +1,189 @@ +import type { + AttributeAnyType, + AttributeDef, + AttributeDefAttrRef, + AttributeDefCombination, + AttributeDefProfileRef, + AttributeDefSyntax, + AttributeDefUnion, + AttributeDefVocabularyRef, + AttrsToObj, + CardinalityType, + Simplify, +} from "../interfaces/index.js" + +export const Attribute = { + /** + * Make an attribute with no specific value checking. The value of this + * attribute is expected to be a string. + * @param details + * @see AttributeDef + */ + makeBase( + details: Simplify< + Omit, "~type" | "defType"> + >, + ): AttributeDef { + return withPhantomType({ + defType: "base", + ...details, + }) + }, + + /** + * Make a syntax attribute + * @param details + * @see AttributeDefSyntax + */ + makeSyntax< + N extends string, + Cardinality extends CardinalityType, + PrimitiveType extends "string" | "number" | "integer" | "boolean", + Whitelist extends string | string[] | undefined = undefined, + >( + details: Simplify< + Omit< + AttributeDefSyntax, + "~type" | "defType" + > + >, + ): AttributeDefSyntax { + return withPhantomType({ + defType: "syntax", + ...details, + }) + }, + + /** + * Make an attribute reference attribute + * @param details + * @see AttributeDefAttrRef + */ + makeAttrRef( + details: Simplify< + Omit, "~type" | "defType"> + >, + ): AttributeDefAttrRef { + return withPhantomType({ + defType: "attrRef", + ...details, + }) + }, + + /** + * Make a profile reference attribute + * @param details + * @see AttributeDefProfileRef + */ + makeProfileRef( + details: Simplify< + Omit, "~type" | "defType"> + >, + ): AttributeDefProfileRef { + return withPhantomType({ + defType: "profileRef", + ...details, + }) + }, + + /** + * Make a combination attribute consisting of multiple other attributes + * @param details + * @see AttributeDefCombination + */ + makeCombination< + N extends string, + Cardinality extends CardinalityType, + AttributesInComb extends AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], + Type extends AttributeAnyType = Simplify>, + >( + details: Simplify< + Omit< + AttributeDefCombination, + "~type" | "defType" + > + >, + ): AttributeDefCombination { + return withPhantomType({ + defType: "combination", + ...details, + }) + }, + + /** + * Make an attribute that is the union of multiple other attributes + * @param details + * @see AttributeDefUnion + */ + makeUnion< + N extends string, + Cardinality extends CardinalityType, + AttributesInUnion extends AttributeDef< + string, + AttributeAnyType, + CardinalityType + >[], + Type extends AttributeAnyType = AttributesInUnion[number]["~type"], + >( + details: Simplify< + Omit< + AttributeDefUnion, + "~type" | "defType" + > + >, + ): AttributeDefUnion { + return withPhantomType({ + defType: "union", + ...details, + }) + }, + + /** + * Make a vocabulary attribute + * @param details + * @see AttributeDefVocabularyRef + */ + makeVocabulary( + details: Simplify< + Omit, "~type" | "defType"> + >, + ): AttributeDefVocabularyRef { + return withPhantomType({ + defType: "vocabulary", + ...details, + }) + }, + + /** + * Make a refined version of an existing attribute, where the cardinality + * is changed. + * @param attribute + * @param newCardinality + */ + makeRefined< + A extends AttributeDef, + NewCardinality extends CardinalityType, + >( + attribute: A, + newCardinality: NewCardinality, + ): AttributeDef { + return { + ...attribute, + cardinality: newCardinality, + } + }, +} + +/** + * Add the `~type` property to the given object on the type layer + * @param obj + */ +function withPhantomType( + obj: Obj, +): Obj & { "~type": Type } { + return obj as Obj & { "~type": Type } +} diff --git a/packages/primitives/src/impl/index.ts b/packages/primitives/src/impl/index.ts index ea5223a..ee6118e 100644 --- a/packages/primitives/src/impl/index.ts +++ b/packages/primitives/src/impl/index.ts @@ -3,3 +3,4 @@ export { DefaultFDORecord } from "./DefaultFDORecord.js" export { LocalFDOGraph } from "./LocalFDOGraph.js" export { PublishedFDOGraph } from "./PublishedFDOGraph.js" export * from "./markers.js" +export * from "./Attribute.js" diff --git a/packages/primitives/src/impl/markers.ts b/packages/primitives/src/impl/markers.ts index d5da97b..52d47b5 100644 --- a/packages/primitives/src/impl/markers.ts +++ b/packages/primitives/src/impl/markers.ts @@ -5,7 +5,7 @@ import type { ReferenceMarker, SkipMarker, } from "../types.js" -import type { Attribute, IdentifiableFDORecord } from "../interfaces/index.js" +import type { IdentifiableFDORecord } from "../interfaces/index.js" import { getRecordIdentifier } from "../utils.js" import type { DefaultAttributeDef } from "../interfaces/index.js" diff --git a/packages/primitives/src/interfaces/Attribute.ts b/packages/primitives/src/interfaces/AttributeDef.ts similarity index 58% rename from packages/primitives/src/interfaces/Attribute.ts rename to packages/primitives/src/interfaces/AttributeDef.ts index b30b3c2..b2dc957 100644 --- a/packages/primitives/src/interfaces/Attribute.ts +++ b/packages/primitives/src/interfaces/AttributeDef.ts @@ -46,7 +46,7 @@ export type DefaultAttributeDef = AttributeDef< type PrimitiveValue< PrimitiveType extends "string" | "number" | "integer" | "boolean", > = PrimitiveType extends "string" - ? string + ? string | ReferenceMarker : PrimitiveType extends "number" ? number : PrimitiveType extends "integer" @@ -211,179 +211,3 @@ export type AttrsToObj< } export type Simplify = { [K in keyof T]: T[K] } & {} - -/** - * Add the `~type` property to the given object on the type layer - * @param obj - */ -function withPhantomType( - obj: Obj, -): Obj & { "~type": Type } { - return obj as Obj & { "~type": Type } -} - -export const Attribute = { - /** - * Make an attribute with no specific value checking. The value of this - * attribute is expected to be a string. - * @param details - * @see AttributeDef - */ - makeBase( - details: Simplify< - Omit, "~type" | "defType"> - >, - ): AttributeDef { - return withPhantomType({ - defType: "base", - ...details, - }) - }, - - /** - * Make a syntax attribute - * @param details - * @see AttributeDefSyntax - */ - makeSyntax< - N extends string, - Cardinality extends CardinalityType, - PrimitiveType extends "string" | "number" | "integer" | "boolean", - Whitelist extends string | string[] | undefined = undefined, - >( - details: Simplify< - Omit< - AttributeDefSyntax, - "~type" | "defType" - > - >, - ): AttributeDefSyntax { - return withPhantomType({ - defType: "syntax", - ...details, - }) - }, - - /** - * Make an attribute reference attribute - * @param details - * @see AttributeDefAttrRef - */ - makeAttrRef( - details: Simplify< - Omit, "~type" | "defType"> - >, - ): AttributeDefAttrRef { - return withPhantomType({ - defType: "attrRef", - ...details, - }) - }, - - /** - * Make a profile reference attribute - * @param details - * @see AttributeDefProfileRef - */ - makeProfileRef( - details: Simplify< - Omit, "~type" | "defType"> - >, - ): AttributeDefProfileRef { - return withPhantomType({ - defType: "profileRef", - ...details, - }) - }, - - /** - * Make a combination attribute consisting of multiple other attributes - * @param details - * @see AttributeDefCombination - */ - makeCombination< - N extends string, - Cardinality extends CardinalityType, - AttributesInComb extends AttributeDef< - string, - AttributeAnyType, - CardinalityType - >[], - Type extends AttributeAnyType = Simplify>, - >( - details: Simplify< - Omit< - AttributeDefCombination, - "~type" | "defType" - > - >, - ): AttributeDefCombination { - return withPhantomType({ - defType: "combination", - ...details, - }) - }, - - /** - * Make an attribute that is the union of multiple other attributes - * @param details - * @see AttributeDefUnion - */ - makeUnion< - N extends string, - Cardinality extends CardinalityType, - AttributesInUnion extends AttributeDef< - string, - AttributeAnyType, - CardinalityType - >[], - Type extends AttributeAnyType = AttributesInUnion[number]["~type"], - >( - details: Simplify< - Omit< - AttributeDefUnion, - "~type" | "defType" - > - >, - ): AttributeDefUnion { - return withPhantomType({ - defType: "union", - ...details, - }) - }, - - /** - * Make a vocabulary attribute - * @param details - * @see AttributeDefVocabularyRef - */ - makeVocabulary( - details: Simplify< - Omit, "~type" | "defType"> - >, - ): AttributeDefVocabularyRef { - return withPhantomType({ - defType: "vocabulary", - ...details, - }) - }, - - /** - * Make a refined version of an existing attribute, where the cardinality - * is changed. - * @param attribute - * @param newCardinality - */ - makeRefined< - A extends AttributeDef, - NewCardinality extends CardinalityType, - >( - attribute: A, - newCardinality: NewCardinality, - ): AttributeDef { - return { - ...attribute, - cardinality: newCardinality, - } - }, -} diff --git a/packages/primitives/src/interfaces/FDOContext.ts b/packages/primitives/src/interfaces/FDOContext.ts index 0b0cc1c..a96660c 100644 --- a/packages/primitives/src/interfaces/FDOContext.ts +++ b/packages/primitives/src/interfaces/FDOContext.ts @@ -1,4 +1,4 @@ -import type { DefaultAttributeDef } from "./Attribute.js" +import type { DefaultAttributeDef } from "./AttributeDef.js" import type { PID } from "../types.js" import type { ProfileDef } from "./Profile.js" diff --git a/packages/primitives/src/interfaces/FDOGraph.ts b/packages/primitives/src/interfaces/FDOGraph.ts index 3899490..46427dc 100644 --- a/packages/primitives/src/interfaces/FDOGraph.ts +++ b/packages/primitives/src/interfaces/FDOGraph.ts @@ -1,6 +1,6 @@ import type { FDORecord, ReadOnlyFDORecord } from "./FDORecord.js" import type { LocalID, PID } from "../types.js" -import type { AttributeAnyType } from "./Attribute.js" +import type { AttributeAnyType } from "./AttributeDef.js" export type FDOGraphAddRecordOptions = Partial<{ /** diff --git a/packages/primitives/src/interfaces/FDORecord.ts b/packages/primitives/src/interfaces/FDORecord.ts index 843b061..2f29786 100644 --- a/packages/primitives/src/interfaces/FDORecord.ts +++ b/packages/primitives/src/interfaces/FDORecord.ts @@ -4,7 +4,7 @@ import type { ReferenceDeclaration, WithMarkers, } from "../types.js" -import type { Attribute } from "./Attribute.js" +import type { Attribute } from "../index.js" import type { AttributeAnyType, AttributeDef, @@ -13,7 +13,7 @@ import type { CardinalityType, DefaultAttributeDef, Simplify, -} from "./Attribute.js" +} from "./AttributeDef.js" import type { ProfileDef } from "./Profile.js" import { DataAttribute, diff --git a/packages/primitives/src/interfaces/Profile.ts b/packages/primitives/src/interfaces/Profile.ts index 3f9c790..1ceafaf 100644 --- a/packages/primitives/src/interfaces/Profile.ts +++ b/packages/primitives/src/interfaces/Profile.ts @@ -2,7 +2,7 @@ import { type AttributeAnyType, type AttributeDef, type CardinalityType, -} from "./Attribute.js" +} from "./AttributeDef.js" import type { PID } from "../types.js" /** diff --git a/packages/primitives/src/interfaces/index.ts b/packages/primitives/src/interfaces/index.ts index 3f10fc4..45ded42 100644 --- a/packages/primitives/src/interfaces/index.ts +++ b/packages/primitives/src/interfaces/index.ts @@ -1,6 +1,6 @@ export * from "./FDORecord.js" export * from "./FDOGraph.js" -export * from "./Attribute.js" +export * from "./AttributeDef.js" export * from "./Profile.js" export * from "./PublishAdapter.js" export * from "./ResolveAdapter.js" diff --git a/packages/primitives/src/type-system/attributes.ts b/packages/primitives/src/type-system/attributes.ts index 797fcf2..ec50652 100644 --- a/packages/primitives/src/type-system/attributes.ts +++ b/packages/primitives/src/type-system/attributes.ts @@ -1,4 +1,4 @@ -import { Attribute } from "../interfaces/Attribute.js" +import { Attribute } from "../impl/index.js" export const TypeAttribute = Attribute.makeAttrRef({ name: "FDO_type", From 47fae4a25cc6eadd1ef564675af7fe54bf98a4e5 Mon Sep 17 00:00:00 2001 From: Christopher Raquet Date: Tue, 1 Dec 2026 15:49:36 +0100 Subject: [PATCH 5/6] fix: allow reference markers in reference attributes --- packages/primitives/src/interfaces/FDORecord.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/primitives/src/interfaces/FDORecord.ts b/packages/primitives/src/interfaces/FDORecord.ts index 2f29786..4498253 100644 --- a/packages/primitives/src/interfaces/FDORecord.ts +++ b/packages/primitives/src/interfaces/FDORecord.ts @@ -2,6 +2,7 @@ import type { LocalID, PID, ReferenceDeclaration, + ReferenceMarker, WithMarkers, } from "../types.js" import type { Attribute } from "../index.js" @@ -176,7 +177,9 @@ export interface FDORecord extends ReadOnlyFDORecord { * @see {@link FDORecord.addReferenceBidi} for bidirectional references */ addReference( - fromAttribute: PID | AttributeDef, + fromAttribute: + | PID + | AttributeDef, toRecord: PID | LocalID | IdentifiableFDORecord, ): void @@ -191,8 +194,12 @@ export interface FDORecord extends ReadOnlyFDORecord { * @see {@link FDORecord.addReference} for unidirectional references */ addReferenceBidi( - fromAttribute: PID | AttributeDef, - inverseAttribute: PID | AttributeDef, + fromAttribute: + | PID + | AttributeDef, + inverseAttribute: + | PID + | AttributeDef, toRecord: PID | LocalID | IdentifiableFDORecord, ): void } From 5bfb3d34d62b86ee0ff22958177eb4a7bac27c6a Mon Sep 17 00:00:00 2001 From: Christopher Raquet Date: Tue, 1 Dec 2026 15:54:11 +0100 Subject: [PATCH 6/6] fix: pipeline --- .github/workflows/build.yml | 2 -- .github/workflows/pages.yml | 2 -- .github/workflows/test.yml | 2 -- 3 files changed, 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3586d69..e1eae2c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -13,8 +13,6 @@ jobs: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - with: - version: 11.18.0 - uses: actions/setup-node@v4 with: diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index b951fab..0d97780 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -21,8 +21,6 @@ jobs: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - with: - version: 11.18.0 - uses: actions/setup-node@v4 with: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 94a6201..52fac5b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,8 +13,6 @@ jobs: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - with: - version: 11.18.0 - uses: actions/setup-node@v4 with: