{"name":"devalue","version":"5.3.2","license":"MIT","_id":"devalue@5.3.2","maintainers":[{"name":"rich_harris","email":"richard.a.harris@gmail.com"},{"name":"svelte-admin","email":"richard.a.harris+svelte@gmail.com"}],"homepage":"https://github.com/sveltejs/devalue#readme","bugs":{"url":"https://github.com/sveltejs/devalue/issues"},"dist":{"shasum":"1d9a00f0d126a2f768589f236da8b67d6988d285","tarball":"http://registry-npm.ywwl.com/devalue/download/devalue-5.3.2.tgz","fileCount":13,"integrity":"sha512-UDsjUbpQn9kvm68slnrs+mfxwFkIflOhkanmyabZ8zOYk8SMEIbJ3TK+88g70hSIeytu4y18f0z/hYHMTrXIWw==","signatures":[{"sig":"MEQCIBpRSiV8QtfMTljA/htjl/JAH4fUpkruSRGj9GH0xEWqAiBr9Nz8SQeswt/U4fMgRllo42nMEvK4E5F30jkIXjQMSQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/devalue@5.3.2","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":34886,"size":10815,"noattachment":false,"key":"/devalue/-/devalue-5.3.2.tgz"},"type":"module","_from":"file:devalue-5.3.2.tgz","types":"./types/index.d.ts","exports":{".":{"types":"./types/index.d.ts","import":"./index.js","default":"./index.js"}},"scripts":{"test":"uvu test","build":"dts-buddy","changeset:publish":"changeset publish","changeset:version":"changeset version"},"_npmUser":{"name":"svelte-admin","email":"richard.a.harris+svelte@gmail.com"},"_resolved":"/tmp/e38cf9b6f6bcef7719b325131253a659/devalue-5.3.2.tgz","_integrity":"sha512-UDsjUbpQn9kvm68slnrs+mfxwFkIflOhkanmyabZ8zOYk8SMEIbJ3TK+88g70hSIeytu4y18f0z/hYHMTrXIWw==","repository":{"url":"git+https://github.com/sveltejs/devalue.git","type":"git"},"_npmVersion":"10.8.2","description":"Gets the job done when JSON.stringify can't","directories":{},"sideEffects":false,"_nodeVersion":"18.20.8","_hasShrinkwrap":false,"packageManager":"pnpm@8.15.9","devDependencies":{"uvu":"^0.5.6","publint":"^0.3.12","dts-buddy":"^0.6.2","typescript":"^5.9.2","@changesets/cli":"^2.29.6","@js-temporal/polyfill":"^0.5.1"},"_npmOperationalInternal":{"tmp":"tmp/devalue_5.3.2_1756246107483_0.7709333957574955","host":"s3://npm-registry-packages-npm-production"},"readme":"# devalue\n\nLike `JSON.stringify`, but handles\n\n- cyclical references (`obj.self = obj`)\n- repeated references (`[value, value]`)\n- `undefined`, `Infinity`, `NaN`, `-0`\n- regular expressions\n- dates\n- `Map` and `Set`\n- `BigInt`\n- `ArrayBuffer` and Typed Arrays\n- `URL` and `URLSearchParams`\n- `Temporal`\n- custom types via replacers, reducers and revivers\n- promises (via `stringifyAsync`)\n\nTry it out [here](https://svelte.dev/repl/138d70def7a748ce9eda736ef1c71239?version=3.49.0).\n\n## Goals:\n\n- Performance\n- Security (see [XSS mitigation](#xss-mitigation))\n- Compact output\n\n## Non-goals:\n\n- Human-readable output\n- Stringifying functions\n- Stability of serialization mechanisms between versions (i.e. if you `devalue.stringify` with one version and `devalue.parse` with another, things may break)\n\n## Usage\n\nThere are two ways to use `devalue`:\n\n### `uneval`\n\nThis function takes a JavaScript value and returns the JavaScript code to create an equivalent value — sort of like `eval` in reverse:\n\n```js\nimport * as devalue from 'devalue';\n\nlet obj = { message: 'hello' };\ndevalue.uneval(obj); // '{message:\"hello\"}'\n\nobj.self = obj;\ndevalue.uneval(obj); // '(function(a){a.message=\"hello\";a.self=a;return a}({}))'\n```\n\nUse `uneval` when you want the most compact possible output and don't want to include any code for parsing the serialized value.\n\n### `stringify` and `parse`\n\nThese two functions are analogous to `JSON.stringify` and `JSON.parse`:\n\n```js\nimport * as devalue from 'devalue';\n\nlet obj = { message: 'hello' };\n\nlet stringified = devalue.stringify(obj); // '[{\"message\":1},\"hello\"]'\ndevalue.parse(stringified); // { message: 'hello' }\n\nobj.self = obj;\n\nstringified = devalue.stringify(obj); // '[{\"message\":1,\"self\":0},\"hello\"]'\ndevalue.parse(stringified); // { message: 'hello', self: [Circular] }\n```\n\nUse `stringify` and `parse` when evaluating JavaScript isn't an option.\n\n### `stringifyAsync`\n\n`stringifyAsync` is an async version of `stringify` that can handle promises:\n\n```js\nimport * as devalue from 'devalue';\n\nlet obj = {\n\tquick: 'data',\n\tslow: fetch('/api/slow').then((r) => r.json())\n};\n\nlet stringified = await devalue.stringifyAsync(obj);\ndevalue.parse(stringified); // { quick: 'data', slow: { ... } }\n```\n\nPromises are awaited and their resolved values are serialized. The output format is identical to `stringify`, so `parse` and `unflatten` work unchanged.\n\n### `unflatten`\n\nIn the case where devalued data is one part of a larger JSON string, `unflatten` allows you to revive just the bit you need:\n\n```js\nimport * as devalue from 'devalue';\n\nconst json = `{\n  \"type\": \"data\",\n  \"data\": ${devalue.stringify(data)}\n}`;\n\nconst data = devalue.unflatten(JSON.parse(json).data);\n```\n\n## Custom types\n\nYou can serialize and deserialize custom types by passing a second argument to `stringify` containing an object of types and their _reducers_, and a second argument to `parse` or `unflatten` containing an object of types and their _revivers_:\n\n```js\nclass Vector {\n\tconstructor(x, y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\tmagnitude() {\n\t\treturn Math.sqrt(this.x * this.x + this.y * this.y);\n\t}\n}\n\nconst stringified = devalue.stringify(new Vector(30, 40), {\n\tVector: (value) => value instanceof Vector && [value.x, value.y]\n});\n\nconsole.log(stringified); // [[\"Vector\",1],[2,3],30,40]\n\nconst vector = devalue.parse(stringified, {\n\tVector: ([x, y]) => new Vector(x, y)\n});\n\nconsole.log(vector.magnitude()); // 50\n```\n\nIf a function passed to `stringify` returns a truthy value, it's treated as a match.\n\nYou can also use custom types with `uneval` by specifying a custom replacer:\n\n```js\ndevalue.uneval(vector, (value, uneval) => {\n\tif (value instanceof Vector) {\n\t\treturn `new Vector(${value.x},${value.y})`;\n\t}\n}); // `new Vector(30,40)`\n```\n\nNote that any variables referenced in the resulting JavaScript (like `Vector` in the example above) must be in scope when it runs.\n\n## Custom operations\n\nEvery introspection `stringify` performs on the value being serialized — property reads, prototype method calls, iteration, type classification — goes through an operations interface that you can override via the `operations` option. Omitted members fall back to the defaults (exported as `defaultStringifyOperations`), which behave exactly as devalue always has.\n\nThis is useful in two situations:\n\n**Side-effect-free serialization.** By default, serializing a value can execute user code: getters and proxy traps fire during property reads, `Object.prototype.toString` consults (potentially getter-defined) `Symbol.toStringTag`, and patched prototype methods like `Date.prototype.toISOString` or `Map.prototype[Symbol.iterator]` are invoked. Deterministic or sandboxed runtimes can replace these operations with implementations based on captured intrinsics and property descriptors:\n\n```js\nconst originalToISOString = Date.prototype.toISOString;\n\nconst stringified = devalue.stringify(value, undefined, {\n\toperations: {\n\t\t// use a captured intrinsic instead of a (possibly patched) prototype method\n\t\ttoISOString: (date) => originalToISOString.call(date),\n\n\t\t// read through descriptors so getters are never invoked\n\t\tget: (object, key) => {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\t\tif (descriptor?.get) throw new Error(`refusing to invoke getter for \"${key}\"`);\n\t\t\treturn descriptor?.value;\n\t\t}\n\t}\n});\n```\n\n**Foreign-runtime serialization.** The `stringify` algorithm never touches the value directly, so \"value\" can be an opaque handle to something living in another JavaScript runtime — a `node:vm` context, a WASM-hosted engine, a remote process — as long as the operations know how to inspect it. Implement `typeOf`/`tagOf` for classification, `toPrimitive`/`get`/`entriesOf`/etc. for extraction, and `identify` to key deduplication and cycle detection on the underlying value's identity rather than the handle's:\n\n```js\nconst stringified = devalue.stringify(rootHandle, undefined, {\n\toperations: {\n\t\tidentify: (handle) => handle.pointer,\n\t\ttypeOf: (handle) => handle.typeOf(),\n\t\tget: (handle, key) => handle.getProperty(key)\n\t\t// ... see StringifyOperations for the full interface\n\t}\n});\n```\n\nSome operations have a non-obvious contract that is easy to get subtly wrong. Where the work is not specific to your values, devalue exports the pieces so you don't have to reimplement them — `filterArrayIndices` does the array-index filtering that `indicesOf` needs, given keys you already have:\n\n```js\nindicesOf: (handle) => devalue.filterArrayIndices(handle.ownEnumerableStringKeys())\n```\n\nReducers compose with custom operations: they receive the raw value/handle, and whatever they return is serialized through the same operations.\n\n### Customizing `parse`\n\nThe mirror image: `parse` and `unflatten` build every value through construction operations (`ParseOperations`, defaults exported as `defaultParseOperations`), so you can control what gets created. The members mirror `StringifyOperations` with the host/value-space boundary running the other way: each `fromXxx` inverts the corresponding `toXxx`, `fromXxxInfo` inverts `xxxInfo`, and the bare-verb mutators invert the bare-verb accessors (`set`/`get`, `addValue`/`valuesOf`, `addEntry`/`entriesOf`, `box`/`unbox`).\n\n**Cross-realm revival.** By default the revived value is built from the intrinsics of whichever realm devalue is running in, so `instanceof` checks fail elsewhere. Constructing from a target realm's intrinsics fixes that:\n\n```js\nconst revived = devalue.parse(serialized, undefined, {\n\toperations: {\n\t\tfromISOString: (iso) => new sandbox.Date(iso),\n\t\tcreateMap: () => new sandbox.Map(),\n\t\tcreateObject: () => sandbox.makeObject()\n\t}\n});\n```\n\n**Foreign-runtime revival.** `parse` never inspects the values it creates — it only passes them back into other operations — so the operations can build values inside another runtime and return opaque handles:\n\n```js\nconst rootHandle = devalue.parse(serialized, undefined, {\n\toperations: {\n\t\tfromPrimitive: (primitive) => vm.toHandle(primitive),\n\t\tcreateObject: () => vm.newObject(),\n\t\tset: (handle, key, value) => handle.setProp(key, value)\n\t\t// ... see ParseOperations for the full interface\n\t}\n});\n```\n\nContainers are created empty and populated afterwards (`createMap` then `addEntry`, `createObject` then `set`, and so on) — that ordering is what allows cyclic values to be revived, since the empty container is cached before its contents are built.\n\nRevivers compose the same way reducers do: they receive whatever the operations built, and their return value is used as-is.\n\n## Error handling\n\nIf `uneval` or `stringify` encounters a function or a non-POJO that isn't handled by a custom replacer/reducer, it will throw an error. You can find where in the input data the offending value lives by inspecting `error.path`:\n\n```js\ntry {\n\tconst map = new Map();\n\tmap.set('key', function invalid() {});\n\n\tuneval({\n\t\tobject: {\n\t\t\tarray: [map]\n\t\t}\n\t});\n} catch (e) {\n\tconsole.log(e.path); // '.object.array[0].get(\"key\")'\n}\n```\n\n## XSS mitigation\n\nSay you're server-rendering a page and want to serialize some state, which could include user input. `JSON.stringify` doesn't protect against XSS attacks:\n\n```js\nconst state = {\n\tuserinput: `</script><script src='https://evil.com/mwahaha.js'>`\n};\n\nconst template = `\n<script>\n  // NEVER DO THIS\n  var preloaded = ${JSON.stringify(state)};\n</script>`;\n```\n\nWhich would result in this:\n\n```html\n<script>\n\t// NEVER DO THIS\n\tvar preloaded = {\"userinput\":\"\n</script>\n<script src=\"https://evil.com/mwahaha.js\">\n\t\"};\n</script>\n```\n\nUsing `uneval` or `stringify`, we're protected against that attack:\n\n```js\nconst template = `\n<script>\n  var preloaded = ${uneval(state)};\n</script>`;\n```\n\n```html\n<script>\n\tvar preloaded = {\n\t\tuserinput:\n\t\t\t\"\\\\u003C\\\\u002Fscript\\\\u003E\\\\u003Cscript src='https:\\\\u002F\\\\u002Fevil.com\\\\u002Fmwahaha.js'\\\\u003E\"\n\t};\n</script>\n```\n\nThis, along with the fact that `uneval` and `stringify` bail on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by `uneval` can be safely deserialized with `eval` or `new Function`:\n\n```js\nconst value = (0, eval)('(' + str + ')');\n```\n\n## Other security considerations\n\nWhile `uneval` prevents the XSS vulnerability shown above, meaning you can use it to send data from server to client, **you should not send user data from client to server** using the same method. Since it has to be evaluated, an attacker that successfully submitted data that bypassed `uneval` would have access to your system.\n\nWhen using `eval`, ensure that you call it _indirectly_ so that the evaluated code doesn't have access to the surrounding scope:\n\n```js\n{\n\tconst sensitiveData = 'Setec Astronomy';\n\teval('sendToEvilServer(sensitiveData)'); // pwned :(\n\t(0, eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!\n}\n```\n\nUsing `new Function(code)` is akin to using indirect eval.\n\n## See also\n\n- [lave](https://github.com/jed/lave) by Jed Schmidt\n- [arson](https://github.com/benjamn/arson) by Ben Newman. The `stringify`/`parse` approach in `devalue` was inspired by `arson`\n- [oson](https://github.com/KnorpelSenf/oson) by Steffen Trog\n- [tosource](https://github.com/marcello3d/node-tosource) by Marcello Bastéa-Forte\n- [serialize-javascript](https://github.com/yahoo/serialize-javascript) by Eric Ferraiuolo\n- [jsesc](https://github.com/mathiasbynens/jsesc) by Mathias Bynens\n- [superjson](https://github.com/blitz-js/superjson) by Blitz\n- [next-json](https://github.com/iccicci/next-json) by Daniele Ricci\n\n## License\n\n[MIT](LICENSE)\n","publish_time":1756246107691,"_cnpm_publish_time":1756246107691,"dist-tags":{"latest":"6.0.3"}}