All files / src/internal/views/read-only registry.ts

100% Statements 10/10
100% Branches 10/10
100% Functions 2/2
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                                                                              22560x 22556x 22556x                     43316x 43311x 43309x    
// The read-only views this copy of the library built. Each read-only constructor records its view
// here, so the unmodifiable-view functions can recognise one by identity: an object made from a
// view's prototype without running a constructor, a `Proxy` around a view, and a view from another
// loaded copy are all absent. Keys are held weakly, so views are collected as usual.
 
import { createWeakMap, stringSlice, weakMapGet, weakMapSet } from '../../intrinsics'
 
/** The family a read-only view belongs to. @internal */
export type ReadOnlyKind =
  | 'collection'
  | 'sequenced-collection'
  | 'list'
  | 'set'
  | 'sequenced-set'
  | 'sorted-set'
  | 'map'
  | 'sequenced-map'
  | 'sorted-map'
 
/** What a registered read-only view is made of. @internal */
export interface ReadOnlyParts {
  /** The collection or map the view reads. */
  readonly source: object
  readonly kind: ReadOnlyKind
  /** The name the view prints with. */
  readonly printed: string
  /** Whether the view is an unmodifiable view (`false` for an immutable collection). */
  readonly unmodifiable: boolean
  /** Maps each member before it is handed out, when the view does so. */
  readonly reveal: ((member: unknown) => unknown) | undefined
}
 
let registry: WeakMap<object, ReadOnlyParts> | undefined
 
/**
 * Records `view` as a read-only view of `kind` reading `source`, printed as `printed`. A view
 * whose `kind` is `undefined` (an instance of a class the library did not define) is not recorded.
 *
 * @internal
 */
export function registerReadOnly(
  view: object,
  kind: ReadOnlyKind | undefined,
  source: object,
  printed: string,
  reveal?: (member: never) => unknown,
): void {
  if (kind === undefined) return
  if (registry === undefined) registry = createWeakMap<object, ReadOnlyParts>()
  weakMapSet(registry, view, {
    source,
    kind,
    printed,
    unmodifiable: stringSlice(printed, 0, 12) === 'Unmodifiable',
    reveal: reveal as ((member: unknown) => unknown) | undefined,
  })
}
 
/** The parts of `value` when it is a read-only view this copy built, else `undefined`. @internal */
export function readOnlyParts(value: unknown): ReadOnlyParts | undefined {
  if (registry === undefined) return undefined
  if (typeof value !== 'object' || value === null) return undefined
  return weakMapGet(registry, value)
}