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 { Storage
} from "./memory.js";
11 import { taggingDiscoveryContext
} from "./names.js";
13 // TODO: Move these somewhere else and allow for modification before
14 // they are used, freezing them only once tags actually start being
15 // constructed (probably on first call to the `TagSystem` initializer
18 // Or else make them properties of the tag system itself and ∼fully
22 * Tag kinds which denote entity tags.
24 * ※ This object is not exposed.
26 const ENTITY_TAG_KINDS
= new Set([
33 * Tag kinds which denote relationship tags.
35 * ※ This object is not exposed.
37 const RELATIONSHIP_TAG_KINDS
= new Set([
39 "FamilialRelationship Tag",
42 "RomanticRelationshipTag",
43 "SexualRelationshipTag",
47 * Tag kinds which denote setting tags.
49 * ※ This object is not exposed.
51 const SETTING_TAG_KINDS
= new Set([
59 * Tag kinds which denote conceptual tags.
61 * ※ This object is not exposed.
63 const CONCEPTUAL_TAG_KINDS
= new Set(function* () {
64 yield "ConceptualTag";
65 yield* RELATIONSHIP_TAG_KINDS
;
69 * All recognized tag kinds.
71 * ※ This object is not exposed.
73 const TAG_KINDS
= new Set(function* () {
76 yield* CONCEPTUAL_TAG_KINDS
;
77 yield* ENTITY_TAG_KINDS
;
79 yield* SETTING_TAG_KINDS
;
83 * Tag kinds which can be in canon.
85 * ※ This object is not exposed.
87 const HAS_IN_CANON
= new Set(function* () {
88 yield* ENTITY_TAG_KINDS
;
89 yield* SETTING_TAG_KINDS
;
93 * Tag kinds which can be involved in relationship tags.
95 * ※ This object is not exposed.
97 const INVOLVABLE_IN_RELATIONSHIP
= new Set(function* () {
99 yield* RELATIONSHIP_TAG_KINDS
;
103 * Properties which take literal values instead of identifiers.
105 * These are the label terms.
107 const LITERAL_TERMS
= new Set([
114 * Properties to skip when diffing.
116 * These are all inverses of properties included in diffs and cannot be
119 const SKIP_IN_DIFF
= new Set([
128 * `Tag`s are not assigned identifiers and do not have side·effects on
129 * other tags in the `TagSystem` until they are persisted with
130 * `::persist`, at which point changes to their relationships are
133 * `Tag`s are also not kept up‐to‐date, but persisting an outdated
134 * `Tag` will *not* undo subsequent changes.
136 * ※ This class is not itself directly exposed, although bound
137 * versions of it are via `TagSystem::Tag`.
140 /** The `TagSystem` this `Tag` belongs to. */
143 /** The `Storage` managed by this `Tag`’s `TagSystem`. */
147 * The 30‐bit W·R·M·G base32 identifier with leading checksum which
148 * has been assigned to this `Tag`.
150 * Will be `null` if this `Tag` has not been persisted. Otherwise,
151 * the format is `cxx-xxxx` (`c` = checksum; `x` = digit).
155 /** The kind of this `Tag`. */
159 * The data which was attached to this `Tag` the last time it was
160 * persisted or retrieved from storage.
162 * Diffing with this will reveal changes.
164 #persistedData
= null;
166 /** The current (modified) data associated with this `Tag`. */
170 * Returns whether or not the provided value is a tag which shares a
171 * storage with this tag.
173 * Sharing a storage also implies sharing a `TagSystem`.
177 // Try to compare the provided value’s internal store with
178 // the provided storage.
179 return $.#storage
== this.#storage
;
181 // The provided value was not a `Tag`.
187 * Constructs a new `Tag` of the provided kind and with the provided
190 * ※ The first two arguments of this constructor are bound when
191 * generating the value of `TagSystem::Tag`. It isn’t possible to
192 * access this constructor in its unbound form from outside this
195 * ☡ This constructor throws if the provided kind is not supported.
197 constructor(system
, storage
, kind
= "Tag", prefLabel
= "") {
198 const kindString
= `${kind}`;
199 if (TAG_KINDS
.has(kindString
)) {
200 // The provided kind is one of the recognized tag kinds.
201 this.#system
= system
;
202 this.#storage
= storage
;
203 this.#kind
= kindString
;
204 this.#data
.prefLabel
= prefLabel
;
206 // The provided kind is not supported.
207 throw new RangeError(
208 `Cannot construct Tag: Unrecognized kind: ${kind}.`,
214 * Yields the tags in the `TagSystem` associated with this
217 * ※ The first two arguments of this function are bound when
218 * generating the value of `TagSystem::Tag`. It isn’t possible to
219 * access this function in its unbound form from outside this module.
221 static *all(system
, storage
) {
222 for (const instance
of storage
.values()) {
223 // Iterate over the entries and yield the ones which are `Tag`s
224 // in this `TagSystem`.
225 if (Tag
.getSystem(instance
) == system
) {
226 // The current instance is a `Tag` in this `TagSystem`.
229 // The current instance is not a `Tag` in this `TagSystem`.
236 * Returns a new `Tag` resolved from the provided I·R·I.
238 * ※ The first two arguments of this function are bound when
239 * generating the value of `TagSystem::Tag`. It isn’t possible to
240 * access this function in its unbound form from outside this module.
242 * ※ If the I·R·I is not recognized, this function returns `null`.
244 static fromIRI(system
, storage
, iri
) {
245 const name
= `${iri}`;
247 `https://${system.authorityName}/tag:${system.taggingEntity}:`;
248 if (!name
.startsWith(prefix
)) {
249 // The I·R·I does not begin with the expected prefix.
252 // The I·R·I begins with the expected prefix.
253 const identifier
= name
.substring(prefix
.length
);
255 // Attempt to resolve the identifier.
256 const instance
= storage
.get(identifier
);
257 return Tag
.getSystem(instance
) == system
? instance
: null;
259 // Do not throw for bad identifiers.
266 * Returns a new `Tag` resolved from the provided identifier.
268 * ※ The first two arguments of this function are bound when
269 * generating the value of `TagSystem::Tag`. It isn’t possible to
270 * access this function in its unbound form from outside this module.
272 * ☡ This function throws if the identifier is invalid.
274 * ※ If the identifier is valid but not recognized, this function
277 static fromIdentifier(system
, storage
, identifier
) {
278 const instance
= storage
.get(identifier
);
279 return Tag
.getSystem(instance
) == system
? instance
: null;
283 * Returns a new `Tag` resolved from the provided Tag U·R·I.
285 * ※ The first two arguments of this function are bound when
286 * generating the value of `TagSystem::Tag`. It isn’t possible to
287 * access this function in its unbound form from outside this module.
289 * ☡ This function throws if the provided Tag U·R·I does not match
290 * the tagging entity of this constructor’s `TagSystem`.
292 * ※ If the specific component of the Tag U·R·I is not recognized,
293 * this function returns `null`.
295 static fromTagURI(system
, storage
, tagURI
) {
296 const tagName
= `${tagURI}`;
297 const tagPrefix
= `tag:${system.taggingEntity}:`;
298 if (!tagName
.startsWith(tagPrefix
)) {
299 // The Tag U·R·I does not begin with the expected prefix.
300 throw new RangeError(
301 `Tag U·R·I did not begin with the expected prefix: ${tagName}`,
304 // The I·R·I begins with the expected prefix.
305 const identifier
= tagName
.substring(tagPrefix
.length
);
307 // Attempt to resolve the identifier.
308 const instance
= storage
.get(identifier
);
309 return Tag
.getSystem(instance
) == system
? instance
: null;
311 // Do not throw for bad identifiers.
318 * Returns the `TagSystem` that the provided value belongs to.
320 * ※ This function can be used to check if the provided value has
321 * private tag features.
323 * ※ This function is not exposed.
325 static getSystem($) {
326 return !(#system
in Object($)) ? null : $.#system
;
330 * Yields the tag identifiers in the `TagSystem` associated with this
333 * ※ The first two arguments of this function are bound when
334 * generating the value of `TagSystem::Tag`. It isn’t possible to
335 * access this function in its unbound form from outside this module.
337 static *identifiers(system
, storage
) {
338 for (const [identifier
, instance
] of storage
.entries()) {
339 // Iterate over the entries and yield the ones which are `Tag`s
340 // in this `TagSystem`.
341 if (Tag
.getSystem(instance
) == system
) {
342 // The current instance is a `Tag` in this `TagSystem`.
345 // The current instance is not a `Tag` in this `TagSystem`.
352 * Returns a new `Tag` constructed from the provided data and with
353 * the provided identifier.
355 * ※ This function will not work if called directly from `Tag` (and
356 * nor is it available *to* be called as such from outside this
357 * module). It must be called from a `TagSystem::Tag` bound
360 * ※ This function is not really intended for public usage.
362 static [Storage
.toInstance
](_system
, _storage
, data
, identifier
) {
363 const tag
= new this(data
.kind
);
364 tag
.#identifier
= `${identifier}`;
365 tag
.#persistedData
= tagData(data
);
366 tag
.#data
= tagData(data
);
371 // Overwrite the default `::constructor` method to instead give the
372 // actual (bound) constructor which was used to generate a given
374 Object
.defineProperties(this.prototype, {
379 // All `Tag`s are constructed via the `.Tag` constructor
380 // available in their `TagSystem`; return it.
381 return this.#system
.Tag
;
389 * Adds the provided label(s) to this `Tag` as alternate labels, then
390 * returns this `Tag`.
392 addAltLabel(...labels
) {
393 const altLabels
= this.#data
.altLabel
;
394 let objectLabels
= null; // initialized on first use
395 for (const $ of labels
) {
396 // Iterate over each provided label and attempt to add it.
397 const literal
= langString($);
398 if (Object(literal
) === literal
) {
399 // The current label is a language‐tagged string.
400 objectLabels
??= [...function* () {
401 for (const altLabel
of altLabels
) {
402 // Iterate over the existing labels and yield the
403 // language‐tagged strings.
404 if (Object(altLabel
) === altLabel
) {
405 // The current existing label is a language‐tagged
409 // The current existing label is not a language‐tagged
416 objectLabels
.some((objectLabel
) =>
417 objectLabel
["@value"] == literal
["@value"] &&
418 objectLabel
["@language"] == literal
["@language"]
421 // There is a match with the current label in the existing
425 // There is no match and this label must be added.
426 altLabels
.add(literal
);
427 objectLabels
.push(literal
);
430 // The current label is a simple string.
431 altLabels
.add(literal
);
438 * Adds the provided tags to the list of tags that this `Tag` is
439 * narrower than, then returns this `Tag`.
441 * Arguments may be string identifiers or objects with an
442 * `.identifier` property.
444 addBroaderTag(...tags
) {
445 const storage
= this.#storage
;
446 const broader
= this.#data
.broader
;
447 for (const $ of tags
) {
448 // Iterate over each tag and attempt to set it as broader than
450 const identifier
= toIdentifier($);
451 if (identifier
== null) {
452 // ☡ The current tag has no identifier.
454 "Cannot assign broader to Tag: Identifier must not be nullish.",
456 } else if (broader
.has(identifier
)) {
457 // Short‐circuit: The identifier is already something this
458 // `Tag` is narrower than.
461 // The current tag has an identifier.
462 const tag
= storage
.get(identifier
);
464 // ☡ The current tag has not been persisted to this `Tag`’s
466 throw new RangeError(
467 `Cannot assign broader to Tag: Identifier is not persisted: ${identifier}.`,
469 } else if (!this.#isTagInStorage(tag
)) {
470 // ☡ The current tag is not a tag in the correct tag system.
472 `Cannot assign broader to Tag: Tags must be from the same Tag System, but got: ${identifier}.`,
475 // The current tag is a tag in the correct tag system; add
477 broader
.add(identifier
);
485 * Adds the provided label(s) to this `Tag` as hidden labels, then
486 * returns this `Tag`.
488 addHiddenLabel(...labels
) {
489 const hiddenLabels
= this.#data
.hiddenLabel
;
490 let objectLabels
= null; // initialized on first use
491 for (const $ of labels
) {
492 // Iterate over each provided label and attempt to add it.
493 const literal
= langString($);
494 if (Object(literal
) === literal
) {
495 // The current label is a language‐tagged string.
496 objectLabels
??= [...function* () {
497 for (const hiddenLabel
of hiddenLabels
) {
498 // Iterate over the existing labels and yield the
499 // language‐tagged strings.
500 if (Object(hiddenLabel
) === hiddenLabel
) {
501 // The current existing label is a language‐tagged
505 // The current existing label is not a language‐tagged
512 objectLabels
.some((objectLabel
) =>
513 objectLabel
["@value"] == literal
["@value"] &&
514 objectLabel
["@language"] == literal
["@language"]
517 // There is a match with the current label in the existing
521 // There is no match and this label must be added.
522 hiddenLabels
.add(literal
);
523 objectLabels
.push(literal
);
526 // The current label is a simple string.
527 hiddenLabels
.add(literal
);
534 * Adds the provided tags to the list of tags that this `Tag` is in
535 * canon with, then returns this `Tag`.
537 * Arguments may be string identifiers or objects with an
538 * `.identifier` property.
540 * ☡ This method will throw if a provided argument does not indicate
541 * a canon tag, or if this `Tag` is not of a kind which can be placed
544 addInCanonTag(...tags
) {
545 const storage
= this.#storage
;
546 const kind
= this.#kind
;
547 const inCanon
= this.#data
.inCanon
;
548 if (!HAS_IN_CANON
.has(kind
)) {
549 // ☡ This is not an entity tag, setting tag, or recognized
552 `Cannot put Tag in canon: Incorrect Tag type: ${kind}.`,
555 // This has a kind which can be placed in canon.
556 for (const $ of tags
) {
557 // Iterate over each tag and attempt to set this `Tag` in canon
559 const identifier
= toIdentifier($);
560 if (identifier
== null) {
561 // ☡ The current tag has no identifier.
563 "Cannot put Tag in canon: Identifier must not be nullish.",
565 } else if (inCanon
.has(identifier
)) {
566 // Short‐circuit: The identifier is already something this
567 // `Tag` is in canon of.
570 // The current tag has an identifier.
571 const tag
= storage
.get(identifier
);
573 // ☡ The current tag has not been persisted to this `Tag`’s
575 throw new RangeError(
576 `Cannot put Tag in canon: Identifier is not persisted: ${identifier}.`,
579 // ※ If the first check succeeds, then the current tag
580 // must have `Tag` private class features.
581 !this.#isTagInStorage(tag
) || tag
.#kind
!= "CanonTag"
583 // ☡ The current tag is not a canon tag in the correct
586 `Cannot put Tag in canon: Tags can only be in Canon Tags from the same Tag System, but got: ${identifier}.`,
589 // The current tag is a canon tag in the correct tag
590 // system; add its identifier.
591 inCanon
.add(identifier
);
600 * Adds the provided tags to the list of tags that this `Tag`
601 * involves, then returns this `Tag`.
603 * Arguments may be string identifiers or objects with an
604 * `.identifier` property.
606 * ☡ This method will throw if this `Tag` is not a conceptual tag, or
607 * if this `Tag` is a relationship tag and a provided argument does
608 * not indicate a character or relationship tag.
610 addInvolvesTag(...tags
) {
611 const storage
= this.#storage
;
612 const kind
= this.#kind
;
613 const involves
= this.#data
.involves
;
614 if (!CONCEPTUAL_TAG_KINDS
.has(kind
)) {
615 // ☡ This is not a conceptual tag or recognized subclass.
617 `Cannot involve Tag: Incorrect Tag type: ${kind}.`,
620 // This is a conceptual tag.
621 for (const $ of tags
) {
622 // Iterate over each tag and attempt to set this `Tag` as
624 const identifier
= toIdentifier($);
625 if (identifier
== null) {
626 // ☡ The current tag has no identifier.
628 "Cannot involve Tag: Identifier must not be nullish.",
630 } else if (involves
.has(identifier
)) {
631 // Short‐circuit: The identifier is already something this
635 // The current tag has an identifier.
636 const tag
= storage
.get(identifier
);
638 // ☡ The current tag has not been persisted to this `Tag`’s
640 throw new RangeError(
641 `Cannot involve Tag: Identifier is not persisted: ${identifier}.`,
644 // ※ If the first check succeeds, then the current tag
645 // must have `Tag` private class features.
646 !this.#isTagInStorage(tag
) ||
647 RELATIONSHIP_TAG_KINDS
.has(kind
) &&
648 !INVOLVABLE_IN_RELATIONSHIP
.has(tag
.#kind
)
650 // ☡ The current tag is in the correct tag system and
653 `Cannot involve Tag: Tags must be the same Tag System and involvable, but got: ${identifier}.`,
656 // The current tag is an involvable tag in the correct tag
657 // system; add its identifier.
658 involves
.add(identifier
);
666 /** Yields the alternative labels of this `Tag`. */
668 yield* this.#data
.altLabel
;
671 /** Returns the authority (domain) name for this `Tag`. */
672 get authorityName() {
673 return this.#system
.authorityName
;
676 /** Yields `Tag`s which are broader than this `Tag`. */
678 const storage
= this.#storage
;
679 for (const identifier
of this.#data
.broader
) {
680 // Iterate over the broader tags and yield them if possible.
681 const tag
= storage
.get(identifier
);
682 if (!this.#isTagInStorage(tag
)) {
683 // The broader tag no longer appears in storage; perhaps it was
687 // The broader tag exists and is constructable from storage.
693 /** Yields `Tag`s which are broader than this `Tag`, transitively. */
694 *broaderTransitiveTags() {
695 const storage
= this.#storage
;
696 const encountered
= new Set();
697 let pending
= new Set(this.#data
.broader
);
698 while (pending
.size
> 0) {
699 // Loop until all broader tags have been encountered.
700 const processing
= pending
;
702 for (const identifier
of processing
) {
703 // Iterate over the broader tags and yield them if possible.
704 if (!encountered
.has(identifier
)) {
705 // The broader tag has not been encountered before.
706 encountered
.add(identifier
);
707 const tag
= storage
.get(identifier
);
708 if (!this.#isTagInStorage(tag
)) {
709 // The broader tag no longer appears in storage; perhaps it
713 // The broader tag exists and is constructable from
716 for (const transitive
of tag
.#data
.broader
) {
717 // Iterate over the broader tags of the current broader
718 // tag and add them to pending as needed.
719 if (!encountered
.has(transitive
)) {
720 // The broader broader tag has not been encountered
722 pending
.add(transitive
);
724 // The broader broader tag has already been
731 // The broader tag has already been encountered.
739 * Removes the provided string label(s) from this `Tag` as alternate
740 * labels, then returns this `Tag`.
742 deleteAltLabel(...labels
) {
743 const altLabels
= this.#data
.altLabel
;
744 let objectLabels
= null; // initialized on first use
745 for (const $ of labels
) {
746 // Iterate over each provided label and attempt to remove it.
747 const literal
= langString($);
748 if (Object(literal
) === literal
) {
749 // The current label is a language‐tagged string.
750 objectLabels
??= [...function* () {
751 for (const altLabel
of altLabels
) {
752 // Iterate over the existing labels and yield the
753 // language‐tagged strings.
754 if (Object(altLabel
) === altLabel
) {
755 // The current existing label is a language‐tagged
759 // The current existing label is not a language‐tagged
765 const existing
= objectLabels
.find((objectLabel
) =>
766 objectLabel
["@value"] == literal
["@value"] &&
767 objectLabel
["@language"] == literal
["@language"]
769 altLabels
.delete(existing
);
771 // The current label is a simple string.
772 altLabels
.delete(literal
);
779 * Removes the provided tags from the list of tags that this `Tag` is
780 * narrower than, then returns this `Tag`.
782 * Arguments may be string identifiers or objects with an
783 * `.identifier` property.
785 deleteBroaderTag(...tags
) {
786 const broader
= this.#data
.broader
;
787 for (const $ of tags
) {
788 // Iterate over the provided tags and delete them.
789 broader
.delete(toIdentifier($));
795 * Removes the provided string label(s) from this `Tag` as hidden
796 * labels, then returns this `Tag`.
798 deleteHiddenLabel(...labels
) {
799 const hiddenLabels
= this.#data
.hiddenLabel
;
800 let objectLabels
= null; // initialized on first use
801 for (const $ of labels
) {
802 // Iterate over each provided label and attempt to remove it.
803 const literal
= langString($);
804 if (Object(literal
) === literal
) {
805 // The current label is a language‐tagged string.
806 objectLabels
??= [...function* () {
807 for (const hiddenLabel
of hiddenLabels
) {
808 // Iterate over the existing labels and yield the
809 // language‐tagged strings.
810 if (Object(hiddenLabel
) === hiddenLabel
) {
811 // The current existing label is a language‐tagged
815 // The current existing label is not a language‐tagged
821 const existing
= objectLabels
.find((objectLabel
) =>
822 objectLabel
["@value"] == literal
["@value"] &&
823 objectLabel
["@language"] == literal
["@language"]
825 hiddenLabels
.delete(existing
);
827 // The current label is a simple string.
828 hiddenLabels
.delete(literal
);
835 * Removes the provided tags from the list of tags that this `Tag` is
836 * in canon with, then returns this `Tag`.
838 * Arguments may be string identifiers or objects with an
839 * `.identifier` property.
841 deleteInCanonTag(...tags
) {
842 const inCanon
= this.#data
.inCanon
;
843 for (const $ of tags
) {
844 // Iterate over the provided tags and delete them.
845 inCanon
.delete(toIdentifier($));
851 * Removes the provided tags from the list of tags that this `Tag`
852 * involves, then returns this `Tag`.
854 * Arguments may be string identifiers or objects with an
855 * `.identifier` property.
857 deleteInvolvesTag(...tags
) {
858 const involves
= this.#data
.involves
;
859 for (const $ of tags
) {
860 // Iterate over the provided tags and delete them.
861 involves
.delete(toIdentifier($));
866 /** Yields `Tag`s that are in canon of this `Tag`. */
868 const storage
= this.#storage
;
869 if (this.#kind
== "CanonTag") {
870 // This is a canon tag.
871 for (const identifier
of this.#data
.hasInCanon
) {
872 // Iterate over the tags in canon and yield them if possible.
873 const tag
= storage
.get(identifier
);
875 !this.#isTagInStorage(tag
) || !HAS_IN_CANON
.has(tag
.#kind
)
877 // The tag in canon no longer appears in storage; perhaps it
881 // The tag in canon exists and is constructable from storage.
890 /** Yields the hidden labels of this `Tag`. */
892 yield* this.#data
.hiddenLabel
;
895 /** Returns the identifier of this `Tag`. */
897 return this.#identifier
;
900 /** Yields `Tag`s that this `Tag` is in canon of. */
902 const storage
= this.#storage
;
903 if (HAS_IN_CANON
.has(this.#kind
)) {
904 // This tag can be placed in canon.
905 for (const identifier
of this.#data
.inCanon
) {
906 // Iterate over the canon tags and yield them if possible.
907 const tag
= storage
.get(identifier
);
908 if (!this.#isTagInStorage(tag
) || tag
.#kind
!= "CanonTag") {
909 // The canon tag no longer appears in storage; perhaps it was
913 // The canon tag exists and is constructable from storage.
918 // This tag cannot be placed in canon.
923 /** Yields `Tag`s which involve this `Tag`. */
925 const storage
= this.#storage
;
926 for (const identifier
of this.#data
.involvedIn
) {
927 // Iterate over the involving tags and yield them if possible.
928 const tag
= storage
.get(identifier
);
929 const tagKind
= tag
.#kind
;
931 !this.#isTagInStorage(tag
) ||
932 !CONCEPTUAL_TAG_KINDS
.has(tagKind
) ||
933 RELATIONSHIP_TAG_KINDS
.has(tagKind
) &&
934 !INVOLVABLE_IN_RELATIONSHIP
.has(this.#kind
)
936 // The including tag no longer appears in storage; perhaps it
940 // The including tag exists and is constructable from storage.
946 /** Yields `Tag`s that this `Tag` involves. */
948 const storage
= this.#storage
;
949 const kind
= this.#kind
;
950 if (CONCEPTUAL_TAG_KINDS
.has(kind
)) {
951 // This tag can involve other tags.
952 for (const identifier
of this.#data
.involves
) {
953 // Iterate over the involved and yield them if possible.
954 const tag
= storage
.get(identifier
);
956 !this.#isTagInStorage(tag
) ||
957 RELATIONSHIP_TAG_KINDS
.has(kind
) &&
958 !INVOLVABLE_IN_RELATIONSHIP
.has(tag
.#kind
)
960 // The involved tag no longer appears in storage; perhaps it
964 // The involved tag exists and is constructable from storage.
969 // This tag cannot involve other tags.
974 /** Returns the I·R·I for this `Tag`. */
976 const tagURI
= this.tagURI
;
977 return tagURI
== null
979 : `https://${this.authorityName}/${tagURI}`;
982 /** Returns the kind of this `Tag`. */
987 /** Yields `Tag`s which are narrower than this `Tag`. */
989 const storage
= this.#storage
;
990 for (const identifier
of this.#data
.narrower
) {
991 const tag
= storage
.get(identifier
);
992 if (!this.#isTagInStorage(tag
)) {
993 // The narrower tag no longer appears in storage; perhaps it
997 // The narrower tag exists and is constructable from storage.
1004 * Yields `Tag`s which are narrower than this `Tag`, transitively.
1006 *narrowerTransitiveTags() {
1007 const storage
= this.#storage
;
1008 const encountered
= new Set();
1009 let pending
= new Set(this.#data
.narrower
);
1010 while (pending
.size
> 0) {
1011 // Loop until all narrower tags have been encountered.
1012 const processing
= pending
;
1013 pending
= new Set();
1014 for (const identifier
of processing
) {
1015 // Iterate over the narrower tags and yield them if possible.
1016 if (!encountered
.has(identifier
)) {
1017 // The narrower tag has not been encountered before.
1018 encountered
.add(identifier
);
1019 const tag
= storage
.get(identifier
);
1020 if (!this.#isTagInStorage(tag
)) {
1021 // The narrower tag no longer appears in storage; perhaps
1025 // The narrower tag exists and is constructable from
1028 for (const transitive
of tag
.#data
.narrower
) {
1029 // Iterate over the narrower tags of the current narrower
1030 // tag and add them to pending as needed.
1031 if (!encountered
.has(transitive
)) {
1032 // The narrower narrower tag has not been encountered
1034 pending
.add(transitive
);
1036 // The narrower narrower tag has already been
1043 // The narrower tag has already been encountered.
1051 * Persist this `Tag` to storage and return an ActivityStreams
1052 * serialization of a Tag Activity representing any changes, or
1053 * `null` if no changes were made.
1055 * If the second argument is `true`, the `Tag` will be persisted but
1056 * no serialization will be made. This is somewhat more efficient.
1058 * ※ Persistence can imply side‐effects on other objects, which are
1059 * not noted explicitly in the activity. For example, marking a tag
1060 * as broader than another causes the other tag to reciprocally be
1061 * marked as narrower.
1063 * ※ The inverse terms `hasInCanon`, `isIncludedIn`, and `narrower`
1064 * will never appear in the predicates of generated activities.
1066 persist(silent
= false) {
1067 const system
= this.#system
;
1068 const storage
= this.#storage
;
1069 const persistedData
= this.#persistedData
;
1070 const data
= this.#data
;
1072 for (const [key
, value
] of Object
.entries(data
)) {
1073 // Iterate over each entry of the tag data and create a diff
1074 // with the last persisted information.
1075 if (SKIP_IN_DIFF
.has(key
) || silent
&& LITERAL_TERMS
.has(key
)) {
1076 // The current property is one which is skipped in diffs.
1078 // In a silent persist, this includes any literal terms.
1081 // The current property should be diffed.
1082 const persisted
= persistedData
?.[key
] ?? null;
1083 if (persisted
== null) {
1084 // There is no persisted data for the current property yet.
1087 new: value
instanceof Set
1091 } else if (value
instanceof Set
) {
1092 // The current property is set‐valued.
1093 let values
= null; // initialized on first use
1094 const oldValues
= new Set(persisted
);
1095 const newValues
= new Set(value
);
1096 for (const existing
of persisted
) {
1097 // Iterate over each persisted property and either remove
1098 // it from the list of new values or add it to the list of
1101 // ※ Some special handling is required here for
1102 // language‐tagged strings.
1104 value
.has(existing
) ||
1105 Object(existing
) === existing
&&
1106 (values
??= [...value
]).some(($) =>
1107 `${$}` == `${existing}` &&
1108 $.language
== existing
.language
1111 // The value is in both the old and new version of the
1113 oldValues
.delete(existing
);
1114 newValues
.delete(existing
);
1116 // The value is not shared.
1125 `${value}` != `${persisted}` ||
1126 value
.language
!= persisted
.language
1128 // The current property is (optionally language‐tagged)
1129 // string‐valued and the value changed.
1131 old
: new Set([persisted
]),
1132 new: new Set([value
]),
1135 // The current property did not change.
1143 const identifier
= this.#identifier
;
1144 if (identifier
!= null) {
1145 // This `Tag` has already been persisted; use its existing
1146 // identifier and persist.
1147 storage
.set(identifier
, this);
1149 // This `Tag` has not been persisted yet; save the new
1150 // identifier after persisting.
1151 this.#identifier
= storage
.add(this);
1153 const persistedIdentifier
= this.#identifier
;
1154 this.#persistedData
= tagData(data
); // cloning here is necessary
1156 const [term
, inverse
] of [
1157 ["broader", "narrower"],
1158 ["inCanon", "hasInCanon"],
1159 ["involves", "involvedIn"],
1162 // Iterate over each term referencing other tags and update the
1163 // inverse property on those tags if possible.
1164 for (const referencedIdentifier
of diffs
[term
].old
) {
1165 // Iterate over the removed tags and remove this `Tag` from
1166 // their inverse property.
1167 const referenced
= storage
.get(referencedIdentifier
);
1169 // Try removing this `Tag`.
1170 referenced
.#data
[inverse
].delete(persistedIdentifier
);
1171 storage
.set(referencedIdentifier
, referenced
);
1173 // Removal failed, possibly because the other tag was
1178 for (const referencedIdentifier
of diffs
[term
].new) {
1179 const referenced
= storage
.get(referencedIdentifier
);
1181 // Try adding this `Tag`.
1182 referenced
.#data
[inverse
].add(persistedIdentifier
);
1183 storage
.set(referencedIdentifier
, referenced
);
1185 // Adding failed, possibly because the other tag was deleted.
1191 // This is a silent persist.
1194 // This is not a silent persist; an activity needs to be
1195 // generated if a change was made.
1197 "@context": taggingDiscoveryContext
,
1200 identifier
== null ? "Create" : "Update",
1202 context
: `${system.iri}`,
1203 object
: `${this.iri}`,
1204 endTime
: new Date().toISOString(),
1206 const statements
= {
1210 const { unstates
, states
} = statements
;
1211 if (identifier
== null) {
1212 // This is a Create activity.
1213 states
.push({ predicate
: "a", object
: `${this.kind}` });
1215 // This is an Update activity.
1222 }] of Object
.entries(diffs
)
1224 // Iterate over the diffs of each term and state/unstate
1225 // things as needed.
1226 for (const oldValue
of oldValues
) {
1227 // Iterate over removals and unstate them.
1228 if (LITERAL_TERMS
.has(term
)) {
1229 // This is a literal term; push the change wrapped in an
1233 object
: Object(oldValue
) === oldValue
1234 ? { ...langString(oldValue
) }
1235 : { "@value": `${oldValue}` },
1238 // This is a named term; attempt to get its I·R·I and
1241 // Attempt to resolve the value and push the change.
1242 const tag
= storage
.get(oldValue
);
1243 if (!this.#isTagInStorage(tag
)) {
1244 // The value did not resolve to a tag in storage.
1247 // The value resolved; push its I·R·I.
1254 // Value resolution failed for some reason; perhaps the
1260 for (const newValue
of newValues
) {
1261 // Iterate over additions and state them.
1262 if (LITERAL_TERMS
.has(term
)) {
1263 // This is a literal term; push the change wrapped in an
1267 object
: Object(newValue
) === newValue
1268 ? { ...langString(newValue
) }
1269 : { "@value": `${newValue}` },
1272 // This is a named term; attempt to get its I·R·I and
1275 // Attempt to resolve the value and push the change.
1276 const tag
= storage
.get(newValue
);
1277 if (!this.#isTagInStorage(tag
)) {
1278 // The value did not resolve to a tag in storage.
1281 // The value resolved; push its I·R·I.
1288 // Value resolution failed for some reason; perhaps the
1295 if (unstates
.length
== 0) {
1296 // Nothing was unstated.
1297 delete statements
.unstates
;
1299 // Things were stated.
1302 if (states
.length
== 0) {
1303 // Nothing was stated.
1304 delete statements
.states
;
1306 // Things were stated.
1313 !Object
.hasOwn(activity
, "states") &&
1314 !Object
.hasOwn(activity
, "unstates")
1316 // No meaningful changes were actually persisted.
1319 // There were meaningful changes persisted regarding this `Tag`.
1325 /** Returns the preferred label for this `Tag`. */
1327 return this.#data
.prefLabel
;
1330 /** Sets the preferred label of this `Tag` to the provided label. */
1332 this.#data
.prefLabel
= langString($);
1335 /** Returns the Tag U·R·I for this `Tag`. */
1337 const { identifier
} = this;
1338 return identifier
== null
1340 : `tag:${this.taggingEntity}:${identifier}`;
1343 /** Returns the tagging entity (domain and date) for this `Tag`. */
1344 get taggingEntity() {
1345 return this.#system
.taggingEntity
;
1348 /** Returns the string form of the preferred label of this `Tag`. */
1350 return `${this.#data.prefLabel}`;
1354 * Returns a new object whose enumerable own properties contain the
1355 * data from this object needed for storage.
1357 * ※ This method is not really intended for public usage.
1359 [Storage
.toObject
]() {
1360 const data
= this.#data
;
1361 return Object
.assign(Object
.create(null), {
1370 * Returns the provided value converted into either a plain string
1371 * primitive or an object with `.["@value"]` and `.["@language"]`
1374 * TODO: Ideally this would be extracted more fully into an R·D·F
1377 * ※ This function is not exposed.
1381 /** Returns the `.["@language"]` of this object. */
1382 const getLanguage
= Object
.defineProperty(
1384 return this["@language"];
1387 { value
: "get language" },
1390 /** Returns the `.["@value"]` of this object. */
1391 const toString = function () {
1392 return this["@value"];
1395 /** Returns the `.["@value"]` of this object. */
1396 const valueOf = function () {
1397 return this["@value"];
1405 ? Object
.preventExtensions(
1406 Object
.create(String
.prototype, {
1409 value
: `${$["@value"]}`,
1413 value
: `${$["@language"]}`,
1415 language
: { enumerable
: false, get: getLanguage
},
1416 toString
: { enumerable
: false, value
: toString
},
1417 valueOf
: { enumerable
: false, value
: valueOf
},
1422 ? Object
.preventExtensions(
1423 Object
.create(String
.prototype, {
1424 "@value": { enumerable
: true, value
: `${$}` },
1427 value
: `${$.language}`,
1429 language
: { enumerable
: false, get: getLanguage
},
1430 toString
: { enumerable
: false, value
: toString
},
1431 valueOf
: { enumerable
: false, value
: valueOf
},
1440 * Returns a normalized tag data object derived from the provided
1443 * ※ The properties of this function need to match the term names used
1444 * in the ActivityStreams serialization.
1446 * ※ This function is not exposed.
1448 const tagData
= ($) => {
1449 const data
= Object($);
1451 // prefLabel intentionally not set here
1461 let prefLabel
= langString(data
.prefLabel
);
1462 return Object
.preventExtensions(Object
.create(null, {
1465 get: () => prefLabel
,
1467 prefLabel
= langString($);
1474 ? Array
.from(altLabel
, langString
)
1482 ? Array
.from(hiddenLabel
, langString
)
1490 ? Array
.from(broader
, toIdentifier
)
1498 ? Array
.from(narrower
, toIdentifier
)
1506 ? Array
.from(inCanon
, toIdentifier
)
1514 ? Array
.from(hasInCanon
, toIdentifier
)
1522 ? Array
.from(involves
, toIdentifier
)
1530 ? Array
.from(involvedIn
, toIdentifier
)
1538 * Returns an identifier corresponding to the provided object.
1540 * This is either the value of its `.identifier` or its string value.
1542 * ※ This function is not exposed.
1544 const toIdentifier
= ($) =>
1547 : Object($) === $ && "identifier" in $
1552 * A tag system, with storage.
1554 * The `::Tag` constructor available on any `TagSystem` instance can be
1555 * used to create new `Tag`s within the system.
1557 export class TagSystem
{
1558 /** The cached bound `Tag` constructor for this `TagSystem`. */
1561 /** The domain of this `TagSystem`. */
1564 /** The date of this `TagSystem`. */
1567 /** The identifier of this `TagSystem`. */
1570 /** The internal `Storage` of this `TagSystem`. */
1571 #storage
= new Storage();
1574 * Constructs a new `TagSystem` with the provided domain and date.
1576 * Only actual, lowercased domain names are allowed for the domain,
1577 * and the date must be “full” (include month and day components).
1578 * This is for alignment with general best practices for Tag URI’s.
1580 * ☡ This constructor throws if provided with an invalid date.
1582 constructor(domain
, date
, identifier
= "") {
1583 const domainString
= `${domain}`;
1584 const dateString
= `${date}`;
1585 this.#identifier
= `${identifier}`;
1587 // If the identifier is a valid storage I·D, reserve it.
1588 this.#storage
.delete(this.#identifier
);
1590 // The identifier is not a valid storage I·D, so no worries.
1594 !/^[a-z](?:[\da-z-]*[\da-z])?(?:\.[a-z](?:[\da-z-]*[\da-z])?)*$/u
1597 // ☡ The domain is invalid.
1598 throw new RangeError(`Invalid domain: ${domain}.`);
1600 !/^\d{4}-\d{2}-\d{2}$/u.test(dateString
) ||
1601 dateString
!= new Date(dateString
).toISOString().split("T")[0]
1603 // ☡ The date is invalid.
1604 throw new RangeError(`Invalid date: ${date}.`);
1606 // The domain and date are 🆗.
1607 this.#domain
= domainString
;
1608 this.#date
= dateString
;
1613 * Returns a bound constructor for constructing `Tags` in this
1617 if (this.#Tag
!= null) {
1618 // A bound constructor has already been generated; return it.
1621 // No bound constructor has been created yet.
1622 const storage
= this.#storage
;
1623 const BoundTag
= Tag
.bind(undefined, this, storage
);
1624 return this.#Tag
= Object
.defineProperties(BoundTag
, {
1628 value
: Tag
.all
.bind(BoundTag
, this, storage
),
1634 value
: Tag
.fromIRI
.bind(BoundTag
, this, storage
),
1640 value
: Tag
.fromIdentifier
.bind(BoundTag
, this, storage
),
1646 value
: Tag
.fromTagURI
.bind(BoundTag
, this, storage
),
1652 value
: Tag
.identifiers
.bind(BoundTag
, this, storage
),
1655 name
: { value
: `${this.tagURI}#${Tag.name}` },
1656 prototype: { value
: Tag
.prototype },
1657 [Storage
.toInstance
]: {
1660 value
: Tag
[Storage
.toInstance
].bind(BoundTag
, this, storage
),
1667 /** Returns the authority name (domain) for this `TagSystem`. */
1668 get authorityName() {
1669 return this.#domain
;
1672 /** Returns the date of this `TagSystem`, as a string. */
1678 * Yields the entities in this `TagSystem`.
1680 * ※ Entities can hypothetically be anything. If you specifically
1681 * want the `Tag`s, use `::Tag.all` instead.
1684 yield* this.#storage
.values();
1688 * Returns the identifier of this `TagSystem`.
1690 * ※ Often this is just the empty string.
1693 return this.#identifier
;
1696 /** Yields the identifiers in use in this `TagSystem`. */
1698 yield* this.#storage
.keys();
1701 /** Returns the I·R·I for this `TagSystem`. */
1703 return `https://${this.authorityName}/${this.tagURI}`;
1706 /** Returns the Tag U·R·I for this `TagSystem`. */
1708 return `tag:${this.taggingEntity}:${this.identifier}`;
1712 * Returns the tagging entity (domain and date) for this `TagSystem`.
1714 get taggingEntity() {
1715 return `${this.authorityName},${this.date}`;