@drfed/models 0.2.0-dev.685 → 0.2.0-dev.703

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/README.md CHANGED
@@ -11,14 +11,15 @@ Document validation
11
11
  -------------------
12
12
 
13
13
  `@drfed/models/document` exports synchronous
14
- `validateDocument(document: unknown)` and `prepareDocument(document, options)`,
15
- plus the `diagnosticReasons` registry. Public types are
16
- `DocumentValidationResult`, `Diagnostic`, `DiagnosticReason`,
17
- `DiagnosticCategory`, `DiagnosticSeverity`, `FieldPath`, `JsonValue`,
18
- `NormalizationChange`, `DocumentAuthority`, `ServerOwnedField`, and
19
- `DocumentPreparationOptions`. Pass parsed JSON, not JSON text. Validation
20
- performs no network access, database writes, permission checks, or delivery,
21
- and never mutates input.
14
+ `validateDocument(document: unknown)`, `prepareDocument(document, options)`,
15
+ and `describeDocument(document: unknown)`, plus the `diagnosticReasons`
16
+ registry. Public types are `DocumentValidationResult`, `Diagnostic`,
17
+ `DiagnosticReason`, `DiagnosticCategory`, `DiagnosticSeverity`, `FieldPath`,
18
+ `JsonValue`, `NormalizationChange`, `DocumentAuthority`, `ServerOwnedField`,
19
+ `DocumentPreparationOptions`, `DocumentNode`, `DocumentNodeKind`, and
20
+ `DocumentIdentifier`. Pass
21
+ parsed JSON, not JSON text. Validation performs no network access, database
22
+ writes, permission checks, or delivery, and never mutates input.
22
23
 
23
24
  ### Consumer contract
24
25
 
@@ -53,12 +54,12 @@ Vocabulary errors describe malformed supported input. Support errors describe
53
54
  unimplemented types, properties, or representations and make `complete` false.
54
55
  Compatibility warnings do not automatically reject the document. An omitted
55
56
  context uses the standard ActivityStreams context with a warning. The exported
56
- authority category is used by prepareDocument for caller-reported denials and
57
- server-owned-field conflicts. validateDocument itself emits no authority
58
- findings.
57
+ authority category is used by `prepareDocument()` for caller-reported denials
58
+ and server-owned-field conflicts. `validateDocument()` itself emits no
59
+ authority findings.
59
60
 
60
61
  Document-only normalization proposes omission of empty arrays on supported,
61
- applicable properties. For example, a Note with `to: []` receives the
62
+ applicable properties. For example, a `Note` with `to: []` receives the
62
63
  `empty_property_list` warning and a removal change with reason
63
64
  `omit_empty_property_list`; its preview omits `to`. Present changes for an
64
65
  explicit caller decision. Validation does not apply them or save the preview.
@@ -70,6 +71,40 @@ document is preserved. Arrays containing any non-null identifier remain errors.
70
71
  It does not assign IDs or timestamps, replace actor/attribution identities,
71
72
  deduplicate recipients, or convert references to embedded values.
72
73
 
74
+ ### Describing documents for write paths
75
+
76
+ `describeDocument(document)` returns the documents the checker reads, as
77
+ `DocumentNode` values, or null unless validation completes without errors. Each
78
+ node has its original path, the standard name of the property embedding it,
79
+ its type IRI, a `kind` (`activity`, `actor`, `collection`, `link`, or
80
+ `object`), and a map from standard property names, including `id` and `type`,
81
+ to the source keys that supply them. Aliases, prefixed or full-IRI keys, and
82
+ `@id`/`@type` aliases are mapped exactly as validation maps them; custom
83
+ extension values are neither listed nor descended into. Each node also lists
84
+ the string IRI references in its own reference properties (`id`, `actor`,
85
+ `object`, addressing, `href`, and so on) as `DocumentIdentifier` values, with
86
+ the original path and value and the IRI after compact-IRI prefix expansion:
87
+ `as:Public` resolves to the full Public IRI, and a context-defined prefix can
88
+ make `local:alice` name another host.
89
+
90
+ ~~~~ ts
91
+ import { describeDocument } from "@drfed/models/document";
92
+
93
+ const nodes = describeDocument({
94
+ "@context": [
95
+ "https://www.w3.org/ns/activitystreams",
96
+ { by: { "@id": "as:actor", "@type": "@id" } },
97
+ ],
98
+ type: "Like",
99
+ by: "https://example.com/alice",
100
+ object: "https://example.com/posts/1",
101
+ });
102
+ // nodes?.[0].properties.get("actor") → ["by"]
103
+ ~~~~
104
+
105
+ Write paths use it to find identity claims, addressing, and relations by their
106
+ meaning instead of their spelling.
107
+
73
108
  ### Preparing server-owned creation fields
