1 // 📧🏷️ Étiquette ∷ model.js
2 // ====================================================================
4 // Copyright © 2023 Lady [@ Lady’s Computer].
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10 import { identity
} from "./deps.js";
11 import { Storage
} from "./memory.js";
12 import { taggingDiscoveryContext
} from "./names.js";
13 import schema
from "./schema.js";
18 * `Tag`s are not assigned identifiers and do not have side·effects on
19 * other tags in the `TagSystem` until they are persisted with
20 * `::persist`, at which point changes to their relationships are
23 * `Tag`s are also not kept up‐to‐date, but persisting an outdated
24 * `Tag` will *not* undo subsequent changes.
26 * ※ This class is not itself directly exposed, although bound
27 * versions of it are via `TagSystem::Tag`.
30 /** The `TagSystem` this `Tag` belongs to. */
33 /** The `Storage` managed by this `Tag`’s `TagSystem`. */
36 /** The schema in use for this `Tag`. */
40 * The 30‐bit W·R·M·G base32 identifier with leading checksum which
41 * has been assigned to this `Tag`.
43 * Will be `null` if this `Tag` has not been persisted. Otherwise,
44 * the format is `cxx-xxxx` (`c` = checksum; `x` = digit).
48 /** The kind of this `Tag`. */
52 * The data which was attached to this `Tag` the last time it was
53 * persisted or retrieved from storage.
55 * Diffing with this will reveal changes.
57 #persistedData
= null;
59 /** The current (modified) data associated with this `Tag`. */
63 * Adds the provided label(s) to this `Tag` as the provided
64 * predicate, then returns this `Tag`.
66 #addLabel(predicate
, ...labels
) {
67 const values
= this.#data
[predicate
];
68 for (const $ of labels
) {
69 // Iterate over each provided label and attempt to add it.
70 const literal
= langString($);
77 * Adds the provided tags to the list of tags that this `Tag` is
78 * related to by the provided predicate, then returns this `Tag`.
80 * Arguments may be string identifiers or objects with an
81 * `.identifier` property.
83 #addTag(predicate
, ...tags
) {
84 const storage
= this.#storage
;
85 const values
= this.#data
[predicate
];
86 for (const $ of tags
) {
87 // Iterate over each tag and attempt to state the predicate.
88 const identifier
= toIdentifier($);
89 if (identifier
== null) {
90 // ☡ The current tag has no identifier.
92 `Cannot state ${predicate} of Tag: Identifier must not be nullish.`,
94 } else if (values
.has(identifier
)) {
95 // Short‐circuit: The identifier has already been stated with
99 // The current tag has an identifier, but it hasn’t been stated
100 // with this predicate yet.
101 const tag
= storage
.get(identifier
);
103 // ☡ The current tag has not been persisted to this `Tag`’s
105 throw new RangeError(
106 `Cannot state ${predicate} of Tag: Identifier is not persisted: ${identifier}.`,
108 } else if (!this.#isTagInStorage(tag
)) {
109 // ☡ The current tag is not a tag in the correct tag system.
111 `Cannot state ${predicate} of Tag: Tags must be from the same Tag System, but got: ${identifier}.`,
114 !isObjectPredicateOK(
121 // ☡ This tag and the current tag form an invalid pair for
124 `Cannot state ${predicate} of Tag: Not valid for domain and range: ${this.#kind}, ${tag.#kind}.`,
127 // The current tag is a tag in the correct tag system; add
129 values
.add(identifier
);
137 * Removes the provided string label(s) from this `Tag` as the
138 * provided predicate, then returns this `Tag`.
140 #deleteLabel(predicate
, ...labels
) {
141 const values
= this.#data
[predicate
];
142 for (const $ of labels
) {
143 // Iterate over each provided label and attempt to remove it.
144 const literal
= langString($);
145 values
.delete(literal
);
151 * Removes the provided tags from the list of tags that this `Tag` is
152 * related to by the provided predicate, then returns this `Tag`.
154 * Arguments may be string identifiers or objects with an
155 * `.identifier` property.
157 #deleteTag(predicate
, ...tags
) {
158 const values
= this.#data
[predicate
];
159 for (const $ of tags
) {
160 // Iterate over the provided tags and delete them.
161 values
.delete(toIdentifier($));
167 * Returns whether or not the provided value is a tag which shares a
168 * storage with this tag.
170 * Sharing a storage also implies sharing a `TagSystem`.
174 // Try to compare the provided value’s internal store with
175 // the provided storage.
176 return $.#storage
== this.#storage
;
178 // The provided value was not a `Tag`.
184 * Yields the labels of this `Tag` according to the provided
187 *#yieldLabels(predicate
) {
188 yield* this.#data
[predicate
];
192 * Yields the tags that this `Tag` is related to by the provided
195 *#yieldTags(predicate
) {
196 const storage
= this.#storage
;
197 for (const identifier
of this.#data
[predicate
]) {
198 // Iterate over the tags in this predicate and yield them if
200 const tag
= storage
.get(identifier
);
202 !this.#isTagInStorage(tag
) || !isObjectPredicateOK(
209 // The tag no longer appears in storage or is not compatible;
210 // perhaps it was deleted.
213 // The tag exists and is constructable from storage.
220 * Yields the tags that this `Tag` is related to by the provided
221 * predicate, figured transitively.
223 *#yieldTransitiveTags(transitivePredicate
, basePredicate
) {
224 const storage
= this.#storage
;
225 const encountered
= new Set();
226 let pending
= new Set(this.#data
[basePredicate
]);
227 while (pending
.size
> 0) {
228 // Loop until all tags of the predicate have been encountered.
229 const processing
= pending
;
231 for (const identifier
of processing
) {
232 // Iterate over the tags and yield them if possible.
233 if (!encountered
.has(identifier
)) {
234 // The tag has not been encountered before.
235 encountered
.add(identifier
);
236 const tag
= storage
.get(identifier
);
238 !this.#isTagInStorage(tag
) || !isObjectPredicateOK(
245 // The tag no longer appears in storage or is not
246 // compatible; perhaps it was deleted.
249 // The tag exists and is constructable from storage.
251 for (const transitive
of tag
.#data
[basePredicate
]) {
252 // Iterate over the nested tags of the current tag and
253 // add them to pending as needed.
254 if (!encountered
.has(transitive
)) {
255 // The nested tag has not been encountered yet.
256 pending
.add(transitive
);
258 // The nested tag has already been encountered.
264 // The tag has already been encountered.
272 * Constructs a new `Tag` of the provided kind and with the provided
275 * ※ The first two arguments of this constructor are bound when
276 * generating the value of `TagSystem::Tag`. It isn’t possible to
277 * access this constructor in its unbound form from outside this
280 * ☡ This constructor throws if the provided kind is not supported.
282 constructor(system
, storage
, schema
, kind
= "Tag", prefLabel
= "") {
283 this.#system
= system
;
284 this.#storage
= storage
;
285 this.#schema
= schema
;
286 const kindString
= `${kind}`;
287 if (!(kindString
in schema
.classes
)) {
288 // The provided kind is not supported.
289 throw new RangeError(
290 `Cannot construct Tag: Unrecognized kind: ${kind}.`,
293 // The provided kind is one of the recognized tag kinds.
294 this.#kind
= kindString
;
295 this.#data
.prefLabel
= prefLabel
;
300 * Returns a new `Tag` constructor for the provided system, storage,
301 * schema, created with an appropriate prototype for the properties
304 * ※ This function is not exposed.
306 static For(system
, storage
, schema
) {
309 transitiveProperties
,
312 const constructor = function (...$s
) {
313 return Reflect
.construct(
315 [system
, storage
, schema
, ...$s
],
319 Object
.defineProperties(constructor, {
320 name
: { value
: "TagSystem::Tag" },
324 value
: Object
.create(
326 Object
.fromEntries(Array
.from(
328 for (const key
in objectProperties
) {
329 // Iterate over each object property and yield any
330 // necessary method definitions.
334 } = objectProperties
[key
];
335 if (key
in transitiveProperties
) {
336 // The current key indicates a transitive property.
338 // Transitive property methods are added by their
339 // nontransitive subproperties.
342 // The current key does not indicate a transitive
344 yield [`${key}Tags`, function* () {
345 yield* this.#yieldTags(key
);
347 if (inverseOf
== null) {
348 // The current key does not indicate an inverse
349 // property, so add and delete methods are also
351 const cased
= key
[0].toUpperCase() +
353 yield [`add${cased}Tag`, function (...tags
) {
354 return this.#addTag(key
, ...tags
);
356 yield [`delete${cased}Tag`, function (...tags
) {
357 return this.#deleteTag(key
, ...tags
);
360 // The current key indicates an inverse property,
361 // so no add and delete methods are necessary.
365 subPropertyOf
!= null &&
366 subPropertyOf
in transitiveProperties
368 // The current key indicates a subproperty of a
369 // transitive property; its method is also added.
370 yield [`${subPropertyOf}Tags`, function* () {
371 yield* this.#yieldTransitiveTags(
377 // The current key does not indicate a subproperty
378 // of a transitive property.
383 for (const key
in dataProperties
) {
384 // Iterate over each data property and yield any
385 // necessary method definitions.
386 if (key
!= "prefLabel") {
387 // The current key is not `"prefLabel"`.
388 const cased
= key
[0].toUpperCase() +
390 yield [`${key}s`, function* () {
391 yield* this.#yieldLabels(key
);
393 yield [`add${cased}`, function (...labels
) {
394 return this.#addLabel(key
, ...labels
);
396 yield [`delete${cased}`, function (...labels
) {
397 return this.#deleteLabel(key
, ...labels
);
400 // The current key is `"prefLabel"`. This is a
401 // special case which is not handled by the schema.
406 ([key
, value
]) => [key
, {
409 value
: Object
.defineProperty(value
, "name", {
419 return new TagConstructor(constructor, system
, storage
, schema
);
423 * Assigns the provided data and identifier to the provided tag.
425 * ☡ This function throws if the provided tag is not a `Tag`.
427 * ※ This function is not exposed.
429 static assignData(tag
, data
, identifier
) {
430 tag
.#identifier
= `${identifier}`;
431 tag
.#persistedData
= tagData(data
);
432 tag
.#data
= tagData(data
);
437 * Returns the `TagSystem` that the provided value belongs to.
439 * ※ This function can be used to check if the provided value has
440 * private tag features.
442 * ※ `Tag::system` is an overridable, publicly‐accessible means of
443 * accessing the system.
445 * ※ This function is not exposed.
447 static getSystem($) {
448 return !(#system
in Object($)) ? null : $.#system
;
452 // Overwrite the default `::constructor` method to instead give the
453 // actual (bound) constructor which was used to generate a given
455 Object
.defineProperties(this.prototype, {
460 // All `Tag`s are constructed via the `.Tag` constructor
461 // available in their `TagSystem`; return it.
462 return this.#system
.Tag
;
469 /** Returns the authority (domain) name for this `Tag`. */
470 get authorityName() {
471 return this.#system
.authorityName
;
474 /** Returns the identifier of this `Tag`. */
476 return this.#identifier
;
479 /** Returns the I·R·I for this `Tag`. */
481 const { identifier
, iriSpace
} = this;
482 return identifier
== null ? null : `${iriSpace}${identifier}`;
485 /** Returns the I·R·I space for this `Tag`. */
487 return this.#system
.iriSpace
;
490 /** Returns the kind of this `Tag`. */
496 * Returns the `TagSystem` for this `Tag`.
498 * ※ Internally, `Tag.getSystem` is preferred.
505 * Persist this `Tag` to storage and return an ActivityStreams
506 * serialization of a Tag Activity representing any changes, or
507 * `null` if no changes were made.
509 * If the second argument is `true`, the `Tag` will be persisted but
510 * no serialization will be made. This is somewhat more efficient.
512 * ※ Persistence can imply side‐effects on other objects, which are
513 * not noted explicitly in the activity. For example, marking a tag
514 * as broader than another causes the other tag to reciprocally be
515 * marked as narrower.
517 * ※ Inverse object properties will never appear in the predicates
518 * of generated activities.
520 persist(silent
= false) {
521 const system
= this.#system
;
522 const storage
= this.#storage
;
525 transitiveProperties
,
528 const persistedData
= this.#persistedData
;
529 const data
= this.#data
;
531 for (const [key
, value
] of Object
.entries(data
)) {
532 // Iterate over each entry of the tag data and create a diff
533 // with the last persisted information.
535 objectProperties
[key
]?.inverseOf
!= null ||
536 silent
&& key
in dataProperties
538 // The current property is one which is skipped in diffs.
540 // In a silent persist, this includes any literal terms.
543 // The current property should be diffed.
544 const persisted
= persistedData
?.[key
] ?? null;
545 if (persisted
== null) {
546 // There is no persisted data for the current property yet.
549 new: value
instanceof Set
553 } else if (value
instanceof Set
) {
554 // The current property is set‐valued.
555 const oldValues
= new Set(persisted
);
556 const newValues
= new Set(value
);
557 for (const existing
of persisted
) {
558 // Iterate over each persisted property and either remove
559 // it from the list of new values or add it to the list of
561 if (value
.has(existing
)) {
562 // The value is in both the old and new version of the
564 oldValues
.delete(existing
);
565 newValues
.delete(existing
);
567 // The value is not shared.
571 diffs
[key
] = { old
: oldValues
, new: newValues
};
573 `${value}` != `${persisted}` ||
574 value
.language
!= persisted
.language
576 // The current property is (optionally language‐tagged)
577 // string‐valued and the value changed.
579 old
: new Set([persisted
]),
580 new: new Set([value
]),
583 // The current property did not change.
584 diffs
[key
] = { old
: new Set(), new: new Set() };
588 const identifier
= this.#identifier
;
589 if (identifier
!= null) {
590 // This `Tag` has already been persisted; use its existing
591 // identifier and persist.
592 storage
.set(identifier
, this);
594 // This `Tag` has not been persisted yet; save the new
595 // identifier after persisting.
596 this.#identifier
= storage
.add(this);
598 const persistedIdentifier
= this.#identifier
;
599 this.#persistedData
= tagData(data
); // cloning here is necessary
600 for (const inverse
in objectProperties
) {
601 // Iterate over each non‐transitive inverse property and update
602 // it based on its inverse on the corresponding tags if possible.
603 const term
= objectProperties
[inverse
].inverseOf
;
604 if (term
== null || term
in transitiveProperties
) {
605 // The current property is not the inverse of an non‐transitive
609 // The current property is the inverse of a non‐transitive
611 for (const referencedIdentifier
of diffs
[term
].old
) {
612 // Iterate over the removed tags and remove this `Tag` from
613 // their inverse property.
614 const referenced
= storage
.get(referencedIdentifier
);
616 // Try removing this `Tag`.
617 referenced
.#data
[inverse
].delete(persistedIdentifier
);
618 storage
.set(referencedIdentifier
, referenced
);
620 // Removal failed, possibly because the other tag was
625 for (const referencedIdentifier
of diffs
[term
].new) {
626 const referenced
= storage
.get(referencedIdentifier
);
628 // Try adding this `Tag`.
629 referenced
.#data
[inverse
].add(persistedIdentifier
);
630 storage
.set(referencedIdentifier
, referenced
);
632 // Adding failed, possibly because the other tag was deleted.
639 // This is a silent persist.
642 // This is not a silent persist; an activity needs to be
643 // generated if a change was made.
645 "@context": taggingDiscoveryContext
,
648 identifier
== null ? "Create" : "Update",
650 context
: `${system.iri}`,
651 object
: `${this.iri}`,
652 endTime
: new Date().toISOString(),
658 const { unstates
, states
} = statements
;
659 if (identifier
== null) {
660 // This is a Create activity.
661 states
.push({ predicate
: "a", object
: `${this.kind}` });
663 // This is an Update activity.
670 }] of Object
.entries(diffs
)
672 // Iterate over the diffs of each term and state/unstate
674 for (const oldValue
of oldValues
) {
675 // Iterate over removals and unstate them.
676 if (term
in dataProperties
) {
677 // This is a literal term; push it.
680 object
: { ...oldValue
},
683 // This is a named term; attempt to get its I·R·I and
686 // Attempt to resolve the value and push the change.
687 const tag
= storage
.get(oldValue
);
688 if (!this.#isTagInStorage(tag
)) {
689 // The value did not resolve to a tag in storage.
692 // The value resolved; push its I·R·I.
699 // Value resolution failed for some reason; perhaps the
705 for (const newValue
of newValues
) {
706 // Iterate over additions and state them.
707 if (term
in dataProperties
) {
708 // This is a literal term; push it.
711 object
: { ...newValue
},
714 // This is a named term; attempt to get its I·R·I and
717 // Attempt to resolve the value and push the change.
718 const tag
= storage
.get(newValue
);
719 if (!this.#isTagInStorage(tag
)) {
720 // The value did not resolve to a tag in storage.
723 // The value resolved; push its I·R·I.
730 // Value resolution failed for some reason; perhaps the
737 if (unstates
.length
== 0) {
738 // Nothing was unstated.
739 delete statements
.unstates
;
741 // Things were stated.
744 if (states
.length
== 0) {
745 // Nothing was stated.
746 delete statements
.states
;
748 // Things were stated.
755 !Object
.hasOwn(activity
, "states") &&
756 !Object
.hasOwn(activity
, "unstates")
758 // No meaningful changes were actually persisted.
761 // There were meaningful changes persisted regarding this `Tag`.
767 /** Returns the preferred label for this `Tag`. */
769 return this.#data
.prefLabel
;
772 /** Sets the preferred label of this `Tag` to the provided label. */
774 this.#data
.prefLabel
= langString($);
777 /** Returns the Tag U·R·I for this `Tag`. */
779 const { identifier
} = this;
780 return identifier
== null
782 : `tag:${this.taggingEntity}:${identifier}`;
785 /** Returns the tagging entity (domain and date) for this `Tag`. */
786 get taggingEntity() {
787 return this.#system
.taggingEntity
;
790 /** Returns the string form of the preferred label of this `Tag`. */
792 return `${this.#data.prefLabel}`;
796 * Returns a new object whose enumerable own properties contain the
797 * data from this object needed for storage.
799 * ※ This method is not really intended for public usage.
801 [Storage
.toObject
]() {
802 const data
= this.#data
;
803 return Object
.assign(Object
.create(null), {
812 * A `Tag` constructor function.
814 * This class extends the identity function, meaning that the object
815 * provided as the constructor is used verbatim (with new private
818 * ※ The instance methods of this class are provided as static
819 * methods on the superclass which all `Tag` constructors inherit
822 * ※ This class is not exposed.
827 * The exposed constructor function from which all `Tag` constructors
830 * ☡ This constructor always throws.
834 const tagConstructorBehaviours
= Object
.create(null);
836 TagConstructor
: class extends identity
{
838 * The `TagSystem` used for `Tag`s constructed by this
843 /** The `Storage` managed by this constructor’s `TagSystem`. */
846 /** The schema in use for this constructor. */
850 * Constructs a new `Tag` constructor by adding the appropriate
851 * private fields to the provided constructor, setting its
852 * prototype, and then returning it.
854 * ※ This constructor does not modify the `name` or `prototype`
855 * properties of the provided constructor.
857 * ※ See `Tag.For`, where this constructor is used.
859 constructor(constructor, system
, storage
, schema
) {
861 Object
.setPrototypeOf(this, TagSuper
);
862 this.#system
= system
;
863 this.#storage
= storage
;
864 this.#schema
= schema
;
868 // Define the superclass constructor which all `Tag`
869 // constructors will inherit from.
870 const superclass
= tagConstructorBehaviours
.TagSuper
=
872 throw new TypeError("Tags must belong to a System.");
874 const { prototype: staticFeatures
} = this;
875 delete staticFeatures
.constructor;
876 Object
.defineProperty(superclass
, "prototype", {
879 value
: Tag
.prototype,
882 Object
.defineProperties(
884 Object
.getOwnPropertyDescriptors(staticFeatures
),
889 * Yields the tags in the `TagSystem` associated with this
893 const system
= this.#system
;
894 const storage
= this.#storage
;
895 for (const instance
of storage
.values()) {
896 // Iterate over the entries and yield the ones which are
897 // `Tag`s in this `TagSystem`.
898 if (Tag
.getSystem(instance
) == system
) {
899 // The current instance is a `Tag` in this `TagSystem`.
902 // The current instance is not a `Tag` in this
910 * Returns a new `Tag` resolved from the provided I·R·I.
912 * ☡ This function throws if the I·R·I is not in the `.iriSpace`
913 * of the `TagSystem` associated with this constructor.
915 * ※ If the I·R·I is not recognized, this function returns
919 const system
= this.#system
;
920 const storage
= this.#storage
;
921 const name
= `${iri}`;
922 const prefix
= `${system.iriSpace}`;
923 if (!name
.startsWith(prefix
)) {
924 // The I·R·I does not begin with the expected prefix.
925 throw new RangeError(
926 `I·R·I did not begin with the expected prefix: ${iri}`,
929 // The I·R·I begins with the expected prefix.
930 const identifier
= name
.substring(prefix
.length
);
932 // Attempt to resolve the identifier.
933 const instance
= storage
.get(identifier
);
934 return Tag
.getSystem(instance
) == system
938 // Do not throw for bad identifiers.
945 * Returns a new `Tag` resolved from the provided identifier.
947 * ☡ This function throws if the identifier is invalid.
949 * ※ If the identifier is valid but not recognized, this
950 * function returns `undefined`.
952 fromIdentifier(identifier
) {
953 const system
= this.#system
;
954 const storage
= this.#storage
;
955 const instance
= storage
.get(identifier
);
956 return Tag
.getSystem(instance
) == system
962 * Returns a new `Tag` resolved from the provided Tag U·R·I.
964 * ☡ This function throws if the provided Tag U·R·I does not
965 * match the tagging entity of this constructor’s `TagSystem`.
967 * ※ If the specific component of the Tag U·R·I is not
968 * recognized, this function returns `undefined`.
971 const system
= this.#system
;
972 const storage
= this.#storage
;
973 const tagName
= `${tagURI}`;
974 const tagPrefix
= `tag:${system.taggingEntity}:`;
975 if (!tagName
.startsWith(tagPrefix
)) {
976 // The Tag U·R·I does not begin with the expected prefix.
977 throw new RangeError(
978 `Tag U·R·I did not begin with the expected prefix: ${tagURI}`,
981 // The I·R·I begins with the expected prefix.
982 const identifier
= tagName
.substring(tagPrefix
.length
);
984 // Attempt to resolve the identifier.
985 const instance
= storage
.get(identifier
);
986 return Tag
.getSystem(instance
) == system
990 // Do not throw for bad identifiers.
997 * Yields the tag identifiers in the `TagSystem` associated with
1001 const system
= this.#system
;
1002 const storage
= this.#storage
;
1003 for (const [identifier
, instance
] of storage
.entries()) {
1004 // Iterate over the entries and yield the ones which are
1005 // `Tag`s in this `TagSystem`.
1006 if (Tag
.getSystem(instance
) == system
) {
1007 // The current instance is a `Tag` in this `TagSystem`.
1010 // The current instance is not a `Tag` in this `TagSystem`.
1016 /** Returns the `TagSystem` for this `Tag` constructor. */
1018 return this.#system
;
1022 * Returns a new `Tag` constructed from the provided data and
1023 * with the provided identifier.
1025 * ※ This function is not really intended for public usage.
1027 [Storage
.toInstance
](data
, identifier
) {
1028 const tag
= new this(data
.kind
);
1029 return Tag
.assignData(tag
, data
, identifier
);
1032 TagSuper
: tagConstructorBehaviours
.TagSuper
,
1038 * Returns whether the provided schema, subject class, object
1039 * property, and object class are consistent.
1041 * This is hardly a full reasoner; it is tuned to the abilites and
1042 * needs of this module.
1044 isObjectPredicateOK
,
1046 const cachedClassAndSuperclasses
= new WeakMap();
1047 const cachedClassRestrictions
= new WeakMap();
1048 const cachedPredicateRestrictions
= new WeakMap();
1050 const classAndSuperclasses
= function* (
1053 touched
= new Set(),
1055 if (baseClass
== "Thing" || touched
.has(baseClass
)) {
1059 touched
.add(baseClass
);
1060 const subClassOf
= classes
[baseClass
]?.subClassOf
?? "Thing";
1062 const superclass
of (
1063 typeof subClassOf
== "string"
1065 : Array
.from(subClassOf
)
1066 ).filter(($) => typeof $ == "string")
1068 yield* classAndSuperclasses(classes
, superclass
, touched
);
1073 const getClassAndSuperclasses
= (schema
, baseClass
) => {
1074 const schemaCache
= cachedClassAndSuperclasses
.get(schema
);
1075 const cached
= schemaCache
?.[baseClass
];
1076 if (cached
!= null) {
1079 const { classes
} = schema
;
1080 const result
= [...classAndSuperclasses(classes
, baseClass
)];
1082 schemaCache
[baseClass
] = result
;
1084 cachedClassRestrictions
.set(
1086 Object
.assign(Object
.create(null), { [baseClass
]: result
}),
1093 const getClassRestrictions
= (schema
, domain
) => {
1094 const schemaCache
= cachedClassRestrictions
.get(schema
);
1095 const cached
= schemaCache
?.[domain
];
1096 if (cached
!= null) {
1099 const { classes
} = schema
;
1100 const restrictions
= Object
.create(null);
1101 const subClassOf
= classes
[domain
]?.subClassOf
?? "Thing";
1103 const superclass
of (
1104 typeof subClassOf
== "string"
1106 : Array
.from(subClassOf
)
1107 ).filter(($) => Object($) === $)
1109 const { onProperty
, allValuesFrom
} = superclass
;
1110 restrictions
[onProperty
] = processSpace(allValuesFrom
);
1113 schemaCache
[domain
] = restrictions
;
1115 cachedClassRestrictions
.set(
1117 Object
.assign(Object
.create(null), {
1118 [domain
]: restrictions
,
1122 return restrictions
;
1126 const getPredicateRestrictions
= (schema
, predicate
) => {
1127 const schemaCache
= cachedPredicateRestrictions
.get(schema
);
1128 const cached
= schemaCache
?.[predicate
];
1129 if (cached
!= null) {
1132 const { objectProperties
} = schema
;
1133 const restrictions
= [
1134 ...predicateRestrictions(objectProperties
, predicate
),
1136 (result
, { domainIntersection
, rangeIntersection
}) => {
1137 result
.domainIntersection
.push(...domainIntersection
);
1138 result
.rangeIntersection
.push(...rangeIntersection
);
1141 Object
.assign(Object
.create(null), {
1142 domainIntersection
: [],
1143 rangeIntersection
: [],
1147 schemaCache
[predicate
] = restrictions
;
1149 cachedPredicateRestrictions
.set(
1151 Object
.assign(Object
.create(null), {
1152 [predicate
]: restrictions
,
1156 return restrictions
;
1160 const processSpace
= (space
) =>
1161 Object(space
) === space
1166 Object(subspace
) === subspace
1167 ? Array
.from(subspace
.unionOf
)
1170 : [Array
.from(space
.unionOf
)]
1173 const predicateRestrictions
= function* (
1176 touched
= new Set(),
1178 if (predicate
== "Property" || touched
.has(predicate
)) {
1181 const { domain
, range
, subPropertyOf
} =
1182 objectProperties
[predicate
];
1183 yield Object
.assign(Object
.create(null), {
1184 domainIntersection
: processSpace(domain
?? "Thing"),
1185 rangeIntersection
: processSpace(range
?? "Thing"),
1187 touched
.add(predicate
);
1189 const superproperty
of (
1190 subPropertyOf
== null
1192 : typeof subPropertyOf
== "string"
1194 : Array
.from(subPropertyOf
)
1197 yield* predicateRestrictions(
1207 isObjectPredicateOK
: (
1213 const { objectProperties
} = schema
;
1214 const predicateDefinition
= objectProperties
[predicate
];
1215 const isInverse
= "inverseOf" in predicateDefinition
;
1216 const usedPredicate
= isInverse
1217 ? predicateDefinition
.inverseOf
1219 const domain
= isInverse
? objectClass
: subjectClass
;
1220 const domains
= new Set(getClassAndSuperclasses(schema
, domain
));
1221 const ranges
= new Set(getClassAndSuperclasses(
1223 isInverse
? subjectClass
: objectClass
,
1225 const predicateRestrictions
= getPredicateRestrictions(
1229 const { domainIntersection
} = predicateRestrictions
;
1230 const rangeIntersection
= [
1231 ...predicateRestrictions
.rangeIntersection
,
1233 for (const domain
of domains
) {
1234 const classRestrictionOnPredicate
=
1235 getClassRestrictions(schema
, domain
)[usedPredicate
];
1236 if (classRestrictionOnPredicate
!= null) {
1237 yield* classRestrictionOnPredicate
;
1244 return domainIntersection
.every((domainUnion
) =>
1245 domainUnion
.some((domain
) =>
1246 domain
== "Thing" || domains
.has(domain
)
1249 rangeIntersection
.every((rangeUnion
) =>
1250 rangeUnion
.some((range
) =>
1251 range
== "Thing" || ranges
.has(range
)
1260 * Returns the provided value converted into a `String` object with
1261 * `.["@value"]` and `.["@language"]` properties.
1263 * The same object will be returned for every call with an equivalent
1266 * TODO: Ideally this would be extracted more fully into an R·D·F
1269 * ※ This function is not exposed.
1274 * Returns the language string object corresponding to the provided
1275 * value and language.
1277 const getLangString
= (value
, language
= "") => {
1278 const valueMap
= languageMap
[language
] ??= Object
.create(null);
1279 const literal
= valueMap
[value
]?.deref();
1280 if (literal
!= null) {
1281 // There is already an object corresponding to the provided value
1285 // No object already exists corresponding to the provided value
1286 // and language; create one.
1287 const result
= Object
.preventExtensions(
1288 Object
.create(String
.prototype, {
1294 enumerable
: !!language
,
1295 value
: language
|| null,
1297 language
: { enumerable
: false, get: getLanguage
},
1298 toString
: { enumerable
: false, value
: toString
},
1299 valueOf
: { enumerable
: false, value
: valueOf
},
1302 const ref
= new WeakRef(result
);
1303 langStringRegistry
.register(result
, { ref
, language
, value
});
1304 valueMap
[value
] = ref
;
1309 /** Returns the `.["@language"]` of this object. */
1310 const getLanguage
= Object
.defineProperty(
1312 return this["@language"] || null;
1315 { value
: "get language" },
1319 * A `FinalizationRegistry` for language string objects.
1321 * This simply cleans up the corresponding `WeakRef` in the language
1324 const langStringRegistry
= new FinalizationRegistry(
1325 ({ ref
, language
, value
}) => {
1326 const valueMap
= languageMap
[language
];
1327 if (valueMap
?.[value
] === ref
) {
1328 delete valueMap
[value
];
1336 * An object whose own values are an object mapping values to
1337 * language string objects for the language specified by the key.
1339 const languageMap
= Object
.create(null);
1341 /** Returns the `.["@value"]` of this object. */
1342 const toString = function () {
1343 return this["@value"];
1347 * Returns this object if it has a `.["@language"]`; otherwise, its
1350 const valueOf = function () {
1351 return this["@language"] ? this : this["@value"];
1361 `${$["@language"] ?? ""}`,
1363 : getLangString(`${$["@value"]}`)
1365 ? getLangString(`${$}`, `${$.language ?? ""}`)
1366 : getLangString(`${$}`)
1367 : getLangString(`${$ ?? ""}`),
1372 * Returns a normalized tag data object derived from the provided
1375 * ※ The properties of this function need to match the term names used
1376 * in the ActivityStreams serialization.
1378 * ※ This function is not exposed.
1380 const tagData
= ($) => {
1381 const data
= Object($);
1383 // prefLabel intentionally not set here
1393 let prefLabel
= langString(data
.prefLabel
);
1394 return Object
.preventExtensions(Object
.create(null, {
1397 get: () => prefLabel
,
1399 prefLabel
= langString($);
1406 ? Array
.from(altLabel
, langString
)
1414 ? Array
.from(hiddenLabel
, langString
)
1422 ? Array
.from(broader
, toIdentifier
)
1430 ? Array
.from(narrower
, toIdentifier
)
1438 ? Array
.from(inCanon
, toIdentifier
)
1446 ? Array
.from(hasInCanon
, toIdentifier
)
1454 ? Array
.from(involves
, toIdentifier
)
1462 ? Array
.from(involvedIn
, toIdentifier
)
1470 * Returns an identifier corresponding to the provided object.
1472 * This is either the value of its `.identifier` or its string value.
1474 * ※ This function is not exposed.
1476 const toIdentifier
= ($) =>
1479 : Object($) === $ && "identifier" in $
1484 * A tag system, with storage.
1486 * The `::Tag` constructor available on any `TagSystem` instance can be
1487 * used to create new `Tag`s within the system.
1489 export class TagSystem
{
1490 /** The cached bound `Tag` constructor for this `TagSystem`. */
1493 /** The domain of this `TagSystem`. */
1496 /** The date of this `TagSystem`. */
1499 /** The identifier of this `TagSystem`. */
1502 /** The internal `Storage` of this `TagSystem`. */
1503 #storage
= new Storage();
1506 * Constructs a new `TagSystem` with the provided domain and date.
1508 * Only actual, lowercased domain names are allowed for the domain,
1509 * and the date must be “full” (include month and day components).
1510 * This is for alignment with general best practices for Tag URI’s.
1512 * ☡ This constructor throws if provided with an invalid date.
1514 constructor(domain
, date
, identifier
= "") {
1515 const domainString
= `${domain}`;
1516 const dateString
= `${date}`;
1517 this.#identifier
= `${identifier}`;
1519 // If the identifier is a valid storage I·D, reserve it.
1520 this.#storage
.delete(this.#identifier
);
1522 // The identifier is not a valid storage I·D, so no worries.
1526 !/^[a-z](?:[\da-z-]*[\da-z])?(?:\.[a-z](?:[\da-z-]*[\da-z])?)*$/u
1529 // ☡ The domain is invalid.
1530 throw new RangeError(`Invalid domain: ${domain}.`);
1532 !/^\d{4}-\d{2}-\d{2}$/u.test(dateString
) ||
1533 dateString
!= new Date(dateString
).toISOString().split("T")[0]
1535 // ☡ The date is invalid.
1536 throw new RangeError(`Invalid date: ${date}.`);
1538 // The domain and date are 🆗.
1539 this.#domain
= domainString
;
1540 this.#date
= dateString
;
1545 * Returns a bound constructor for constructing `Tags` in this
1549 if (this.#Tag
!= null) {
1550 // A bound constructor has already been generated; return it.
1553 // No bound constructor has been created yet.
1554 const storage
= this.#storage
;
1555 return this.#Tag
= Tag
.For(this, storage
, schema
);
1559 /** Returns the authority name (domain) for this `TagSystem`. */
1560 get authorityName() {
1561 return this.#domain
;
1564 /** Returns the date of this `TagSystem`, as a string. */
1570 * Yields the entities in this `TagSystem`.
1572 * ※ Entities can hypothetically be anything. If you specifically
1573 * want the `Tag`s, use `::Tag.all` instead.
1576 yield* this.#storage
.values();
1580 * Returns the identifier of this `TagSystem`.
1582 * ※ Often this is just the empty string.
1585 return this.#identifier
;
1588 /** Yields the identifiers in use in this `TagSystem`. */
1590 yield* this.#storage
.keys();
1593 /** Returns the I·R·I for this `TagSystem`. */
1595 return `${this.iriSpace}${this.identifier}`;
1599 * Returns the prefix used for I·R·I’s of `Tag`s in this `TagSystem`.
1602 return `https://${this.authorityName}/tag:${this.taggingEntity}:`;
1605 /** Returns the Tag U·R·I for this `TagSystem`. */
1607 return `tag:${this.taggingEntity}:${this.identifier}`;
1611 * Returns the tagging entity (domain and date) for this `TagSystem`.
1613 get taggingEntity() {
1614 return `${this.authorityName},${this.date}`;