WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
#zuul --local 8080 --no-coverage -- test/index.js
zuul --local 8080 --no-coverage -- test/fastest.js

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_class_apply_descriptor_destructure.js";

View File

@@ -0,0 +1,222 @@
var _typeof = require("./typeof.js")["default"];
var checkInRHS = require("./checkInRHS.js");
var setFunctionName = require("./setFunctionName.js");
var toPropertyKey = require("./toPropertyKey.js");
function applyDecs2301Factory() {
function createAddInitializerMethod(e, t) {
return function (r) {
!function (e) {
if (e.v) throw Error("attempted to call addInitializer after decoration was finished");
}(t), assertCallable(r, "An initializer"), e.push(r);
};
}
function assertInstanceIfPrivate(e, t) {
if (!e(t)) throw new TypeError("Attempted to access private element on non-instance");
}
function memberDec(e, t, r, n, a, i, s, o, c) {
var u;
switch (a) {
case 1:
u = "accessor";
break;
case 2:
u = "method";
break;
case 3:
u = "getter";
break;
case 4:
u = "setter";
break;
default:
u = "field";
}
var l,
f,
p = {
kind: u,
name: s ? "#" + t : toPropertyKey(t),
"static": i,
"private": s
},
d = {
v: !1
};
if (0 !== a && (p.addInitializer = createAddInitializerMethod(n, d)), s || 0 !== a && 2 !== a) {
if (2 === a) l = function l(e) {
return assertInstanceIfPrivate(c, e), r.value;
};else {
var h = 0 === a || 1 === a;
(h || 3 === a) && (l = s ? function (e) {
return assertInstanceIfPrivate(c, e), r.get.call(e);
} : function (e) {
return r.get.call(e);
}), (h || 4 === a) && (f = s ? function (e, t) {
assertInstanceIfPrivate(c, e), r.set.call(e, t);
} : function (e, t) {
r.set.call(e, t);
});
}
} else l = function l(e) {
return e[t];
}, 0 === a && (f = function f(e, r) {
e[t] = r;
});
var v = s ? c.bind() : function (e) {
return t in e;
};
p.access = l && f ? {
get: l,
set: f,
has: v
} : l ? {
get: l,
has: v
} : {
set: f,
has: v
};
try {
return e(o, p);
} finally {
d.v = !0;
}
}
function assertCallable(e, t) {
if ("function" != typeof e) throw new TypeError(t + " must be a function");
}
function assertValidReturnValue(e, t) {
var r = _typeof(t);
if (1 === e) {
if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init");
} else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0");
}
function curryThis2(e) {
return function (t) {
e(this, t);
};
}
function applyMemberDec(e, t, r, n, a, i, s, o, c) {
var u,
l,
f,
p,
d,
h,
v,
y,
g = r[0];
if (s ? (0 === a || 1 === a ? (u = {
get: (d = r[3], function () {
return d(this);
}),
set: curryThis2(r[4])
}, f = "get") : 3 === a ? (u = {
get: r[3]
}, f = "get") : 4 === a ? (u = {
set: r[3]
}, f = "set") : u = {
value: r[3]
}, 0 !== a && (1 === a && setFunctionName(u.set, "#" + n, "set"), setFunctionName(u[f || "value"], "#" + n, f))) : 0 !== a && (u = Object.getOwnPropertyDescriptor(t, n)), 1 === a ? p = {
get: u.get,
set: u.set
} : 2 === a ? p = u.value : 3 === a ? p = u.get : 4 === a && (p = u.set), "function" == typeof g) void 0 !== (h = memberDec(g, n, u, o, a, i, s, p, c)) && (assertValidReturnValue(a, h), 0 === a ? l = h : 1 === a ? (l = h.init, v = h.get || p.get, y = h.set || p.set, p = {
get: v,
set: y
}) : p = h);else for (var m = g.length - 1; m >= 0; m--) {
var b;
void 0 !== (h = memberDec(g[m], n, u, o, a, i, s, p, c)) && (assertValidReturnValue(a, h), 0 === a ? b = h : 1 === a ? (b = h.init, v = h.get || p.get, y = h.set || p.set, p = {
get: v,
set: y
}) : p = h, void 0 !== b && (void 0 === l ? l = b : "function" == typeof l ? l = [l, b] : l.push(b)));
}
if (0 === a || 1 === a) {
if (void 0 === l) l = function l(e, t) {
return t;
};else if ("function" != typeof l) {
var I = l;
l = function l(e, t) {
for (var r = t, n = 0; n < I.length; n++) r = I[n].call(e, r);
return r;
};
} else {
var w = l;
l = function l(e, t) {
return w.call(e, t);
};
}
e.push(l);
}
0 !== a && (1 === a ? (u.get = p.get, u.set = p.set) : 2 === a ? u.value = p : 3 === a ? u.get = p : 4 === a && (u.set = p), s ? 1 === a ? (e.push(function (e, t) {
return p.get.call(e, t);
}), e.push(function (e, t) {
return p.set.call(e, t);
})) : 2 === a ? e.push(p) : e.push(function (e, t) {
return p.call(e, t);
}) : Object.defineProperty(t, n, u));
}
function applyMemberDecs(e, t, r) {
for (var n, a, i, s = [], o = new Map(), c = new Map(), u = 0; u < t.length; u++) {
var l = t[u];
if (Array.isArray(l)) {
var f,
p,
d = l[1],
h = l[2],
v = l.length > 3,
y = d >= 5,
g = r;
if (y ? (f = e, 0 != (d -= 5) && (p = a = a || []), v && !i && (i = function i(t) {
return checkInRHS(t) === e;
}), g = i) : (f = e.prototype, 0 !== d && (p = n = n || [])), 0 !== d && !v) {
var m = y ? c : o,
b = m.get(h) || 0;
if (!0 === b || 3 === b && 4 !== d || 4 === b && 3 !== d) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h);
!b && d > 2 ? m.set(h, d) : m.set(h, !0);
}
applyMemberDec(s, f, l, h, d, y, v, p, g);
}
}
return pushInitializers(s, n), pushInitializers(s, a), s;
}
function pushInitializers(e, t) {
t && e.push(function (e) {
for (var r = 0; r < t.length; r++) t[r].call(e);
return e;
});
}
return function (e, t, r, n) {
return {
e: applyMemberDecs(e, t, n),
get c() {
return function (e, t) {
if (t.length > 0) {
for (var r = [], n = e, a = e.name, i = t.length - 1; i >= 0; i--) {
var s = {
v: !1
};
try {
var o = t[i](n, {
kind: "class",
name: a,
addInitializer: createAddInitializerMethod(r, s)
});
} finally {
s.v = !0;
}
void 0 !== o && (assertValidReturnValue(10, o), n = o);
}
return [n, function () {
for (var e = 0; e < r.length; e++) r[e].call(n);
}];
}
}(e, r);
}
};
};
}
function applyDecs2301(e, t, r, n) {
return (module.exports = applyDecs2301 = applyDecs2301Factory(), module.exports.__esModule = true, module.exports["default"] = module.exports)(e, t, r, n);
}
module.exports = applyDecs2301, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blake2b = exports.BLAKE2b = void 0;
/**
* Blake2b hash function. Focuses on 64-bit platforms, but in JS speed different from Blake2s is negligible.
* @module
* @deprecated
*/
const blake2_ts_1 = require("./blake2.js");
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.BLAKE2b = blake2_ts_1.BLAKE2b;
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.blake2b = blake2_ts_1.blake2b;
//# sourceMappingURL=blake2b.js.map