74
109
 
75
110
  `prepareDocument(document, options)` returns the same DocumentValidationResult
@@ -101,15 +136,15 @@ values alone never request creation or modification of resources.
101
136
  Authority paths are caller-supplied diagnostic locations; they are not checked
102
137
  against writable document targets. This differs from server-owned field paths.
103
138
 
104
- Owned-field paths must name id, actor, attributedTo, published, or updated on
105
- existing supported root/nested documents. Supported aliases resolve to the same
106
- field; diagnostics and changes retain original source spellings and indexes.
107
- Conflicts in arrays point to the non-null entries. When filling an absent value,
108
- preparation prefers the requested key if it exists, then an existing alias,
109
- and otherwise adds the requested key.
110
- References and opaque extension data cannot be targets. The caller lists only
111
- the fields it owns for that explicit creation operation; no default fields are
112
- invented, and no values are generated from the clock or random IDs here.
139
+ Owned-field paths must name `id`, `actor`, `attributedTo`, `published`, or
140
+ `updated` on existing supported root/nested documents. Supported aliases
141
+ resolve to the same field; diagnostics and changes retain original source
142
+ spellings and indexes. Conflicts in arrays point to the non-null entries. When
143
+ filling an absent value, preparation prefers the requested key if it exists,
144
+ then an existing alias, and otherwise adds the requested key. References and
145
+ opaque extension data cannot be targets. The caller lists only the fields it
146
+ owns for that explicit creation operation; no default fields are invented, and
147
+ no values are generated from the clock or random IDs here.
113
148
 
114
149
  | Submitted value | Preparation behavior |
115
150
  | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
@@ -141,66 +176,71 @@ proposals remain unchanged.
141
176
  Denied authority, conflicts, unsupported input, and truncated diagnostics
142
177
  withhold both preview and changes. The input and trusted options are unchanged.
143
178
 
144
- #152 owns actual permission checks, value allocation, preview-to-commit
145
- coordination, persistence, and permission rechecks at write time. It must keep
146
- the committed values consistent with the accepted preview. This module neither
147
- saves anything nor adapts createObject. Both editors can display the shared
148
- results; saving, publication, and sending remain separate operations.
179
+ The common write operations in `@drfed/federation/local-write` own permission
180
+ checks, value allocation, preview-to-commit coordination, persistence, and
181
+ permission rechecks at write time, and commit exactly the values of an
182
+ accepted preview; see the [local write internals]. This module saves nothing.
183
+ Both editors can display the shared results; saving, publication, and sending
184
+ remain separate operations.
185
+
186
+ [local write internals]: https://drfed.org/internals/local-writes
149
187
 
150
188
  ### Supported types and properties
151
189
 
152
190
  The checker admits both activity base types and all 28 named activity subtypes,
153
- plus Object, Note, Article, Application, Group, Organization, Person, Service,
154
- Collection, OrderedCollection, CollectionPage, OrderedCollectionPage, Link,
155
- and Mention. Optional properties stay optional. Each document needs one
156
- supported type string; all type arrays, including singleton arrays, are
157
- unsupported. Unknown types are retained without being converted to Note.
191
+ plus `Object`, `Note`, `Article`, `Application`, `Group`, `Organization`,
192
+ `Person`, `Service`, `Collection`, `OrderedCollection`, `CollectionPage`,
193
+ `OrderedCollectionPage`, `Link`, and `Mention`. Optional properties stay
194
+ optional. Each document needs one supported `type` string; all `type` arrays,
195
+ including singleton arrays, are unsupported. Unknown types are retained without
196
+ being converted to `Note`.
158
197
 
