@fedify/vocab-tools 2.5.0-dev.2687 → 2.5.0-dev.2726

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mod.cjs CHANGED
@@ -8,7 +8,7 @@ let yaml = require("yaml");
8
8
  let es_toolkit = require("es-toolkit");
9
9
  //#region deno.json
10
10
  var name = "@fedify/vocab-tools";
11
- var version = "2.5.0-dev.2687+924da5ce";
11
+ var version = "2.5.0-dev.2726+da549263";
12
12
  //#endregion
13
13
  //#region src/type.ts
14
14
  const HEURISTICS_CONTEXTS = [
@@ -549,7 +549,17 @@ function getEncoder(typeUri, types, variable, optionsVariable, compact = false)
549
549
  ...(${optionsVariable}),
550
550
  format: undefined,
551
551
  context: undefined,
552
- })` : `await ${variable}.toJsonLd(${optionsVariable})`;
552
+ // @ts-ignore: an internal option
553
+ _embedding: true,
554
+ })` : `await encodeNestedVocabularyValue(
555
+ ${optionsVariable},
556
+ ${variable},
557
+ () => ${variable}.toJsonLd({
558
+ ...(${optionsVariable}),
559
+ // @ts-ignore: an internal option
560
+ _embedding: true,
561
+ }),
562
+ )`;
553
563
  throw new Error(`Unknown type: ${typeUri}`);
554
564
  }
555
565
  function getTypeGuard(typeUri, types, variable) {
@@ -575,7 +585,14 @@ function getDecoder(typeUri, types, variable, optionsVariable, baseUrlVariable)
575
585
  if (typeUri in scalarTypes) return scalarTypes[typeUri].decoder(variable, baseUrlVariable);
576
586
  if (typeUri in types) return `await ${types[typeUri].name}.fromJsonLd(
577
587
  ${variable},
578
- { ...${optionsVariable}, baseUrl: ${baseUrlVariable} }
588
+ {
589
+ ...${optionsVariable},
590
+ baseUrl: ${baseUrlVariable},
591
+ // @ts-ignore: an internal option
592
+ _retainsRawProperties: true,
593
+ // @ts-ignore: an internal option
594
+ _expanded: true,
595
+ }
579
596
  )`;
580
597
  throw new Error(`Unknown type: ${typeUri}`);
581
598
  }
@@ -745,6 +762,701 @@ async function loadSchemaFiles(dir) {
745
762
  return Object.fromEntries(entries);
746
763
  }
747
764
  //#endregion