View File

@@ -0,0 +1,50 @@
import * as core from "../core/index.cjs";
import type { ZodType } from "./schemas.cjs";
export type {
/** @deprecated Use `z.output<T>` instead. */
output as TypeOf,
/** @deprecated Use `z.output<T>` instead. */
output as Infer,
/** @deprecated Use `z.core.$$ZodFirstPartyTypes` instead */
$ZodTypes as ZodFirstPartySchemaTypes, } from "../core/index.cjs";
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
export declare const ZodIssueCode: {
readonly invalid_type: "invalid_type";
readonly too_big: "too_big";
readonly too_small: "too_small";
readonly invalid_format: "invalid_format";
readonly not_multiple_of: "not_multiple_of";
readonly unrecognized_keys: "unrecognized_keys";
readonly invalid_union: "invalid_union";
readonly invalid_key: "invalid_key";
readonly invalid_element: "invalid_element";
readonly invalid_value: "invalid_value";
readonly custom: "custom";
};
/** @deprecated Use `z.$ZodFlattenedError` */
export type inferFlattenedErrors<T extends core.$ZodType, U = string> = core.$ZodFlattenedError<core.output<T>, U>;
/** @deprecated Use `z.$ZodFormattedError` */
export type inferFormattedError<T extends core.$ZodType<any, any>, U = string> = core.$ZodFormattedError<core.output<T>, U>;
/** Use `z.$brand` instead */
export type BRAND<T extends string | number | symbol = string | number | symbol> = {
[core.$brand]: {
[k in T]: true;
};
};
export { $brand, config } from "../core/index.cjs";
/** @deprecated Use `z.config(params)` instead. */
export declare function setErrorMap(map: core.$ZodErrorMap): void;
/** @deprecated Use `z.config()` instead. */
export declare function getErrorMap(): core.$ZodErrorMap<core.$ZodIssue> | undefined;
export type {
/** @deprecated Use z.ZodType (without generics) instead. */
ZodType as ZodTypeAny,
/** @deprecated Use `z.ZodType` */
ZodType as ZodSchema,
/** @deprecated Use `z.ZodType` */
ZodType as Schema, };
/** Included for Zod 3 compatibility */
export type ZodRawShape = core.$ZodShape;
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
export declare enum ZodFirstPartyTypeKind {
}

View File

@@ -0,0 +1,10 @@
function _classApplyDescriptorDestructureSet(e, t) {
if (t.set) return "__destrObj" in t || (t.__destrObj = {
set value(r) {
t.set.call(e, r);
}
}), t.__destrObj;
if (!t.writable) throw new TypeError("attempted to set read only private field");
return t;
}
export { _classApplyDescriptorDestructureSet as default };

View File

@@ -0,0 +1,37 @@
'use strict'
module.exports = interpretConditionals
const getPropertyValue = require('./get-property-value')
/**
* Translates all conditional blocks from within the messageFormat. Translates
* any matching {if key}{key}{end} statements and returns everything between
* if and else blocks if the key provided was found in log.
*
* @param {MessageFormatString|MessageFormatFunction} messageFormat A format
* string or function that defines how the logged message should be
* conditionally formatted.
* @param {object} log The log object to be modified.
*
* @returns {string} The parsed messageFormat.
*/
function interpretConditionals (messageFormat, log) {
messageFormat = messageFormat.replace(/{if (.*?)}(.*?){end}/g, replacer)
// Remove non-terminated if blocks
messageFormat = messageFormat.replace(/{if (.*?)}/g, '')
// Remove floating end blocks
messageFormat = messageFormat.replace(/{end}/g, '')
return messageFormat.replace(/\s+/g, ' ').trim()
function replacer (_, key, value) {
const propertyValue = getPropertyValue(log, key)
if (propertyValue && value.includes(key)) {
return value.replace(new RegExp('{' + key + '}', 'g'), propertyValue)
} else {
return ''
}
}
}

View File