159
198
  Type detection uses Fedify's public registry and inheritance, with an explicit
160
- implemented-type set. Link and Mention use their exported classes because the
161
- installed registry excludes them. Models and federation share the catalog
199
+ implemented-type set. `Link` and `Mention` use their exported classes because
200
+ the installed registry excludes them. Models and federation share the catalog
162
201
  version of `@fedify/vocab` (currently 2.4.3); context data comes from the
163
202
  matching `@fedify/vocab-runtime`. Recognition by Fedify alone does not
164
203
  establish checker coverage. No vocabulary parser or full JSON-LD expansion runs
165
204
  here.
166
205
 
167
- In the table, Object includes its admitted subtypes, including activities,
206
+ In the table, `Object` includes its admitted subtypes, including activities,
168
207
  actors, and collections. References are absolute IRIs or supported embedded
169
- Object/Link values. Reference lists retain order, duplicates, and source
208
+ `Object`/`Link` values. Reference lists retain order, duplicates, and source
170
209
  indexes.
171
210
 
172
- | Applies to | Properties and rules |
173
- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
174
- | Object and Link | id: one IRI; mediaType: one MIME type; preview: references/lists; name/nameMap: text without HTML. |
175
- | Object | summary/content and summaryMap/contentMap: text, including HTML and empty strings; location and attributedTo: references/lists. |
176
- | Object | published, updated, startTime, endTime: one date-time each; to, cc, bto, bcc, audience: references/lists, with empty-array omission previews. |
177
- | Activity | actor, object, target, origin, result, instrument: references/lists. IntransitiveActivity, Arrive, Travel, and Question reject non-null object values. |
178
- | Actor types | preferredUsername: text; inbox/outbox: one IRI or embedded OrderedCollection or OrderedCollectionPage; following/followers/liked: one IRI or embedded Collection subtype. |
179
- | Collection and subtypes | items/orderedItems: references/lists; totalItems: non-negative integer; current/first/last: one IRI or CollectionPage subtype. Counts need not match visible members. |
180
- | CollectionPage subtypes | partOf: one IRI or Collection subtype; next/prev: one IRI or CollectionPage subtype. |
181
- | OrderedCollectionPage | startIndex: non-negative integer. |
182
- | Link and Mention | href: one IRI; hreflang: one language tag; rel: relation tokens/IRIs or lists; height/width: non-negative integers. Object-only fields, such as content and location, receive property\_not\_applicable. |
183
-
184
- Except for id, single-value properties accept a scalar or array containing at
211
+ | Applies to | Properties and rules |
212
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
213
+ | `Object` and `Link` | `id`: one IRI; `mediaType`: one MIME type; `preview`: references/lists; `name`/`nameMap`: text without HTML. |
214
+ | `Object` | `summary`/`content` and `summaryMap`/`contentMap`: text, including HTML and empty strings; `location` and `attributedTo`: references/lists. |
215
+ | `Object` | `published`, `updated`, `startTime`, `endTime`: one date-time each; `to`, `cc`, `bto`, `bcc`, `audience`: references/lists, with empty-array omission previews. |
216
+ | `Activity` | `actor`, `object`, `target`, `origin`, `result`, `instrument`: references/lists. `IntransitiveActivity`, `Arrive`, `Travel`, and `Question` reject non-null `object` values. |
217
+ | Actor types | `preferredUsername`: text; `inbox`/`outbox`: one IRI or embedded `OrderedCollection` or `OrderedCollectionPage`; `following`/`followers`/`liked`: one IRI or embedded `Collection` subtype. |
218
+ | `Collection` and subtypes | `items`/`orderedItems`: references/lists; `totalItems`: non-negative integer; `current`/`first`/`last`: one IRI or `CollectionPage` subtype. Counts need not match visible members. |
219
+ | `CollectionPage` subtypes | `partOf`: one IRI or `Collection` subtype; `next`/`prev`: one IRI or `CollectionPage` subtype. |
220
+ | `OrderedCollectionPage` | `startIndex`: non-negative integer. |
221
+ | `Link` and `Mention` | `href`: one IRI; `hreflang`: one language tag; `rel`: relation tokens/IRIs or lists; `height`/`width`: non-negative integers. `Object`-only fields, such as `content` and `location`, receive `property_not_applicable`. |
222
+
223
+ Except for `id`, single-value properties accept a scalar or array containing at
185
224
  most one non-null value; multiple values receive `invalid_multiplicity`. Null