765
+ //#region src/raw-property.ts
766
+ /**
767
+ * Emits the body of a loop that encodes the values of a property into the
768
+ * shape that `toJsonLd({ format: "expand" })` passes to `jsonld.expand()`.
769
+ * The loop pushes encoded values into a local `array`, and expects the
770
+ * current value in `v` and the encoding options in `options`.
771
+ * @param property The property to encode.
772
+ * @param types The type schemas.
773
+ * @param signedValueScope The expression of the signed-value scope whose
774
+ * placeholders should replace retained signed values,
775
+ * or `undefined` to encode them as they are.
776
+ * @returns The code of the loop body.
777
+ */
778
+ function* generateExpandedPropertyElement(property, types, signedValueScope) {
779
+ yield `
780
+ let element = (
781
+ `;
782
+ const scalar = areAllScalarTypes(property.range, types);
783
+ if (!scalar) {
784
+ if (signedValueScope != null) yield `retainedSignedValueRef(v, ${signedValueScope}) ?? (`;
785
+ yield "v instanceof URL ? { \"@id\": formatIri(v) } : ";
786
+ }
787
+ for (const code of getEncoders(property.range, types, "v", "options")) yield code;
788
+ if (!scalar && signedValueScope != null) yield ")";
789
+ yield `
790
+ );
791
+ if (Array.isArray(element)) {
792
+ if (element.length < 1) continue;
793
+ if (element.length == 1) element = element[0];
794
+ }
795
+ if (typeof element === "undefined") continue;
796
+ `;
797
+ if (isNonFunctionalProperty(property) && property.container === "graph") yield `array.push({ "@graph": element });`;
798
+ else yield `array.push(element);`;
799
+ }
800
+ /**
801
+ * Emits module-private support for the raw property functions, shared by all
802
+ * generated classes, and the public functions themselves.
803
+ */
804
+ function generateRawPropertyHelpers() {
805
+ return `
806
+ type RawPropertyEncoder = (
807
+ object: object,
808
+ options: { format: "expand"; contextLoader?: DocumentLoader },
809
+ ) => Promise<unknown>;
810
+
811
+ interface RawPropertyDescriptor {
812
+ readonly canonicalIri: string;
813
+ readonly encode: RawPropertyEncoder;
814
+ }
815
+
816
+ // Unknown properties retained while decoding, keyed by the decoded object:
817
+ const retainedRawProperties = new WeakMap<object, RetainedRawProperties>();
818
+
819
+ // Encoders of the properties each generated class declares, keyed by the
820
+ // class's prototype and then by the property IRIs, including aliases:
821
+ const rawPropertyDescriptors = new Map<
822
+ object,
823
+ ReadonlyMap<string, RawPropertyDescriptor>
824
+ >();
825
+
826
+ function getRawPropertyDescriptor(
827
+ object: object,
828
+ iri: string,
829
+ ): RawPropertyDescriptor | undefined {
830
+ let prototype: object | null = globalThis.Object.getPrototypeOf(object);
831
+ while (prototype != null) {
832
+ const descriptor = rawPropertyDescriptors.get(prototype)?.get(iri);
833
+ if (descriptor != null) {
834
+ // A subclass can declare the property again without an alias that only
835
+ // a superclass declares, so the property's own IRI is looked up again
836
+ // to take the encoder of the most derived class:
837
+ return descriptor.canonicalIri === iri
838
+ ? descriptor
839
+ : (getRawPropertyDescriptor(object, descriptor.canonicalIri) ??
840
+ descriptor);
841
+ }
842
+ prototype = globalThis.Object.getPrototypeOf(prototype);
843
+ }
844
+ return undefined;
845
+ }
846
+
847
+ function copyRawProperties(source: object, destination: object): void {
848
+ const retained = retainedRawProperties.get(source);
849
+ if (retained == null) retainedRawProperties.delete(destination);
850
+ else retainedRawProperties.set(destination, retained);
851
+ }
852
+
853
+ // Objects that were given the document they were received as, or whose values
854
+ // changed after decoding, which that document no longer describes:
855
+ const receivedJsonLd = new WeakSet<object>();
856
+
857
+ // Retains the unknown properties of the node a preprocessor made a value of,
858
+ // such as an Image of a Link, by the class of that value, since the value was
859
+ // not decoded from the node by that class:
860
+ function retainPreprocessedRawProperties(value: unknown, node: unknown): void {
861
+ if (
862
+ value == null || typeof value !== "object" || node == null ||
863
+ typeof node !== "object" || globalThis.Array.isArray(node)
864
+ ) {
865
+ return;
866
+ }
867
+ const known = new Set<string>();
868
+ let prototype: object | null = globalThis.Object.getPrototypeOf(value);
869
+ while (prototype != null) {
870
+ for (const iri of rawPropertyDescriptors.get(prototype)?.keys() ?? []) {
871
+ known.add(iri);
872
+ }
873
+ prototype = globalThis.Object.getPrototypeOf(prototype);
874
+ }
875
+ const retained = retainRawProperties(node as Record<string, unknown>, known);
876
+ if (retained != null) retainedRawProperties.set(value, retained);
877
+ }
878
+
879
+ function skipReceivedJsonLd(value: unknown): void {
880
+ if (value != null && typeof value === "object") receivedJsonLd.add(value);
881
+ }
882
+
883
+ function invalidateCachedJsonLd(object: object): void {
884
+ (object as unknown as { _cachedJsonLd?: unknown })._cachedJsonLd =
885
+ undefined;
886
+ receivedJsonLd.add(object);
887
+ }
888
+
889
+ // The received documents of embedded objects that have their own context,
890
+ // keyed by the expanded nodes they became while the outermost object was
891
+ // decoded:
892
+ type ReceivedDocuments = WeakMap<object, object>;
893
+
894
+ // Collects the embedded documents of a received document, at any depth: the
895
+ // objects with their own context other than the outermost node, under keys
896
+ // other than keywords, also inside arrays and @set, @list, and @graph. Value
897
+ // objects and graph objects never become embedded objects, and the marker
898
+ // would change what they mean, so they are left out, as far as their keys
899
+ // tell: an object with @graph and nothing but @context, @id, and @index is a
900
+ // graph object. One with other keys is marked, whatever they are aliases of,
901
+ // as the comparison of the expansions catches a marker that made a node of a
902
+ // graph object:
903
+ function collectEmbeddedDocuments(root: object): object[] {
904
+ const outermost = globalThis.Array.isArray(root) ? root[0] : root;
905
+ const documents: object[] = [];
906
+ const pending: unknown[] = [root];
907
+ while (pending.length > 0) {
908
+ const value = pending.pop();
909
+ if (globalThis.Array.isArray(value)) {
910
+ // A loop, as spreading a long array into arguments overflows the stack:
911
+ for (const element of value) pending.push(element);
912
+ continue;
913
+ }
914
+ if (value == null || typeof value !== "object") continue;
915
+ if (
916
+ value !== outermost && "@context" in value && !("@value" in value) &&
917
+ (!("@graph" in value) ||
918
+ globalThis.Object.keys(value).some((key) =>
919
+ key !== "@context" && key !== "@graph" && key !== "@id" &&
920
+ key !== "@index"
921
+ )) &&
922
+ !("@set" in value) && !("@list" in value)
923
+ ) {
924
+ documents.push(value);
925
+ }
926
+ for (const [key, child] of globalThis.Object.entries(value)) {
927
+ if (
928
+ !key.startsWith("@") || key === "@set" || key === "@list" ||
929
+ key === "@graph"
930
+ ) {
931
+ pending.push(child);
932
+ }
933
+ }
934
+ }
935
+ return documents;
936
+ }
937
+
938
+ // Copies a document without recursion, copying the replacements of the
939
+ // objects in the map instead of the objects. The replacements are copied in
940
+ // turn, so that objects nested in them are replaced as well:
941
+ function replaceInDocument(
942
+ document: object,
943
+ replacements: ReadonlyMap<object, object>,
944
+ ): unknown {
945
+ const root: unknown = globalThis.Array.isArray(document) ? [] : {};
946
+ const pending: [object, Record<string, unknown> | unknown[]][] = [
947
+ [replacements.get(document) ?? document, root as Record<string, unknown>],
948
+ ];
949
+ while (pending.length > 0) {
950
+ const [source, target] = pending.pop()!;
951
+ for (const [key, child] of globalThis.Object.entries(source)) {
952
+ let copy: unknown = child;
953
+ if (child != null && typeof child === "object") {
954
+ copy = globalThis.Array.isArray(child) ? [] : {};
955
+ pending.push([
956
+ replacements.get(child) ?? child,
957
+ copy as Record<string, unknown>,
958
+ ]);
959
+ }
960
+ if (globalThis.Array.isArray(target)) target.push(copy);
961
+ // An own __proto__ member, as JSON.parse() makes, would otherwise set
962
+ // the prototype of the copy instead:
963
+ else {
964
+ globalThis.Object.defineProperty(target, key, {
965
+ value: copy,
966
+ writable: true,
967
+ enumerable: true,
968
+ configurable: true,
969
+ });
970
+ }
971
+ }
972
+ }
973
+ return root;
974
+ }
975
+
976
+ // Tells whether two JSON values are the same, without recursion, as expanded
977
+ // documents can nest values deeply. The order of object keys does not
978
+ // matter, while the order of array elements does:
979
+ function isSameJsonValue(a: unknown, b: unknown): boolean {
980
+ const pending: [unknown, unknown][] = [[a, b]];
981
+ while (pending.length > 0) {
982
+ const [x, y] = pending.pop()!;
983
+ if (x === y) continue;
984
+ if (
985
+ x == null || y == null || typeof x !== "object" || typeof y !== "object"
986
+ ) {
987
+ return false;
988
+ }
989
+ if (globalThis.Array.isArray(x)) {
990
+ if (!globalThis.Array.isArray(y) || x.length !== y.length) return false;
991
+ for (let i = 0; i < x.length; i++) pending.push([x[i], y[i]]);
992
+ continue;
993
+ }
994
+ if (globalThis.Array.isArray(y)) return false;
995
+ const xKeys = globalThis.Object.keys(x);
996
+ if (xKeys.length !== globalThis.Object.keys(y).length) return false;
997
+ for (const key of xKeys) {
998
+ if (!globalThis.Object.hasOwn(y, key)) return false;
999
+ pending.push([
1000
+ (x as Record<string, unknown>)[key],
1001
+ (y as Record<string, unknown>)[key],
1002
+ ]);
1003
+ }
1004
+ }
1005
+ return true;
1006
+ }
1007
+
1008
+ // Expands a received document, and tells which expanded node each embedded
1009
+ // document with its own context became. Each such document gets a property
1010
+ // with a random IRI as its marker before the expansion, so that JSON-LD
1011
+ // processing itself, with every context as it applies, tells where each
1012
+ // document ends up; the markers are taken out of the expanded document right
1013
+ // after, and the decoders never see them. If a document cannot take the
1014
+ // marker, e.g., as it is a value object under an alias of @value, the document
1015
+ // is expanded as it is, and no embedded object gets its received document:
1016
+ async function expandReceivedJsonLd(
1017
+ json: unknown,
1018
+ contextLoader: DocumentLoader,
1019
+ ): Promise<{ expanded: unknown[]; documents?: ReceivedDocuments }> {
1020
+ // Both expansions below take the contexts that one of them loaded, so that
1021
+ // a context is not loaded twice, and cannot fail the second time:
1022
+ const loads = new Map<string, Promise<RemoteDocument>>();
1023
+ const sharedLoader: DocumentLoader = (url, loaderOptions) => {
1024
+ let load = loads.get(url);
1025
+ if (load == null) {
1026
+ load = contextLoader(url, loaderOptions);
1027
+ loads.set(url, load);
1028
+ load.catch(() => loads.delete(url));
1029
+ }
1030
+ return load;
1031
+ };
1032
+ const options = { documentLoader: sharedLoader, keepFreeFloatingNodes: true };
1033
+ // A document under an alias of @nest merges into the node around it, marker
1034
+ // and all, so that node would be taken for the document; any context that
1035
+ // mentions @nest, which few do, makes the document be expanded without
1036
+ // markers. Only contexts count, not, e.g., a content that reads @nest:
1037
+ const mentionsNest = (value: unknown): boolean => {
1038
+ // A loader can return a document as a JSON string, which jsonld.js parses;
1039
+ // one that cannot be parsed counts as a mention, so that no marker is
1040
+ // put in a document that this cannot tell about:
1041
+ if (typeof value === "string") {
1042
+ try {
1043
+ value = globalThis.JSON.parse(value);
1044
+ } catch {
1045
+ return true;
1046
+ }
1047
+ }
1048
+ // Without recursion, as a document can nest values deeply, e.g., under a
1049
+ // term that its context maps to nothing. An object met again on its own
1050
+ // path, i.e., a cycle, counts as a mention, so that no marker is put in it
1051
+ // and jsonld.js rejects the cycle as it would without markers; one shared
1052
+ // by several paths is scanned once:
1053
+ const pending: { item: unknown; exit?: object; context?: boolean }[] = [
1054
+ { item: value },
1055
+ ];
1056
+ const onPath = new WeakSet<object>();
1057
+ // An object can be reached both outside and inside a context, and only
1058
+ // a scan inside one tells whether it mentions @nest:
1059
+ const scannedInContext = new WeakSet<object>();
1060
+ const scannedOutside = new WeakSet<object>();
1061
+ while (pending.length > 0) {
1062
+ const { item, exit, context } = pending.pop()!;
1063
+ if (exit != null) {
1064
+ onPath.delete(exit);
1065
+ (context ? scannedInContext : scannedOutside).add(exit);
1066
+ continue;
1067
+ }
1068
+ if (context && item === "@nest") return true;
1069
+ if (
1070
+ item == null || typeof item !== "object" ||
1071
+ scannedInContext.has(item) || (!context && scannedOutside.has(item))
1072
+ ) {
1073
+ continue;
1074
+ }
1075
+ if (onPath.has(item)) return true;
1076
+ onPath.add(item);
1077
+ pending.push({ item: undefined, exit: item, context });
1078
+ if (globalThis.Array.isArray(item)) {
1079
+ for (const element of item) pending.push({ item: element, context });
1080
+ continue;
1081
+ }
1082
+ for (const [key, child] of globalThis.Object.entries(item)) {
1083
+ if (context && key === "@nest") return true;
1084
+ pending.push({ item: child, context: context || key === "@context" });
1085
+ }
1086
+ }
1087
+ return false;
1088
+ };
1089
+ const candidates = json != null && typeof json === "object" &&
1090
+ !mentionsNest(json)
1091
+ ? collectEmbeddedDocuments(json)
1092
+ : [];
1093
+ // The embedded objects get the documents as they are in one copy of the
1094
+ // whole document, rather than a copy each, which would copy a document as
1095
+ // many times as there are documents around it:
1096
+ const received = candidates.length > 0 ? copyJsonValue(json) : undefined;
1097
+ const documents = received == null ? [] : collectEmbeddedDocuments(received);
1098
+ if (documents.length < 1) {
1099
+ return {
1100
+ expanded: await jsonld.expand(json as Record<string, unknown>, options),
1101
+ };
1102
+ }
1103
+ // An IRI that a context cannot know, and that cannot be a compact IRI, as
1104
+ // its suffix after the scheme starts with //. Some runtimes do not make
1105
+ // random values everywhere, e.g., Cloudflare Workers outside handlers, in
1106
+ // which case the document is expanded without markers:
1107
+ let token: string;
1108
+ try {
1109
+ token = globalThis.crypto.randomUUID();
1110
+ } catch {
1111
+ return {
1112
+ expanded: await jsonld.expand(json as Record<string, unknown>, options),
1113
+ };
1114
+ }
1115
+ const marker = "https://fedify.dev/ns/received#" + token;
1116
+ const replacements = new Map<object, object>();
1117
+ for (const [index, document] of documents.entries()) {
1118
+ replacements.set(document, {
1119
+ ...document,
1120
+ [marker]: globalThis.String(index),
1121
+ });
1122
+ }
1123
+ // Only a document that cannot take its marker makes the document be
1124
+ // expanded again without markers; a context that fails to load fails the
1125
+ // decoding as it would without them:
1126
+ let loadFailed = false;
1127
+ let nestLoaded = false;
1128
+ const markedOptions = {
1129
+ ...options,
1130
+ documentLoader: (async (url, loaderOptions) => {
1131
+ try {
1132
+ const loaded = await sharedLoader(url, loaderOptions);
1133
+ if (mentionsNest(loaded.document)) nestLoaded = true;
1134
+ return loaded;
1135
+ } catch (error) {
1136
+ loadFailed = true;
1137
+ throw error;
1138
+ }
1139
+ }) as DocumentLoader,
1140
+ };
1141
+ let expanded: unknown[];
1142
+ try {
1143
+ expanded = await jsonld.expand(
1144
+ replaceInDocument(received as object, replacements) as Record<
1145
+ string,
1146
+ unknown
1147
+ >,
1148
+ markedOptions,
1149
+ );
1150
+ } catch (error) {
1151
+ if (loadFailed) throw error;
1152
+ getLogger(["fedify", "vocab"]).debug(
1153
+ "Failed to mark the embedded documents of {json}: {error}",
1154
+ { json, error },
1155
+ );
1156
+ return {
1157
+ expanded: await jsonld.expand(json as Record<string, unknown>, options),
1158
+ };
1159
+ }
1160
+ const nodes: ReceivedDocuments = new WeakMap();
1161
+ // Whether two documents became one node, as one under an alias of @nest
1162
+ // merged into the node around it, which leaves the expansion as it would be
1163
+ // without markers but would give that node the wrong document:
1164
+ let merged = false;
1165
+ // Takes the markers out, also from JSON literals, which keep the documents
1166
+ // in them as they are:
1167
+ const pending: { value: unknown; literal: boolean }[] = [
1168
+ { value: expanded, literal: false },
1169
+ ];
1170
+ while (pending.length > 0) {
1171
+ const { value, literal } = pending.pop()!;
1172
+ if (globalThis.Array.isArray(value)) {
1173
+ // A loop, as spreading a long array into arguments overflows the stack:
1174
+ for (const element of value) pending.push({ value: element, literal });
1175
+ continue;
1176
+ }
1177
+ if (value == null || typeof value !== "object") continue;
1178
+ const object = value as Record<string, unknown>;
1179
+ if (marker in object) {
1180
+ const mark = object[marker];
1181
+ const index = literal
1182
+ ? undefined
1183
+ : (globalThis.Array.isArray(mark)
1184
+ ? (mark[0] as { "@value"?: unknown } | undefined)?.["@value"]
1185
+ : undefined);
1186
+ delete object[marker];
1187
+ if (!literal && globalThis.Array.isArray(mark) && mark.length > 1) {
1188
+ merged = true;
1189
+ break;
1190
+ }
1191
+ if (typeof index === "string") {
1192
+ const document = documents[globalThis.Number(index)];
1193
+ if (document != null) nodes.set(object, document);
1194
+ }
1195
+ }
1196
+ if (!literal && object["@type"] === "@json") {
1197
+ pending.push({ value: object["@value"], literal: true });
1198
+ continue;
1199
+ }
1200
+ for (const [key, child] of globalThis.Object.entries(object)) {
1201
+ if (literal || key !== "@value") pending.push({ value: child, literal });
1202
+ }
1203
+ }
1204
+ // A marker can change what a document expands to in more ways than can be
1205
+ // told before expanding it, e.g., a key of an index map that reads @context
1206
+ // is no context, and a graph object with a marker is a node, so the
1207
+ // document is expanded without markers as well, and the markers' mapping is
1208
+ // used only if both expansions are the same:
1209
+ const unmarked = await jsonld.expand(
1210
+ json as Record<string, unknown>,
1211
+ options,
1212
+ );
1213
+ if (merged || nestLoaded || !isSameJsonValue(expanded, unmarked)) {
1214
+ return { expanded: unmarked };
1215
+ }
1216
+ return { expanded, documents: nodes };
1217
+ }
1218
+
1219
+ // Gives an embedded object the document it was received as, which toJsonLd()
1220
+ // has to return as is, as a proof can cover it. The object is decoded from the
1221
+ // whole document, since an embedded document alone cannot rebuild what its
1222
+ // parents' contexts contributed to it:
1223
+ function keepReceivedJsonLd(
1224
+ object: unknown,
1225
+ node: unknown,
1226
+ options: unknown,
1227
+ ): void {
1228
+ const documents = (options as { _receivedDocuments?: ReceivedDocuments })
1229
+ ._receivedDocuments;
1230
+ if (
1231
+ documents == null || node == null || typeof node !== "object" ||
1232
+ object == null || typeof object !== "object" ||
1233
+ !(RAW_PROPERTY_PROTOCOL in object) || receivedJsonLd.has(object) ||
1234
+ // Decoding dropped some of the document as malformed, which the document
1235
+ // would bring back:
1236
+ (object as unknown as { _shouldCacheJsonLd?: boolean })
1237
+ ._shouldCacheJsonLd === false
1238
+ ) {
1239
+ return;
1240
+ }
1241
+ // A graph object with nothing else is decoded from its first node, as
1242
+ // expansion would take that node out of it:
1243
+ const graph = (node as { "@graph"?: unknown })["@graph"];
1244
+ const decodedNode = globalThis.Object.keys(node).length === 1 &&
1245
+ globalThis.Array.isArray(graph) && graph[0] != null &&
1246
+ typeof graph[0] === "object"
1247
+ ? graph[0]
1248
+ : node;
1249
+ const document = documents.get(decodedNode);
1250
+ if (document == null) return;
1251
+ receivedJsonLd.add(object);
1252
+ (object as unknown as { _cachedJsonLd?: unknown })._cachedJsonLd = document;
1253
+ embeddedReceivedJsonLd.add(document);
1254
+ }
1255
+
1256
+ // The documents that embedded objects were received as, which they keep as
1257
+ // their cached JSON-LD. Such a document can rely on what the documents around
1258
+ // it define, e.g., terms of their contexts and their base IRIs, so a parent
1259
+ // that encodes its values anew encodes such an object from its values instead;
1260
+ // the object's own toJsonLd() still returns the document as is, as a proof can
1261
+ // cover it. The documents rather than the objects are kept, as a cache can be
1262
+ // copied to another object, e.g., by @fedify/testing:
1263
+ const embeddedReceivedJsonLd = new WeakSet<object>();
1264
+
1265
+ async function readRawProperty(
1266
+ object: object,
1267
+ request: RawPropertyRequest,
1268
+ contextLoader: DocumentLoader,
1269
+ ): Promise<readonly unknown[]> {
1270
+ const retained = retainedRawProperties.get(object);
1271
+ for (const iri of request.candidates) {
1272
+ const descriptor = getRawPropertyDescriptor(object, iri);
1273
+ if (descriptor != null) {
1274
+ const value = await descriptor.encode(
1275
+ object,
1276
+ createRawPropertyEncodingOptions(request.stack, contextLoader),
1277
+ );
1278
+ return value === undefined ? [] : await expandRawPropertyValue(
1279
+ descriptor.canonicalIri,
1280
+ value,
1281
+ contextLoader,
1282
+ );
1283
+ }
1284
+ if (retained != null && globalThis.Object.hasOwn(retained, iri)) {
1285
+ return retained[iri];
1286
+ }
1287
+ }
1288
+ return [];
1289
+ }
1290
+
1291
+ /**
1292
+ * Gets the values of a property of a vocabulary object in expanded JSON-LD,
1293
+ * looking the property up by its full IRI. This works for properties that
1294
+ * have no typed accessor as well as for those that do.
1295
+ *
1296
+ * *Raw* means untyped expanded JSON-LD values, such as
1297
+ * \`{ "@value": "Hello" }\` or \`{ "@id": "https://example.com/" }\`, as
1298
+ * opposed to the values that typed accessors return. It does not mean the
1299
+ * received document:
1300
+ *
1301
+ * - For a property that the object's class has no accessor for, the result
1302
+ * is the values retained when the object was decoded by \`fromJsonLd()\`.
1303
+ * Objects constructed locally have none.
1304
+ * - For a property that the class has an accessor for, including a
1305
+ * redundant alias of such a property, the result is the current typed
1306
+ * values encoded back into expanded JSON-LD. It reflects \`clone()\`
1307
+ * replacements and objects fetched by dereferencing accessors, and it can
1308
+ * differ from the received values: for example, values that failed to
1309
+ * decode are missing, and lexical forms such as date-times are
1310
+ * normalized. When a later release adds an accessor for a property,
1311
+ * the result for that property switches from the retained values to the
1312
+ * encoded ones.
1313
+ *
1314
+ * The values are not verified in any way, and IRIs in them are never
1315
+ * dereferenced. Validate them before use, as with any other data received
1316
+ * from a remote server. The result is a deep copy, so modifying it does not
1317
+ * affect the object.
1318
+ *
1319
+ * The IRI is matched as given, and then as normalized by the WHATWG URL
1320
+ * parser. Prefixes are never expanded: \`"as:content"\` is a valid IRI with
1321
+ * the \`as:\` scheme, so it normally matches nothing. An IRI whose scheme is
1322
+ * not \`http:\` or \`https:\` is therefore logged as a warning under the
1323
+ * \`["fedify", "vocab"]\` category.
1324
+ *
1325
+ * \`\`\`typescript ignore
1326
+ * const values = await getRawPropertyValues(
1327
+ * note,
1328
+ * "https://w3id.org/quantpub#structuredUrl",
1329
+ * );
1330
+ * for (const value of values) {
1331
+ * if ("@id" in value && typeof value["@id"] === "string") {
1332
+ * console.log(new URL(value["@id"]));
1333
+ * }
1334
+ * }
1335
+ * \`\`\`
1336
+ *
1337
+ * @param object The vocabulary object to read. It can be an object of any
1338
+ * module generated by \`@fedify/vocab-tools\`.
1339
+ * @param propertyIri The full IRI of the property.
1340
+ * @returns The values of the property, or an empty array if it has none.
1341
+ * @throws {TypeError} If \`propertyIri\` is not an absolute IRI, e.g., an
1342
+ * empty string, a JSON-LD keyword such as \`"@id"\`, a
1343
+ * blank node identifier, a term, or a relative
1344
+ * reference; if \`object\` is not a generated vocabulary
1345
+ * object; or if encoding the values of a known property
1346
+ * meets a cycle of objects.
1347
+ * @since 2.5.0
1348
+ */
1349
+ export function getRawPropertyValues(
1350
+ object: VocabularyObject,
1351
+ propertyIri: string | URL,
1352
+ ): Promise<RawPropertyValue[]> {
1353
+ return readRawPropertyValues(object, propertyIri, "getRawPropertyValues");
1354
+ }
1355
+
1356
+ /**
1357
+ * Gets the first value of a property of a vocabulary object in expanded
1358
+ * JSON-LD, looking the property up by its full IRI. It is equivalent to
1359
+ * \`(await getRawPropertyValues(object, propertyIri))[0] ?? null\`; see
1360
+ * {@link getRawPropertyValues} for how the values are obtained.
1361
+ *
1362
+ * It does not throw when the property has multiple values. JSON-LD does not
1363
+ * order the values of a property unless it is a list, so the first value is
1364
+ * not more significant than the others. A list property has a single value,
1365
+ * the \`{ "@list": [...] }\` object.
1366
+ *
1367
+ * @param object The vocabulary object to read. It can be an object of any
1368
+ * module generated by \`@fedify/vocab-tools\`.
1369
+ * @param propertyIri The full IRI of the property.
1370
+ * @returns The first value of the property, or \`null\` if it has none.
1371
+ * @throws {TypeError} In the same cases as {@link getRawPropertyValues}.
1372
+ * @since 2.5.0
1373
+ */
1374
+ export async function getRawPropertyValue(
1375
+ object: VocabularyObject,
1376
+ propertyIri: string | URL,
1377
+ ): Promise<RawPropertyValue | null> {
1378
+ const values = await readRawPropertyValues(
1379
+ object,
1380
+ propertyIri,
1381
+ "getRawPropertyValue",
1382
+ );
1383
+ return values[0] ?? null;
1384
+ }
1385
+ `;
1386
+ }
1387
+ /**
1388
+ * Collects the full IRIs of the properties that the given class decodes,
1389
+ * including inherited properties and redundant aliases.
1390
+ */
1391
+ function getKnownPropertyIris(typeUri, types) {
1392
+ const iris = /* @__PURE__ */ new Set();
1393
+ for (const property of getAllProperties(typeUri, types)) {
1394
+ iris.add(property.uri);
1395
+ if (property.redundantProperties != null) for (const alias of property.redundantProperties) iris.add(alias.uri);
1396
+ }
1397
+ return [...iris].sort();
1398
+ }
1399
+ /**
1400
+ * Emits a static block that registers the encoders of the properties the
1401
+ * given class declares, keeping them and their private-field access out of
1402
+ * the declaration files. A root class also installs the method through which
1403
+ * the raw property functions reach these encoders and the retained unknown
1404
+ * properties.
1405
+ */
1406
+ async function* generateRawPropertyDescriptors(typeUri, types) {
1407
+ const type = types[typeUri];
1408
+ if (type.extends != null && type.properties.length < 1) return;
1409
+ yield "static {\n";
1410
+ if (type.extends == null) yield `
1411
+ globalThis.Object.defineProperty(this.prototype, RAW_PROPERTY_PROTOCOL, {
1412
+ value: function (
1413
+ this: ${type.name},
1414
+ request: RawPropertyRequest,
1415
+ ): Promise<readonly unknown[]> {
1416
+ return readRawProperty(
1417
+ this,
1418
+ request,
1419
+ this.#contextLoader ?? getDocumentLoader(),
1420
+ );
1421
+ },
1422
+ configurable: true,
1423
+ enumerable: false,
1424
+ writable: true,
1425
+ });
1426
+ `;
1427
+ if (type.properties.length > 0) yield `
1428
+ const descriptors = new Map<string, RawPropertyDescriptor>();
1429
+ let descriptor: RawPropertyDescriptor;
1430
+ `;
1431
+ for (const property of type.properties) {
1432
+ let element = "";
1433
+ for (const code of generateExpandedPropertyElement(property, types)) element += code;
1434
+ yield `
1435
+ descriptor = {
1436
+ canonicalIri: ${JSON.stringify(property.uri)},
1437
+ ${element.includes("await") ? "" : "// oxlint-disable-next-line require-await"}
1438
+ async encode(
1439
+ object: object,
1440
+ options: { format: "expand"; contextLoader?: DocumentLoader },
1441
+ ): Promise<unknown> {
1442
+ const array: unknown[] = [];
1443
+ for (const v of (object as ${type.name}).${await getFieldName(property.uri)}) {
1444
+ `;
1445
+ yield element;
1446
+ yield `
1447
+ }
1448
+ if (array.length < 1) return undefined;
1449
+ return ${isNonFunctionalProperty(property) && property.container === "list" ? `{ "@list": array }` : "array"};
1450
+ },
1451
+ };
1452
+ descriptors.set(${JSON.stringify(property.uri)}, descriptor);
1453
+ `;
1454
+ for (const alias of property.redundantProperties ?? []) yield `descriptors.set(${JSON.stringify(alias.uri)}, descriptor);\n`;
1455
+ }
1456
+ if (type.properties.length > 0) yield "rawPropertyDescriptors.set(this.prototype, descriptors);\n";
1457
+ yield "}\n";
1458
+ }
1459
+ //#endregion
748
1460
  //#region src/codec.ts