@@ -0,0 +1,153 @@
<div align="center">
<a href="https://github.com/elpheria/rpc-websockets">
<img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/logo.png">
</a>
<br>
<p>
WebSockets for <a href="http://nodejs.org">Node.js</a> and <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a>/<a href="https://en.wikipedia.org/wiki/TypeScript">TypeScript</a> with <a href="https://www.jsonrpc.org/specification">JSON RPC 2.0</a> support on top. </p>
<a href="https://www.npmjs.com/package/rpc-websockets">
<img src="https://img.shields.io/npm/v/rpc-websockets.svg">
</a>
<a href="https://travis-ci.org/elpheria/rpc-websockets">
<img src="https://travis-ci.org/elpheria/rpc-websockets.svg?branch=master">
</a>
<a href="https://www.npmjs.com/package/rpc-websockets">
<img src="https://img.shields.io/npm/dm/rpc-websockets.svg?maxAge=2592000">
</a>
<br><br><br>
</div>
## About
The **rpc-websockets** library enables developers to easily implement their business logic that includes messaging between users, machines or any devices. It provides a possibility to send and receive JSON data through the WebSocket communication protocol in order to support two-way notification push, running RPC methods and firing any types of event signalling. Only clients can call RPC methods and not vice versa at the moment. Both frontend (HTML/JS-based) and backend (Node.js-based) development environments are supported.
**rpc-websockets** is built on Node.js and supports both LTS and Current versions.
Use the free OSS edition in order to implement and manage your own WebSocket server instances, or subscribe for our [Pro plan](#pro-features) and have us manage your instances and provide you with management of your methods, events and notifications on an easy-to-use Web Management portal.
## Quick start
Install our OSS library in your project:
```
npm install rpc-websockets
```
Write your source code using `rpc-websockets`:
```js
var WebSocket = require('rpc-websockets').Client
var WebSocketServer = require('rpc-websockets').Server
// instantiate Server and start listening for requests
var server = new WebSocketServer({
port: 8080,
host: 'localhost'
})
// register an RPC method
server.register('sum', function(params) {
return params[0] + params[1]
})
// ...and maybe a protected one also
server.register('account', function() {
return ['confi1', 'confi2']
}).protected()
// create an event
server.event('feedUpdated')
// get events
console.log(server.eventList())
// emit an event to subscribers
server.emit('feedUpdated')
// close the server
server.close()
// instantiate Client and connect to an RPC server
var ws = new WebSocket('ws://localhost:8080')
ws.on('open', function() {
// call an RPC method with parameters
ws.call('sum', [5, 3]).then(function(result) {
require('assert').equal(result, 8)
})
// send a notification to an RPC server
ws.notify('openedNewsModule')
// subscribe to receive an event
ws.subscribe('feedUpdated')
ws.on('feedUpdated', function() {
updateLogic()
})
// unsubscribe from an event
ws.unsubscribe('feedUpdated')
// login your client to be able to use protected methods
ws.login({'username': 'confi1', 'password':'foobar'}).then(function() {
ws.call('account').then(function(result) {
require('assert').equal(result, ['confi1', 'confi2'])
})
}).catch(function(error) {
console.log('auth failed')
})
// close a websocket connection
ws.close()
})
```
## Documentation
Please consult our [API documentation](API.md) for both WebSocket server and client JavaScript and TypeScript classes.
## OSS Features
Features of the free open-source edition.
![OSS Features](assets/oss-features.png)
All library's open-source features are documented in our [API documentation](API.md) and can be used free of charge. You are free to implement your solutions based on provided methods in any way you are comfortable with, as long as you use our work along our very permissive [license](LICENSE) conditions.
## Pro Features
In order to support your production-ready environments, we can provide you with additional features built on top of our free OSS edition along with the skill set to turn your business case or a Proof-of-Concept idea into reality.
![Pro Features](assets/pro-features.png)
Describe us your use case by [contacting us](mailto:info@elpheria.com?subject=Pro%20Plan%20enquiry) and we will swiftly get back to you with a proposed solution that meets your needs.
## Professional support
We offer professional support for **rpc-websockets** and beyond. We have many years of expertise on building robust, scalable Node.js applications and can help you overcome issues and challenges preventing you to ship your great products. We excel in software architecture and implementation, being able to provide you with development, planning, consulting, training and customization services. Feel free to [contact us](mailto:support@elpheria.com?subject=rpc-websockets%20support%20enquiry) so we can discuss how to help you finish your products!
## Users
**rpc-websockets** is being actively used in production by multiple companies in a variety of different use cases.
<br>
<a href="https://scratchbox.io" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-scratchbox.png" alt="Scratchbox" height=50px></a>&emsp;
<a href="https://loomx.io" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-loom.png" alt="Loom Network" height=50px></a>&emsp;
<a href="https://www.uniqcast.com" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-uniqcast.png" alt="uniqCast" height=50px></a>&emsp;
<a href="https://leapdao.org" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-leapdao.png" alt="LeapDAO" height=50px></a>&emsp;
<a href="https://klika-tech.com" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-klikatech.png" alt="Klika Tech, Inc." height=50px></a>&emsp;
<a href="https://kodebox.io" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-kodebox.png" alt="Kodebox, Inc." height=50px></a>&emsp;
<a href="https://hey.network" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-heynetwork.png" alt="Hey-Group S.A./N.V." height=50px></a>&emsp;
<a href="https://www.hylo.com" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-hylo.png" alt="Hylo, Inc." height=50px></a>&emsp;
<a href="https://witnet.foundation" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-witnet.png" alt="Witnet Foundation" height=50px></a>&emsp;
<a href="https://www.scaleleap.com" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-scaleleap.png" alt="Scale Leap" height=50px></a>&emsp;
<a href="https://codice.org" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-codice.png" alt="Codice Foundation, Inc." height=50px></a>&emsp;
<a href="https://holo.host" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-holo.png" alt="Holo Ltd." height=50px></a>&emsp;
<a href="https://solana.com" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-solana.png" alt="Solana Labs, Inc." height=50px></a>&emsp;
<a href="https://filecoin.io" target="_blank"><img src="https://raw.githubusercontent.com/elpheria/rpc-websockets/master/assets/user-filecoin.png" alt="Filecoin" height=50px></a>&emsp;
## Sponsors
Become a sponsor and get your logo on project's README on GitHub with a link to your site. Feel free to [contact us](mailto:info@elpheria.com?subject=Sponsors) for the arrangement!
## License
This library is licensed under LGPLv3. Please see [LICENSE](LICENSE) for licensing details.

View File

@@ -0,0 +1,7 @@
import classApplyDescriptorSet from "./classApplyDescriptorSet.js";
import classPrivateFieldGet2 from "./classPrivateFieldGet2.js";
function _classPrivateFieldSet(e, t, r) {
var s = classPrivateFieldGet2(t, e);
return classApplyDescriptorSet(e, s, r), r;
}
export { _classPrivateFieldSet as default };

View File

@@ -0,0 +1,98 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'prefer-readonly-parameter-types',
meta: {
type: 'suggestion',
docs: {
description: 'Require function parameters to be typed as `readonly` to prevent accidental mutation of inputs',
requiresTypeChecking: true,
},
messages: {
shouldBeReadonly: 'Parameter should be a read only type.',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allow: {
...util_1.readonlynessOptionsSchema.properties.allow,
description: 'An array of type specifiers to ignore.',
},
checkParameterProperties: {
type: 'boolean',
description: 'Whether to check class parameter properties.',
},
ignoreInferredTypes: {
type: 'boolean',
description: "Whether to ignore parameters which don't explicitly specify a type.",
},
treatMethodsAsReadonly: {
...util_1.readonlynessOptionsSchema.properties.treatMethodsAsReadonly,
description: 'Whether to treat all mutable methods as though they are readonly.',
},
},
},
],
},
defaultOptions: [
{
allow: util_1.readonlynessOptionsDefaults.allow,
checkParameterProperties: true,
ignoreInferredTypes: false,
treatMethodsAsReadonly: util_1.readonlynessOptionsDefaults.treatMethodsAsReadonly,
},
],
create(context, [{ allow, checkParameterProperties, ignoreInferredTypes, treatMethodsAsReadonly, },]) {
const services = (0, util_1.getParserServices)(context);
function getParameterType(actualParam) {
if (actualParam.typeAnnotation?.typeAnnotation) {
// Get type from annotation node to preserve aliasSymbol
const checker = services.program.getTypeChecker();
const tsTypeNode = services.esTreeNodeToTSNodeMap.get(actualParam.typeAnnotation.typeAnnotation);
return checker.getTypeFromTypeNode(tsTypeNode);
}
return services.getTypeAtLocation(actualParam);
}
return {
[[
utils_1.AST_NODE_TYPES.ArrowFunctionExpression,
utils_1.AST_NODE_TYPES.FunctionDeclaration,
utils_1.AST_NODE_TYPES.FunctionExpression,
utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration,
utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration,
utils_1.AST_NODE_TYPES.TSDeclareFunction,
utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression,
utils_1.AST_NODE_TYPES.TSFunctionType,
utils_1.AST_NODE_TYPES.TSMethodSignature,
].join(', ')](node) {
for (const param of node.params) {
if (!checkParameterProperties &&
param.type === utils_1.AST_NODE_TYPES.TSParameterProperty) {
continue;
}
const actualParam = param.type === utils_1.AST_NODE_TYPES.TSParameterProperty
? param.parameter
: param;
if (ignoreInferredTypes && actualParam.typeAnnotation == null) {
continue;
}
const type = getParameterType(actualParam);
const isReadOnly = (0, util_1.isTypeReadonly)(services.program, type, {
allow,
treatMethodsAsReadonly: !!treatMethodsAsReadonly,
});
if (!isReadOnly && !(0, util_1.isTypeBrandedLiteralLike)(type)) {
context.report({
node: actualParam,
messageId: 'shouldBeReadonly',
});
}
}
},
};
},
});

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_type_of.cjs",
"module": "../../esm/_type_of.js"
}