186
225
  means absence, including null list entries. Empty arrays on supported
187
226
  properties receive `empty_property_list` and an inspectable omission preview;
188
- nested lists remain unsupported. Type and context arrays do not use this
227
+ nested lists remain unsupported. `type` and `@context` arrays do not use this
189
228
  omission rule. Unknown custom arrays are preserved as opaque data, while empty
190
229
  arrays on unsupported or inapplicable fields retain their existing errors.
191
230
  Identifiers require an IRI string when present. Null, empty arrays, and
192
231
  null-only arrays receive omission previews; arrays containing non-null values
193
232
  receive `invalid_value_shape`, even when they contain only one identifier.
194
- Embedded activity actors and Object `attributedTo` values must use Application,
195
- Group, Organization, Person, or Service for Fedify compatibility. Other
196
- ActivityStreams-permitted embedded types receive `unsupported_value_form`; IRI
197
- references remain supported without remote type checks. Object-only fields such
198
- as `attributedTo` on Link receive `property_not_applicable`. Link `preview` and
199
- `nameMap` remain supported by the vocabulary and Fedify's decoder. Collection
200
- navigation accepts embedded CollectionPage values for current, first, last,
201
- next, and prev, and Collection values for partOf, including subtypes. Embedded
202
- Links in these fields receive `unsupported_value_form` because Fedify rejects
203
- them. Diagnostics retain the original field/list paths.
233
+ Embedded activity actors and `Object` `attributedTo` values must use
234
+ `Application`, `Group`, `Organization`, `Person`, or `Service` for Fedify
235
+ compatibility. Other ActivityStreams-permitted embedded types receive
236
+ `unsupported_value_form`; IRI references remain supported without remote type
237
+ checks. `Object`-only fields such as `attributedTo` on `Link` receive
238
+ `property_not_applicable`. `Link` `preview` and `nameMap` remain supported by
239
+ the vocabulary and Fedify's decoder. `Collection` navigation accepts embedded
240
+ `CollectionPage` values for `current`, `first`, `last`, `next`, and `prev`, and
241
+ `Collection` values for `partOf`, including subtypes. Embedded `Link` values in
242
+ these fields receive `unsupported_value_form` because Fedify rejects them.
243
+ Diagnostics retain the original field/list paths.
204
244
 
205
245
  Text accepts strings, flat lists, and supported `@value`/`@language` objects.
206
246
  Language maps contain strings or null. Complex text attributes are unsupported.
@@ -213,15 +253,15 @@ unsupported. Validation preserves these values without adding seconds or
213
253
  truncating precision. Timestamp validation does not establish server ownership
214
254
  or ordering between fields.
215
255
 
216
- Question is supported standalone and inside Create/Update using shared rules.
217
- Its `oneOf`, `anyOf`, and `closed` fields remain unsupported pending #155's
218
- poll rules. Open-ended Question needs no choices. Other types without
219
- implemented rules, such as Place, receive support findings.
256
+ `Question` is supported standalone and inside `Create`/`Update` using shared
257
+ rules. Its `oneOf`, `anyOf`, and `closed` fields remain unsupported pending
258
+ #155's poll rules. Open-ended `Question` needs no choices. Other types without
259
+ implemented rules, such as `Place`, receive support findings.
220
260
 
