penambahan web socket

This commit is contained in:
2025-09-18 19:01:22 +07:00
parent 1d053646a9
commit d7bb2eb5bb
15070 changed files with 2402916 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
Copyright (c) 2018-19 [these people](https://github.com/nuxt-contrib/devalue/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,146 @@
# @nuxt/devalue
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![codecov][codecov-src]][codecov-href]
[![package phobia][package-phobia-src]][package-phobia-href]
[![bundle phobia][bundle-phobia-src]][bundle-phobia-href]
> Forked from [devalue](https://github.com/Rich-Harris/devalue) to log errors on non-serializable properties rather than throwing `Error`.
Like `JSON.stringify`, but handles
* cyclical references (`obj.self = obj`)
* repeated references (`[value, value]`)
* `undefined`, `Infinity`, `NaN`, `-0`
* regular expressions
* dates
* `Map` and `Set`
* `.toJSON()` method for non-POJOs
Try it out on [runkit.com](https://npm.runkit.com/@nuxt/devalue).
## Goals:
* Performance
* Security (see [XSS mitigation](#xss-mitigation))
* Compact output
## Non-goals:
* Human-readable output
* Stringifying functions or arbritary non-POJOs
## Usage
```js
import devalue from '@nuxt/devalue';
let obj = { a: 1, b: 2 };
obj.c = 3;
devalue(obj); // '{a:1,b:2,c:3}'
obj.self = obj;
devalue(obj); // '(function(a){a.a=1;a.b=2;a.c=3;a.self=a;return a}({}))'
```
If `devalue` encounters a function or a non-POJO, it will throw an error.
## XSS mitigation
Say 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:
```js
const state = {
userinput: `</script><script src='https://evil.com/mwahaha.js'>`
};
const template = `
<script>
// NEVER DO THIS
var preloaded = ${JSON.stringify(state)};
</script>`;
```
Which would result in this:
```html
<script>
// NEVER DO THIS
var preloaded = {"userinput":"</script><script src='https://evil.com/mwahaha.js'>"};
</script>
```
Using `devalue`, we're protected against that attack:
```js
const template = `
<script>
var preloaded = ${devalue(state)};
</script>`;
```
```html
<script>
var preloaded = {userinput:"\\u003C\\u002Fscript\\u003E\\u003Cscript src=\'https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js\'\\u003E"};
</script>
```
This, along with the fact that `devalue` bails on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by `devalue` can be safely deserialized with `eval` or `new Function`:
```js
const value = (0,eval)('(' + str + ')');
```
## Other security considerations
While `devalue` 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 `devalue` would have access to your system.
When using `eval`, ensure that you call it *indirectly* so that the evaluated code doesn't have access to the surrounding scope:
```js
{
const sensitiveData = 'Setec Astronomy';
eval('sendToEvilServer(sensitiveData)'); // pwned :(
(0,eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
}
```
Using `new Function(code)` is akin to using indirect eval.
## See also
* [lave](https://github.com/jed/lave) by Jed Schmidt
* [arson](https://github.com/benjamn/arson) by Ben Newman
* [tosource](https://github.com/marcello3d/node-tosource) by Marcello Bastéa-Forte
* [serialize-javascript](https://github.com/yahoo/serialize-javascript) by Eric Ferraiuolo
## License
[MIT](LICENSE)
<!-- Refs -->
[npm-version-src]: https://flat.badgen.net/npm/v/@nuxt/devalue/latest
[npm-version-href]: https://www.npmjs.com/package/@nuxt/devalue
[npm-downloads-src]: https://flat.badgen.net/npm/dm/@nuxt/devalue
[npm-downloads-href]: https://www.npmjs.com/package/@nuxt/devalue
[circleci-src]: https://flat.badgen.net/circleci/github/nuxt-contrib/devalue
[circleci-href]: https://circleci.com/gh/nuxt-contrib/devalue
[package-phobia-src]: https://flat.badgen.net/packagephobia/install/@nuxt/devalue
[package-phobia-href]: https://packagephobia.now.sh/result?p=@nuxt/devalue
[bundle-phobia-src]: https://flat.badgen.net/bundlephobia/minzip/@nuxt/devalue
[bundle-phobia-href]: https://bundlephobia.com/result?p=@nuxt/devalue
[codecov-src]: https://flat.badgen.net/codecov/c/github/nuxt-contrib/devalue/master
[codecov-href]: https://codecov.io/gh/nuxt-contrib/devalue

View File

@@ -0,0 +1,236 @@
'use strict';
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
const unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const escaped = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function devalue(value) {
const counts = /* @__PURE__ */ new Map();
let logNum = 0;
function log(message) {
if (logNum < 100) {
console.warn(message);
logNum += 1;
}
}
function walk(thing) {
if (typeof thing === "function") {
log(`Cannot stringify a function ${thing.name}`);
return;
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
case "Date":
case "RegExp":
return;
case "Array":
thing.forEach(walk);
break;
case "Set":
case "Map":
Array.from(thing).forEach(walk);
break;
default:
const proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype && proto !== null && Object.getOwnPropertyNames(proto).sort().join("\0") !== objectProtoOwnPropertyNames) {
if (typeof thing.toJSON !== "function") {
log(`Cannot stringify arbitrary non-POJOs ${thing.constructor.name}`);
}
} else if (Object.getOwnPropertySymbols(thing).length > 0) {
log(`Cannot stringify POJOs with symbolic keys ${Object.getOwnPropertySymbols(thing).map((symbol) => symbol.toString())}`);
} else {
Object.keys(thing).forEach((key) => walk(thing[key]));
}
}
}
}
walk(value);
const names = /* @__PURE__ */ new Map();
Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
return `Object(${stringify(thing.valueOf())})`;
case "RegExp":
return thing.toString();
case "Date":
return `new Date(${thing.getTime()})`;
case "Array":
const members = thing.map((v, i) => i in thing ? stringify(v) : "");
const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ",";
return `[${members.join(",")}${tail}]`;
case "Set":
case "Map":
return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`;
default:
if (thing.toJSON) {
let json = thing.toJSON();
if (getType(json) === "String") {
try {
json = JSON.parse(json);
} catch (e) {
}
}
return stringify(json);
}
if (Object.getPrototypeOf(thing) === null) {
if (Object.keys(thing).length === 0) {
return "Object.create(null)";
}
return `Object.create(null,{${Object.keys(thing).map((key) => `${safeKey(key)}:{writable:true,enumerable:true,value:${stringify(thing[key])}}`).join(",")}})`;
}
return `{${Object.keys(thing).map((key) => `${safeKey(key)}:${stringify(thing[key])}`).join(",")}}`;
}
}
const str = stringify(value);
if (names.size) {
const params = [];
const statements = [];
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (isPrimitive(thing)) {
values.push(stringifyPrimitive(thing));
return;
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case "RegExp":
values.push(thing.toString());
break;
case "Date":
values.push(`new Date(${thing.getTime()})`);
break;
case "Array":
values.push(`Array(${thing.length})`);
thing.forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case "Set":
values.push("new Set");
statements.push(`${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}`);
break;
case "Map":
values.push("new Map");
statements.push(`${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}`);
break;
default:
values.push(Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}");
Object.keys(thing).forEach((key) => {
statements.push(`${name}${safeProp(key)}=${stringify(thing[key])}`);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(",")}){${statements.join(";")}}(${values.join(",")}))`;
} else {
return str;
}
}
function getName(num) {
let name = "";
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === "string") {
return stringifyString(thing);
}
if (thing === void 0) {
return "void 0";
}
if (thing === 0 && 1 / thing < 0) {
return "-0";
}
const str = String(thing);
if (typeof thing === "number") {
return str.replace(/^(-)?0\./, "$1.");
}
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escapeUnsafeChars(JSON.stringify(key))}]`;
}
function stringifyString(str) {
let result = '"';
for (let i = 0; i < str.length; i += 1) {
const char = str.charAt(i);
const code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
} else if (char in escaped) {
result += escaped[char];
} else if (code >= 55296 && code <= 57343) {
const next = str.charCodeAt(i + 1);
if (code <= 56319 && (next >= 56320 && next <= 57343)) {
result += char + str[++i];
} else {
result += `\\u${code.toString(16).toUpperCase()}`;
}
} else {
result += char;
}
}
result += '"';
return result;
}
module.exports = devalue;

View File

@@ -0,0 +1,234 @@
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
const unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const escaped = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function devalue(value) {
const counts = /* @__PURE__ */ new Map();
let logNum = 0;
function log(message) {
if (logNum < 100) {
console.warn(message);
logNum += 1;
}
}
function walk(thing) {
if (typeof thing === "function") {
log(`Cannot stringify a function ${thing.name}`);
return;
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
case "Date":
case "RegExp":
return;
case "Array":
thing.forEach(walk);
break;
case "Set":
case "Map":
Array.from(thing).forEach(walk);
break;
default:
const proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype && proto !== null && Object.getOwnPropertyNames(proto).sort().join("\0") !== objectProtoOwnPropertyNames) {
if (typeof thing.toJSON !== "function") {
log(`Cannot stringify arbitrary non-POJOs ${thing.constructor.name}`);
}
} else if (Object.getOwnPropertySymbols(thing).length > 0) {
log(`Cannot stringify POJOs with symbolic keys ${Object.getOwnPropertySymbols(thing).map((symbol) => symbol.toString())}`);
} else {
Object.keys(thing).forEach((key) => walk(thing[key]));
}
}
}
}
walk(value);
const names = /* @__PURE__ */ new Map();
Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
return `Object(${stringify(thing.valueOf())})`;
case "RegExp":
return thing.toString();
case "Date":
return `new Date(${thing.getTime()})`;
case "Array":
const members = thing.map((v, i) => i in thing ? stringify(v) : "");
const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ",";
return `[${members.join(",")}${tail}]`;
case "Set":
case "Map":
return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`;
default:
if (thing.toJSON) {
let json = thing.toJSON();
if (getType(json) === "String") {
try {
json = JSON.parse(json);
} catch (e) {
}
}
return stringify(json);
}
if (Object.getPrototypeOf(thing) === null) {
if (Object.keys(thing).length === 0) {
return "Object.create(null)";
}
return `Object.create(null,{${Object.keys(thing).map((key) => `${safeKey(key)}:{writable:true,enumerable:true,value:${stringify(thing[key])}}`).join(",")}})`;
}
return `{${Object.keys(thing).map((key) => `${safeKey(key)}:${stringify(thing[key])}`).join(",")}}`;
}
}
const str = stringify(value);
if (names.size) {
const params = [];
const statements = [];
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (isPrimitive(thing)) {
values.push(stringifyPrimitive(thing));
return;
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case "RegExp":
values.push(thing.toString());
break;
case "Date":
values.push(`new Date(${thing.getTime()})`);
break;
case "Array":
values.push(`Array(${thing.length})`);
thing.forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case "Set":
values.push("new Set");
statements.push(`${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}`);
break;
case "Map":
values.push("new Map");
statements.push(`${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}`);
break;
default:
values.push(Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}");
Object.keys(thing).forEach((key) => {
statements.push(`${name}${safeProp(key)}=${stringify(thing[key])}`);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(",")}){${statements.join(";")}}(${values.join(",")}))`;
} else {
return str;
}
}
function getName(num) {
let name = "";
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === "string") {
return stringifyString(thing);
}
if (thing === void 0) {
return "void 0";
}
if (thing === 0 && 1 / thing < 0) {
return "-0";
}
const str = String(thing);
if (typeof thing === "number") {
return str.replace(/^(-)?0\./, "$1.");
}
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escapeUnsafeChars(JSON.stringify(key))}]`;
}
function stringifyString(str) {
let result = '"';
for (let i = 0; i < str.length; i += 1) {
const char = str.charAt(i);
const code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
} else if (char in escaped) {
result += escaped[char];
} else if (code >= 55296 && code <= 57343) {
const next = str.charCodeAt(i + 1);
if (code <= 56319 && (next >= 56320 && next <= 57343)) {
result += char + str[++i];
} else {
result += `\\u${code.toString(16).toUpperCase()}`;
}
} else {
result += char;
}
}
result += '"';
return result;
}
export { devalue as default };

View File

@@ -0,0 +1,3 @@
declare function devalue(value: any): string;
export { devalue as default };

View File

@@ -0,0 +1,39 @@
{
"name": "@nuxt/devalue",
"version": "2.0.2",
"description": "Gets the job done when JSON.stringify can't",
"repository": "nuxt/devalue",
"license": "MIT",
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/devalue.js",
"import": "./dist/devalue.mjs"
}
},
"main": "./dist/devalue.js",
"module": "./dist/devalue.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "unbuild",
"prepack": "yarn build",
"lint": "eslint --ext .ts,.js .",
"test": "yarn lint && jest",
"release": "yarn test && standard-version && git push --follow-tags && npm publish"
},
"devDependencies": {
"@nuxtjs/eslint-config-typescript": "^6.0.0",
"@types/jest": "^26.0.23",
"@types/mocha": "^8.2.2",
"@types/node": "^15.3.0",
"eslint": "^7.26.0",
"jest": "^26.6.3",
"standard-version": "^9.3.0",
"ts-jest": "^26.5.6",
"typescript": "^4.2.4",
"unbuild": "^1.2.1"
}
}