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 @@
{"version":3,"file":"_shortw_utils.d.ts","sourceRoot":"","sources":["../src/_shortw_utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,sEAAsE;AACtE,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,SAAS,EAAe,MAAM,2BAA2B,CAAC;AACtF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,4CAA4C;AAC5C,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK,GAAG;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,CAEpD;AACD,+EAA+E;AAC/E,MAAM,MAAM,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;AACzD,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG;IAAE,MAAM,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,OAAO,CAAA;CAAE,CAAC;AAE/E,gEAAgE;AAChE,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,GAAG,iBAAiB,CAGjF"}

View File

@@ -0,0 +1,5 @@
module.exports = noop;
module.exports.HttpsAgent = noop;
// Noop function for browser since native api's don't use agents.
function noop () {}

View File

@@ -0,0 +1,17 @@
import { ParsedStack } from '@vitest/utils';
interface SnapshotEnvironment {
getVersion: () => string;
getHeader: () => string;
resolvePath: (filepath: string) => Promise<string>;
resolveRawPath: (testPath: string, rawPath: string) => Promise<string>;
saveSnapshotFile: (filepath: string, snapshot: string) => Promise<void>;
readSnapshotFile: (filepath: string) => Promise<string | null>;
removeSnapshotFile: (filepath: string) => Promise<void>;
processStackTrace?: (stack: ParsedStack) => ParsedStack;
}
interface SnapshotEnvironmentOptions {
snapshotsDirName?: string;
}
export type { SnapshotEnvironment as S, SnapshotEnvironmentOptions as a };

View File

@@ -0,0 +1,325 @@
# magic-string
<a href="https://github.com/Rich-Harris/magic-string/actions/workflows/test.yml">
<img src="https://img.shields.io/github/actions/workflow/status/Rich-Harris/magic-string/test.yml"
alt="build status">
</a>
<a href="https://npmjs.org/package/magic-string">
<img src="https://img.shields.io/npm/v/magic-string.svg"
alt="npm version">
</a>
<a href="https://github.com/Rich-Harris/magic-string/blob/master/LICENSE.md">
<img src="https://img.shields.io/npm/l/magic-string.svg"
alt="license">
</a>
Suppose you have some source code. You want to make some light modifications to it - replacing a few characters here and there, wrapping it with a header and footer, etc - and ideally you'd like to generate a [source map](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/) at the end of it. You've thought about using something like [recast](https://github.com/benjamn/recast) (which allows you to generate an AST from some JavaScript, manipulate it, and reprint it with a sourcemap without losing your comments and formatting), but it seems like overkill for your needs (or maybe the source code isn't JavaScript).
Your requirements are, frankly, rather niche. But they're requirements that I also have, and for which I made magic-string. It's a small, fast utility for manipulating strings and generating sourcemaps.
## Installation
magic-string works in both node.js and browser environments. For node, install with npm:
```bash
npm i magic-string
```
To use in browser, grab the [magic-string.umd.js](https://unpkg.com/magic-string/dist/magic-string.umd.js) file and add it to your page:
```html
<script src="magic-string.umd.js"></script>
```
(It also works with various module systems, if you prefer that sort of thing - it has a dependency on [vlq](https://github.com/Rich-Harris/vlq).)
## Usage
These examples assume you're in node.js, or something similar:
```js
import MagicString from 'magic-string';
import fs from 'fs';
const s = new MagicString('problems = 99');
s.update(0, 8, 'answer');
s.toString(); // 'answer = 99'
s.update(11, 13, '42'); // character indices always refer to the original string
s.toString(); // 'answer = 42'
s.prepend('var ').append(';'); // most methods are chainable
s.toString(); // 'var answer = 42;'
const map = s.generateMap({
source: 'source.js',
file: 'converted.js.map',
includeContent: true,
}); // generates a v3 sourcemap
fs.writeFileSync('converted.js', s.toString());
fs.writeFileSync('converted.js.map', map.toString());
```
You can pass an options argument:
```js
const s = new MagicString(someCode, {
// these options will be used if you later call `bundle.addSource( s )` - see below
filename: 'foo.js',
indentExclusionRanges: [
/*...*/
],
// mark source as ignore in DevTools, see below #Bundling
ignoreList: false,
// adjust the incoming position - see below
offset: 0,
});
```
## Properties
### s.offset
Sets the offset property to adjust the incoming position for the following APIs: `slice`, `update`, `overwrite`, `appendLeft`, `prependLeft`, `appendRight`, `prependRight`, `move`, `reset`, and `remove`.
Example usage:
```ts
const s = new MagicString('hello world', { offset: 0 });
s.offset = 6;
s.slice() === 'world';
```
## Methods
### s.addSourcemapLocation( index )
Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is `false` (see below).
### s.append( content )
Appends the specified content to the end of the string. Returns `this`.
### s.appendLeft( index, content )
Appends the specified `content` at the `index` in the original string. If a range _ending_ with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependLeft(...)`.
### s.appendRight( index, content )
Appends the specified `content` at the `index` in the original string. If a range _starting_ with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependRight(...)`.
### s.clone()
Does what you'd expect.
### s.generateDecodedMap( options )
Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. See `generateMap` documentation below for options details. Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
### s.generateMap( options )
Generates a [version 3 sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). All options are, well, optional:
- `file` - the filename where you plan to write the sourcemap
- `source` - the filename of the file containing the original source
- `includeContent` - whether to include the original content in the map's `sourcesContent` array
- `hires` - whether the mapping should be high-resolution. Hi-res mappings map every single character, meaning (for example) your devtools will always be able to pinpoint the exact location of function calls and so on. With lo-res mappings, devtools may only be able to identify the correct line - but they're quicker to generate and less bulky. You can also set `"boundary"` to generate a semi-hi-res mappings segmented per word boundary instead of per character, suitable for string semantics that are separated by words. If sourcemap locations have been specified with `s.addSourcemapLocation()`, they will be used here.
The returned sourcemap has two (non-enumerable) methods attached for convenience:
- `toString` - returns the equivalent of `JSON.stringify(map)`
- `toUrl` - returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
```js
code += '\n//# sourceMappingURL=' + map.toUrl();
```
### s.hasChanged()
Indicates if the string has been changed.
### s.indent( prefix[, options] )
Prefixes each line of the string with `prefix`. If `prefix` is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. Returns `this`.
The `options` argument can have an `exclude` property, which is an array of `[start, end]` character ranges. These ranges will be excluded from the indentation - useful for (e.g.) multiline strings.
### s.insertLeft( index, content )
**DEPRECATED** since 0.17 use `s.appendLeft(...)` instead
### s.insertRight( index, content )
**DEPRECATED** since 0.17 use `s.prependRight(...)` instead
### s.isEmpty()
Returns true if the resulting source is empty (disregarding white space).
### s.locate( index )
**DEPRECATED** since 0.10 see [#30](https://github.com/Rich-Harris/magic-string/pull/30)
### s.locateOrigin( index )
**DEPRECATED** since 0.10 see [#30](https://github.com/Rich-Harris/magic-string/pull/30)
### s.move( start, end, index )
Moves the characters from `start` and `end` to `index`. Returns `this`.
### s.overwrite( start, end, content[, options] )
Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in that range. The same restrictions as `s.remove()` apply. Returns `this`.
The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and a `contentOnly` property which determines whether only the content is overwritten, or anything that was appended/prepended to the range as well.
It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
### s.prepend( content )
Prepends the string with the specified content. Returns `this`.
### s.prependLeft ( index, content )
Same as `s.appendLeft(...)`, except that the inserted content will go _before_ any previous appends or prepends at `index`
### s.prependRight ( index, content )
Same as `s.appendRight(...)`, except that the inserted content will go _before_ any previous appends or prepends at `index`
### s.replace( regexpOrString, substitution )
String replacement with RegExp or string. The `substitution` parameter supports strings and functions. Returns `this`.
```ts
import MagicString from 'magic-string';
const s = new MagicString(source);
s.replace('foo', 'bar');
s.replace('foo', (str, index, s) => str + '-' + index);
s.replace(/foo/g, 'bar');
s.replace(/(\w)(\d+)/g, (_, $1, $2) => $1.toUpperCase() + $2);
```
The differences from [`String.replace`](<(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)>):
- It will always match against the **original string**
- It mutates the magic string state (use `.clone()` to be immutable)
### s.replaceAll( regexpOrString, substitution )
Same as `s.replace`, but replace all matched strings instead of just one.
If `regexpOrString` is a regex, then it must have the global (`g`) flag set, or a `TypeError` is thrown. Matches the behavior of the builtin [`String.property.replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll). Returns `this`.
### s.remove( start, end )
Removes the characters from `start` to `end` (of the original string, **not** the generated string). Removing the same content twice, or making removals that partially overlap, will cause an error. Returns `this`.
### s.reset( start, end )
Resets the characters from `start` to `end` (of the original string, **not** the generated string).
It can be used to restore previously removed characters and discard unwanted changes.
### s.slice( start, end )
Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. Throws error if the indices are for characters that were already removed.
### s.snip( start, end )
Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
### s.toString()
Returns the generated string.
### s.trim([ charType ])
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. Returns `this`.
### s.trimStart([ charType ])
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. Returns `this`.
### s.trimEnd([ charType ])
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. Returns `this`.
### s.trimLines()
Removes empty lines from the start and end. Returns `this`.
### s.update( start, end, content[, options] )
Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. Returns `this`.
The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and an `overwrite` property which defaults to `false` and determines whether anything that was appended/prepended to the range will be overwritten along with the original content.
`s.update(start, end, content)` is equivalent to `s.overwrite(start, end, content, { contentOnly: true })`.
## Bundling
To concatenate several sources, use `MagicString.Bundle`:
```js
const bundle = new MagicString.Bundle();
bundle.addSource({
filename: 'foo.js',
content: new MagicString('var answer = 42;'),
});
bundle.addSource({
filename: 'bar.js',
content: new MagicString('console.log( answer )'),
});
// Sources can be marked as ignore-listed, which provides a hint to debuggers
// to not step into this code and also don't show the source files depending
// on user preferences.
bundle.addSource({
filename: 'some-3rdparty-library.js',
content: new MagicString('function myLib(){}'),
ignoreList: false, // <--
});
// Advanced: a source can include an `indentExclusionRanges` property
// alongside `filename` and `content`. This will be passed to `s.indent()`
// - see documentation above
bundle
.indent() // optionally, pass an indent string, otherwise it will be guessed
.prepend('(function () {\n')
.append('}());');
bundle.toString();
// (function () {
// var answer = 42;
// console.log( answer );
// }());
// options are as per `s.generateMap()` above
const map = bundle.generateMap({
file: 'bundle.js',
includeContent: true,
hires: true,
});
```
As an alternative syntax, if you a) don't have `filename` or `indentExclusionRanges` options, or b) passed those in when you used `new MagicString(...)`, you can simply pass the `MagicString` instance itself:
```js
const bundle = new MagicString.Bundle();
const source = new MagicString(someCode, {
filename: 'foo.js',
});
bundle.addSource(source);
```
## License
MIT

View File

@@ -0,0 +1,24 @@
'use strict';
const {Transform} = require('stream');
const {next} = require('./asGen');
const {sanitize} = require('../index');
const gen = (...fns) => {
fns = fns.filter(fn => fn);
return fns.length
? new Transform({
writableObjectMode: true,
readableObjectMode: true,
transform(chunk, encoding, callback) {
(async () => {
for await (let value of next(chunk, fns, 0)) {
sanitize(value, this);
}
})().then(() => callback(null), error => callback(error));
}
})
: null;
};
module.exports = gen;

View File

@@ -0,0 +1,45 @@
function _asyncIterator(r) {
var n,
t,
o,
e = 2;
for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
if (t && null != (n = r[t])) return n.call(r);
if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
t = "@@asyncIterator", o = "@@iterator";
}
throw new TypeError("Object is not async iterable");
}
function AsyncFromSyncIterator(r) {
function AsyncFromSyncIteratorContinuation(r) {
if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
var n = r.done;
return Promise.resolve(r.value).then(function (r) {
return {
value: r,
done: n
};
});
}
return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {
this.s = r, this.n = r.next;
}, AsyncFromSyncIterator.prototype = {
s: null,
n: null,
next: function next() {
return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
},
"return": function _return(r) {
var n = this.s["return"];
return void 0 === n ? Promise.resolve({
value: r,
done: !0
}) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
},
"throw": function _throw(r) {
var n = this.s["return"];
return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
}
}, new AsyncFromSyncIterator(r);
}
module.exports = _asyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,100 @@
import * as ts from 'typescript';
import type { TypeOrValueSpecifier } from './TypeOrValueSpecifier';
export interface ReadonlynessOptions {
readonly allow?: TypeOrValueSpecifier[];
readonly treatMethodsAsReadonly?: boolean;
}
export declare const readonlynessOptionsSchema: {
additionalProperties: false;
properties: {
allow: {
readonly items: {
readonly oneOf: [{
readonly type: 'string';
}, {
readonly additionalProperties: false;
readonly properties: {
readonly from: {
readonly enum: ["file"];
readonly type: 'string';
};
readonly name: {
readonly oneOf: [{
readonly type: 'string';
}, {
readonly items: {
readonly type: 'string';
};
readonly minItems: 1;
readonly type: 'array';
readonly uniqueItems: true;
}];
};
readonly path: {
readonly type: 'string';
};
};
readonly required: ["from", "name"];
readonly type: 'object';
}, {
readonly additionalProperties: false;
readonly properties: {
readonly from: {
readonly enum: ["lib"];
readonly type: 'string';
};
readonly name: {
readonly oneOf: [{
readonly type: 'string';
}, {
readonly items: {
readonly type: 'string';
};
readonly minItems: 1;
readonly type: 'array';
readonly uniqueItems: true;
}];
};
};
readonly required: ["from", "name"];
readonly type: 'object';
}, {
readonly additionalProperties: false;
readonly properties: {
readonly from: {
readonly enum: ["package"];
readonly type: 'string';
};
readonly name: {
readonly oneOf: [{
readonly type: 'string';
}, {
readonly items: {
readonly type: 'string';
};
readonly minItems: 1;
readonly type: 'array';
readonly uniqueItems: true;
}];
};
readonly package: {
readonly type: 'string';
};
};
readonly required: ["from", "name", "package"];
readonly type: 'object';
}];
};
readonly type: 'array';
};
treatMethodsAsReadonly: {
type: "boolean";
};
};
type: "object";
};
export declare const readonlynessOptionsDefaults: ReadonlynessOptions;
/**
* Checks if the given type is readonly
*/
export declare function isTypeReadonly(program: ts.Program, type: ts.Type, options?: ReadonlynessOptions): boolean;

View File

@@ -0,0 +1 @@
"use strict";var s=Object.defineProperty;var o=(e,i)=>s(e,"name",{value:i,configurable:!0});var c=require("node:worker_threads"),a=require("../node-features-CEjg7cMX.cjs"),r=require("../register-Ciecs-Zx.cjs");require("node:crypto"),require("../get-pipe-path-D4YM6rQt.cjs"),require("node:module"),require("node:path"),require("node:url"),require("../register-C557imBs.cjs"),require("node:fs"),require("esbuild"),require("../index-6kqi0x0U.cjs"),require("../client-D3mGB526.cjs"),require("../require-DDxgG93A.cjs"),require("node:fs/promises"),require("module"),require("../temporary-directory-B83uKxJF.cjs"),require("node:os"),require("fs"),require("os"),require("path"),require("node:util"),require("../index-BWFBUo6r.cjs"),require("node:net");function q(e){var i=Object.create(null);return e&&Object.keys(e).forEach(function(t){if(t!=="default"){var l=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,l.get?l:{enumerable:!0,get:o(function(){return e[t]},"get")})}}),i.default=e,Object.freeze(i)}o(q,"_interopNamespaceDefault");var n=q(c);(a.isFeatureSupported(a.moduleRegisterHooksCjsReload)&&!n.isInternalThread||a.isFeatureSupported(a.moduleRegister)&&n.isMainThread)&&r.register();const u=r.createDefaultData(),d=r.createInitialize(u),f=r.createGlobalPreload(u),p=r.createLoad(u),b=r.createResolve(u);exports.globalPreload=f,exports.initialize=d,exports.load=p,exports.resolve=b;

View File

@@ -0,0 +1,9 @@
// Code generated by Herebyfile.mjs generate:enums from internal/core/compileroptions.go. DO NOT EDIT.
export var ModuleDetectionKind;
(function (ModuleDetectionKind) {
ModuleDetectionKind[ModuleDetectionKind["None"] = 0] = "None";
ModuleDetectionKind[ModuleDetectionKind["Auto"] = 1] = "Auto";
ModuleDetectionKind[ModuleDetectionKind["Legacy"] = 2] = "Legacy";
ModuleDetectionKind[ModuleDetectionKind["Force"] = 3] = "Force";
})(ModuleDetectionKind || (ModuleDetectionKind = {}));
//# sourceMappingURL=moduleDetectionKind.enum.js.map

View File

@@ -0,0 +1,25 @@
# tinyglobby
[![npm version](https://img.shields.io/npm/v/tinyglobby.svg?maxAge=3600)](https://npmjs.com/package/tinyglobby)
[![weekly downloads](https://img.shields.io/npm/dw/tinyglobby.svg?maxAge=3600)](https://npmjs.com/package/tinyglobby)
A fast and minimal alternative to globby and fast-glob, meant to behave the same way.
Both globby and fast-glob present some behavior no other globbing lib has,
which makes it hard to manually replace with something smaller and better.
This library uses only two subdependencies, compared to `globby`'s [23](https://npmgraph.js.org/?q=globby@16.2.0)
and `fast-glob`'s [17](https://npmgraph.js.org/?q=fast-glob@3.3.3).
## Usage
```js
import { glob, globSync } from 'tinyglobby';
await glob(['files/*.ts', '!**/*.d.ts'], { cwd: 'src' });
globSync('src/**/*.ts', { ignore: '**/*.d.ts' });
```
## Documentation
Visit https://superchupu.dev/tinyglobby to read the full documentation.

View File

@@ -0,0 +1,95 @@
{
"name": "@typescript-eslint/typescript-estree",
"version": "8.67.0",
"description": "A parser that converts TypeScript source code into an ESTree compatible form",
"files": [
"dist",
"!**/*.tsbuildinfo"
],
"type": "commonjs",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json",
"./use-at-your-own-risk": {
"types": "./dist/use-at-your-own-risk.d.ts",
"default": "./dist/use-at-your-own-risk.js"
}
},
"types": "./dist/index.d.ts",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"repository": {
"type": "git",
"url": "https://github.com/typescript-eslint/typescript-eslint.git",
"directory": "packages/typescript-estree"
},
"bugs": {
"url": "https://github.com/typescript-eslint/typescript-eslint/issues"
},
"homepage": "https://typescript-eslint.io/packages/typescript-estree",
"license": "MIT",
"keywords": [
"ast",
"estree",
"ecmascript",
"javascript",
"typescript",
"parser",
"syntax"
],
"dependencies": {
"debug": "^4.4.3",
"minimatch": "^10.2.2",
"semver": "^7.7.3",
"tinyglobby": "^0.2.15",
"ts-api-utils": "^2.5.0",
"@typescript-eslint/project-service": "8.67.0",
"@typescript-eslint/types": "8.67.0",
"@typescript-eslint/tsconfig-utils": "8.67.0",
"@typescript-eslint/visitor-keys": "8.67.0"
},
"devDependencies": {
"@typescript/native": "npm:typescript@^7.0.2",
"@vitest/coverage-v8": "^4.0.18",
"eslint": "^10.0.0",
"glob": "^11.1.0",
"rimraf": "^5.0.10",
"typescript": ">=4.8.4 <6.1.0",
"vitest": "^4.0.18",
"yaml": "^2.8.2"
},
"peerDependencies": {
"typescript": ">=4.8.4 <6.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"nx": {
"name": "typescript-estree",
"includedScripts": [
"clean"
],
"targets": {
"lint": {
"command": "eslint"
},
"typecheck:tsgo": {},
"attw-check": {}
}
},
"scripts": {
"build": "pnpm exec nx build",
"clean": "rimraf dist/ coverage/",
"format": "pnpm -w run format",
"lint": "pnpm -w exec nx lint",
"test": "pnpm -w exec nx test",
"typecheck": "pnpm -w exec nx typecheck",
"typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo",
"attw-check": "pnpm -w exec nx attw-check"
}
}

View File

@@ -0,0 +1,53 @@
'use strict';
const {Transform} = require('stream');
const {StringDecoder} = require('string_decoder');
class Utf8Stream extends Transform {
constructor(options) {
super(Object.assign({}, options, {writableObjectMode: false}));
this._buffer = '';
}
_transform(chunk, encoding, callback) {
if (typeof chunk == 'string') {
this._transform = this._transformString;
} else {
this._stringDecoder = new StringDecoder();
this._transform = this._transformBuffer;
}
this._transform(chunk, encoding, callback);
}
_transformBuffer(chunk, _, callback) {
this._buffer += this._stringDecoder.write(chunk);
this._processBuffer(callback);
}
_transformString(chunk, _, callback) {
this._buffer += chunk.toString();
this._processBuffer(callback);
}
_processBuffer(callback) {
if (this._buffer) {
this.push(this._buffer, 'utf8');
this._buffer = '';
}
callback(null);
}
_flushInput() {
// meant to be called from _flush()
if (this._stringDecoder) {
this._buffer += this._stringDecoder.end();
}
}
_flush(callback) {
this._flushInput();
this._processBuffer(callback);
}
}
module.exports = Utf8Stream;

View File

@@ -0,0 +1,137 @@
[
{
"_id": "59ef4a83ee8364808d761beb",
"index": 0,
"guid": "e50ffae9-7128-4148-9ee5-40c3fc523c5d",
"isActive": false,
"balance": "$2,341.81",
"picture": "http://placehold.it/32x32",
"age": 28,
"eyeColor": "brown",
"name": "Carey Savage",
"gender": "female",
"company": "VERAQ",
"email": "careysavage@veraq.com",
"phone": "+1 (897) 574-3014",
"address": "458 Willow Street, Henrietta, California, 7234",
"about": "Nisi reprehenderit nulla ad officia pariatur non dolore laboris irure cupidatat laborum. Minim eu ex Lorem adipisicing exercitation irure minim sunt est enim mollit incididunt voluptate nulla. Ut mollit anim reprehenderit et aliqua ex esse aliquip. Aute sit duis deserunt do incididunt consequat minim qui dolor commodo deserunt et voluptate.\r\n",
"registered": "2014-05-21T01:56:51 -01:00",
"latitude": 63.89502,
"longitude": 62.369807,
"tags": [
"nostrud",
"nisi",
"consectetur",
"ullamco",
"cupidatat",
"culpa",
"commodo"
],
"friends": [
{
"id": 0,
"name": "Henry Walls"
},
{
"id": 1,
"name": "Janice Baker"
},
{
"id": 2,
"name": "Russell Bush"
}
],
"greeting": "Hello, Carey Savage! You have 4 unread messages.",
"favoriteFruit": "banana"
},
{
"_id": "59ef4a83ff5774a691454e89",
"index": 1,
"guid": "2bee9efc-4095-4c2e-87ef-d08c8054c89d",
"isActive": true,
"balance": "$1,618.15",
"picture": "http://placehold.it/32x32",
"age": 35,
"eyeColor": "blue",
"name": "Elinor Pearson",
"gender": "female",
"company": "FLEXIGEN",
"email": "elinorpearson@flexigen.com",
"phone": "+1 (923) 548-3751",
"address": "600 Bayview Avenue, Draper, Montana, 3088",
"about": "Mollit commodo ea sit Lorem velit. Irure anim esse Lorem sint quis officia ut. Aliqua nisi dolore in aute deserunt mollit ex ea in mollit.\r\n",
"registered": "2017-04-22T07:58:41 -01:00",
"latitude": -87.824919,
"longitude": 69.538927,
"tags": [
"fugiat",
"labore",
"proident",
"quis",
"eiusmod",
"qui",
"est"
],
"friends": [
{
"id": 0,
"name": "Massey Wagner"
},
{
"id": 1,
"name": "Marcella Ferrell"
},
{
"id": 2,
"name": "Evans Mckee"
}
],
"greeting": "Hello, Elinor Pearson! You have 3 unread messages.",
"favoriteFruit": "strawberry"
},
{
"_id": "59ef4a839ec8a4be4430b36b",
"index": 2,
"guid": "ddd6e8c0-95bd-416d-8b46-a768d6363809",
"isActive": false,
"balance": "$2,046.95",
"picture": "http://placehold.it/32x32",
"age": 40,
"eyeColor": "green",
"name": "Irwin Davidson",
"gender": "male",
"company": "DANJA",
"email": "irwindavidson@danja.com",
"phone": "+1 (883) 537-2041",
"address": "439 Cook Street, Chapin, Kentucky, 7398",
"about": "Irure velit non commodo aliqua exercitation ut nostrud minim magna. Dolor ad ad ut irure eu. Non pariatur dolor eiusmod ipsum do et exercitation cillum. Et amet laboris minim eiusmod ullamco magna ea reprehenderit proident sunt.\r\n",
"registered": "2016-09-01T07:49:08 -01:00",
"latitude": -49.803812,
"longitude": 104.93279,
"tags": [
"consequat",
"enim",
"quis",
"magna",
"est",
"culpa",
"tempor"
],
"friends": [
{
"id": 0,
"name": "Ruth Hansen"
},
{
"id": 1,
"name": "Kathrine Austin"
},
{
"id": 2,
"name": "Rivera Munoz"
}
],
"greeting": "Hello, Irwin Davidson! You have 2 unread messages.",
"favoriteFruit": "banana"
}
]

View File

@@ -0,0 +1,184 @@
const { bench, group, run } = require('mitata')
const slowRedact = require('../index.js')
const fastRedact = require('fast-redact')
// Test objects
const smallObj = {
user: { name: 'john', password: 'secret123' },
headers: { cookie: 'session-token', authorization: 'Bearer abc123' }
}
const largeObj = {
users: [],
metadata: {
version: '1.0.0',
secret: 'app-secret-key',
database: {
host: 'localhost',
password: 'db-password'
}
}
}
// Populate users array with for loop instead of Array.from
for (let i = 0; i < 100; i++) {
largeObj.users.push({
id: i,
name: `user${i}`,
email: `user${i}@example.com`,
password: `secret${i}`,
profile: {
age: 20 + (i % 50),
preferences: {
theme: 'dark',
notifications: true,
apiKey: `key-${i}-secret`
}
}
})
}
// Redaction configurations
const basicSlowRedact = slowRedact({
paths: ['user.password', 'headers.cookie']
})
const basicFastRedact = fastRedact({
paths: ['user.password', 'headers.cookie']
})
const wildcardSlowRedact = slowRedact({
paths: ['users.*.password', 'users.*.profile.preferences.apiKey']
})
const wildcardFastRedact = fastRedact({
paths: ['users.*.password', 'users.*.profile.preferences.apiKey']
})
const deepSlowRedact = slowRedact({
paths: ['metadata.secret', 'metadata.database.password']
})
const deepFastRedact = fastRedact({
paths: ['metadata.secret', 'metadata.database.password']
})
group('Small Object Redaction - @pinojs/redact', () => {
bench('basic paths', () => {
basicSlowRedact(smallObj)
})
bench('serialize: false', () => {
const redact = slowRedact({
paths: ['user.password'],
serialize: false
})
redact(smallObj)
})
bench('custom censor function', () => {
const redact = slowRedact({
paths: ['user.password'],
censor: (value, path) => `HIDDEN:${path}`
})
redact(smallObj)
})
})
group('Small Object Redaction - fast-redact', () => {
bench('basic paths', () => {
basicFastRedact(smallObj)
})
bench('serialize: false', () => {
const redact = fastRedact({
paths: ['user.password'],
serialize: false
})
redact(smallObj)
})
bench('custom censor function', () => {
const redact = fastRedact({
paths: ['user.password'],
censor: (value, path) => `HIDDEN:${path}`
})
redact(smallObj)
})
})
group('Large Object Redaction - @pinojs/redact', () => {
bench('wildcard patterns', () => {
wildcardSlowRedact(largeObj)
})
bench('deep nested paths', () => {
deepSlowRedact(largeObj)
})
bench('multiple wildcards', () => {
const redact = slowRedact({
paths: ['users.*.password', 'users.*.profile.preferences.*']
})
redact(largeObj)
})
})
group('Large Object Redaction - fast-redact', () => {
bench('wildcard patterns', () => {
wildcardFastRedact(largeObj)
})
bench('deep nested paths', () => {
deepFastRedact(largeObj)
})
bench('multiple wildcards', () => {
const redact = fastRedact({
paths: ['users.*.password', 'users.*.profile.preferences.*']
})
redact(largeObj)
})
})
group('Direct Performance Comparison', () => {
bench('@pinojs/redact - basic paths', () => {
basicSlowRedact(smallObj)
})
bench('fast-redact - basic paths', () => {
basicFastRedact(smallObj)
})
bench('@pinojs/redact - wildcards', () => {
wildcardSlowRedact(largeObj)
})
bench('fast-redact - wildcards', () => {
wildcardFastRedact(largeObj)
})
})
group('Object Cloning Overhead', () => {
bench('@pinojs/redact - no redaction (clone only)', () => {
const redact = slowRedact({ paths: [] })
redact(smallObj)
})
bench('fast-redact - no redaction', () => {
const redact = fastRedact({ paths: [] })
redact(smallObj)
})
bench('@pinojs/redact - large object clone', () => {
const redact = slowRedact({ paths: [] })
redact(largeObj)
})
bench('fast-redact - large object', () => {
const redact = fastRedact({ paths: [] })
redact(largeObj)
})
})
run()

View File

@@ -0,0 +1,50 @@
{
"name": "expect-type",
"version": "1.4.0",
"engines": {
"node": ">=12.0.0"
},
"keywords": [
"typescript",
"type-check",
"assert",
"types",
"typings",
"test",
"testing"
],
"homepage": "https://github.com/mmkal/expect-type#readme",
"repository": {
"type": "git",
"url": "https://github.com/mmkal/expect-type.git"
},
"license": "Apache-2.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist",
"*.md"
],
"devDependencies": {
"@arethetypeswrong/cli": "0.18.3",
"@types/node": "^24.0.0",
"@typescript/native-preview": "7.0.0-dev.20260609.1",
"@vitest/ui": "^4.0.0",
"eslint": "^8.57.0",
"eslint-plugin-mmkal": "0.9.0",
"np": "^11.0.0",
"pkg-pr-new": "0.0.75",
"strip-ansi": "7.2.0",
"ts-morph": "27.0.2",
"typescript": "5.9.3",
"vitest": "^4.0.0"
},
"scripts": {
"eslint": "eslint --max-warnings 0",
"lint": "tsc && pnpm eslint .",
"type-check": "tsc",
"build": "tsc -p tsconfig.lib.json",
"arethetypeswrong": "attw --pack",
"test": "vitest run"
}
}

View File

@@ -0,0 +1,10 @@
/* global test */
const pino = require('../../pino')
test('transport should work in jest', function () {
pino({
transport: {
target: 'pino-pretty'
}
})
})

View File

@@ -0,0 +1,19 @@
Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and 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,30 @@
// Code generated by Herebyfile.mjs generate:enums from internal/lsp/lsproto/lsp_generated.go. DO NOT EDIT.
export var CompletionItemKind;
(function (CompletionItemKind) {
CompletionItemKind[CompletionItemKind["Text"] = 1] = "Text";
CompletionItemKind[CompletionItemKind["Method"] = 2] = "Method";
CompletionItemKind[CompletionItemKind["Function"] = 3] = "Function";
CompletionItemKind[CompletionItemKind["Constructor"] = 4] = "Constructor";
CompletionItemKind[CompletionItemKind["Field"] = 5] = "Field";
CompletionItemKind[CompletionItemKind["Variable"] = 6] = "Variable";
CompletionItemKind[CompletionItemKind["Class"] = 7] = "Class";
CompletionItemKind[CompletionItemKind["Interface"] = 8] = "Interface";
CompletionItemKind[CompletionItemKind["Module"] = 9] = "Module";
CompletionItemKind[CompletionItemKind["Property"] = 10] = "Property";
CompletionItemKind[CompletionItemKind["Unit"] = 11] = "Unit";
CompletionItemKind[CompletionItemKind["Value"] = 12] = "Value";
CompletionItemKind[CompletionItemKind["Enum"] = 13] = "Enum";
CompletionItemKind[CompletionItemKind["Keyword"] = 14] = "Keyword";
CompletionItemKind[CompletionItemKind["Snippet"] = 15] = "Snippet";
CompletionItemKind[CompletionItemKind["Color"] = 16] = "Color";
CompletionItemKind[CompletionItemKind["File"] = 17] = "File";
CompletionItemKind[CompletionItemKind["Reference"] = 18] = "Reference";
CompletionItemKind[CompletionItemKind["Folder"] = 19] = "Folder";
CompletionItemKind[CompletionItemKind["EnumMember"] = 20] = "EnumMember";
CompletionItemKind[CompletionItemKind["Constant"] = 21] = "Constant";
CompletionItemKind[CompletionItemKind["Struct"] = 22] = "Struct";
CompletionItemKind[CompletionItemKind["Event"] = 23] = "Event";
CompletionItemKind[CompletionItemKind["Operator"] = 24] = "Operator";
CompletionItemKind[CompletionItemKind["TypeParameter"] = 25] = "TypeParameter";
})(CompletionItemKind || (CompletionItemKind = {}));
//# sourceMappingURL=completionItemKind.enum.js.map

View File

@@ -0,0 +1,121 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): T | undefined;
}
interface ReadonlyArray<T> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): T | undefined;
}
interface Int8Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint8Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint8ClampedArray {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Int16Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint16Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Int32Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint32Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Float32Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Float64Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface BigInt64Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): bigint | undefined;
}
interface BigUint64Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): bigint | undefined;
}

View File

@@ -0,0 +1,246 @@
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 = () => {
// Hebrew labels + grammatical gender
const TypeNames: Record<string, { label: string; gender: "m" | "f" }> = {
string: { label: "מחרוזת", gender: "f" },
number: { label: "מספר", gender: "m" },
boolean: { label: "ערך בוליאני", gender: "m" },
bigint: { label: "BigInt", gender: "m" },
date: { label: "תאריך", gender: "m" },
array: { label: "מערך", gender: "m" },
object: { label: "אובייקט", gender: "m" },
null: { label: "ערך ריק (null)", gender: "m" },
undefined: { label: "ערך לא מוגדר (undefined)", gender: "m" },
symbol: { label: "סימבול (Symbol)", gender: "m" },
function: { label: "פונקציה", gender: "f" },
map: { label: "מפה (Map)", gender: "f" },
set: { label: "קבוצה (Set)", gender: "f" },
file: { label: "קובץ", gender: "m" },
promise: { label: "Promise", gender: "m" },
NaN: { label: "NaN", gender: "m" },
unknown: { label: "ערך לא ידוע", gender: "m" },
value: { label: "ערך", gender: "m" },
};
// Sizing units for size-related messages + localized origin labels
const Sizable: Record<string, { unit: string; shortLabel?: string; longLabel?: string }> = {
string: { unit: "תווים", shortLabel: "קצר", longLabel: "ארוך" },
file: { unit: "בייטים", shortLabel: "קטן", longLabel: "גדול" },
array: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" },
set: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" },
number: { unit: "", shortLabel: "קטן", longLabel: "גדול" }, // no unit
};
// Helpers — labels, articles, and verbs
const typeEntry = (t?: string | null) => (t ? TypeNames[t] : undefined);
const typeLabel = (t?: string | null): string => {
const e = typeEntry(t);
if (e) return e.label;
// fallback: show raw string if unknown
return t ?? TypeNames.unknown.label;
};
const withDefinite = (t?: string | null): string => `ה${typeLabel(t)}`;
const verbFor = (t?: string | null): string => {
const e = typeEntry(t);
const gender = e?.gender ?? "m";
return gender === "f" ? "צריכה להיות" : "צריך להיות";
};
const getSizing = (origin?: string | null) => {
if (!origin) return null;
return Sizable[origin] ?? null;
};
const FormatDictionary: {
[k in $ZodStringFormats]: { label: string; gender: "m" | "f" };
} = {
regex: { label: "קלט", gender: "m" },
email: { label: "כתובת אימייל", gender: "f" },
url: { label: "כתובת רשת", gender: "f" },
emoji: { label: "אימוג'י", gender: "m" },
uuid: { label: "UUID", gender: "m" },
nanoid: { label: "nanoid", gender: "m" },
guid: { label: "GUID", gender: "m" },
cuid: { label: "cuid", gender: "m" },
cuid2: { label: "cuid2", gender: "m" },
ulid: { label: "ULID", gender: "m" },
xid: { label: "XID", gender: "m" },
ksuid: { label: "KSUID", gender: "m" },
datetime: { label: "תאריך וזמן ISO", gender: "m" },
date: { label: "תאריך ISO", gender: "m" },
time: { label: "זמן ISO", gender: "m" },
duration: { label: "משך זמן ISO", gender: "m" },
ipv4: { label: "כתובת IPv4", gender: "f" },
ipv6: { label: "כתובת IPv6", gender: "f" },
cidrv4: { label: "טווח IPv4", gender: "m" },
cidrv6: { label: "טווח IPv6", gender: "m" },
base64: { label: "מחרוזת בבסיס 64", gender: "f" },
base64url: { label: "מחרוזת בבסיס 64 לכתובות רשת", gender: "f" },
json_string: { label: "מחרוזת JSON", gender: "f" },
e164: { label: "מספר E.164", gender: "m" },
jwt: { label: "JWT", gender: "m" },
ends_with: { label: "קלט", gender: "m" },
includes: { label: "קלט", gender: "m" },
lowercase: { label: "קלט", gender: "m" },
starts_with: { label: "קלט", gender: "m" },
uppercase: { label: "קלט", gender: "m" },
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
// Expected type: show without definite article for clearer Hebrew
const expectedKey = issue.expected as string | undefined;
const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey);
// Received: show localized label if known, otherwise constructor/raw
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? 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])}`;
}
// Join values with proper Hebrew formatting
const stringified = issue.values.map((v) => util.stringifyPrimitive(v));
if (issue.values.length === 2) {
return `ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`;
}
// For 3+ values: "a", "b" או "c"
const lastValue = stringified[stringified.length - 1];
const restValues = stringified.slice(0, -1).join(", ");
return `ערך לא תקין: האפשרויות המתאימות הן ${restValues} או ${lastValue}`;
}
case "too_big": {
const sizing = getSizing(issue.origin);
const subject = withDefinite(issue.origin ?? "value");
if (issue.origin === "string") {
// Special handling for strings - more natural Hebrew
return `${sizing?.longLabel ?? "ארוך"} מדי: ${subject} צריכה להכיל ${issue.maximum.toString()} ${sizing?.unit ?? ""} ${issue.inclusive ? "או פחות" : "לכל היותר"}`.trim();
}
if (issue.origin === "number") {
// Natural Hebrew for numbers
const comparison = issue.inclusive ? `קטן או שווה ל-${issue.maximum}` : `קטן מ-${issue.maximum}`;
return `גדול מדי: ${subject} צריך להיות ${comparison}`;
}
if (issue.origin === "array" || issue.origin === "set") {
// Natural Hebrew for arrays and sets
const verb = issue.origin === "set" ? "צריכה" : "צריך";
const comparison = issue.inclusive
? `${issue.maximum} ${sizing?.unit ?? ""} או פחות`
: `פחות מ-${issue.maximum} ${sizing?.unit ?? ""}`;
return `גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim();
}
const adj = issue.inclusive ? "<=" : "<";
const be = verbFor(issue.origin ?? "value");
if (sizing?.unit) {
return `${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()} ${sizing.unit}`;
}
return `${sizing?.longLabel ?? "גדול"} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const sizing = getSizing(issue.origin);
const subject = withDefinite(issue.origin ?? "value");
if (issue.origin === "string") {
// Special handling for strings - more natural Hebrew
return `${sizing?.shortLabel ?? "קצר"} מדי: ${subject} צריכה להכיל ${issue.minimum.toString()} ${sizing?.unit ?? ""} ${issue.inclusive ? "או יותר" : "לפחות"}`.trim();
}
if (issue.origin === "number") {
// Natural Hebrew for numbers
const comparison = issue.inclusive ? `גדול או שווה ל-${issue.minimum}` : `גדול מ-${issue.minimum}`;
return `קטן מדי: ${subject} צריך להיות ${comparison}`;
}
if (issue.origin === "array" || issue.origin === "set") {
// Natural Hebrew for arrays and sets
const verb = issue.origin === "set" ? "צריכה" : "צריך";
// Special case for singular (minimum === 1)
if (issue.minimum === 1 && issue.inclusive) {
const singularPhrase = issue.origin === "set" ? "לפחות פריט אחד" : "לפחות פריט אחד";
return `קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`;
}
const comparison = issue.inclusive
? `${issue.minimum} ${sizing?.unit ?? ""} או יותר`
: `יותר מ-${issue.minimum} ${sizing?.unit ?? ""}`;
return `קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim();
}
const adj = issue.inclusive ? ">=" : ">";
const be = verbFor(issue.origin ?? "value");
if (sizing?.unit) {
return `${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `${sizing?.shortLabel ?? "קטן"} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
// These apply to strings — use feminine grammar + ה׳ הידיעה
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}`;
// Handle gender agreement for formats
const nounEntry = FormatDictionary[_issue.format];
const noun = nounEntry?.label ?? _issue.format;
const gender = nounEntry?.gender ?? "m";
const adjective = gender === "f" ? "תקינה" : "תקין";
return `${noun} לא ${adjective}`;
}
case "not_multiple_of":
return `מספר לא תקין: חייב להיות מכפלה של ${issue.divisor}`;
case "unrecognized_keys":
return `מפתח${issue.keys.length > 1 ? "ות" : ""} לא מזוה${issue.keys.length > 1 ? "ים" : "ה"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key": {
return `שדה לא תקין באובייקט`;
}
case "invalid_union":
return "קלט לא תקין";
case "invalid_element": {
const place = withDefinite(issue.origin ?? "array");
return `ערך לא תקין ב${place}`;
}
default:
return `קלט לא תקין`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,12 @@
import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/typescript-estree';
import type * as ts from 'typescript';
/**
* Resolves the given node's type. Will return the type's generic constraint, if it has one.
*
* Warning - if the type is generic and does _not_ have a constraint, the type will be
* returned as-is, rather than returning an `unknown` type. This can be checked
* for by checking for the type flag ts.TypeFlags.TypeParameter.
*
* @see https://github.com/typescript-eslint/typescript-eslint/issues/10438
*/
export declare function getConstrainedTypeAtLocation(services: ParserServicesWithTypeInformation, node: TSESTree.Node): ts.Type;

View File

@@ -0,0 +1,3 @@
// ensure `@vitest/expect` provides `chai` types
import type {} from '@vitest/expect'
export * from './dist/config.js'

View File

@@ -0,0 +1,73 @@
'use strict';
module.exports = function generate_oneOf(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $currentBaseId = $it.baseId,
$prevValid = 'prevValid' + $lvl,
$passingSchemas = 'passingSchemas' + $lvl;
out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$sch = arr1[$i += 1];
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
} else {
out += ' var ' + ($nextValid) + ' = true; ';
}
if ($i) {
out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
$closingBraces += '}';
}
out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
}
}
it.compositeRule = $it.compositeRule = $wasComposite;
out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should match exactly one schema in oneOf\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError(vErrors); ';
} else {
out += ' validate.errors = vErrors; return false; ';
}
}
out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
if (it.opts.allErrors) {
out += ' } ';
}
return out;
}