221
- For 0.2.0, Object property rules for `tag`, `inReplyTo`, `url`, `attachment`,
261
+ For 0.2.0, `Object` property rules for `tag`, `inReplyTo`, `url`, `attachment`,
222
262
  `replies`, `icon`, `image`, `context`, `source`, `duration`, and `generator`
223
263
  remain unimplemented. Null values are treated as absent and preserved without
224
- diagnostics or normalization. On Object documents, non-null values produce
264
+ diagnostics or normalization. On `Object` documents, non-null values produce
225
265
  `unsupported_property` errors and set `complete: false`, preventing successful
226
266
  validation even when their values are valid ActivityStreams. This limits which
227
267
  documents pasted from fediverse servers can pass validation. Unknown custom
@@ -309,7 +349,8 @@ category and severity are checked against the registry. Input preservation and
309
349
  preview contents are asserted. Additional tests exercise network avoidance,
310
350
  contexts, representation limits, and nested traversal. Preparation tests
311
351
  exercise supplied authority outcomes and generated-field previews. Database
312
- permission enforcement and transaction integration remain #152 responsibilities.
352
+ permission enforcement and transaction integration are tested with the common
353
+ write operations in `@drfed/federation`.
313
354
 
314
355
  [the fixture file]: ../../fixtures/document-validation/initial.json
315
356
  [the document tests]: src/document.test.ts
@@ -330,12 +371,15 @@ Resource revisions
330
371
 
331
372
  `@drfed/models/resource-revision` provides trusted append and history reads for
332
373
  full ActivityStreams JSON, with compare-and-swap heads and terminal deletion
333
- markers. Existing local and inbound Create writers capture their documents in
374
+ markers. Existing local and inbound `Create` writers capture their documents in
334
375
  the same transaction. Retained JSON can contain blind recipients; model reads
335
376
  do not authorize access or prepare wire documents.
336
377
 
337
- See the [resource revision internals] for API examples, projections, legacy
338
- upgrades and the boundaries of editor, federation and dispatch integration.
378
+ `writeTypedResourceRevision()` edits or deletes an object that also has a
379
+ legacy typed row, keeping the row, its current addressing, and the history in
380
+ step. See the [resource revision internals] for API examples, projections,
381
+ legacy upgrades and the boundaries of editor, federation and dispatch
382
+ integration.
339
383
 
340
384
  [resource revision internals]: https://drfed.org/internals/resource-revisions
341
385
 
@@ -149,6 +149,8 @@ interface DocumentPreparationOptions {
149
149
  readonly authority: readonly [DocumentAuthority, ...DocumentAuthority[]];
150
150
  readonly serverOwnedFields: readonly ServerOwnedField[];
151
151
  }
152
+ /** The ActivityStreams properties that address a document's recipients. */
153
+ declare const addressingProperties: readonly ["to", "cc", "bto", "bcc", "audience"];
152
154
  /**
153
155
  * Checks the implemented Activity Vocabulary types, including nested
154
156
  * activity objects, without network access or writes. Embedded objects inherit
@@ -195,6 +197,54 @@ declare function validateDocument(document: unknown): DocumentValidationResult;
195
197
  * @returns Original-input diagnostics and any explicit creation preview changes.
196
198
  */
197
199
  declare function prepareDocument(document: unknown, options: DocumentPreparationOptions): DocumentValidationResult;