View File

@@ -0,0 +1,2 @@
export declare var ScriptTarget: any;
//# sourceMappingURL=scriptTarget.d.ts.map

View File

@@ -0,0 +1,10 @@
#ifndef IS_UTF8
#include <stddef.h>
// Check whether the provided string is UTF-8.
// The function is designed for use cases where
// 99.99% of the inputs are valid UTF-8.
// Thus the function unconditionally scans the
// whole input.
extern "C" bool is_utf8(const char *src, size_t len);
#endif // IS_UTF8

View File

@@ -0,0 +1,62 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{? ($schema || $isData) && it.opts.uniqueItems !== false }}
{{? $isData }}
var {{=$valid}};
if ({{=$schemaValue}} === false || {{=$schemaValue}} === undefined)
{{=$valid}} = true;
else if (typeof {{=$schemaValue}} != 'boolean')
{{=$valid}} = false;
else {
{{?}}
var i = {{=$data}}.length
, {{=$valid}} = true
, j;
if (i > 1) {
{{
var $itemType = it.schema.items && it.schema.items.type
, $typeIsArray = Array.isArray($itemType);
}}
{{? !$itemType || $itemType == 'object' || $itemType == 'array' ||
($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) }}
outer:
for (;i--;) {
for (j = i; j--;) {
if (equal({{=$data}}[i], {{=$data}}[j])) {
{{=$valid}} = false;
break outer;
}
}
}
{{??}}
var itemIndices = {}, item;
for (;i--;) {
var item = {{=$data}}[i];
{{ var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); }}
if ({{= it.util[$method]($itemType, 'item', it.opts.strictNumbers, true) }}) continue;
{{? $typeIsArray}}
if (typeof item == 'string') item = '"' + item;
{{?}}
if (typeof itemIndices[item] == 'number') {
{{=$valid}} = false;
j = itemIndices[item];
break;
}
itemIndices[item] = i;
}
{{?}}
}
{{? $isData }} } {{?}}
if (!{{=$valid}}) {
{{# def.error:'uniqueItems' }}
} {{? $breakOnError }} else { {{?}}
{{??}}
{{? $breakOnError }} if (true) { {{?}}
{{?}}

View File

@@ -0,0 +1,24 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2022_error = void 0;
const base_config_1 = require("./base-config");
const es2021_promise_1 = require("./es2021.promise");
exports.es2022_error = {
libs: [es2021_promise_1.es2021_promise],
variables: [
['ErrorOptions', base_config_1.TYPE],
['Error', base_config_1.TYPE],
['ErrorConstructor', base_config_1.TYPE],
['EvalErrorConstructor', base_config_1.TYPE],
['RangeErrorConstructor', base_config_1.TYPE],
['ReferenceErrorConstructor', base_config_1.TYPE],
['SyntaxErrorConstructor', base_config_1.TYPE],
['TypeErrorConstructor', base_config_1.TYPE],
['URIErrorConstructor', base_config_1.TYPE],
['AggregateErrorConstructor', base_config_1.TYPE],
],
};

View File

@@ -0,0 +1,108 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "karakter", verb: "legyen" },
file: { unit: "byte", verb: "legyen" },
array: { unit: "elem", verb: "legyen" },
set: { unit: "elem", verb: "legyen" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "bemenet",
email: "email cím",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO időbélyeg",
date: "ISO dátum",
time: "ISO idő",
duration: "ISO időintervallum",
ipv4: "IPv4 cím",
ipv6: "IPv6 cím",
cidrv4: "IPv4 tartomány",
cidrv6: "IPv6 tartomány",
base64: "base64-kódolt string",
base64url: "base64url-kódolt string",
json_string: "JSON string",
e164: "E.164 szám",
jwt: "JWT",
template_literal: "bemenet",
};
const TypeDictionary = {
nan: "NaN",
number: "szám",
array: "tömb",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Érvénytelen bemenet: a várt érték instanceof ${issue.expected}, a kapott érték ${received}`;
}
return `Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Érvénytelen bemenet: a várt érték ${util.stringifyPrimitive(issue.values[0])}`;
return `Érvénytelen opció: valamelyik érték várt ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Túl nagy: ${issue.origin ?? "érték"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elem"}`;
return `Túl nagy: a bemeneti érték ${issue.origin ?? "érték"} túl nagy: ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;
if (_issue.format === "ends_with")
return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;
if (_issue.format === "includes")
return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;
if (_issue.format === "regex")
return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;
return `Érvénytelen ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`;
case "unrecognized_keys":
return `Ismeretlen kulcs${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Érvénytelen kulcs ${issue.origin}`;
case "invalid_union":
return "Érvénytelen bemenet";
case "invalid_element":
return `Érvénytelen érték: ${issue.origin}`;
default:
return `Érvénytelen bemenet`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,38 @@
/**
* @fileoverview Rule to flag use of ternary operators.
* @author Ian Christian Myers
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow ternary operators",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/no-ternary",
},
schema: [],
messages: {
noTernaryOperator: "Ternary operator used.",
},
},
create(context) {
return {
ConditionalExpression(node) {
context.report({ node, messageId: "noTernaryOperator" });
},
};
},
};

View File

@@ -0,0 +1,400 @@
declare module "node:https" {
import * as http from "node:http";
import { Duplex } from "node:stream";
import * as tls from "node:tls";
import { URL } from "node:url";
interface ServerOptions<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends http.ServerOptions<Request, Response>, tls.TlsOptions {}
interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions {
checkServerIdentity?:
| ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined)
| undefined;
rejectUnauthorized?: boolean | undefined; // Defaults to true
servername?: string | undefined; // SNI TLS Extension
}
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
maxCachedSessions?: number | undefined;
}
/**
* An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information.
*
* Like `http.Agent`, the `createConnection(options[, callback])` method can be overridden
* to customize how TLS connections are established.
*
* > See `agent.createConnection()` for details on overriding this method,
* > including asynchronous socket creation with a callback.
* @since v0.4.5
*/
class Agent extends http.Agent {
constructor(options?: AgentOptions);
options: AgentOptions;
createConnection(
options: RequestOptions,
callback?: (err: Error | null, stream: Duplex) => void,
): Duplex | null | undefined;
getName(options?: RequestOptions): string;
}
interface ServerEventMap<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends http.ServerEventMap<Request, Response>, tls.ServerEventMap {}
/**
* See `http.Server` for more information.
* @since v0.3.4
*/
class Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends tls.Server {
constructor(requestListener?: http.RequestListener<Request, Response>);
constructor(
options: ServerOptions<Request, Response>,
requestListener?: http.RequestListener<Request, Response>,
);
/**
* Closes all connections connected to this server.
* @since v18.2.0
*/
closeAllConnections(): void;
/**
* Closes all connections connected to this server which are not sending a request or waiting for a response.
* @since v18.2.0
*/
closeIdleConnections(): void;
// #region InternalEventEmitter
addListener<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
emit<E extends keyof ServerEventMap>(eventName: E, ...args: ServerEventMap<Request, Response>[E]): boolean;
emit(eventName: string | symbol, ...args: any[]): boolean;
listenerCount<E extends keyof ServerEventMap>(
eventName: E,
listener?: (...args: ServerEventMap<Request, Response>[E]) => void,
): number;
listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number;
listeners<E extends keyof ServerEventMap>(
eventName: E,
): ((...args: ServerEventMap<Request, Response>[E]) => void)[];
listeners(eventName: string | symbol): ((...args: any[]) => void)[];
off<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
off(eventName: string | symbol, listener: (...args: any[]) => void): this;
on<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
on(eventName: string | symbol, listener: (...args: any[]) => void): this;
once<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
prependListener<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
rawListeners<E extends keyof ServerEventMap>(
eventName: E,
): ((...args: ServerEventMap<Request, Response>[E]) => void)[];
rawListeners(eventName: string | symbol): ((...args: any[]) => void)[];
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
removeAllListeners<E extends keyof ServerEventMap>(eventName?: E): this;
removeAllListeners(eventName?: string | symbol): this;
removeListener<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
// #endregion
}
interface Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends http.Server<Request, Response> {}
/**
* ```js
* // curl -k https://localhost:8000/
* import https from 'node:https';
* import fs from 'node:fs';
*
* const options = {
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
* };
*
* https.createServer(options, (req, res) => {
* res.writeHead(200);
* res.end('hello world\n');
* }).listen(8000);
* ```
*
* Or
*
* ```js
* import https from 'node:https';
* import fs from 'node:fs';
*
* const options = {
* pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
* passphrase: 'sample',
* };
*
* https.createServer(options, (req, res) => {
* res.writeHead(200);
* res.end('hello world\n');
* }).listen(8000);
* ```
* @since v0.3.4
* @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`.
* @param requestListener A listener to be added to the `'request'` event.
*/
function createServer<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
>(requestListener?: http.RequestListener<Request, Response>): Server<Request, Response>;
function createServer<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
>(
options: ServerOptions<Request, Response>,
requestListener?: http.RequestListener<Request, Response>,
): Server<Request, Response>;
/**
* Makes a request to a secure web server.
*
* The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`,
* `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`.
*
* `options` can be an object, a string, or a `URL` object. If `options` is a
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
*
* `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to
* upload a file with a POST request, then write to the `ClientRequest` object.
*
* ```js
* import https from 'node:https';
*
* const options = {
* hostname: 'encrypted.google.com',
* port: 443,
* path: '/',
* method: 'GET',
* };
*
* const req = https.request(options, (res) => {
* console.log('statusCode:', res.statusCode);
* console.log('headers:', res.headers);
*
* res.on('data', (d) => {
* process.stdout.write(d);
* });
* });
*
* req.on('error', (e) => {
* console.error(e);
* });
* req.end();
* ```
*
* Example using options from `tls.connect()`:
*
* ```js
* const options = {
* hostname: 'encrypted.google.com',
* port: 443,
* path: '/',
* method: 'GET',
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
* };
* options.agent = new https.Agent(options);
*
* const req = https.request(options, (res) => {
* // ...
* });
* ```
*
* Alternatively, opt out of connection pooling by not using an `Agent`.
*
* ```js
* const options = {
* hostname: 'encrypted.google.com',
* port: 443,
* path: '/',
* method: 'GET',
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
* agent: false,
* };
*
* const req = https.request(options, (res) => {
* // ...
* });
* ```
*
* Example using a `URL` as `options`:
*
* ```js
* const options = new URL('https://abc:xyz@example.com');
*
* const req = https.request(options, (res) => {
* // ...
* });
* ```
*
* Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`):
*
* ```js
* import tls from 'node:tls';
* import https from 'node:https';
* import crypto from 'node:crypto';
*
* function sha256(s) {
* return crypto.createHash('sha256').update(s).digest('base64');
* }
* const options = {
* hostname: 'github.com',
* port: 443,
* path: '/',
* method: 'GET',
* checkServerIdentity: function(host, cert) {
* // Make sure the certificate is issued to the host we are connected to
* const err = tls.checkServerIdentity(host, cert);
* if (err) {
* return err;
* }
*
* // Pin the public key, similar to HPKP pin-sha256 pinning
* const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
* if (sha256(cert.pubkey) !== pubkey256) {
* const msg = 'Certificate verification error: ' +
* `The public key of '${cert.subject.CN}' ` +
* 'does not match our pinned fingerprint';
* return new Error(msg);
* }
*
* // Pin the exact certificate, rather than the pub key
* const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
* 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
* if (cert.fingerprint256 !== cert256) {
* const msg = 'Certificate verification error: ' +
* `The certificate of '${cert.subject.CN}' ` +
* 'does not match our pinned fingerprint';
* return new Error(msg);
* }
*
* // This loop is informational only.
* // Print the certificate and public key fingerprints of all certs in the
* // chain. Its common to pin the public key of the issuer on the public
* // internet, while pinning the public key of the service in sensitive
* // environments.
* do {
* console.log('Subject Common Name:', cert.subject.CN);
* console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256);
*
* hash = crypto.createHash('sha256');
* console.log(' Public key ping-sha256:', sha256(cert.pubkey));
*
* lastprint256 = cert.fingerprint256;
* cert = cert.issuerCertificate;
* } while (cert.fingerprint256 !== lastprint256);
*
* },
* };
*
* options.agent = new https.Agent(options);
* const req = https.request(options, (res) => {
* console.log('All OK. Server matched our pinned cert or public key');
* console.log('statusCode:', res.statusCode);
* // Print the HPKP values
* console.log('headers:', res.headers['public-key-pins']);
*
* res.on('data', (d) => {});
* });
*
* req.on('error', (e) => {
* console.error(e.message);
* });
* req.end();
* ```
*
* Outputs for example:
*
* ```text
* Subject Common Name: github.com
* Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
* Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
* Subject Common Name: DigiCert SHA2 Extended Validation Server CA
* Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
* Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
* Subject Common Name: DigiCert High Assurance EV Root CA
* Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
* Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
* All OK. Server matched our pinned cert or public key
* statusCode: 200
* headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=";
* pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=";
* pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains
* ```
* @since v0.3.6
* @param options Accepts all `options` from `request`, with some differences in default values:
*/
function request(
options: RequestOptions | string | URL,
callback?: (res: http.IncomingMessage) => void,
): http.ClientRequest;
function request(
url: string | URL,
options: RequestOptions,
callback?: (res: http.IncomingMessage) => void,
): http.ClientRequest;
/**
* Like `http.get()` but for HTTPS.
*
* `options` can be an object, a string, or a `URL` object. If `options` is a
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
*
* ```js
* import https from 'node:https';
*
* https.get('https://encrypted.google.com/', (res) => {
* console.log('statusCode:', res.statusCode);
* console.log('headers:', res.headers);
*
* res.on('data', (d) => {
* process.stdout.write(d);
* });
*
* }).on('error', (e) => {
* console.error(e);
* });
* ```
* @since v0.3.6
* @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`.
*/
function get(
options: RequestOptions | string | URL,
callback?: (res: http.IncomingMessage) => void,
): http.ClientRequest;
function get(
url: string | URL,
options: RequestOptions,
callback?: (res: http.IncomingMessage) => void,
): http.ClientRequest;
let globalAgent: Agent;
}
declare module "https" {
export * from "node:https";
}

View File

@@ -0,0 +1,5 @@
import { SolanaError } from './error';
export declare function getSolanaErrorFromTransactionError(transactionError: string | {
[key: string]: unknown;
}): SolanaError;
//# sourceMappingURL=transaction-error.d.ts.map

View File

@@ -0,0 +1,119 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "حروف", verb: "ہونا" },
file: { unit: "بائٹس", verb: "ہونا" },
array: { unit: "آئٹمز", verb: "ہونا" },
set: { unit: "آئٹمز", verb: "ہونا" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "ان پٹ",
email: "ای میل ایڈریس",
url: "یو آر ایل",
emoji: "ایموجی",
uuid: "یو یو آئی ڈی",
uuidv4: "یو یو آئی ڈی وی 4",
uuidv6: "یو یو آئی ڈی وی 6",
nanoid: "نینو آئی ڈی",
guid: "جی یو آئی ڈی",
cuid: "سی یو آئی ڈی",
cuid2: "سی یو آئی ڈی 2",
ulid: "یو ایل آئی ڈی",
xid: "ایکس آئی ڈی",
ksuid: "کے ایس یو آئی ڈی",
datetime: "آئی ایس او ڈیٹ ٹائم",
date: "آئی ایس او تاریخ",
time: "آئی ایس او وقت",
duration: "آئی ایس او مدت",
ipv4: "آئی پی وی 4 ایڈریس",
ipv6: "آئی پی وی 6 ایڈریس",
cidrv4: "آئی پی وی 4 رینج",
cidrv6: "آئی پی وی 6 رینج",
base64: "بیس 64 ان کوڈڈ سٹرنگ",
base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",
json_string: "جے ایس او این سٹرنگ",
e164: "ای 164 نمبر",
jwt: "جے ڈبلیو ٹی",
template_literal: "ان پٹ",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
number: "نمبر",
array: "آرے",
null: "نل",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `غلط ان پٹ: instanceof ${issue.expected} متوقع تھا، ${received} موصول ہوا`;
}
return `غلط ان پٹ: ${expected} متوقع تھا، ${received} موصول ہوا`;
}
case "invalid_value":
if (issue.values.length === 1) return `غلط ان پٹ: ${util.stringifyPrimitive(issue.values[0])} متوقع تھا`;
return `غلط آپشن: ${util.joinValues(issue.values, "|")} میں سے ایک متوقع تھا`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `بہت بڑا: ${issue.origin ?? "ویلیو"} کے ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`;
return `بہت بڑا: ${issue.origin ?? "ویلیو"} کا ${adj}${issue.maximum.toString()} ہونا متوقع تھا`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `بہت چھوٹا: ${issue.origin} کے ${adj}${issue.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;
}
return `بہت چھوٹا: ${issue.origin} کا ${adj}${issue.minimum.toString()} ہونا متوقع تھا`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") {
return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`;
}
if (_issue.format === "ends_with") return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`;
if (_issue.format === "includes") return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`;
if (_issue.format === "regex") return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;
return `غلط ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `غلط نمبر: ${issue.divisor} کا مضاعف ہونا چاہیے`;
case "unrecognized_keys":
return `غیر تسلیم شدہ کی${issue.keys.length > 1 ? "ز" : ""}: ${util.joinValues(issue.keys, "، ")}`;
case "invalid_key":
return `${issue.origin} میں غلط کی`;
case "invalid_union":
return "غلط ان پٹ";
case "invalid_element":
return `${issue.origin} میں غلط ویلیو`;
default:
return `غلط ان پٹ`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,276 @@
/**
* @fileoverview Rule to flag comparisons to the value NaN
* @author James Allardice
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Determines if the given node is a NaN `Identifier` node.
* @param {ASTNode|null} node The node to check.
* @param {SourceCode} sourceCode The source code object.
* @returns {boolean} `true` if the node is a global 'NaN' identifier.
*/
function isNaNIdentifier(node, sourceCode) {
if (!node) {
return false;
}
const nodeToCheck =
node.type === "SequenceExpression" ? node.expressions.at(-1) : node;
if (astUtils.isSpecificId(nodeToCheck, "NaN")) {
return sourceCode.isGlobalReference(nodeToCheck);
}
if (astUtils.isSpecificMemberAccess(nodeToCheck, "Number", "NaN")) {
const objectNode = astUtils.skipChainExpression(nodeToCheck).object;
return sourceCode.isGlobalReference(objectNode);
}
return false;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
hasSuggestions: true,
type: "problem",
docs: {
description: "Require calls to `isNaN()` when checking for `NaN`",
recommended: true,
url: "https://eslint.org/docs/latest/rules/use-isnan",
},
schema: [
{
type: "object",
properties: {
enforceForSwitchCase: {
type: "boolean",
},
enforceForIndexOf: {
type: "boolean",
},
},
additionalProperties: false,
},
],
defaultOptions: [
{
enforceForIndexOf: false,
enforceForSwitchCase: true,
},
],
messages: {
comparisonWithNaN: "Use the isNaN function to compare with NaN.",
switchNaN:
"'switch(NaN)' can never match a case clause. Use Number.isNaN instead of the switch.",
caseNaN:
"'case NaN' can never match. Use Number.isNaN before the switch.",
indexOfNaN:
"Array prototype method '{{ methodName }}' cannot find NaN.",
replaceWithIsNaN: "Replace with Number.isNaN.",
replaceWithCastingAndIsNaN:
"Replace with Number.isNaN and cast to a Number.",
replaceWithFindIndex:
"Replace with Array.prototype.{{ methodName }}.",
},
},
create(context) {
const [{ enforceForIndexOf, enforceForSwitchCase }] = context.options;
const sourceCode = context.sourceCode;
const fixableOperators = new Set(["==", "===", "!=", "!=="]);
const castableOperators = new Set(["==", "!="]);
/**
* Get a fixer for a binary expression that compares to NaN.
* @param {ASTNode} node The node to fix.
* @param {function(string): string} wrapValue A function that wraps the compared value with a fix.
* @returns {function(Fixer): Fix} The fixer function.
*/
function getBinaryExpressionFixer(node, wrapValue) {
return fixer => {
const comparedValue = isNaNIdentifier(node.left, sourceCode)
? node.right
: node.left;
const shouldWrap = comparedValue.type === "SequenceExpression";
const shouldNegate = node.operator[0] === "!";
const negation = shouldNegate ? "!" : "";
let comparedValueText = sourceCode.getText(comparedValue);
if (shouldWrap) {
comparedValueText = `(${comparedValueText})`;
}
const fixedValue = wrapValue(comparedValueText);
return fixer.replaceText(node, `${negation}${fixedValue}`);
};
}
/**
* Checks the given `BinaryExpression` node for `foo === NaN` and other comparisons.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkBinaryExpression(node) {
if (
/^(?:[<>]|[!=]=)=?$/u.test(node.operator) &&
(isNaNIdentifier(node.left, sourceCode) ||
isNaNIdentifier(node.right, sourceCode))
) {
const suggestedFixes = [];
const NaNNode = isNaNIdentifier(node.left, sourceCode)
? node.left
: node.right;
const isSequenceExpression =
NaNNode.type === "SequenceExpression";
const isSuggestable =
fixableOperators.has(node.operator) &&
!isSequenceExpression;
const isCastable = castableOperators.has(node.operator);
if (isSuggestable) {
suggestedFixes.push({
messageId: "replaceWithIsNaN",
fix: getBinaryExpressionFixer(
node,
value => `Number.isNaN(${value})`,
),
});
if (isCastable) {
suggestedFixes.push({
messageId: "replaceWithCastingAndIsNaN",
fix: getBinaryExpressionFixer(
node,
value => `Number.isNaN(Number(${value}))`,
),
});
}
}
context.report({
node,
messageId: "comparisonWithNaN",
suggest: suggestedFixes,
});
}
}
/**
* Checks the discriminant and all case clauses of the given `SwitchStatement` node for `switch(NaN)` and `case NaN:`
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkSwitchStatement(node) {
if (isNaNIdentifier(node.discriminant, sourceCode)) {
context.report({ node, messageId: "switchNaN" });
}
for (const switchCase of node.cases) {
if (isNaNIdentifier(switchCase.test, sourceCode)) {
context.report({ node: switchCase, messageId: "caseNaN" });
}
}
}
/**
* Checks the given `CallExpression` node for `.indexOf(NaN)` and `.lastIndexOf(NaN)`.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkCallExpression(node) {
const callee = astUtils.skipChainExpression(node.callee);
if (callee.type === "MemberExpression") {
const methodName = astUtils.getStaticPropertyName(callee);
if (
(methodName === "indexOf" ||
methodName === "lastIndexOf") &&
node.arguments.length <= 2 &&
isNaNIdentifier(node.arguments[0], sourceCode)
) {
/*
* To retain side effects, it's essential to address `NaN` beforehand, which
* is not possible with fixes like `arr.findIndex(Number.isNaN)`.
*/
const isSuggestable =
node.arguments[0].type !== "SequenceExpression" &&
!node.arguments[1];
const suggestedFixes = [];
if (isSuggestable) {
const shouldWrap = callee.computed;
const findIndexMethod =
methodName === "indexOf"
? "findIndex"
: "findLastIndex";
const propertyName = shouldWrap
? `"${findIndexMethod}"`
: findIndexMethod;
suggestedFixes.push({
messageId: "replaceWithFindIndex",
data: { methodName: findIndexMethod },
fix: fixer => [
fixer.replaceText(
callee.property,
propertyName,
),
fixer.replaceText(
node.arguments[0],
"Number.isNaN",
),
],
});
}
context.report({
node,
messageId: "indexOfNaN",
data: { methodName },
suggest: suggestedFixes,
});
}
}
}
const listeners = {
BinaryExpression: checkBinaryExpression,
};
if (enforceForSwitchCase) {
listeners.SwitchStatement = checkSwitchStatement;
}
if (enforceForIndexOf) {
listeners.CallExpression = checkCallExpression;
}
return listeners;
},
};