@fedify/vocab-tools 2.5.0-dev.2664 → 2.5.0-dev.2710

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/src/class.ts DELETED
@@ -1,486 +0,0 @@
1
- import { generateDecoder, generateEncoder } from "./codec.ts";
2
- import {
3
- generateCloner,
4
- generateConstructor,
5
- generateDeepCloner,
6
- } from "./constructor.ts";
7
- import {
8
- generateDeepCloneDescriptor,
9
- generateDeepCloneHelpers,
10
- } from "./deep-clone.ts";
11
- import { generateFields } from "./field.ts";
12
- import { generateInspector, generateInspectorPostClass } from "./inspector.ts";
13
- import { generateProperties } from "./property.ts";
14
- import { generatePropertyArrayHelpers } from "./property-array.ts";
15
- import {
16
- type PropertySchema,
17
- type TypeSchema,
18
- validateTypeSchemas,
19
- } from "./schema.ts";
20
- import { emitOverride } from "./type.ts";
21
-
22
- const XSD_ANY_URI = "http://www.w3.org/2001/XMLSchema#anyURI";
23
- const FEDIFY_URL = "fedify:url";
24
- const FEDIFY_ABSOLUTE_IRI = "fedify:absoluteIri";
25
- const INTERNAL_RUNTIME_IMPORTS = [
26
- "compactJsonLdCache",
27
- "createScopedContextLoader",
28
- "getJsonLdContext",
29
- "getPortableActorGateways",
30
- "isTrustedIriOrigin",
31
- "normalizeJsonLdIris",
32
- ].join(",\n ");
33
- const PORTABLE_DEREFERENCE_IMPORTS = [
34
- "copyPortableProvenance",
35
- "createSnapshotContextLoader",
36
- "dereferencePortableIri",
37
- "getPortableResponseClaim",
38
- "getReferrerGateways",
39
- "isPortableIri",
40
- "isPortableMode",
41
- "isUnsecuredPortableObject",
42
- "isUnverifiedPortableClaim",
43
- "markUnverifiedPortableClaim",
44
- "mustDereferencePortableObject",
45
- "parseCompatibleEf61Reference",
46
- "type PortableResponseClaim",
47
- "recordPortableReferrer",
48
- "retargetPortableReferrer",
49
- "rejectMalformedCompatibleReference",
50
- "warnUnverifiableEmbeddedObject",
51
- ].join(",\n ");
52
- const SIGNED_REPRESENTATION_IMPORTS = [
53
- "enterSignedValueScope",
54
- "resolveSignedValues",
55
- "retainedSignedValueRef",
56
- ].join(",\n ");
57
- const RUNTIME_IMPORTS = [
58
- "canParseDecimal",
59
- "decodeMultibase",
60
- "type Decimal",
61
- "type DocumentLoader",
62
- "encodeMultibase",
63
- "exportMultibaseKey",
64
- "exportSpki",
65
- "formatIri",
66
- "getDocumentLoader",
67
- "importMultibaseKey",
68
- "importPem",
69
- "isDecimal",
70
- "isGatewayUrl",
71
- "LanguageString",
72
- "normalizeLanguageTag",
73
- "parseDecimal",
74
- "parseGatewayUrl",
75
- "parseIri",
76
- "parseJsonLdId",
77
- "type PortableObjectVerifier",
78
- "type RemoteDocument",
79
- ].join(",\n ");
80
-
81
- /**
82
- * Sorts the given types topologically so that the base types come before the
83
- * extended types.
84
- * @param types The types to sort.
85
- * @returns The sorted type URIs.
86
- */
87
- export function sortTopologically(types: Record<string, TypeSchema>): string[] {
88
- const sorted: string[] = [];
89
- const visited = new Set<string>();
90
- const visiting = new Set<string>();
91
- for (const node of Object.values(types)) {
92
- visit(node);
93
- }
94
- return sorted;
95
-
96
- function visit(node: TypeSchema) {
97
- if (visited.has(node.uri)) return;
98
- if (visiting.has(node.uri)) {
99
- throw new Error(`Detected cyclic inheritance: ${node.uri}`);
100
- }
101
- visiting.add(node.uri);
102
- if (node.extends) visit(types[node.extends]);
103
- visiting.delete(node.uri);
104
- visited.add(node.uri);
105
- sorted.push(node.uri);
106
- }
107
- }
108
-
109
- async function* generateClass(
110
- typeUri: string,
111
- types: Record<string, TypeSchema>,
112
- moduleVarNames: ReadonlyMap<string, string>,
113
- ): AsyncIterable<string> {
114
- const type = types[typeUri];
115
- yield `/** ${type.description.replaceAll("\n", "\n * ")}\n */\n`;
116
- if (type.extends) {
117
- const baseType = types[type.extends];
118
- yield `export class ${type.name} extends ${baseType.name} {\n`;
119
- } else {
120
- yield `export class ${type.name} {\n`;
121
- }
122
- if (type.extends == null) {
123
- yield `
124
- readonly #documentLoader?: DocumentLoader;
125
- readonly #contextLoader?: DocumentLoader;
126
- readonly #tracerProvider?: TracerProvider;
127
- readonly #verifyPortableObject?: PortableObjectVerifier;
128
- readonly #warning?: {
129
- category: string[];
130
- message: string;
131
- values?: Record<string, unknown>;
132
- };
133
- #cachedJsonLd?: unknown;
134
- readonly #_baseUrl?: URL;
135
- #shouldCacheJsonLd = true;
136
- readonly id: URL | null;
137
-
138
- protected get _documentLoader(): DocumentLoader | undefined {
139
- return this.#documentLoader;
140
- }
141
-
142
- protected get _contextLoader(): DocumentLoader | undefined {
143
- return this.#contextLoader;
144
- }
145
-
146
- protected get _tracerProvider(): TracerProvider | undefined {
147
- return this.#tracerProvider;
148
- }
149
-
150
- protected get _verifyPortableObject(): PortableObjectVerifier | undefined {
151
- return this.#verifyPortableObject;
152
- }
153
-
154
- protected get _warning(): {
155
- category: string[];
156
- message: string;
157
- values?: Record<string, unknown>;
158
- } | undefined {
159
- return this.#warning;
160
- }
161
-
162
- /**
163
- * Internal cross-package contract with @fedify/testing, which copies this
164
- * cache when attaching document loaders to an activity clone. Keep this
165
- * accessor name and its getter/setter semantics stable.
166
- */
167
- protected get _cachedJsonLd(): unknown | undefined {
168
- return this.#cachedJsonLd;
169
- }
170
-
171
- protected set _cachedJsonLd(value: unknown | undefined) {
172
- this.#cachedJsonLd = value;
173
- }
174
-
175
- protected get _baseUrl(): URL | undefined {
176
- return this.#_baseUrl;
177
- }
178
-
179
- protected get _shouldCacheJsonLd(): boolean {
180
- return this.#shouldCacheJsonLd;
181
- }
182
-
183
- protected set _shouldCacheJsonLd(value: boolean) {
184
- this.#shouldCacheJsonLd = value;
185
- }
186
-
187
- protected static _shouldCacheDecodedJsonLd(value: unknown): boolean {
188
- if (value == null || typeof value !== "object") return true;
189
- if (!("_shouldCacheJsonLd" in value)) return true;
190
- return (value as { _shouldCacheJsonLd: boolean })._shouldCacheJsonLd;
191
- }
192
- `;
193
- }
194
- yield `
195
- /**
196
- * The type URI of {@link ${type.name}}: \`${typeUri}\`.
197
- */
198
- static ${emitOverride(typeUri, types)} get typeId(): URL {
199
- return new URL(${JSON.stringify(typeUri)});
200
- }
201
- `;
202
- for await (const code of generateFields(typeUri, types)) yield code;
203
- for await (const code of generateConstructor(typeUri, types)) yield code;
204
- for await (const code of generateCloner(typeUri, types)) yield code;
205
- for await (const code of generateDeepCloner(typeUri, types)) {
206
- yield code.replace(/[ \t]+$/gm, "");
207
- }
208
- for await (const code of generateDeepCloneDescriptor(typeUri, types)) {
209
- yield code.replace(/[ \t]+$/gm, "");
210
- }
211
- for await (const code of generateProperties(typeUri, types, moduleVarNames)) {
212
- yield code;
213
- }
214
- for await (const code of generateEncoder(typeUri, types)) yield code;
215
- for await (const code of generateDecoder(typeUri, types, moduleVarNames)) {
216
- yield code;
217
- }
218
- for await (const code of generateInspector(typeUri, types)) yield code;
219
- yield "}\n\n";
220
- for await (const code of generateInspectorPostClass(typeUri, types)) {
221
- yield code;
222
- }
223
- }
224
-
225
- function* generateEntityTypeHelpers(
226
- sortedTypeUris: string[],
227
- types: Record<string, TypeSchema>,
228
- ): Iterable<string> {
229
- const entityTypes = sortedTypeUris.flatMap((typeUri) =>
230
- types[typeUri].entity ? [{ name: types[typeUri].name, uri: typeUri }] : []
231
- );
232
- const entityTypeNames = entityTypes.map((entityType) => entityType.name);
233
- const entityTypeUnion = entityTypeNames.length < 1
234
- ? " never"
235
- : `\n | typeof ${entityTypeNames.join("\n | typeof ")}`;
236
- yield `/**
237
- * Constructor types for all generated vocabulary entity classes.
238
- */
239
- export type $EntityType =${entityTypeUnion};
240
-
241
- const entityTypes: readonly $EntityType[] = [
242
- `;
243
- for (const entityTypeName of entityTypeNames) {
244
- yield ` ${entityTypeName},\n`;
245
- }
246
- yield `];
247
-
248
- const entityTypeSet: ReadonlySet<$EntityType> = new Set(entityTypes);
249
-
250
- const entityTypeIds: ReadonlyMap<string, $EntityType> = new Map<string, $EntityType>(
251
- [
252
- `;
253
- for (const entityType of entityTypes) {
254
- yield ` [${JSON.stringify(entityType.uri)}, ${entityType.name}],\n`;
255
- }
256
- yield ` ],
257
- );
258
-
259
- /**
260
- * Checks whether the given value is a generated vocabulary entity class.
261
- */
262
- export function isEntityType(value: unknown): value is $EntityType {
263
- return entityTypeSet.has(value as $EntityType);
264
- }
265
-
266
- /**
267
- * Gets the generated vocabulary entity class for the given type URI.
268
- */
269
- export function getEntityTypeById(id: string | URL): $EntityType | undefined {
270
- return entityTypeIds.get(typeof id === "string" ? id : id?.href);
271
- }
272
-
273
- `;
274
- }
275
-
276
- function canContainIriValue(
277
- property: PropertySchema,
278
- types: Record<string, TypeSchema>,
279
- ): boolean {
280
- return property.range.some((typeUri) =>
281
- typeUri === XSD_ANY_URI || typeUri === FEDIFY_URL ||
282
- typeUri === FEDIFY_ABSOLUTE_IRI || types[typeUri]?.entity
283
- );
284
- }
285
-
286
- function addKeys(
287
- keys: Set<string>,
288
- property: { uri: string; compactName?: string },
289
- ): void {
290
- keys.add(property.uri);
291
- if (property.compactName != null) keys.add(property.compactName);
292
- }
293
-
294
- function addPortableIriKeys(
295
- keys: Set<string>,
296
- property: PropertySchema,
297
- types: Record<string, TypeSchema>,
298
- ): void {
299
- if (!canContainIriValue(property, types)) return;
300
- addKeys(keys, property);
301
- if (
302
- "redundantProperties" in property &&
303
- property.redundantProperties != null
304
- ) {
305
- for (const redundantProperty of property.redundantProperties) {
306
- addKeys(keys, redundantProperty);
307
- }
308
- }
309
- }
310
-
311
- /**
312
- * Generates the TypeScript classes from the given types.
313
- * @param types The types to generate classes from.
314
- * @returns The source code of the generated classes.
315
- */
316
- export async function* generateClasses(
317
- types: Record<string, TypeSchema>,
318
- ): AsyncIterable<string> {
319
- validateTypeSchemas(types);
320
- yield "// deno-lint-ignore-file ban-unused-ignore no-explicit-any no-unused-vars prefer-const verbatim-module-syntax\n";
321
- yield "// oxlint-disable typescript/no-explicit-any, no-unused-vars, prefer-const\n";
322
- yield 'import jsonld from "@fedify/vocab-runtime/jsonld";\n';
323
- yield 'import { getLogger } from "@logtape/logtape";\n';
324
- yield `import { type Span, SpanStatusCode, type TracerProvider, trace }
325
- from "@opentelemetry/api";\n`;
326
- yield `import {\n ${RUNTIME_IMPORTS}\n} from "@fedify/vocab-runtime";\n`;
327
- yield `import {\n ${INTERNAL_RUNTIME_IMPORTS}\n} from "@fedify/vocab-runtime/internal/jsonld-cache";\n`;
328
- yield `import {\n ${PORTABLE_DEREFERENCE_IMPORTS}\n} from "@fedify/vocab-runtime/internal/portable-dereference";\n`;
329
- yield `import {\n ${SIGNED_REPRESENTATION_IMPORTS}\n} from "@fedify/vocab-runtime/internal/signed-representation";\n`;
330
- yield `import {
331
- isTemporalDuration,
332
- isTemporalInstant,
333
- } from "@fedify/vocab-runtime/temporal";\n`;
334
- yield `
335
- function canDecodeIri(iri: string): boolean {
336
- try { parseIri(iri); return true; } catch { return iri.startsWith("at://"); }
337
- }
338
-
339
- function decodeIri(iri: string): URL {
340
- return !URL.canParse(iri) && iri.startsWith("at://")
341
- ? new URL("at://" + encodeURIComponent(iri.substring(5)))
342
- : parseIri(iri);
343
- }
344
-
345
- function inspectIri(iri: URL): string {
346
- // Inspecting an object must not throw, even for a URL that cannot be
347
- // formatted as an IRI, e.g., a malformed portable ID:
348
- try { return formatIri(iri); } catch { return iri.href; }
349
- }
350
- `;
351
- yield generatePropertyArrayHelpers();
352
- yield generateDeepCloneHelpers();
353
- yield `
354
- function isValidLanguageTag(language: string): boolean {
355
- try {
356
- new Intl.Locale(normalizeLanguageTag(language));
357
- return true;
358
- } catch (error) {
359
- if (error instanceof RangeError) return false;
360
- throw error;
361
- }
362
- }
363
- `;
364
- if (
365
- Object.values(types).some((type) =>
366
- type.properties.some((property) =>
367
- property.range.includes(FEDIFY_ABSOLUTE_IRI)
368
- )
369
- )
370
- ) {
371
- // An absolute IRI may arrive as an IRI node or, when the publisher's
372
- // context does not coerce the term, as a string or IRI-typed literal.
373
- // It is never resolved against a base IRI.
374
- yield `
375
- function getAbsoluteIriValue(value: unknown): string | undefined {
376
- if (value == null || typeof value !== "object") return undefined;
377
- const node = value as Record<string, unknown>;
378
- if (typeof node["@id"] === "string") {
379
- return node["@id"].startsWith("_:") ? undefined : node["@id"];
380
- }
381
- // A language tag can come from a context's default language, so it does
382
- // not make a literal any less of an IRI:
383
- if (typeof node["@value"] !== "string") return undefined;
384
- const type = node["@type"];
385
- return type == null ||
386
- type === "http://www.w3.org/2001/XMLSchema#string" ||
387
- type === "http://www.w3.org/2001/XMLSchema#anyURI"
388
- ? node["@value"]
389
- : undefined;
390
- }
391
-
392
- function isAbsoluteIriValue(value: unknown): boolean {
393
- const iri = getAbsoluteIriValue(value);
394
- return iri != null && canDecodeIri(iri);
395
- }
396
- `;
397
- }
398
- // Contexts are activated by the expanded property IRIs of the values to be
399
- // compacted, and by the contexts that already serialized children carry.
400
- // They are detected before compaction, because a default context may
401
- // define a prefix that would otherwise hide a property IRI behind a compact
402
- // IRI such as `dc:license`.
403
- const extraContexts = Object.fromEntries(
404
- Object.values(types).flatMap((type) =>
405
- type.properties.flatMap((property) =>
406
- property.extraContext == null
407
- ? []
408
- : [[property.uri, property.extraContext]]
409
- )
410
- ),
411
- );
412
- if (Object.keys(extraContexts).length > 0) {
413
- yield `
414
- const extraPropertyContexts: Readonly<Record<string, string>> =
415
- ${JSON.stringify(extraContexts)};
416
-
417
- const extraContextUrls: readonly string[] =
418
- ${JSON.stringify([...new Set(Object.values(extraContexts))])};
419
-
420
- function getExtraContexts(document: unknown): string[] {
421
- const contexts = new Set<string>();
422
- const pending: unknown[] = [document];
423
- while (pending.length > 0) {
424
- const value = pending.pop();
425
- if (value == null || typeof value !== "object") continue;
426
- if (Array.isArray(value)) {
427
- for (const item of value) pending.push(item);
428
- continue;
429
- }
430
- if ("@value" in value) continue;
431
- for (const [key, child] of globalThis.Object.entries(value)) {
432
- if (key === "@context") {
433
- for (const context of Array.isArray(child) ? child : [child]) {
434
- if (
435
- typeof context === "string" && extraContextUrls.includes(context)
436
- ) {
437
- contexts.add(context);
438
- }
439
- }
440
- continue;
441
- }
442
- if (globalThis.Object.hasOwn(extraPropertyContexts, key)) {
443
- contexts.add(extraPropertyContexts[key]);
444
- }
445
- pending.push(child);
446
- }
447
- }
448
- return [...contexts];
449
- }
450
- `;
451
- }
452
- yield "\n\n";
453
- const portableIriKeys = new Set(["@id", "id"]);
454
- for (const type of Object.values(types)) {
455
- for (const property of type.properties) {
456
- addPortableIriKeys(portableIriKeys, property, types);
457
- }
458
- }
459
- yield "const PORTABLE_IRI_PATTERN = /^ap(?:\\+ef61)?:\\/\\//i;\n";
460
- yield `const PORTABLE_IRI_KEYS: ReadonlySet<string> = new Set(${
461
- JSON.stringify([...portableIriKeys].sort())
462
- });\n\n`;
463
- const moduleVarNames = new Map<string, string>();
464
- const sorted = sortTopologically(types);
465
- for (const typeUri of sorted) {
466
- for (const property of types[typeUri].properties) {
467
- if (property.preprocessors == null) continue;
468
- for (const pp of property.preprocessors) {
469
- if (!moduleVarNames.has(pp.module)) {
470
- const name = `_ppM${moduleVarNames.size}`;
471
- moduleVarNames.set(pp.module, name);
472
- }
473
- }
474
- }
475
- }
476
- for (const [modulePath, varName] of moduleVarNames) {
477
- yield `import * as ${varName} from ${JSON.stringify(modulePath)};\n`;
478
- }
479
- if (moduleVarNames.size > 0) yield "\n";
480
- for (const typeUri of sorted) {
481
- for await (const code of generateClass(typeUri, types, moduleVarNames)) {
482
- yield code;
483
- }
484
- }
485
- for (const code of generateEntityTypeHelpers(sorted, types)) yield code;
486
- }