200
+ /** The vocabulary category of a described document. */
201
+ type DocumentNodeKind = "activity" | "actor" | "collection" | "link" | "object";
202
+ /** One document reached by vocabulary traversal, as the checker read it. */
203
+ interface DocumentNode {
204
+ /** Source path of the document; `[]` is the root. */
205
+ readonly path: FieldPath;
206
+ /**
207
+ * The standard name of the property that embeds the document, whatever
208
+ * its source spelling; absent for the root.
209
+ */
210
+ readonly property?: string;
211
+ /** The ActivityStreams type IRI, such as `…/activitystreams#Note`. */
212
+ readonly type: string;
213
+ readonly kind: DocumentNodeKind;
214
+ /**
215
+ * Standard property names, including `id` and `type`, mapped to the source
216
+ * keys that supply them, in source key order. Custom extension keys are
217
+ * not listed.
218
+ */
219
+ readonly properties: ReadonlyMap<string, readonly string[]>;
220
+ /**
221
+ * String IRI references held by this document's own reference properties
222
+ * (`id`, `actor`, `object`, addressing, `href`, and so on), with compact
223
+ * IRIs expanded through the context's prefixes. Values inside embedded
224
+ * documents belong to those documents' nodes.
225
+ */
226
+ readonly identifiers: readonly DocumentIdentifier[];
227
+ }
228
+ /** One IRI reference as written and as the context resolves it. */
229
+ interface DocumentIdentifier {
230
+ /** The standard property name, such as `actor` or `to`. */
231
+ readonly property: string;
232
+ /** Source path of the value, including its list index if any. */
233
+ readonly path: FieldPath;
234
+ /** The value as written. */
235
+ readonly value: string;
236
+ /** The value with a compact IRI prefix expanded. */
237
+ readonly iri: string;
238
+ }
239
+ /**
240
+ * Describes the vocabulary documents the checker reads, so that write paths
241
+ * interpret aliases, full-IRI keys, and keyword aliases exactly as
242
+ * validation did, instead of matching literal key spellings. Opaque
243
+ * extension values are not descended into.
244
+ * @returns The root and every embedded document in traversal order, or
245
+ * `null` unless validation completes without errors.
246
+ */
247
+ declare function describeDocument(document: unknown): readonly DocumentNode[] | null;
198
248
  //#endregion
199
- export { Diagnostic, DiagnosticCategory, DiagnosticReason, DiagnosticSeverity, DocumentAuthority, DocumentPreparationOptions, DocumentValidationResult, FieldPath, JsonValue, NormalizationChange, ServerOwnedField, diagnosticReasons, prepareDocument, validateDocument };
249
+ export { Diagnostic, DiagnosticCategory, DiagnosticReason, DiagnosticSeverity, DocumentAuthority, DocumentIdentifier, DocumentNode, DocumentNodeKind, DocumentPreparationOptions, DocumentValidationResult, FieldPath, JsonValue, NormalizationChange, ServerOwnedField, addressingProperties, describeDocument, diagnosticReasons, prepareDocument, validateDocument };
200
250
  //# sourceMappingURL=document.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"document.d.mts","names":[],"sources":["../src/document.ts"],"mappings":";;KAqEY;KAEA;KAMA;;cAGC;;aACc;aAAwB;;;aAC/B;aAAwB;;;aACnB;aAAwB;;;aAChC;aAAwB;;;aACnB;aAAwB;;;aACpB;aAAwB;;;aACrB;aAAwB;;;aAChC;aAAwB;;;aACZ;aAAuB;;;aACvB;aAAuB;;;aACvB;aAAqB;;;aACxB;aAAqB;;;aAC7B;aAAqB;;;aACjB;aAAqB;;;aACnB;aAAqB;;;aAClB;aAAqB;;;aACtB;aAAqB;;;aAE/C;aACA;;;aAGA;aACA;;;aAEqB;aAA2B;;;aAC7B;aAA2B;;;KAStC,gCAAgC;UAE3B;WACN,QAAQ;WACR,UAAU;WACV,UAAU;WACV,MAAM;WACN;;KAGC,wDAKC;YACG,cAAc;;;KAGlB;WAEG;WACA;WACA,MAAM;WACN,OAAO;WACP;;WAGA;WACA;WACA,MAAM;WACN,QAAQ;WACR,OAAO;WACP;;WAGA;WACA;WACA,MAAM;WACN,QAAQ;WACR;;UAGE;;WAEN;WACA,sBAAsB;WACtB;cAAiC,cAAc;;WAC/C,kBAAkB;;;UAIZ;WACN;;WAEA,MAAM;;;UAIA;;WAEN,MAAM;WACN;;;UAIM;;WAEN,qBAAqB,sBAAsB;WAC3C,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8yDvB,iBAAiB,oBAAoB;;;;;;;;;;;;;;;;;;iBA0QrC,gBACd,mBACA,SAAS,6BACR"}
