devalue

  • Version 6.0.3
  • Published
  • 135 kB
  • No dependencies
  • MIT license

Install

npm i devalue
yarn add devalue
pnpm add devalue

Overview

Gets the job done when JSON.stringify can't

Index

Variables

variable defaultParseOperations

const defaultParseOperations: Readonly<DefaultParseOperations>;

    variable defaultStringifyOperations

    const defaultStringifyOperations: Readonly<DefaultStringifyOperations>;

      Functions

      function filterArrayIndices

      filterArrayIndices: (keys: readonly string[]) => string[];
      • Given the own enumerable string keys of an array-like value, in property order, returns the leading run of them that are valid array indices.

        This is the filtering half of the indicesOf stringify operation, exposed so that custom operations — which typically already have the keys in hand, e.g. from a foreign runtime — don't have to reimplement it.

        Does not modify keys.

        Parameter keys

        Returns

        {string[]}

      function parse

      parse: (
      serialized: string,
      revivers?: Record<string, (value: any) => any>,
      options?: import('./types.js').ParseOptions
      ) => any;
      • Revive a value serialized with devalue.stringify

        Parameter serialized

        Parameter revivers

        Parameter options

      function stringify

      stringify: (
      value: any,
      reducers?: Record<string, (value: any) => any>,
      options?: import('./types.js').StringifyOptions
      ) => string;
      • Turn a value into a JSON string that can be parsed with devalue.parse

        Parameter value

        Parameter reducers

        Parameter options

      function stringifyAsync

      stringifyAsync: (
      value: any,
      reducers?: Record<string, (value: any) => any>,
      options?: import('./types.js').StringifyOptions
      ) => Promise<string>;
      • Turn a value into a JSON string that can be parsed with devalue.parse

        Parameter value

        Parameter reducers

        Parameter options

      function uneval

      uneval: (value: any, replacer?: UnevalReplacer) => string;
      • Turn a value into the JavaScript that creates an equivalent value

        Parameter value

        Parameter replacer

      function unflatten

      unflatten: (
      parsed: number | any[],
      revivers?: Record<string, (value: any) => any>,
      options?: import('./types.js').ParseOptions
      ) => any;
      • Revive a value flattened with devalue.stringify

        Parameter parsed

        Parameter revivers

        Parameter options

      Classes

      class DevalueError

      class DevalueError extends Error {}

        constructor

        constructor(message: string, keys: string[], value?: any, root?: any);
        • Parameter message

          Parameter keys

          Parameter value

          The value that failed to be serialized

          Parameter root

          The root value being serialized

        property path

        path: string;

          property root

          root: any;

            property value

            value: any;

              Interfaces

              interface DefaultParseOperations

              interface DefaultParseOperations extends ParseOperations {}
              • The native JavaScript implementation exported as defaultParseOperations.

              method addEntry

              addEntry: (map: Map<any, any>, key: any, value: any) => void;

                method addValue

                addValue: (set: Set<any>, value: any) => void;

                  method box

                  box: (value: any) => object;

                    method createArray

                    createArray: (length: number) => any[];

                      method createMap

                      createMap: () => Map<any, any>;

                        method createNullPrototypeObject

                        createNullPrototypeObject: () => Record<string, any>;

                          method createObject

                          createObject: () => Record<string, any>;

                            method createSet

                            createSet: () => Set<any>;

                              method createSparseArray

                              createSparseArray: (length: number) => any[];

                                method fromArrayBuffer

                                fromArrayBuffer: (buffer: ArrayBuffer) => ArrayBuffer;

                                  method fromISOString

                                  fromISOString: (iso: string) => Date;

                                    method fromPrimitive

                                    fromPrimitive: (
                                    primitive: string | number | boolean | bigint | null | undefined
                                    ) => string | number | boolean | bigint | null | undefined;

                                      method fromRegExpInfo

                                      fromRegExpInfo: (source: string, flags: string | undefined) => RegExp;

                                        method fromStringValue

                                        fromStringValue: (
                                        tag: StringValueTag,
                                        text: string
                                        ) => URL | URLSearchParams | object;

                                          method fromViewInfo

                                          fromViewInfo: (
                                          tag: ViewTag,
                                          buffer: ArrayBufferLike,
                                          byteOffset: number | undefined,
                                          length: number | undefined
                                          ) => TypedArray | DataView;

                                            interface DefaultStringifyOperations

                                            interface DefaultStringifyOperations extends StringifyOperations {}
                                            • The native JavaScript implementation exported as defaultStringifyOperations.

                                            method entriesOf

                                            entriesOf: (map: Map<any, any>) => Map<any, any>;

                                              method identify

                                              identify: (value: any) => any;

                                                method indicesOf

                                                indicesOf: (array: any[]) => string[];

                                                  method lengthOf

                                                  lengthOf: (array: any[]) => number;

                                                    method regExpInfo

                                                    regExpInfo: (regexp: RegExp) => { source: string; flags: string };

                                                      method toArrayBuffer

                                                      toArrayBuffer: (buffer: ArrayBuffer) => ArrayBuffer;

                                                        method toISOString

                                                        toISOString: (date: Date) => string;

                                                          method toPrimitive

                                                          toPrimitive: (
                                                          value: undefined | null | boolean | number | bigint | string
                                                          ) => undefined | null | boolean | number | bigint | string;

                                                            method valuesOf

                                                            valuesOf: (set: Set<any>) => Set<any>;

                                                              method viewInfo

                                                              viewInfo: (view: any) => {
                                                              buffer: ArrayBufferLike;
                                                              byteOffset: number;
                                                              byteLength: number;
                                                              length?: number;
                                                              bufferByteLength: number;
                                                              };

                                                                interface JavaScriptTag

                                                                interface JavaScriptTag {}
                                                                • A tagged template function for building trusted JavaScript. The string bits are emitted verbatim, while the "holes" are recursively serialized. Identifier-like words in the string bits are reserved when generating names.

                                                                call signature

                                                                (strings: TemplateStringsArray, ...values: unknown[]): JavaScriptFragment;

                                                                  interface ParseOperations

                                                                  interface ParseOperations {}
                                                                  • The construction operations parse and unflatten perform while reviving a value. Every value the algorithm creates — primitives, built-in instances, containers — and every mutation it performs to populate those containers goes through this interface, so overriding members lets you control exactly what gets built.

                                                                    Use cases: - **Cross-realm revival**: construct values from the intrinsics of a different realm (e.g. a node:vm context) so that the result passes instanceof checks inside that realm. - **Foreign-runtime revival**: build values inside another JavaScript runtime (a WASM-hosted engine, a remote process) by implementing the operations over handle objects. The algorithm never inspects the values it creates — it only passes them back into other operations — so "value" can be any opaque token.

                                                                    The naming follows the same scheme as StringifyOperations, with the host/value-space boundary running the other way:

                                                                    - fromXxx — conversions whose input is entirely host data and whose result crosses into value space; each is the inverse of the corresponding toXxx (fromPrimitive / toPrimitive, fromISOString / toISOString, fromStringValue / toStringValue, fromArrayBuffer / toArrayBuffer). - fromXxxInfo — construction from a multi-field descriptor, the inverse of the corresponding xxxInfo (fromRegExpInfo / regExpInfo, fromViewInfo / viewInfo). - createXxx — empty value-space containers, populated afterwards by the mutators. That ordering is what makes cyclic values possible: the empty container is cached before its contents are revived. - bare verbs — value-space operations whose operands and results stay in value space (box inverts unbox, set inverts get, addValue inverts valuesOf, addEntry inverts entriesOf).

                                                                    All members are optional when passed to parse/unflatten — omitted members fall back to the defaults (native behavior, exported as defaultParseOperations).

                                                                  method addEntry

                                                                  addEntry: (map: any, key: any, value: any) => void;
                                                                  • Adds an entry to a Map created by createMap. The inverse of entriesOf.

                                                                  method addValue

                                                                  addValue: (set: any, value: any) => void;
                                                                  • Adds a value to a Set created by createSet. The inverse of valuesOf.

                                                                  method box

                                                                  box: (value: any) => any;
                                                                  • Creates a boxed primitive object (Number, String, Boolean, BigInt wrapper) around an already-revived inner primitive. The inverse of unbox. Equivalent to Object(value).

                                                                  method createArray

                                                                  createArray: (length: number) => any;
                                                                  • Creates an array of the given length, to be populated with set. The length is bounded by the size of the input, so it is safe to allocate eagerly. Indices that are never set must remain holes.

                                                                  method createMap

                                                                  createMap: () => any;
                                                                  • Creates an empty Map, to be populated with addEntry.

                                                                  method createNullPrototypeObject

                                                                  createNullPrototypeObject: () => any;
                                                                  • Creates an empty null-prototype object, to be populated with set. Equivalent to Object.create(null).

                                                                  method createObject

                                                                  createObject: () => any;
                                                                  • Creates an empty object, to be populated with set.

                                                                  method createSet

                                                                  createSet: () => any;
                                                                  • Creates an empty Set, to be populated with addValue.

                                                                  method createSparseArray

                                                                  createSparseArray: (length: number) => any;
                                                                  • Creates a sparse array of the given length, to be populated with set. Unlike createArray, the length comes from the input rather than being bounded by it, so implementations must not allocate storage proportional to it.

                                                                  method fromArrayBuffer

                                                                  fromArrayBuffer: (buffer: ArrayBuffer) => any;
                                                                  • Creates an ArrayBuffer from a host ArrayBuffer holding the decoded bytes. The inverse of toArrayBuffer. Default: the buffer itself. Foreign-runtime implementations should copy the bytes into the target runtime.

                                                                  method fromISOString

                                                                  fromISOString: (iso: string) => any;
                                                                  • Creates a Date from an ISO string. The inverse of toISOString. An empty string represents an invalid date (as produced for new Date(NaN)).

                                                                  method fromPrimitive

                                                                  fromPrimitive: (
                                                                  primitive: string | number | boolean | bigint | null | undefined
                                                                  ) => any;
                                                                  • Wraps a host primitive (string, number, boolean, bigint, null, undefined, and the special values NaN, ±Infinity, -0) into the representation the other operations expect. The inverse of toPrimitive. Default: the value itself.

                                                                  method fromRegExpInfo

                                                                  fromRegExpInfo: (source: string, flags: string | undefined) => any;
                                                                  • Creates a RegExp from its source and flags. The inverse of regExpInfo. flags is undefined when the pattern had no flags.

                                                                  method fromStringValue

                                                                  fromStringValue: (tag: StringValueTag, text: string) => any;
                                                                  • Creates a URL, URLSearchParams or Temporal.* value from its string form — the same tags toStringValue serializes, and its inverse. tag distinguishes them (e.g. 'URL', 'Temporal.Instant').

                                                                  method fromViewInfo

                                                                  fromViewInfo: (
                                                                  tag: ViewTag,
                                                                  buffer: any,
                                                                  byteOffset: number | undefined,
                                                                  length: number | undefined
                                                                  ) => any;
                                                                  • Creates a typed array or DataView over an already-revived buffer. The inverse of viewInfo. tag is the constructor name (e.g. 'Uint8Array', 'DataView'). byteOffset and length are undefined when the view spans the whole buffer; otherwise length is the element count for typed arrays and the byte length for DataView, matching the constructor signatures.

                                                                    Implementations must validate that buffer represents a genuine backing buffer, since custom revivers can return other values. In particular, passing a number or array-like value to a native typed array constructor can allocate storage unrelated to the size of the serialized input.

                                                                  method set

                                                                  set: (target: any, key: string | number, value: any) => void;
                                                                  • Sets an element or property on a value created by createArray, createSparseArray, createObject or createNullPrototypeObject. The inverse of get, which likewise serves both arrays and objects.

                                                                  interface ParseOptions

                                                                  interface ParseOptions {}
                                                                  • Options for parse and unflatten.

                                                                  property operations

                                                                  operations?: Partial<ParseOperations>;
                                                                  • Overrides for the construction operations used while reviving. Omitted members fall back to defaultParseOperations.

                                                                  interface StringifyOperations

                                                                  interface StringifyOperations {}
                                                                  • The introspection/extraction operations stringify performs on the value being serialized. Every dynamic operation — property reads, prototype method calls, iteration, type classification — goes through this interface, so overriding members lets you control exactly how values are inspected.

                                                                    Use cases: - **Side-effect-free serialization**: replace operations that can execute user code (getters, proxy traps, patched prototypes, Symbol.toStringTag accessors) with implementations based on captured intrinsics, internal slots, or property descriptors. - **Foreign-runtime serialization**: serialize values that live in another JavaScript runtime (a node:vm context, a WASM-hosted engine, a remote process) by implementing the operations over handle objects. The stringify algorithm never touches the value directly, so "value" can be any opaque token as long as the operations agree on what it means.

                                                                    All members are optional when passed to stringify — omitted members fall back to the defaults (native behavior, exported as defaultStringifyOperations).

                                                                    Members are named by what they do with the value: - isXxx/hasXxx — predicates returning booleans - toXxx — conversions whose whole result crosses into host JavaScript (toPrimitive, toISOString) or into a native container (toPromise) - xxxOf — queries returning host data *about* the value (typeOf, tagOf, lengthOf) or its constituents, which remain in value space (valuesOf, entriesOf) - xxxInfo — multi-field descriptors mixing host data and constituent values (viewInfo, regExpInfo) - bare verbs (get, unbox, identify) — accessors whose results remain in value space

                                                                    (toStringValue and unbox deliberately avoid the names toString and valueOf, which would shadow Object.prototype methods on the operations object.)

                                                                  method entriesOf

                                                                  entriesOf: (map: any) => Iterable<[any, any]>;
                                                                  • Returns an iterable over the [key, value] entries of a Map value. The iterable is consumed on the host; keys/values may be foreign values/handles.

                                                                  method get

                                                                  get: (value: any, key: string | number) => any;
                                                                  • Reads a property from an Array or plain-object value. Equivalent to value[key]. Hardened implementations can read through property descriptors to control what happens for accessor properties.

                                                                  method hasOwn

                                                                  hasOwn: (value: any, key: string | number) => boolean;
                                                                  • Returns true if a value has an own property at key. Same contract as Object.hasOwn(value, key).

                                                                  method identify

                                                                  identify: (value: any) => unknown;
                                                                  • Returns the key used for deduplication and cycle detection (compared with Map key semantics). Two values that represent the same logical object must return the same key. Default: the value itself.

                                                                    Override this when serializing through handles, where two distinct handle objects may refer to the same underlying value.

                                                                    Keys are compared across *every* value in the payload, including primitives, so an implementation that derives keys for objects must make sure they cannot collide with a primitive that appears in the same payload — returning e.g. the string '42' as an object's key would alias it to the string '42' elsewhere in the payload and emit a wrong back-reference. Prefer keys that are unforgeable, such as the underlying object itself, a symbol, or a wrapper object.

                                                                  method indicesOf

                                                                  indicesOf: (array: any) => string[];
                                                                  • Returns the populated indices of a (sparse) Array value as strings, in ascending order.

                                                                    Implementations that already have the value's own enumerable string keys — as a foreign-runtime implementation typically does — should pass them through the exported filterArrayIndices helper rather than reimplementing the filtering, which encodes the sparse-array heuristic.

                                                                    Equivalent to Object.keys(array) filtered to valid array indices.

                                                                  method isThenable

                                                                  isThenable: (value: any) => boolean;
                                                                  • Returns true if the object value should be treated as a thenable.

                                                                  method lengthOf

                                                                  lengthOf: (array: any) => number;
                                                                  • Returns the length of an Array value.

                                                                  method regExpInfo

                                                                  regExpInfo: (regexp: any) => { source: string; flags: string };
                                                                  • Returns the source and flags of a RegExp value.

                                                                  method shapeOf

                                                                  shapeOf: (
                                                                  value: any
                                                                  ) =>
                                                                  | { kind: 'plain' | 'null-proto'; keys: string[] }
                                                                  | { kind: 'not-plain' }
                                                                  | { kind: 'symbol-keys' };
                                                                  • Classifies a plain-object candidate: - { kind: 'plain' | 'null-proto', keys } — a serializable POJO and its own enumerable string keys - { kind: 'not-plain' } — a non-POJO (stringify throws) - { kind: 'symbol-keys' } — a POJO with enumerable symbol keys (stringify throws)

                                                                  method tagOf

                                                                  tagOf: (value: any) => string;
                                                                  • Returns the brand of an object value — the strings produced by Object.prototype.toString without the wrapping ('Date', 'Array', 'Map', 'Object', 'Temporal.Instant', …). This decides which serialization strategy is used, so hardened implementations should use engine-level brand checks rather than (spoofable, getter-invoking) Symbol.toStringTag lookups.

                                                                  method toArrayBuffer

                                                                  toArrayBuffer: (buffer: any) => ArrayBuffer;
                                                                  • Returns a host ArrayBuffer with the bytes of an ArrayBuffer value. Default: the value itself. Foreign-runtime implementations should copy the bytes into a host buffer.

                                                                  method toISOString

                                                                  toISOString: (date: any) => string;
                                                                  • Returns the ISO string for a Date value, or '' for an invalid date. Equivalent to date.toISOString().

                                                                  method toPrimitive

                                                                  toPrimitive: (
                                                                  value: any
                                                                  ) => undefined | null | boolean | number | bigint | string;
                                                                  • Extracts the host-JavaScript primitive from a value whose typeOf is 'null', 'boolean', 'number', 'bigint' or 'string'. Default: the value itself (it already is the primitive).

                                                                  method toPromise

                                                                  toPromise: (thenable: any) => Promise<any>;
                                                                  • Converts a thenable into a native promise, whose settled value is then serialized. The returned promise may reject, in which case stringifyAsync rejects. Only called from stringifyAsync, for values where isThenable returned true.

                                                                  method toStringValue

                                                                  toStringValue: (value: any) => string;
                                                                  • Returns the string form of a URL, URLSearchParams or Temporal.* value. Equivalent to value.toString().

                                                                  method typeOf

                                                                  typeOf: (
                                                                  value: any
                                                                  ) =>
                                                                  | 'undefined'
                                                                  | 'null'
                                                                  | 'boolean'
                                                                  | 'number'
                                                                  | 'bigint'
                                                                  | 'string'
                                                                  | 'symbol'
                                                                  | 'function'
                                                                  | 'object';
                                                                  • Classifies a value. Same contract as the typeof operator, except null must be reported as 'null' (not 'object').

                                                                  method unbox

                                                                  unbox: (boxed: any) => any;
                                                                  • Extracts the inner value of a boxed primitive (Number, String, Boolean, BigInt objects). Equivalent to boxed.valueOf(). The result is serialized recursively, so it may be a foreign value/handle.

                                                                  method valuesOf

                                                                  valuesOf: (set: any) => Iterable<any>;
                                                                  • Returns an iterable over the elements of a Set value. The iterable is consumed on the host; elements may be foreign values/handles.

                                                                  method viewInfo

                                                                  viewInfo: (view: any) => {
                                                                  buffer: any;
                                                                  byteOffset: number;
                                                                  byteLength: number;
                                                                  length?: number;
                                                                  bufferByteLength: number;
                                                                  };
                                                                  • Returns the view metadata of a typed array or DataView value. length is only meaningful for typed arrays. buffer is serialized recursively in full, so it may be a foreign value/handle. The default copies Node Buffers into an exact-sized backing buffer with byteOffset 0 to avoid exposing unrelated bytes from Node's shared pool. Overrides must take equivalent care with pooled views.

                                                                  interface StringifyOptions

                                                                  interface StringifyOptions {}
                                                                  • Options for stringify and stringifyAsync.

                                                                  property operations

                                                                  operations?: Partial<StringifyOperations>;
                                                                  • Overrides for the introspection/extraction operations used while serializing. Omitted members fall back to defaultStringifyOperations.

                                                                  Type Aliases

                                                                  type JavaScriptFragment

                                                                  type JavaScriptFragment = {
                                                                  readonly [SOURCE]: JavaScriptSource;
                                                                  };

                                                                    type StringValueTag

                                                                    type StringValueTag =
                                                                    | 'URL'
                                                                    | 'URLSearchParams'
                                                                    | 'Temporal.Duration'
                                                                    | 'Temporal.Instant'
                                                                    | 'Temporal.PlainDate'
                                                                    | 'Temporal.PlainTime'
                                                                    | 'Temporal.PlainDateTime'
                                                                    | 'Temporal.PlainMonthDay'
                                                                    | 'Temporal.PlainYearMonth'
                                                                    | 'Temporal.ZonedDateTime';

                                                                      type TypedArray

                                                                      type TypedArray =
                                                                      | Int8Array
                                                                      | Uint8Array
                                                                      | Uint8ClampedArray
                                                                      | Int16Array
                                                                      | Uint16Array
                                                                      | Float16Array
                                                                      | Int32Array
                                                                      | Uint32Array
                                                                      | Float32Array
                                                                      | Float64Array
                                                                      | BigInt64Array
                                                                      | BigUint64Array;

                                                                        type UnevalReplacer

                                                                        type UnevalReplacer = (
                                                                        value: unknown,
                                                                        js: JavaScriptTag
                                                                        ) => JavaScriptFragment | false | null | void;
                                                                        • A function that replaces a value with a JavaScript expression that can be evaluated to reproduce that value. The expression is trusted JavaScript. Return undefined, null or false when the value should be serialized normally.

                                                                        type ViewTag

                                                                        type ViewTag =
                                                                        | 'Int8Array'
                                                                        | 'Uint8Array'
                                                                        | 'Uint8ClampedArray'
                                                                        | 'Int16Array'
                                                                        | 'Uint16Array'
                                                                        | 'Float16Array'
                                                                        | 'Int32Array'
                                                                        | 'Uint32Array'
                                                                        | 'Float32Array'
                                                                        | 'Float64Array'
                                                                        | 'BigInt64Array'
                                                                        | 'BigUint64Array'
                                                                        | 'DataView';

                                                                          Package Files (7)

                                                                          Dependencies (0)

                                                                          No dependencies.

                                                                          Dev Dependencies (8)

                                                                          Peer Dependencies (0)

                                                                          No peer dependencies.

                                                                          Badge

                                                                          To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                          You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/devalue.

                                                                          • Markdown
                                                                            [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/devalue)
                                                                          • HTML
                                                                            <a href="https://www.jsdocs.io/package/devalue"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>