@fedify/vocab-tools 2.5.0-dev.2513 → 2.5.0-dev.2532

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 CHANGED
@@ -1,8 +1,17 @@
1
1
  import { generateDecoder, generateEncoder } from "./codec.ts";
2
- import { generateCloner, generateConstructor } from "./constructor.ts";
2
+ import {
3
+ generateCloner,
4
+ generateConstructor,
5
+ generateDeepCloner,
6
+ } from "./constructor.ts";
7
+ import {
8
+ generateDeepCloneDescriptor,
9
+ generateDeepCloneHelpers,
10
+ } from "./deep-clone.ts";
3
11
  import { generateFields } from "./field.ts";
4
12
  import { generateInspector, generateInspectorPostClass } from "./inspector.ts";
5
13
  import { generateProperties } from "./property.ts";
14
+ import { generatePropertyArrayHelpers } from "./property-array.ts";
6
15
  import {
7
16
  type PropertySchema,
8
17
  type TypeSchema,
@@ -36,6 +45,7 @@ const PORTABLE_DEREFERENCE_IMPORTS = [
36
45
  "parseCompatibleEf61Reference",
37
46
  "type PortableResponseClaim",
38
47
  "recordPortableReferrer",
48
+ "retargetPortableReferrer",
39
49
  "rejectMalformedCompatibleReference",
40
50
  "warnUnverifiableEmbeddedObject",
41
51
  ].join(",\n ");
@@ -192,6 +202,12 @@ async function* generateClass(
192
202
  for await (const code of generateFields(typeUri, types)) yield code;
193
203
  for await (const code of generateConstructor(typeUri, types)) yield code;
194
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
+ }
195
211
  for await (const code of generateProperties(typeUri, types, moduleVarNames)) {
196
212
  yield code;
197
213
  }
@@ -330,6 +346,8 @@ function inspectIri(iri: URL): string {
330
346
  try { return formatIri(iri); } catch { return iri.href; }
331
347
  }
332
348
  `;
349
+ yield generatePropertyArrayHelpers();
350
+ yield generateDeepCloneHelpers();
333
351
  yield `
334
352
  function isValidLanguageTag(language: string): boolean {
335
353
  try {
@@ -69,6 +69,40 @@ async function* generateParametersType(
69
69
  if (parentheses) yield "}\n";
70
70
  }
71
71
 
72
+ function generateValidatedArrayCopy(
73
+ name: string,
74
+ typeNames: string,
75
+ typeGuards: string,
76
+ ): string {
77
+ return `
78
+ let copied!: (${typeNames})[];
79
+ let valid = false;
80
+ if (Array.isArray(values.${name})) {
81
+ const array = values.${name};
82
+ const test = (v: ${typeNames}): boolean => ${typeGuards};
83
+ let checked: VocabArrayValidation | undefined;
84
+ if (array.length < vocabSparseArrayMinimumLength
85
+ ? array.every(test)
86
+ : (checked = vocabValidatePropertyArray(array, test)).valid) {
87
+ const input = values.${name};
88
+ if (input.length < vocabSparseArrayMinimumLength && !checked?.sparse) {
89
+ copied = input.slice();
90
+ valid = true;
91
+ } else {
92
+ const result = vocabCopyValidatedPropertyArray(
93
+ input, test, checked ?? { valid: true, sparse: false },
94
+ );
95
+ if (result.ok) {
96
+ copied = result.array;
97
+ valid = true;
98
+ }
99
+ }
100
+ }
101
+ }
102
+ if (valid) {
103
+ `.trimEnd() + "\n";
104
+ }
105
+
72
106
  export async function* generateConstructor(
73
107
  typeUri: string,
74
108
  types: Record<string, TypeSchema>,
@@ -175,17 +209,18 @@ export async function* generateConstructor(
175
209
  }
176
210
  `;
177
211
  }
212
+ yield generateValidatedArrayCopy(
213
+ property.pluralName,
214
+ typeNames,
215
+ typeGuards,
216
+ );
178
217
  yield `
179
- if (Array.isArray(values.${property.pluralName}) &&
180
- values.${property.pluralName}.every(v => ${typeGuards})) {
181
218
  // @ts-ignore: type is checked above.
182
- this.${fieldName} = values.${property.pluralName}.slice();
219
+ this.${fieldName} = copied;
183
220
  `;
184
221
  if (!allScalarTypes) {
185
222
  yield `
186
- for (let i = 0; i < values.${property.pluralName}.length; i++) {
187
- this.${trustFieldName}.add(i);
188
- }
223
+ vocabSetTrustPrefix(this.${trustFieldName}, this.${fieldName}.length);
189
224
  `;
190
225
  }
191
226
  yield `
@@ -219,8 +254,8 @@ export async function* generateCloner(
219
254
  * object. Hydrating a top-level property of the clone does not update this
220
255
  * instance's property.
221
256
  *
222
- * To resolve properties without sharing nested objects, serialize and
223
- * re-parse the instance before hydration rather than using this method.
257
+ * To resolve properties without sharing nested objects, use
258
+ * {@link ${type.name}.deepClone} before hydration.
224
259
  * See the [vocabulary manual](https://fedify.dev/manual/vocab#immutability)
225
260
  * for details, including how cached JSON-LD affects serialization.
226
261
  *
@@ -272,9 +307,12 @@ export async function* generateCloner(
272
307
  const fieldName = await getFieldName(property.uri);
273
308
  const trustFieldName = await getFieldName(property.uri, "#_trust");
274
309
  const allScalarTypes = areAllScalarTypes(property.range, types);
275
- yield `clone.${fieldName} = this.${fieldName}.slice();`;
310
+ yield `clone.${fieldName} = this.${fieldName}.length < vocabSparseArrayMinimumLength
311
+ ? this.${fieldName}.slice() : vocabCopyPropertyArray(this.${fieldName});`;
276
312
  if (!allScalarTypes) {
277
- yield `clone.${trustFieldName} = new Set(this.${trustFieldName});`;
313
+ yield `clone.${trustFieldName} = vocabCopyTrustSet(
314
+ this.${trustFieldName}, clone.${trustFieldName},
315
+ );`;
278
316
  }
279
317
  if (hasSingularAccessor(property)) {
280
318
  let typeGuards = getTypeGuards(
@@ -297,7 +335,8 @@ export async function* generateCloner(
297
335
  clone.${fieldName} = [values.${property.singularName}];
298
336
  `;
299
337
  if (!allScalarTypes) {
300
- yield `clone.${trustFieldName} = new Set([0]);`;
338
+ yield `clone.${trustFieldName} = new Set();
339
+ clone.${trustFieldName}[vocabTrustPrefix] = 1;`;
301
340
  }
302
341
  yield `
303
342
  } else {
@@ -332,18 +371,19 @@ export async function* generateCloner(
332
371
  }
333
372
  `;
334
373
  }
374
+ yield generateValidatedArrayCopy(
375
+ property.pluralName,
376
+ typeNames,
377
+ typeGuards,
378
+ );
335
379
  yield `
336
- if (Array.isArray(values.${property.pluralName}) &&
337
- values.${property.pluralName}.every(v => ${typeGuards})) {
338
380
  // @ts-ignore: type is checked above.
339
- clone.${fieldName} = values.${property.pluralName}.slice();
381
+ clone.${fieldName} = copied;
340
382
  `;
341
383
  if (!allScalarTypes) {
342
384
  yield `
343
385
  clone.${trustFieldName} = new Set();
344
- for (let i = 0; i < values.${property.pluralName}.length; i++) {
345
- clone.${trustFieldName}.add(i);
346
- }
386
+ vocabSetTrustPrefix(clone.${trustFieldName}, clone.${fieldName}.length);
347
387
  `;
348
388
  }
349
389
  yield `
@@ -360,5 +400,65 @@ export async function* generateCloner(
360
400
  yield `
361
401
  return clone;
362
402
  }
403
+ `.trimEnd() + "\n";
404
+ }
405
+
406
+ export async function* generateDeepCloner(
407
+ typeUri: string,
408
+ types: Record<string, TypeSchema>,
409
+ ): AsyncIterable<string> {
410
+ const type = types[typeUri];
411
+ yield `
412
+ /**
413
+ * Copies this instance and its nested vocabulary objects, optionally
414
+ * replacing property values. Replacement values are copied too.
415
+ *
416
+ * Property arrays, URLs and byte arrays are independent of the source.
417
+ * Repeated references remain shared within the copy. References to this
418
+ * source in replacement values receive a separate copy of its pre-update
419
+ * values, rather than referring back to the updated root.
420
+ * Other scalar values, including opaque cryptographic keys, are shared.
421
+ *
422
+ * Each copied object retains its own default loaders, tracer, verifier
423
+ * and base URL. Options override defaults only on the root instance.
424
+ * This method does not fetch or serialize objects. Cached JSON-LD and
425
+ * retained signed representations are not copied; unknown JSON-LD
426
+ * properties and original formatting are not preserved. Sign the copy
427
+ * again if it needs a valid proof.
428
+ *
429
+ * Trust and portable provenance follow clone() rules at every level.
430
+ * Historical referrers within the graph are copied without replacements;
431
+ * referrers outside the graph still point at the original external objects.
432
+ * Custom clone() overrides must return fresh, compatible instances and
433
+ * remain responsible for their own constructor and cloning side effects.
434
+ * Large sparse property arrays with ordinary data entries are copied using
435
+ * a snapshot of their length and present indices. Entries added after a
436
+ * snapshot are not visited; deleted entries are skipped, and values changed
437
+ * after the snapshot are read when reached. Custom
438
+ * clone() overrides must avoid structurally changing a field being copied
439
+ * if they need all its nested objects to be independent of the source.
440
+ *
441
+ * @param values The values to replace before copying the graph.
442
+ * @param options Root loader and verifier overrides. Undefined options
443
+ * retain the corresponding defaults.
444
+ * @returns An independent copy of the stored vocabulary graph.
445
+ * @since 2.5.0
446
+ */
447
+ ${emitOverride(typeUri, types)} deepClone(values:
363
448
  `;
449
+ for await (const code of generateParametersType(typeUri, types)) yield code;
450
+ yield `= {}, options: {
451
+ documentLoader?: DocumentLoader,
452
+ contextLoader?: DocumentLoader,
453
+ verifyPortableObject?: PortableObjectVerifier,
454
+ } = {}): ${type.name} {
455
+ const cloneOptions = {
456
+ documentLoader: options.documentLoader ?? this._documentLoader,
457
+ contextLoader: options.contextLoader ?? this._contextLoader,
458
+ verifyPortableObject: options.verifyPortableObject ?? this._verifyPortableObject,
459
+ tracerProvider: this._tracerProvider,
460
+ baseUrl: this._baseUrl,
461
+ };
462
+ return deepCloneGraph(this, this.clone(values, cloneOptions));
463
+ }\n`;
364
464
  }
@@ -0,0 +1,175 @@
1
+ import { getFieldName } from "./field.ts";
2
+ import type { PropertySchema, TypeSchema } from "./schema.ts";
3
+ import { getTypeName } from "./type.ts";
4
+
5
+ function needsCopy(
6
+ property: PropertySchema,
7
+ types: Record<string, TypeSchema>,
8
+ ): boolean {
9
+ return property.range.some((uri) =>
10
+ uri in types || ["URL", "Uint8Array"].includes(getTypeName(uri, types))
11
+ );
12
+ }
13
+
14
+ /** Emits module-private graph-copy support, shared by all generated classes. */
15
+ export function generateDeepCloneHelpers(): string {
16
+ return `
17
+ interface DeepCloneContext {
18
+ value<T>(value: T): T;
19
+ }
20
+
21
+ interface DeepCloneDescriptor {
22
+ create(source: object): object;
23
+ copy(destination: object, context: DeepCloneContext): void;
24
+ }
25
+
26
+ const deepCloneDescriptors = new Map<object, DeepCloneDescriptor>();
27
+
28
+ function getDeepCloneDescriptor(value: object): DeepCloneDescriptor | undefined {
29
+ let prototype: object | null = globalThis.Object.getPrototypeOf(value);
30
+ while (prototype != null) {
31
+ const descriptor = deepCloneDescriptors.get(prototype);
32
+ if (descriptor != null) return descriptor;
33
+ prototype = globalThis.Object.getPrototypeOf(prototype);
34
+ }
35
+ return undefined;
36
+ }
37
+
38
+ function deepCloneGraph<T extends object>(source: object, root: T): T {
39
+ const memo = new Map<object, object>();
40
+ const destinations = new Set<object>();
41
+ const shells: object[] = [];
42
+ let next = 0;
43
+
44
+ function enqueue(original: object, destination: object): void {
45
+ if (destination == null || typeof destination !== "object" ||
46
+ original === destination || destinations.has(destination) ||
47
+ !globalThis.Object.prototype.isPrototypeOf.call(
48
+ globalThis.Object.getPrototypeOf(original), destination
49
+ ) || getDeepCloneDescriptor(destination) == null) {
50
+ throw new TypeError("clone() must return a fresh, compatible instance.");
51
+ }
52
+ destinations.add(destination);
53
+ shells.push(destination);
54
+ }
55
+
56
+ const context: DeepCloneContext = {
57
+ value<V>(value: V): V {
58
+ if (value == null || typeof value !== "object") return value;
59
+ const existing = memo.get(value);
60
+ if (existing != null) return existing as V;
61
+ if (value instanceof URL) {
62
+ const copy = new URL(value.href);
63
+ memo.set(value, copy);
64
+ return copy as V;
65
+ }
66
+ if (value instanceof Uint8Array) {
67
+ const copy = new Uint8Array(value);
68
+ memo.set(value, copy);
69
+ return copy as V;
70
+ }
71
+ const descriptor = getDeepCloneDescriptor(value);
72
+ // Other supported scalars (Temporal, LanguageString, Intl.Locale,
73
+ // CryptoKey and class constructors) are shared as immutable values.
74
+ if (descriptor == null) return value;
75
+ const copy = descriptor.create(value);
76
+ enqueue(value, copy);
77
+ memo.set(value, copy);
78
+ return copy as V;
79
+ },
80
+ };
81
+
82
+ function drain(): void {
83
+ while (next < shells.length) {
84
+ const shell = shells[next++];
85
+ getDeepCloneDescriptor(shell)!.copy(shell, context);
86
+ }
87
+ }
88
+
89
+ // The effective root includes replacements. References to the source root
90
+ // instead receive a separate copy of its pre-update values.
91
+ enqueue(source, root);
92
+ drain();
93
+
94
+ // Discover historical root ancestry without substituting replacement values
95
+ // into it. The resolver deliberately returns undefined in this first pass.
96
+ const count = shells.length;
97
+ for (let i = 0; i < count; i++) {
98
+ retargetPortableReferrer(shells[i], (original) => {
99
+ if (original === source) context.value(source);
100
+ return undefined;
101
+ });
102
+ }
103
+ drain();
104
+ for (const shell of shells) {
105
+ retargetPortableReferrer(shell, (original) => memo.get(original));
106
+ }
107
+ return root;
108
+ }
109
+ `;
110
+ }
111
+
112
+ /** Emits private-field copiers inside static blocks, keeping them out of d.ts. */
113
+ export async function* generateDeepCloneDescriptor(
114
+ typeUri: string,
115
+ types: Record<string, TypeSchema>,
116
+ ): AsyncIterable<string> {
117
+ const type = types[typeUri];
118
+ const properties = type.properties.filter((p) => needsCopy(p, types));
119
+ if (type.extends != null && properties.length < 1) return;
120
+ yield `static {\n`;
121
+ if (type.extends == null) {
122
+ yield `deepCloneDescriptors.set(this.prototype, {
123
+ create(value: object): object {
124
+ const source = value as ${type.name};
125
+ const options = {
126
+ documentLoader: source.#documentLoader,
127
+ contextLoader: source.#contextLoader,
128
+ tracerProvider: source.#tracerProvider,
129
+ verifyPortableObject: source.#verifyPortableObject,
130
+ baseUrl: source.#_baseUrl,
131
+ };
132
+ return source.clone({}, options);
133
+ },
134
+ copy(value: object, context: DeepCloneContext): void {
135
+ const node = value as ${type.name};
136
+ const identified = node as { id: URL | null };
137
+ identified.id = context.value(identified.id);
138
+ `;
139
+ } else {
140
+ yield `const base = getDeepCloneDescriptor(this.prototype)!;
141
+ deepCloneDescriptors.set(this.prototype, {
142
+ create: base.create,
143
+ copy(value: object, context: DeepCloneContext): void {
144
+ base.copy(value, context);
145
+ const node = value as ${type.name};
146
+ `;
147
+ }
148
+ for (const property of properties) {
149
+ const field = await getFieldName(property.uri);
150
+ yield `
151
+ {
152
+ const array = node.${field};
153
+ const snapshot = array.length < vocabSparseArrayMinimumLength
154
+ ? undefined : vocabSparseArraySnapshot(array);
155
+ if (snapshot != null) {
156
+ for (const i of snapshot.indices) {
157
+ if (!globalThis.Object.hasOwn(array, i)) continue;
158
+ const value = array[i];
159
+ if (value != null && typeof value === "object") {
160
+ array[i] = context.value(value);
161
+ }
162
+ }
163
+ } else {
164
+ for (let i = 0; i < node.${field}.length; i++) {
165
+ const value = node.${field}[i];
166
+ if (value != null && typeof value === "object") {
167
+ node.${field}[i] = context.value(value);
168
+ }
169
+ }
170
+ }
171
+ }
172
+ `;
173
+ }
174
+ yield `} }); }\n`;
175
+ }
package/src/field.ts CHANGED
@@ -30,7 +30,7 @@ export async function generateField(
30
30
  const trustFieldName = await getFieldName(property.uri, `${prefix}_trust`);
31
31
  return `
32
32
  ${fieldName}: (${typeNames} | URL)[] = [];
33
- ${trustFieldName}: Set<number> = new Set();
33
+ ${trustFieldName}: VocabTrustSet = new Set();
34
34
  `;
35
35
  }
36
36
  }
@@ -0,0 +1,198 @@
1
+ /** Emits module-private sparse property-array validation and copying helpers. */
2
+ export function generatePropertyArrayHelpers(): string {
3
+ return `
4
+ interface VocabSparseArraySnapshot {
5
+ length: number;
6
+ indices: number[];
7
+ }
8
+
9
+ interface VocabArrayValidation {
10
+ valid: boolean;
11
+ sparse: boolean;
12
+ }
13
+
14
+ type VocabArrayCopy<T> = { ok: true; array: T[] } | { ok: false };
15
+
16
+ // Most fields have no trusted prefix. Keep that metadata on the existing Set
17
+ // so empty fields need neither another object nor another instance slot.
18
+ const vocabTrustPrefix: unique symbol = Symbol("vocabulary trust prefix");
19
+ type VocabTrustSet = Set<number> & { [vocabTrustPrefix]?: number };
20
+
21
+ function vocabSetTrustPrefix(trust: VocabTrustSet, prefix: number): void {
22
+ if (prefix > 0) trust[vocabTrustPrefix] = prefix;
23
+ }
24
+
25
+ function vocabCopyTrustSet(
26
+ trust: VocabTrustSet,
27
+ destination: VocabTrustSet,
28
+ ): VocabTrustSet {
29
+ // clone() already constructed the destination. Reuse its empty Set only
30
+ // when constructor defaults cannot contribute trust to the copied field.
31
+ const copy: VocabTrustSet = trust !== destination && trust.size === 0 &&
32
+ destination.size === 0 && destination[vocabTrustPrefix] == null
33
+ ? destination : new Set(trust);
34
+ const prefix = trust[vocabTrustPrefix];
35
+ if (prefix != null && prefix > 0) copy[vocabTrustPrefix] = prefix;
36
+ return copy;
37
+ }
38
+
39
+ // These thresholds select an optimization, not a limit on property arrays.
40
+ const vocabSparseArrayMinimumLength = 4096;
41
+ const vocabSparseArrayProbeCount = 8;
42
+ const vocabSparseArrayPresentProbeLimit = 4;
43
+ const vocabArrayPrototype = Array.prototype;
44
+ const vocabObjectPrototype = globalThis.Object.prototype;
45
+ const vocabArrayDescriptors = ["constructor", "every", "slice"].map(
46
+ key => globalThis.Object.getOwnPropertyDescriptor(vocabArrayPrototype, key),
47
+ );
48
+ const vocabArraySpeciesDescriptor = globalThis.Object.getOwnPropertyDescriptor(
49
+ Array, Symbol.species,
50
+ );
51
+
52
+ function vocabSameArrayDescriptor(
53
+ actual: PropertyDescriptor | undefined,
54
+ expected: PropertyDescriptor | undefined,
55
+ ): boolean {
56
+ return actual?.value === expected?.value && actual?.get === expected?.get &&
57
+ actual?.set === expected?.set && actual?.writable === expected?.writable &&
58
+ actual?.enumerable === expected?.enumerable &&
59
+ actual?.configurable === expected?.configurable;
60
+ }
61
+
62
+ function vocabArrayIndex(key: string): number | undefined {
63
+ const index = Number(key);
64
+ return Number.isInteger(index) && index >= 0 && index < 0xffffffff &&
65
+ String(index) === key
66
+ ? index
67
+ : undefined;
68
+ }
69
+
70
+ function vocabSparseArraySnapshot(
71
+ array: unknown[],
72
+ ): VocabSparseArraySnapshot | undefined {
73
+ if (!Array.isArray(array)) return undefined;
74
+ const length = array.length;
75
+ // Small dense fields take no prototype or key-enumeration overhead.
76
+ if (length < vocabSparseArrayMinimumLength) return undefined;
77
+ if (!Number.isInteger(length) || length > 0xffffffff ||
78
+ globalThis.Object.getPrototypeOf(array) !== vocabArrayPrototype ||
79
+ globalThis.Object.getPrototypeOf(vocabArrayPrototype) !==
80
+ vocabObjectPrototype ||
81
+ globalThis.Object.getPrototypeOf(vocabObjectPrototype) !== null) {
82
+ return undefined;
83
+ }
84
+ const methods = ["constructor", "every", "slice"];
85
+ for (let i = 0; i < methods.length; i++) {
86
+ const key = methods[i];
87
+ if (globalThis.Object.hasOwn(array, key) ||
88
+ !vocabSameArrayDescriptor(
89
+ globalThis.Object.getOwnPropertyDescriptor(vocabArrayPrototype, key),
90
+ vocabArrayDescriptors[i],
91
+ )) return undefined;
92
+ }
93
+ if (!vocabSameArrayDescriptor(
94
+ globalThis.Object.getOwnPropertyDescriptor(Array, Symbol.species),
95
+ vocabArraySpeciesDescriptor,
96
+ )) return undefined;
97
+
98
+ // Descriptor probes do not invoke element getters. Plainly dense arrays
99
+ // keep native iteration without enumerating all their keys.
100
+ let present = 0;
101
+ for (let i = 0; i < vocabSparseArrayProbeCount; i++) {
102
+ const index = Math.floor(i * (length - 1) / (vocabSparseArrayProbeCount - 1));
103
+ if (globalThis.Object.getOwnPropertyDescriptor(array, index) != null &&
104
+ ++present >= vocabSparseArrayPresentProbeLimit) return undefined;
105
+ }
106
+ for (const prototype of [vocabArrayPrototype, vocabObjectPrototype]) {
107
+ for (const key of globalThis.Object.getOwnPropertyNames(prototype)) {
108
+ if (vocabArrayIndex(key) != null) return undefined;
109
+ }
110
+ }
111
+ const indices: number[] = [];
112
+ for (const key of globalThis.Object.getOwnPropertyNames(array)) {
113
+ const index = vocabArrayIndex(key);
114
+ if (index != null && index < length) indices.push(index);
115
+ }
116
+ if (indices.length >= length / 2) return undefined;
117
+ for (const index of indices) {
118
+ const descriptor = globalThis.Object.getOwnPropertyDescriptor(array, index);
119
+ if (descriptor == null || !("value" in descriptor)) return undefined;
120
+ }
121
+ // Ordinary array keys already have canonical index order. This guard is
122
+ // not a Proxy detector; reflection traps and errors remain observable.
123
+ return { length, indices };
124
+ }
125
+
126
+ function vocabValidatePropertyArray<T>(
127
+ array: T[],
128
+ test: (value: T) => boolean,
129
+ ): VocabArrayValidation {
130
+ const snapshot = vocabSparseArraySnapshot(array);
131
+ if (snapshot == null) return { valid: array.every(test), sparse: false };
132
+ for (const index of snapshot.indices) {
133
+ if (globalThis.Object.hasOwn(array, index) && !test(array[index])) {
134
+ return { valid: false, sparse: true };
135
+ }
136
+ }
137
+ return { valid: true, sparse: true };
138
+ }
139
+
140
+ function vocabDefineArrayEntry<T>(array: T[], index: number, value: T): void {
141
+ globalThis.Object.defineProperty(array, index, {
142
+ value, writable: true, enumerable: true, configurable: true,
143
+ });
144
+ }
145
+
146
+ function vocabCopySparsePropertyArray<T>(
147
+ array: T[],
148
+ snapshot: VocabSparseArraySnapshot,
149
+ test?: (value: T) => boolean,
150
+ ): VocabArrayCopy<T> {
151
+ const copy: T[] = [];
152
+ // Seed dictionary storage before low indices or the final length can
153
+ // allocate storage for every hole. The temporary entry stays private.
154
+ if (snapshot.indices[snapshot.indices.length - 1] !== snapshot.length - 1) {
155
+ globalThis.Object.defineProperty(copy, snapshot.length - 1, {
156
+ value: undefined, writable: true, enumerable: true, configurable: true,
157
+ });
158
+ delete copy[snapshot.length - 1];
159
+ }
160
+ for (const index of snapshot.indices) {
161
+ if (!globalThis.Object.hasOwn(array, index)) continue;
162
+ const value = array[index];
163
+ if (test != null && !test(value)) return { ok: false };
164
+ vocabDefineArrayEntry(copy, index, value);
165
+ }
166
+ // A validation callback may have deleted the last snapshot entry.
167
+ if (copy.length < snapshot.length) {
168
+ globalThis.Object.defineProperty(copy, snapshot.length - 1, {
169
+ value: undefined, writable: true, enumerable: true, configurable: true,
170
+ });
171
+ delete copy[snapshot.length - 1];
172
+ }
173
+ copy.length = snapshot.length;
174
+ return { ok: true, array: copy };
175
+ }
176
+
177
+ function vocabCopyPropertyArray<T>(array: T[]): T[] {
178
+ const snapshot = vocabSparseArraySnapshot(array);
179
+ if (snapshot == null) return array.slice();
180
+ const copied = vocabCopySparsePropertyArray(array, snapshot);
181
+ // Without a predicate the private copy cannot fail validation.
182
+ return (copied as { ok: true; array: T[] }).array;
183
+ }
184
+
185
+ function vocabCopyValidatedPropertyArray<T>(
186
+ array: T[],
187
+ test: (value: T) => boolean,
188
+ previous: VocabArrayValidation,
189
+ ): VocabArrayCopy<T> {
190
+ const snapshot = vocabSparseArraySnapshot(array);
191
+ if (snapshot != null) return vocabCopySparsePropertyArray(array, snapshot, test);
192
+ // Sparse validation may have changed the next input's density, descriptors
193
+ // or prototype. Validate that native-copy input before falling back.
194
+ if (previous.sparse && !array.every(test)) return { ok: false };
195
+ return { ok: true, array: array.slice() };
196
+ }
197
+ `;
198
+ }
package/src/property.ts CHANGED
@@ -442,7 +442,11 @@ async function* generateProperty(
442
442
  }
443
443
  let v = this.${await getFieldName(property.uri)}[0];
444
444
  if (!(v instanceof URL) &&
445
- !this.${await getFieldName(property.uri, "#_trust")}.has(0)) {
445
+ !(0 < (this.${await getFieldName(
446
+ property.uri,
447
+ "#_trust",
448
+ )}[vocabTrustPrefix] ?? 0) ||
449
+ this.${await getFieldName(property.uri, "#_trust")}.has(0))) {
446
450
  if (v.id == null) {
447
451
  if (isUnsecuredPortableObject(this)) {
448
452
  warnUnverifiableEmbeddedObject(this, ${
@@ -514,7 +518,11 @@ async function* generateProperty(
514
518
  mustDereferencePortableObject(
515
519
  this, ${trustOwner}, v.id, options,
516
520
  )) &&
517
- !this.${await getFieldName(property.uri, "#_trust")}.has(0)) {
521
+ !(0 < (this.${await getFieldName(
522
+ property.uri,
523
+ "#_trust",
524
+ )}[vocabTrustPrefix] ?? 0) ||
525
+ this.${await getFieldName(property.uri, "#_trust")}.has(0))) {
518
526
  if (options.crossOrigin === "throw") {
519
527
  throw new Error(
520
528
  "The property object's @id (" + v.id.href + ") has a different " +
@@ -611,7 +619,11 @@ async function* generateProperty(
611
619
  for (let i = 0; i < vs.length; i++) {
612
620
  let v = vs[i];
613
621
  if (!(v instanceof URL) &&
614
- !this.${await getFieldName(property.uri, "#_trust")}.has(i)) {
622
+ !(i < (this.${await getFieldName(
623
+ property.uri,
624
+ "#_trust",
625
+ )}[vocabTrustPrefix] ?? 0) ||
626
+ this.${await getFieldName(property.uri, "#_trust")}.has(i))) {
615
627
  if (v.id == null) {
616
628
  if (isUnsecuredPortableObject(this)) {
617
629
  warnUnverifiableEmbeddedObject(this, ${
@@ -689,7 +701,11 @@ async function* generateProperty(
689
701
  mustDereferencePortableObject(
690
702
  this, ${trustOwner}, v.id, options,
691
703
  )) &&
692
- !this.${await getFieldName(property.uri, "#_trust")}.has(i)) {
704
+ !(i < (this.${await getFieldName(
705
+ property.uri,
706
+ "#_trust",
707
+ )}[vocabTrustPrefix] ?? 0) ||
708
+ this.${await getFieldName(property.uri, "#_trust")}.has(i))) {
693
709
  if (options.crossOrigin === "throw") {
694
710
  throw new Error(
695
711
  "The property object's @id (" + v.id.href + ") has a different " +