1
+ {"version":3,"file":"document.d.mts","names":[],"sources":["../src/document.ts"],"mappings":";;KAqEY;KAEA;KAMA;;cAGC;;aACc;aAAwB;;;aAC/B;aAAwB;;;aACnB;aAAwB;;;aAChC;aAAwB;;;aACnB;aAAwB;;;aACpB;aAAwB;;;aACrB;aAAwB;;;aAChC;aAAwB;;;aACZ;aAAuB;;;aACvB;aAAuB;;;aACvB;aAAqB;;;aACxB;aAAqB;;;aAC7B;aAAqB;;;aACjB;aAAqB;;;aACnB;aAAqB;;;aAClB;aAAqB;;;aACtB;aAAqB;;;aAE/C;aACA;;;aAGA;aACA;;;aAEqB;aAA2B;;;aAC7B;aAA2B;;;KAStC,gCAAgC;UAE3B;WACN,QAAQ;WACR,UAAU;WACV,UAAU;WACV,MAAM;WACN;;KAGC,wDAKC;YACG,cAAc;;;KAGlB;WAEG;WACA;WACA,MAAM;WACN,OAAO;WACP;;WAGA;WACA;WACA,MAAM;WACN,QAAQ;WACR,OAAO;WACP;;WAGA;WACA;WACA,MAAM;WACN,QAAQ;WACR;;UAGE;;WAEN;WACA,sBAAsB;WACtB;cAAiC,cAAc;;WAC/C,kBAAkB;;;UAIZ;WACN;;WAEA,MAAM;;;UAIA;;WAEN,MAAM;WACN;;;UAIM;;WAEN,qBAAqB,sBAAsB;WAC3C,4BAA4B;;;cAQ1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+yDG,iBAAiB,oBAAoB;;;;;;;;;;;;;;;;;;iBA0QrC,gBACd,mBACA,SAAS,6BACR;;KAsGS;;UAQK;;WAEN,MAAM;;;;;WAKN;;WAEA;WACA,MAAM;;;;;;WAMN,YAAY;;;;;;;WAOZ,sBAAsB;;;UAIhB;;WAEN;;WAEA,MAAM;;WAEN;;WAEA;;;;;;;;;;iBA0DK,iBACd,6BACU"}
package/dist/document.mjs CHANGED
@@ -99,6 +99,7 @@ const actorTypes = [
99
99
  Person,
100
100
  Service
101
101
  ];
102
+ /** The ActivityStreams properties that address a document's recipients. */
102
103
  const addressingProperties = [
103
104
  "to",
104
105
  "cc",
@@ -933,7 +934,7 @@ function checkDocumentValue(rootDocument, rootPath, reporter, changes, onDocumen
933
934
  return;
934
935
  }
935
936
  checkEmbeddedFedifyRange(Type, fedifyTypes, path, report);
936
- onDocument?.(values, path, context);
937
+ onDocument?.(values, path, context, Type, fields);
937
938
  const isObject = isTypeOrSubtype(Type, Object$1);
938
939
  const isLink = isTypeOrSubtype(Type, Link);
939
940
  const isActivity = isTypeOrSubtype(Type, Activity);
@@ -1258,7 +1259,118 @@ function prepareDocument(document, options) {
1258
1259
  normalizedDocument: preview
1259
1260
  };
1260
1261
  }
