]> Lady’s Gitweb - Etiquette/blobdiff - model.js
Enable application of activities onto tag systems
[Etiquette] / model.js
index cfd228d88f12e7e7625a1f2374f3775d57021683..3c8287ea5b27433f854114cc8ea3ccc0037beeea 100644 (file)
--- a/model.js
+++ b/model.js
@@ -433,12 +433,41 @@ class Tag {
     return tag;
   }
 
+  /**
+   * Returns a new `Tag` with the provided identifier, kind, and
+   * prefLabel.
+   *
+   * ※ This function exists to enable `TagSystem`s to replay Create
+   * activities, maintaining the identifier of the original.
+   *
+   * ☡ This function throws if the provided identifier is already in
+   * use.
+   *
+   * ※ This function is not exposed.
+   */
+  static new(system, identifier, kind = "Tag", prefLabel = "") {
+    const storage = (new system.Tag()).#storage;
+    if (storage.has(identifier)) {
+      throw new RangeError(
+        `Cannot create Tag: Identifier already in use: ${identifier}.`,
+      );
+    } else {
+      const createdTag = new system.Tag(kind, prefLabel);
+      createdTag.#identifier = identifier;
+      createdTag.persist(true);
+      return createdTag;
+    }
+  }
+
   /**
    * Returns the `TagSystem` that the provided value belongs to.
    *
    * ※ This function can be used to check if the provided value has
    * private tag features.
    *
+   * ※ `Tag::system` is an overridable, publicly‐accessible means of
+   * accessing the system.
+   *
    * ※ This function is not exposed.
    */
   static getSystem($) {
@@ -489,6 +518,15 @@ class Tag {
     return this.#kind;
   }
 
+  /**
+   * Returns the `TagSystem` for this `Tag`.
+   *
+   * ※ Internally, `Tag.getSystem` is preferred.
+   */
+  get system() {
+    return this.#system;
+  }
+
   /**
    * Persist this `Tag` to storage and return an ActivityStreams
    * serialization of a Tag Activity representing any changes, or
@@ -859,8 +897,8 @@ const {
           function Tag() {
             throw new TypeError("Tags must belong to a System.");
           };
-        const { prototype: methods } = this;
-        delete methods.constructor;
+        const { prototype: staticFeatures } = this;
+        delete staticFeatures.constructor;
         Object.defineProperty(superclass, "prototype", {
           configurable: false,
           enumerable: false,
@@ -869,7 +907,7 @@ const {
         });
         Object.defineProperties(
           superclass,
-          Object.getOwnPropertyDescriptors(methods),
+          Object.getOwnPropertyDescriptors(staticFeatures),
         );
       }
 
@@ -1001,6 +1039,11 @@ const {
         }
       }
 
+      /** Returns the `TagSystem` for this `Tag` constructor. */
+      get system() {
+        return this.#system;
+      }
+
       /**
        * Returns a new `Tag` constructed from the provided data and
        * with the provided identifier.
@@ -1482,6 +1525,9 @@ export class TagSystem {
   /** The identifier of this `TagSystem`. */
   #identifier;
 
+  /** The schema used by this `TagSystem. */
+  #schema = schema;
+
   /** The internal `Storage` of this `TagSystem`. */
   #storage = new Storage();
 
@@ -1535,7 +1581,166 @@ export class TagSystem {
     } else {
       // No bound constructor has been created yet.
       const storage = this.#storage;
-      return this.#Tag = Tag.For(this, storage, schema);
+      return this.#Tag = Tag.For(this, storage, this.#schema);
+    }
+  }
+
+  /**
+   * Applies the provided activity to this `TagSystem` by replaying its
+   * statement changes.
+   *
+   * ※ This method assumes that the provided activity conforms to the
+   * assumptions made by this module; i·e that its tags use the same
+   * identifier format and its activities do not use statements with
+   * inverse property predicates. It is not intended for the generic
+   * playback of activities produced by other scripts or mechanisms,
+   * for which a more sophisticated solution is required.
+   *
+   * ☡ This method throws an error if the provided activity cannot be
+   * processed.
+   */
+  apply(activity) {
+    const { Tag: TagConstructor } = this;
+    const {
+      classes,
+      objectProperties,
+      transitiveProperties,
+      dataProperties,
+    } = this.#schema;
+    const { object, states, unstates } = activity;
+    const activityTypes = [].concat(activity["@type"]);
+    if (!object) {
+      // ☡ The provided activity has no object.
+      throw new TypeError(
+        "Cannot apply activity: Activity lacks an object.",
+      );
+    } else {
+      // The provided activity has an object.
+      const iri = `${object}`;
+      const iriSpace = `${this.iriSpace}`;
+      const identifier = (() => {
+        // Extract the identifier from the object I·R·I.
+        if (!iri.startsWith(iriSpace)) {
+          // ☡ The object of the provided activity is not in the I·R·I
+          // space of this `TagSystem`.
+          throw new RangeError(
+            `Cannot apply activity: Object is not in I·R·I space: ${object}`,
+          );
+        } else {
+          // ☡ The object of the provided activity is in the I·R·I
+          // space of this `TagSystem`.
+          return iri.substring(iriSpace.length);
+        }
+      })();
+      const tag = (() => {
+        // Either resolve the identifier to an existing tag or create
+        // a new one.
+        if (activityTypes.includes("Create")) {
+          // The provided activity is a Create activity.
+          const kind = states.findLast(
+            ({ predicate, object }) =>
+              predicate == "a" && `${object}` in classes,
+          )?.object;
+          if (kind == null) {
+            // ☡ There is no recognized tag class provided for the tag;
+            // it cannot be created.
+            throw new RangeError(
+              `Cannot apply activity: Tag type not recognized.`,
+            );
+          } else {
+            // There is a recognized tag class provided for the tag.
+            return Tag.new(this, identifier, kind);
+          }
+        } else {
+          // The provided activity is not a Create activity.
+          return TagConstructor.fromIdentifier(identifier);
+        }
+      })();
+      if (!tag) {
+        // ☡ Resolving the tag identifier failed.
+        throw new RangeError(
+          `Cannot apply activity: No tag for identifier: ${identifier}.`,
+        );
+      } else {
+        // Resolving the identifier succeeded; apply the changes to the
+        // tag and then silently persist it.
+        for (
+          const [statements, mode] of [
+            [unstates ?? [], "delete"],
+            [states ?? [], "add"],
+          ]
+        ) {
+          // Delete unstatements, then add statements.
+          for (const { predicate: $p, object: $o } of statements) {
+            // Iterate over the statements and apply them.
+            const predicate = `${$p}`;
+            const term = predicate in dataProperties
+              ? langString($o)
+              : predicate in objectProperties &&
+                  !(predicate in transitiveProperties ||
+                    objectProperties[predicate].inverseOf != null)
+              ? `${$o}`
+              : null;
+            if (term == null) {
+              // The provided predicate is not recognized; ignore it.
+              /* do nothing */
+            } else if (predicate == "prefLabel") {
+              // Preflabels are handled specially.
+              if (mode == "delete") {
+                // Unstating a preflabel has no effect unless a new one
+                // is also stated.
+                /* do nothing */
+              } else {
+                // Update the preflabel.
+                tag.prefLabel = term;
+              }
+            } else {
+              // The predicate is not `"prefLabel"`.
+              const related = (() => {
+                // If the predicate is an object property, attempt to
+                // resolve the object.
+                if (!(predicate in objectProperties)) {
+                  // The predicate is not an object property; return
+                  // null.
+                  return null;
+                } else {
+                  // The predicate is an object property.
+                  try {
+                    // Attempt to resolve the object.
+                    return TagConstructor.fromIRI(term);
+                  } catch {
+                    // Resolving failed; return undefined.
+                    return undefined;
+                  }
+                }
+              })();
+              if (related === undefined) {
+                // The predicate is an object property, but its object
+                // was not resolvable.
+                //
+                // ☡ This is a silent error to allow for selective
+                // replay of activities while ignoring terms which are
+                // not covered.
+                /* do nothing */
+              } else {
+                // The predicate is not an object property or has a
+                // resolvable object.
+                //
+                // Apply the statement.
+                tag[
+                  mode.concat(
+                    predicate[0].toUpperCase(),
+                    predicate.substring(1),
+                    predicate in objectProperties ? "Tag" : "",
+                  )
+                ](related ?? term);
+              }
+            }
+          }
+        }
+        tag.persist(true);
+        return tag;
+      }
     }
   }
 
This page took 0.062438 seconds and 4 git commands to generate.