749
1461
  function* generatePreprocessorBlock(property, rangeTypeName, variable, baseUrlExpr, moduleVarNames) {
750
1462
  if (property.preprocessors == null || property.preprocessors.length === 0) return;
@@ -767,12 +1479,15 @@ function* generatePreprocessorBlock(property, rangeTypeName, variable, baseUrlEx
767
1479
  if (_result instanceof Error) throw _result;
768
1480
  if (_result !== undefined) {
769
1481
  _handled = _result as ${rangeTypeName};
1482
+ retainPreprocessedRawProperties(_handled, v);
770
1483
  }
771
1484
  }
772
1485
  `;
773
1486
  }
774
1487
  yield `
775
1488
  if (_handled !== undefined) {
1489
+ // The document does not describe what a preprocessor made of it:
1490
+ skipReceivedJsonLd(_handled);
776
1491
  ${variable}.push(_handled);
777
1492
  continue;
778
1493
  }
@@ -797,7 +1512,17 @@ async function* generateEncoder(typeUri, types) {
797
1512
  contextLoader?: DocumentLoader,
798
1513
  context?: string | Record<string, string> | (string | Record<string, string>)[],
799
1514
  } = {}): Promise<unknown> {
800
- if (options.format == null && this._cachedJsonLd != null) {
1515
+ if (
1516
+ options.format == null &&
1517
+ this._cachedJsonLd != null &&
1518
+ // A parent encoding its values anew does not embed the document this
1519
+ // object was received in, which can rely on what was around it there:
1520
+ !(
1521
+ "_embedding" in options &&
1522
+ options._embedding &&
1523
+ embeddedReceivedJsonLd.has(this._cachedJsonLd)
1524
+ )
1525
+ ) {
801
1526
  return this._cachedJsonLd;
802
1527
  }
803
1528
  if (options.format !== "compact" && options.context != null) {
@@ -910,24 +1635,8 @@ async function* generateEncoder(typeUri, types) {
910
1635
  yield `
911
1636
  array = [];
912
1637
  for (const v of this.${await getFieldName(property.uri)}) {
913
- let element = (
914
- `;
915
- if (!areAllScalarTypes(property.range, types)) {
916
- yield "retainedSignedValueRef(v, signedValues.scope) ?? (";
917
- yield "v instanceof URL ? { \"@id\": formatIri(v) } : ";
918
- }
919
- for (const code of getEncoders(property.range, types, "v", "options")) yield code;
920
- if (!areAllScalarTypes(property.range, types)) yield ")";
921
- yield `
922
- );
923
- if (Array.isArray(element)) {
924
- if (element.length < 1) continue;
925
- if (element.length == 1) element = element[0];
926
- }
927
- if (typeof element === "undefined") continue;
928
1638
  `;
929
- if (isNonFunctionalProperty(property) && property.container === "graph") yield `array.push({ "@graph": element });`;
930
- else yield `array.push(element);`;
1639
+ yield* generateExpandedPropertyElement(property, types, "signedValues.scope");
931
1640
  yield `;
932
1641
  }
933
1642
  if (array.length > 0) {
@@ -1039,6 +1748,8 @@ async function* generateEncoder(typeUri, types) {
1039
1748
  async function* generateDecoder(typeUri, types, moduleVarNames) {
1040
1749
  const type = types[typeUri];
1041
1750
  yield `
1751
+ static readonly #knownRawPropertyIris: ReadonlySet<string> = new Set(${JSON.stringify(getKnownPropertyIris(typeUri, types))});
1752
+
1042
1753
  /**
1043
1754
  * Converts a JSON-LD structure to an object of this type.
1044
1755
  * @param json The JSON-LD structure to convert.
@@ -1117,6 +1828,27 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
1117
1828
  let values: Record<string, any[]> & { "@id"?: string };
1118
1829
  let expanded: unknown[];
1119
1830
  if (
1831
+ "_expanded" in options &&
1832
+ options._expanded &&
1833
+ typeof json === "object" &&
1834
+ !Array.isArray(json)
1835
+ ) {
1836
+ // An embedded value, which its parent has expanded already; expanding
1837
+ // it again would make other nodes than the ones the received documents
1838
+ // are known by. This comes before _fromSubclass, which an embedded
1839
+ // value inherits from a superclass decoding its parent:
1840
+ // Expansion takes the first node out of a graph object that has nothing
1841
+ // else, which an expanded value can still be:
1842
+ const graph = globalThis.Object.keys(json).length === 1 &&
1843
+ Array.isArray((json as { "@graph"?: unknown })["@graph"])
1844
+ ? (json as { "@graph": unknown[] })["@graph"]
1845
+ : undefined;
1846
+ values =
1847
+ // deno-lint-ignore no-explicit-any
1848
+ (graph == null ? json : graph[0] ?? {}) as
1849
+ (Record<string, any[]> & { "@id"?: string });
1850
+ expanded = [values];
1851
+ } else if (
1120
1852
  "_fromSubclass" in options &&
1121
1853
  options._fromSubclass &&
1122
1854
  typeof json === "object" &&
@@ -1130,10 +1862,15 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
1130
1862
  values = {};
1131
1863
  expanded = [values];
1132
1864
  } else {
1133
- expanded = await jsonld.expand(json, {
1134
- documentLoader: options.contextLoader,
1135
- keepFreeFloatingNodes: true,
1136
- });
1865
+ const received = await expandReceivedJsonLd(
1866
+ json,
1867
+ options.contextLoader ?? getDocumentLoader(),
1868
+ );
1869
+ expanded = received.expanded;
1870
+ if (received.documents != null) {
1871
+ options = { ...options, _receivedDocuments: received.documents } as
1872
+ typeof options;
1873
+ }
1137
1874
  values =
1138
1875
  // deno-lint-ignore no-explicit-any
1139
1876
  (expanded[0] ?? {}) as (Record<string, any[]> & { "@id"?: string });
@@ -1183,12 +1920,19 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
1183
1920
  );
1184
1921
  `;
1185
1922
  else yield `
1186
- const superValues = structuredClone(values);
1923
+ // A shallow copy, as the received documents of embedded objects are known
1924
+ // by the expanded nodes they became:
1925
+ const superValues = { ...values };
1187
1926
  delete superValues["@type"];
1188
1927
  const instance = await super.fromJsonLd(superValues, {
1189
1928
  ...options,
1190
1929
  // @ts-ignore: an internal option
1191
1930
  _fromSubclass: true,
1931
+ // The values are the subclass's, not an embedded value:
1932
+ _expanded: false,
1933
+ // The subclass retains the unknown properties, since only it knows all
1934
+ // properties of the object:
1935
+ _retainsRawProperties: false,
1192
1936
  });
1193
1937
  if (!(instance instanceof ${type.name})) {
1194
1938
  throw new TypeError("Unexpected type: " + instance.constructor.name);
@@ -1264,6 +2008,7 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
1264
2008
  if (!this._shouldCacheDecodedJsonLd(decoded)) {
1265
2009
  shouldCacheJsonLd = false;
1266
2010
  }
2011
+ keepReceivedJsonLd(decoded, v, options);
1267
2012
  ${variable}.push(decoded);
1268
2013
  `;
1269
2014
  yield `
@@ -1272,6 +2017,16 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
1272
2017
  `;
1273
2018
  }
1274
2019
  yield `
2020
+ if (
2021
+ !("_retainsRawProperties" in options) ||
2022
+ options._retainsRawProperties !== false
2023
+ ) {
2024
+ const retained = retainRawProperties(
2025
+ values,
2026
+ ${type.name}.#knownRawPropertyIris,
2027
+ );
2028
+ if (retained != null) retainedRawProperties.set(instance, retained);
2029
+ }
1275
2030
  instance._shouldCacheJsonLd = shouldCacheJsonLd;
1276
2031
  if (
1277
2032
  shouldCacheJsonLd &&
@@ -1485,6 +2240,10 @@ async function* generateCloner(typeUri, types) {
1485
2240
  * See the [vocabulary manual](https://fedify.dev/manual/vocab#immutability)
1486
2241
  * for details, including how cached JSON-LD affects serialization.
1487
2242
  *
2243
+ * Unknown properties retained when this instance was decoded are shared
2244
+ * with the clone, so \`getRawPropertyValues()\` returns them for the clone
2245
+ * as well, even if the clone replaces other values.
2246
+ *
1488
2247
  * A clone never inherits a signed JSON-LD representation retained by
1489
2248
  * \`signObject()\`: the clone may differ from the document that the proof
1490
2249
  * covers, so embedding the original secured JSON in a parent document
@@ -1524,6 +2283,7 @@ async function* generateCloner(typeUri, types) {
1524
2283
  options
1525
2284
  );
1526
2285
  copyPortableProvenance(this, clone);
2286
+ copyRawProperties(this, clone);
1527
2287
  `;
1528
2288
  else yield `const clone = super.clone(values, options) as unknown as ${type.name};`;
1529
2289
  for (const property of type.properties) {
@@ -1622,9 +2382,10 @@ async function* generateDeepCloner(typeUri, types) {
1622
2382
  * Each copied object retains its own default loaders, tracer, verifier
1623
2383
  * and base URL. Options override defaults only on the root instance.
1624
2384
  * This method does not fetch or serialize objects. Cached JSON-LD and
1625
- * retained signed representations are not copied; unknown JSON-LD
1626
- * properties and original formatting are not preserved. Sign the copy
1627
- * again if it needs a valid proof.
2385
+ * retained signed representations are not copied, and original formatting
2386
+ * is not preserved. Unknown properties retained when an object was decoded
2387
+ * are shared with its copy, so \`getRawPropertyValues()\` returns them for
2388
+ * the copy as well. Sign the copy again if it needs a valid proof.
1628
2389
  *
1629
2390
  * Trust and portable provenance follow clone() rules at every level.
1630
2391
  * Historical referrers within the graph are copied without replacements;
@@ -1934,13 +2695,6 @@ async function* generateProperty(type, property, types, moduleVarNames) {
1934
2695
  const override = emitOverride(type.uri, types, property);
1935
2696
  const trustOwner = type.trustEmbeddedObjects === false ? "null" : "this.id";
1936
2697
  const doc = `\n/** ${property.description.replaceAll("\n", "\n * ")}\n */\n`;
1937
- const cachedPropertyBaseUrl = `(options as { baseUrl?: URL }).baseUrl ??
1938
- this._baseUrl ??
1939
- (this.id != null &&
1940
- (this.id.protocol === "http:" ||
1941
- this.id.protocol === "https:")
1942
- ? this.id
1943
- : undefined)`;
1944
2698
  if (areAllScalarTypes(property.range, types)) {
1945
2699
  if (hasSingularAccessor(property)) {
1946
2700
  yield doc;
@@ -2229,7 +2983,10 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2229
2983
  baseUrl,
2230
2984
  });
2231
2985
  if (_result instanceof Error) throw _result;
2232
- if (_result !== undefined) return _result as ${getTypeNames(property.range, types)};
2986
+ if (_result !== undefined) {
2987
+ retainPreprocessedRawProperties(_result, _pp_obj);
2988
+ return _result as ${getTypeNames(property.range, types)};
2989
+ }
2233
2990
  }
2234
2991
  `;
2235
2992
  }
@@ -2293,6 +3050,13 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2293
3050
  tracerProvider?: TracerProvider,
2294
3051
  crossOrigin?: "ignore" | "throw" | "trust";
2295
3052
  gateways?: readonly (string | URL)[];
3053
+ /**
3054
+ * Whether to fetch referenced objects. Defaults to \`true\`.
3055
+ * If \`false\`, returns only embedded or cached objects accepted
3056
+ * by existing trust checks, or \`null\` when fetching is required.
3057
+ * @since 2.5.0
3058
+ */
3059
+ dereference?: boolean;
2296
3060
  verifyPortableObject?: PortableObjectVerifier;
2297
3061
  /**
2298
3062
  * Whether objects that this call newly fetches use the
@@ -2343,6 +3107,7 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2343
3107
  }
2344
3108
  }
2345
3109
  if (v instanceof URL) {
3110
+ if (options.dereference === false) return null;
2346
3111
  const fetched =
2347
3112
  await this.#fetch${(0, es_toolkit.pascalCase)(property.singularName)}(v, options);
2348
3113
  if (fetched == null) return null;
@@ -2351,40 +3116,11 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2351
3116
  if (isUnverifiedPortableClaim(fetched)) return fetched;
2352
3117
  this.${await getFieldName(property.uri)}[0] = fetched;
2353
3118
  this.${await getFieldName(property.uri, "#_trust")}.add(0);
2354
- this._cachedJsonLd = undefined;
3119
+ invalidateCachedJsonLd(this);
2355
3120
  recordPortableReferrer(this, fetched, ${JSON.stringify(property.uri)});
2356
3121
  return fetched;
2357
3122
  }
2358
3123
  `;
2359
- if (property.compactName != null) yield `
2360
- if (
2361
- this._cachedJsonLd != null &&
2362
- typeof this._cachedJsonLd === "object" &&
2363
- "@context" in this._cachedJsonLd &&
2364
- ${JSON.stringify(property.compactName)} in this._cachedJsonLd
2365
- ) {
2366
- const prop = this._cachedJsonLd[
2367
- ${JSON.stringify(property.compactName)}];
2368
- const doc = Array.isArray(prop) ? prop[0] : prop;
2369
- if (doc != null && typeof doc === "object" && "@context" in doc) {
2370
- try {
2371
- v = await this.#${property.singularName}_fromJsonLd(doc, {
2372
- ...options,
2373
- // Keep the parent default for embedded objects.
2374
- verifyPortableObject: this._verifyPortableObject,
2375
- baseUrl: ${cachedPropertyBaseUrl},
2376
- });
2377
- } catch (error) {
2378
- if (!options.suppressError) throw error;
2379
- getLogger(["fedify", "vocab"]).debug(
2380
- "Failed to parse embedded value of {property}: {error}",
2381
- { property: ${JSON.stringify(property.uri)}, error },
2382
- );
2383
- return null;
2384
- }
2385
- }
2386
- }
2387
- `;
2388
3124
  yield `
2389
3125
  if (v?.id != null &&
2390
3126
  ((${type.trustEmbeddedObjects === false ? "" : "this.id != null && "}!isTrustedIriOrigin(options, v.id, ${trustOwner})) ||
@@ -2447,6 +3183,13 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2447
3183
  tracerProvider?: TracerProvider,
2448
3184
  crossOrigin?: "ignore" | "throw" | "trust";
2449
3185
  gateways?: readonly (string | URL)[];
3186
+ /**
3187
+ * Whether to fetch referenced objects. Defaults to \`true\`.
3188
+ * If \`false\`, yields only embedded or cached objects accepted
3189
+ * by existing trust checks, skipping values that require fetching.
3190
+ * @since 2.5.0
3191
+ */
3192
+ dereference?: boolean;
2450
3193
  verifyPortableObject?: PortableObjectVerifier;
2451
3194
  /**
2452
3195
  * Whether objects that this call newly fetches use the
@@ -2498,6 +3241,7 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2498
3241
  }
2499
3242
  }
2500
3243
  if (v instanceof URL) {
3244
+ if (options.dereference === false) continue;
2501
3245
  const fetched =
2502
3246
  await this.#fetch${(0, es_toolkit.pascalCase)(property.singularName)}(v, options);
2503
3247
  if (fetched == null) continue;
@@ -2509,41 +3253,12 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2509
3253
  }
2510
3254
  vs[i] = fetched;
2511
3255
  this.${await getFieldName(property.uri, "#_trust")}.add(i);
2512
- this._cachedJsonLd = undefined;
3256
+ invalidateCachedJsonLd(this);
2513
3257
  recordPortableReferrer(this, fetched, ${JSON.stringify(property.uri)});
2514
3258
  yield fetched;
2515
3259
  continue;
2516
3260
  }
2517
3261
  `;
2518
- if (property.compactName != null) yield `
2519
- if (
2520
- this._cachedJsonLd != null &&
2521
- typeof this._cachedJsonLd === "object" &&
2522
- "@context" in this._cachedJsonLd &&
2523
- ${JSON.stringify(property.compactName)} in this._cachedJsonLd
2524
- ) {
2525
- const prop = this._cachedJsonLd[
2526
- ${JSON.stringify(property.compactName)}];
2527
- const obj = Array.isArray(prop) ? prop[i] : prop;
2528
- if (obj != null && typeof obj === "object" && "@context" in obj) {
2529
- try {
2530
- v = await this.#${property.singularName}_fromJsonLd(obj, {
2531
- ...options,
2532
- // Keep the parent default for embedded objects.
2533
- verifyPortableObject: this._verifyPortableObject,
2534
- baseUrl: ${cachedPropertyBaseUrl},
2535
- });
2536
- } catch (error) {
2537
- if (!options.suppressError) throw error;
2538
- getLogger(["fedify", "vocab"]).debug(
2539
- "Failed to parse embedded value of {property} at index {index}: {error}",
2540
- { property: ${JSON.stringify(property.uri)}, index: i, error },
2541
- );
2542
- continue;
2543
- }
2544
- }
2545
- }
2546
- `;
2547
3262
  yield `
2548
3263
  if (v?.id != null &&
2549
3264
  ((${type.trustEmbeddedObjects === false ? "" : "this.id != null && "}!isTrustedIriOrigin(options, v.id, ${trustOwner})) ||
@@ -2816,6 +3531,17 @@ const PORTABLE_DEREFERENCE_IMPORTS = [
2816
3531
  "rejectMalformedCompatibleReference",
2817
3532
  "warnUnverifiableEmbeddedObject"
2818
3533
  ].join(",\n ");
3534
+ const RAW_PROPERTY_IMPORTS = [
3535
+ "copyJsonValue",
3536
+ "createRawPropertyEncodingOptions",
3537
+ "encodeNestedVocabularyValue",
3538
+ "expandRawPropertyValue",
3539
+ "RAW_PROPERTY_PROTOCOL",
3540
+ "type RawPropertyRequest",
3541
+ "readRawPropertyValues",
3542
+ "retainRawProperties",
3543
+ "type RetainedRawProperties"
3544
+ ].join(",\n ");
2819
3545
  const SIGNED_REPRESENTATION_IMPORTS = [
2820
3546
  "enterSignedValueScope",
2821
3547
  "resolveSignedValues",
@@ -2842,7 +3568,9 @@ const RUNTIME_IMPORTS = [
2842
3568
  "parseIri",
2843
3569
  "parseJsonLdId",
2844
3570
  "type PortableObjectVerifier",
2845
- "type RemoteDocument"
3571
+ "type RawPropertyValue",
3572
+ "type RemoteDocument",
3573
+ "type VocabularyObject"
2846
3574
  ].join(",\n ");
2847
3575
  /**
2848
3576
  * Sorts the given types topologically so that the base types come before the
@@ -2872,7 +3600,7 @@ async function* generateClass(typeUri, types, moduleVarNames) {
2872
3600
  if (type.extends) {
2873
3601
  const baseType = types[type.extends];
2874
3602
  yield `export class ${type.name} extends ${baseType.name} {\n`;
2875
- } else yield `export class ${type.name} {\n`;
3603
+ } else yield `export class ${type.name} implements VocabularyObject {\n`;
2876
3604
  if (type.extends == null) yield `
2877
3605
  readonly #documentLoader?: DocumentLoader;
2878
3606
  readonly #contextLoader?: DocumentLoader;
@@ -2888,6 +3616,14 @@ async function* generateClass(typeUri, types, moduleVarNames) {
2888
3616
  #shouldCacheJsonLd = true;
2889
3617
  readonly id: URL | null;
2890
3618
 
3619
+ /**
3620
+ * Marks this object as a {@link VocabularyObject}. It is always \`true\`.
3621
+ * @since 2.5.0
3622
+ */
3623
+ get "~fedify.vocab"(): true {
3624
+ return true;
3625
+ }
3626
+
2891
3627
  protected get _documentLoader(): DocumentLoader | undefined {
2892
3628
  return this.#documentLoader;
2893
3629
  }
@@ -2956,6 +3692,7 @@ async function* generateClass(typeUri, types, moduleVarNames) {
2956
3692
  for await (const code of generateCloner(typeUri, types)) yield code;
2957
3693
  for await (const code of generateDeepCloner(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
2958
3694
  for await (const code of generateDeepCloneDescriptor(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
3695
+ for await (const code of generateRawPropertyDescriptors(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
2959
3696
  for await (const code of generateProperties(typeUri, types, moduleVarNames)) yield code;
2960
3697
  for await (const code of generateEncoder(typeUri, types)) yield code;
2961
3698
  for await (const code of generateDecoder(typeUri, types, moduleVarNames)) yield code;
@@ -3032,6 +3769,7 @@ async function* generateClasses(types) {
3032
3769
  yield `import {\n ${RUNTIME_IMPORTS}\n} from "@fedify/vocab-runtime";\n`;
3033
3770
  yield `import {\n ${INTERNAL_RUNTIME_IMPORTS}\n} from "@fedify/vocab-runtime/internal/jsonld-cache";\n`;
3034
3771
  yield `import {\n ${PORTABLE_DEREFERENCE_IMPORTS}\n} from "@fedify/vocab-runtime/internal/portable-dereference";\n`;
3772
+ yield `import {\n ${RAW_PROPERTY_IMPORTS}\n} from "@fedify/vocab-runtime/internal/raw-property";\n`;
3035
3773
  yield `import {\n ${SIGNED_REPRESENTATION_IMPORTS}\n} from "@fedify/vocab-runtime/internal/signed-representation";\n`;
3036
3774
  yield `import {
3037
3775
  isTemporalDuration,
@@ -3056,6 +3794,7 @@ function inspectIri(iri: URL): string {
3056
3794
  `;
3057
3795
  yield generatePropertyArrayHelpers();
3058
3796
  yield generateDeepCloneHelpers();
3797
+ yield generateRawPropertyHelpers();
3059
3798
  yield `
3060
3799
  function isValidLanguageTag(language: string): boolean {
3061
3800
  try {