1262
+ const identifierProperties = /* @__PURE__ */ new Set([
1263
+ "id",
1264
+ "actor",
1265
+ "object",
1266
+ "target",
1267
+ "origin",
1268
+ "result",
1269
+ "instrument",
1270
+ "attributedTo",
1271
+ "location",
1272
+ "preview",
1273
+ ...addressingProperties,
1274
+ "items",
1275
+ "orderedItems",
1276
+ "current",
1277
+ "first",
1278
+ "last",
1279
+ "partOf",
1280
+ "next",
1281
+ "prev",
1282
+ "inbox",
1283
+ "outbox",
1284
+ "following",
1285
+ "followers",
1286
+ "liked",
1287
+ "href"
1288
+ ]);
1289
+ function expandIdentifier(value, context) {
1290
+ const colon = value.indexOf(":");
1291
+ if (colon <= 0 || value.startsWith("//", colon + 1)) return value;
1292
+ const prefix = context.terms.get(value.slice(0, colon));
1293
+ if (prefix?.prefix !== true || prefix.iri.startsWith("@")) return value;
1294
+ return prefix.iri + value.slice(colon + 1);
1295
+ }
1296
+ function nodeKind(Type) {
1297
+ if (isTypeOrSubtype(Type, Link)) return "link";
1298
+ if (isTypeOrSubtype(Type, Activity)) return "activity";
1299
+ if (actorTypes.some((Actor) => isTypeOrSubtype(Type, Actor))) return "actor";
1300
+ if (isTypeOrSubtype(Type, Collection)) return "collection";
1301
+ return "object";
1302
+ }
1303
+ /**
1304
+ * Describes the vocabulary documents the checker reads, so that write paths
1305
+ * interpret aliases, full-IRI keys, and keyword aliases exactly as
1306
+ * validation did, instead of matching literal key spellings. Opaque
1307
+ * extension values are not descended into.
1308
+ * @returns The root and every embedded document in traversal order, or
1309
+ * `null` unless validation completes without errors.
1310
+ */
1311
+ function describeDocument(document) {
1312
+ const reporter = createReporter();
1313
+ const visited = [];
1314
+ checkDocumentValue(document, [], reporter, [], (values, path, context, Type, fields) => {
1315
+ visited.push({
1316
+ values,
1317
+ path,
1318
+ context,
1319
+ Type,
1320
+ fields
1321
+ });
1322
+ });
1323
+ const result = reporter.result();
1324
+ if (!result.complete || result.diagnostics.some(({ severity }) => severity === "error")) return null;
1325
+ const nodes = visited.map(({ values, path, context, Type, fields }) => {
1326
+ const properties = /* @__PURE__ */ new Map();
1327
+ const identifiers = [];
1328
+ for (const { source, name, compatible } of fields) {
1329
+ if (name == null || !compatible) continue;
1330
+ const sources = properties.get(name) ?? [];
1331
+ sources.push(source);
1332
+ properties.set(name, sources);
1333
+ if (!identifierProperties.has(name)) continue;
1334
+ const value = values[source];
1335
+ const entries = Array.isArray(value) ? value.map((entry, index) => [entry, [
1336
+ ...path,
1337
+ source,
1338
+ index
1339
+ ]]) : [[value, [...path, source]]];
1340
+ for (const [entry, entryPath] of entries) {
1341
+ if (typeof entry !== "string") continue;
1342
+ identifiers.push({
1343
+ property: name,
1344
+ path: entryPath,
1345
+ value: entry,
1346
+ iri: expandIdentifier(entry, context)
1347
+ });
1348
+ }
1349
+ }
1350
+ return {
1351
+ path,
1352
+ type: Type.typeId.href,
1353
+ kind: nodeKind(Type),
1354
+ properties,
1355
+ identifiers
1356
+ };
1357
+ });
1358
+ const byPath = new Map(nodes.map((node) => [JSON.stringify(node.path), node]));
1359
+ return nodes.map((node) => {
1360
+ if (node.path.length === 0) return node;
1361
+ for (const length of [node.path.length - 1, node.path.length - 2]) {
1362
+ const parent = byPath.get(JSON.stringify(node.path.slice(0, length)));
1363
+ const key = node.path[length];
1364
+ if (parent == null || typeof key !== "string") continue;
1365
+ for (const [name, sources] of parent.properties) if (sources.includes(key)) return {
1366
+ ...node,
1367
+ property: name
1368
+ };
1369
+ }
1370
+ return node;
1371
+ });
1372
+ }
1261
1373
  //#endregion
1262
- export { diagnosticReasons, prepareDocument, validateDocument };
1374
+ export { addressingProperties, describeDocument, diagnosticReasons, prepareDocument, validateDocument };
1263
1375
 
1264
1376
  //# sourceMappingURL=document.mjs.map