WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_async_generator_delegate.js";
|
||||
@@ -0,0 +1,12 @@
|
||||
import type * as ts from 'typescript';
|
||||
interface DirectoryStructureHost {
|
||||
readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[];
|
||||
}
|
||||
interface CachedDirectoryStructureHost extends DirectoryStructureHost {
|
||||
readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[];
|
||||
}
|
||||
export interface WatchCompilerHostOfConfigFile<T extends ts.BuilderProgram> extends ts.WatchCompilerHostOfConfigFile<T> {
|
||||
extraFileExtensions?: readonly ts.FileExtensionInfo[];
|
||||
onCachedDirectoryStructureHostCreate(host: CachedDirectoryStructureHost): void;
|
||||
}
|
||||
export {};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,673 @@
|
||||
import { createRequire } from "node:module";
|
||||
//#region \0rolldown/runtime.js
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
||||
key = keys[i];
|
||||
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
||||
get: ((k) => from[k]).bind(null, key),
|
||||
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
||||
});
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
||||
value: mod,
|
||||
enumerable: true
|
||||
}) : target, mod));
|
||||
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
||||
//#endregion
|
||||
//#region src/webcontainer-fallback.cjs
|
||||
var require_webcontainer_fallback = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
||||
const fs = __require("node:fs");
|
||||
const childProcess = __require("node:child_process");
|
||||
const version = JSON.parse(fs.readFileSync(__require.resolve("rolldown/package.json"), "utf-8")).version;
|
||||
const baseDir = `/tmp/rolldown-${version}`;
|
||||
const bindingEntry = `${baseDir}/node_modules/@rolldown/binding-wasm32-wasi/rolldown-binding.wasi.cjs`;
|
||||
if (!fs.existsSync(bindingEntry)) {
|
||||
const bindingPkg = `@rolldown/binding-wasm32-wasi@${version}`;
|
||||
fs.rmSync(baseDir, {
|
||||
recursive: true,
|
||||
force: true
|
||||
});
|
||||
fs.mkdirSync(baseDir, { recursive: true });
|
||||
console.log(`[rolldown] Downloading ${bindingPkg} on WebContainer...`);
|
||||
childProcess.execFileSync("pnpm", ["i", bindingPkg], {
|
||||
cwd: baseDir,
|
||||
stdio: "inherit"
|
||||
});
|
||||
}
|
||||
module.exports = __require(bindingEntry);
|
||||
}));
|
||||
//#endregion
|
||||
//#region src/binding.cjs
|
||||
var require_binding = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
||||
const { readFileSync } = __require("fs");
|
||||
let nativeBinding = null;
|
||||
const loadErrors = [];
|
||||
const isMusl = () => {
|
||||
let musl = false;
|
||||
if (process.platform === "linux") {
|
||||
musl = isMuslFromFilesystem();
|
||||
if (musl === null) musl = isMuslFromReport();
|
||||
if (musl === null) musl = isMuslFromChildProcess();
|
||||
}
|
||||
return musl;
|
||||
};
|
||||
const isFileMusl = (f) => f.includes("libc.musl-") || f.includes("ld-musl-");
|
||||
const isMuslFromFilesystem = () => {
|
||||
try {
|
||||
return readFileSync("/usr/bin/ldd", "utf-8").includes("musl");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const isMuslFromReport = () => {
|
||||
let report = null;
|
||||
if (process.report && typeof process.report.getReport === "function") {
|
||||
process.report.excludeNetwork = true;
|
||||
report = process.report.getReport();
|
||||
}
|
||||
if (!report) return null;
|
||||
if (report.header && report.header.glibcVersionRuntime) return false;
|
||||
if (Array.isArray(report.sharedObjects)) {
|
||||
if (report.sharedObjects.some(isFileMusl)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const isMuslFromChildProcess = () => {
|
||||
try {
|
||||
return __require("child_process").execSync("ldd --version", { encoding: "utf8" }).includes("musl");
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
function requireNative() {
|
||||
if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) try {
|
||||
return __require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH);
|
||||
} catch (err) {
|
||||
loadErrors.push(err);
|
||||
}
|
||||
else if (process.platform === "android") {
|
||||
if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.android-arm64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-android-arm64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-android-arm64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm") {
|
||||
try {
|
||||
return __require("./rolldown-binding.android-arm-eabi.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-android-arm-eabi");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-android-arm-eabi/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Android ${process.arch}`));
|
||||
} else if (process.platform === "win32") {
|
||||
if (process.arch === "x64") {
|
||||
if (process.config && process.config.variables && process.config.variables.shlib_suffix === "dll.a" || process.config && process.config.variables && process.config.variables.node_target_type === "shared_library") {
|
||||
try {
|
||||
return __require("./rolldown-binding.win32-x64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-win32-x64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-win32-x64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.win32-x64-msvc.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-win32-x64-msvc");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-win32-x64-msvc/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
} else if (process.arch === "ia32") {
|
||||
try {
|
||||
return __require("./rolldown-binding.win32-ia32-msvc.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-win32-ia32-msvc");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-win32-ia32-msvc/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.win32-arm64-msvc.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-win32-arm64-msvc");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-win32-arm64-msvc/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Windows: ${process.arch}`));
|
||||
} else if (process.platform === "darwin") {
|
||||
try {
|
||||
return __require("./rolldown-binding.darwin-universal.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-darwin-universal");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-darwin-universal/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
if (process.arch === "x64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.darwin-x64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-darwin-x64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-darwin-x64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.darwin-arm64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-darwin-arm64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-darwin-arm64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on macOS: ${process.arch}`));
|
||||
} else if (process.platform === "freebsd") {
|
||||
if (process.arch === "x64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.freebsd-x64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-freebsd-x64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-freebsd-x64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.freebsd-arm64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-freebsd-arm64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-freebsd-arm64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on FreeBSD: ${process.arch}`));
|
||||
} else if (process.platform === "linux") {
|
||||
if (process.arch === "x64") {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-x64-musl.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-x64-musl");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-x64-musl/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("../rolldown-binding.linux-x64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-x64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-x64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
} else if (process.arch === "arm64") {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-arm64-musl.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-arm64-musl");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-arm64-musl/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-arm64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-arm64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-arm64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
} else if (process.arch === "arm") {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-arm-musleabihf.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-arm-musleabihf");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-arm-musleabihf/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-arm-gnueabihf.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-arm-gnueabihf");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-arm-gnueabihf/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
} else if (process.arch === "loong64") {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-loong64-musl.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-loong64-musl");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-loong64-musl/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-loong64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-loong64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-loong64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
} else if (process.arch === "riscv64") {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-riscv64-musl.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-riscv64-musl");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-riscv64-musl/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-riscv64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-riscv64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-riscv64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
} else if (process.arch === "ppc64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-ppc64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-ppc64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-ppc64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "s390x") {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-s390x-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-s390x-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-s390x-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Linux: ${process.arch}`));
|
||||
} else if (process.platform === "openharmony") {
|
||||
if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.openharmony-arm64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-openharmony-arm64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-openharmony-arm64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "x64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.openharmony-x64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-openharmony-x64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-openharmony-x64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm") {
|
||||
try {
|
||||
return __require("./rolldown-binding.openharmony-arm.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-openharmony-arm");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-openharmony-arm/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`));
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`));
|
||||
}
|
||||
function createLoadErrorChain(errors) {
|
||||
return errors.reduce((previous, current) => {
|
||||
let message;
|
||||
try {
|
||||
message = current && typeof current.message === "string" ? current.message : String(current);
|
||||
} catch {
|
||||
message = "Unknown error";
|
||||
}
|
||||
const error = new Error(message);
|
||||
error.cause = previous;
|
||||
return error;
|
||||
}, null);
|
||||
}
|
||||
const __napiWasiFlavors = ["wasm32-wasi"];
|
||||
const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR;
|
||||
const __napiWasiFlavorRequested = typeof __napiWasiFlavor === "string" && __napiWasiFlavor.length > 0;
|
||||
if (__napiWasiFlavorRequested && __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1) throw new Error("Unsupported WASI flavor \"" + __napiWasiFlavor + "\". Available flavors: " + __napiWasiFlavors.join(", "));
|
||||
const forceWasiError = process.env.NAPI_RS_FORCE_WASI === "error";
|
||||
const forceWasi = process.env.NAPI_RS_FORCE_WASI === "true" || forceWasiError || __napiWasiFlavorRequested;
|
||||
if (!forceWasi) nativeBinding = requireNative();
|
||||
if (!nativeBinding || forceWasi) {
|
||||
let wasiBinding = null;
|
||||
let wasiBindingLoaded = false;
|
||||
const wasiBindingErrors = [];
|
||||
const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => {
|
||||
try {
|
||||
__require.resolve(specifier);
|
||||
} catch (resolveError) {
|
||||
if (!resolveError || resolveError.code !== "MODULE_NOT_FOUND") throw resolveError;
|
||||
if (isPackage) {
|
||||
try {
|
||||
__require.resolve(specifier + "/package.json");
|
||||
} catch (packageError) {
|
||||
if (packageError && packageError.code === "MODULE_NOT_FOUND") return resolveError;
|
||||
throw resolveError;
|
||||
}
|
||||
throw resolveError;
|
||||
}
|
||||
return resolveError;
|
||||
}
|
||||
if (localArtifacts) {
|
||||
let artifactError = null;
|
||||
for (let i = 0; i < localArtifacts.length; i++) try {
|
||||
__require.resolve(localArtifacts[i]);
|
||||
return null;
|
||||
} catch (resolveError) {
|
||||
if (!resolveError || resolveError.code !== "MODULE_NOT_FOUND") throw resolveError;
|
||||
artifactError = resolveError;
|
||||
}
|
||||
return artifactError;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) {
|
||||
let candidateError = null;
|
||||
let candidateFailed = false;
|
||||
try {
|
||||
candidateError = __napiWasiResolveCandidate("./rolldown-binding.wasi.cjs", false, ["./rolldown-binding.wasm32-wasi.debug.wasm", "./rolldown-binding.wasm32-wasi.wasm"]);
|
||||
candidateFailed = candidateError !== null;
|
||||
if (!candidateFailed) {
|
||||
wasiBinding = __require("../rolldown-binding.wasi.cjs");
|
||||
nativeBinding = wasiBinding;
|
||||
wasiBindingLoaded = true;
|
||||
}
|
||||
} catch (err) {
|
||||
candidateError = err;
|
||||
candidateFailed = true;
|
||||
}
|
||||
if (candidateFailed) {
|
||||
wasiBindingErrors.push(candidateError);
|
||||
loadErrors.push(candidateError);
|
||||
}
|
||||
}
|
||||
if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) {
|
||||
let candidateError = null;
|
||||
let candidateFailed = false;
|
||||
try {
|
||||
candidateError = __napiWasiResolveCandidate("@rolldown/binding-wasm32-wasi", true, void 0);
|
||||
candidateFailed = candidateError !== null;
|
||||
if (!candidateFailed) {
|
||||
if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
|
||||
const bindingPackageVersion = __require("@rolldown/binding-wasm32-wasi/package.json").version;
|
||||
if (bindingPackageVersion !== "1.2.4") throw new Error(`WASI binding package version mismatch, expected 1.2.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
}
|
||||
wasiBinding = __require("@rolldown/binding-wasm32-wasi");
|
||||
nativeBinding = wasiBinding;
|
||||
wasiBindingLoaded = true;
|
||||
}
|
||||
} catch (err) {
|
||||
candidateError = err;
|
||||
candidateFailed = true;
|
||||
}
|
||||
if (candidateFailed) {
|
||||
wasiBindingErrors.push(candidateError);
|
||||
loadErrors.push(candidateError);
|
||||
}
|
||||
}
|
||||
if (!wasiBindingLoaded && forceWasi && !forceWasiError && !__napiWasiFlavorRequested) nativeBinding = requireNative();
|
||||
if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) {
|
||||
const error = /* @__PURE__ */ new Error(__napiWasiFlavorRequested ? "WASI binding for flavor \"" + __napiWasiFlavor + "\" not found" : "WASI binding not found and NAPI_RS_FORCE_WASI is set to error");
|
||||
error.cause = createLoadErrorChain(wasiBindingErrors);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (!nativeBinding && globalThis.process?.versions?.["webcontainer"]) try {
|
||||
nativeBinding = require_webcontainer_fallback();
|
||||
} catch (err) {
|
||||
loadErrors.push(err);
|
||||
}
|
||||
if (!nativeBinding) {
|
||||
if (loadErrors.length > 0) {
|
||||
const error = /* @__PURE__ */ new Error("Cannot find native binding. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). Please try `npm i` again after removing both package-lock.json and node_modules directory.");
|
||||
error.cause = createLoadErrorChain(loadErrors);
|
||||
throw error;
|
||||
}
|
||||
throw new Error(`Failed to load native binding`);
|
||||
}
|
||||
module.exports = nativeBinding;
|
||||
module.exports.LegalCommentsMode = nativeBinding.LegalCommentsMode;
|
||||
module.exports.minify = nativeBinding.minify;
|
||||
module.exports.minifySync = nativeBinding.minifySync;
|
||||
module.exports.Severity = nativeBinding.Severity;
|
||||
module.exports.ParseResult = nativeBinding.ParseResult;
|
||||
module.exports.ExportExportNameKind = nativeBinding.ExportExportNameKind;
|
||||
module.exports.ExportImportNameKind = nativeBinding.ExportImportNameKind;
|
||||
module.exports.ExportLocalNameKind = nativeBinding.ExportLocalNameKind;
|
||||
module.exports.ImportNameKind = nativeBinding.ImportNameKind;
|
||||
module.exports.parse = nativeBinding.parse;
|
||||
module.exports.parseSync = nativeBinding.parseSync;
|
||||
module.exports.rawTransferSupported = nativeBinding.rawTransferSupported;
|
||||
module.exports.ResolverFactory = nativeBinding.ResolverFactory;
|
||||
module.exports.EnforceExtension = nativeBinding.EnforceExtension;
|
||||
module.exports.ModuleType = nativeBinding.ModuleType;
|
||||
module.exports.sync = nativeBinding.sync;
|
||||
module.exports.HelperMode = nativeBinding.HelperMode;
|
||||
module.exports.isolatedDeclaration = nativeBinding.isolatedDeclaration;
|
||||
module.exports.isolatedDeclarationSync = nativeBinding.isolatedDeclarationSync;
|
||||
module.exports.moduleRunnerTransform = nativeBinding.moduleRunnerTransform;
|
||||
module.exports.moduleRunnerTransformSync = nativeBinding.moduleRunnerTransformSync;
|
||||
module.exports.transform = nativeBinding.transform;
|
||||
module.exports.transformSync = nativeBinding.transformSync;
|
||||
module.exports.BindingBundleEndEventData = nativeBinding.BindingBundleEndEventData;
|
||||
module.exports.BindingBundleErrorEventData = nativeBinding.BindingBundleErrorEventData;
|
||||
module.exports.BindingBundler = nativeBinding.BindingBundler;
|
||||
module.exports.BindingCallableBuiltinPlugin = nativeBinding.BindingCallableBuiltinPlugin;
|
||||
module.exports.BindingChunkingContext = nativeBinding.BindingChunkingContext;
|
||||
module.exports.BindingDecodedMap = nativeBinding.BindingDecodedMap;
|
||||
module.exports.BindingDevEngine = nativeBinding.BindingDevEngine;
|
||||
module.exports.BindingLoadPluginContext = nativeBinding.BindingLoadPluginContext;
|
||||
module.exports.BindingMagicString = nativeBinding.BindingMagicString;
|
||||
module.exports.BindingModuleInfo = nativeBinding.BindingModuleInfo;
|
||||
module.exports.BindingNormalizedOptions = nativeBinding.BindingNormalizedOptions;
|
||||
module.exports.BindingOutputAsset = nativeBinding.BindingOutputAsset;
|
||||
module.exports.BindingOutputChunk = nativeBinding.BindingOutputChunk;
|
||||
module.exports.BindingPluginContext = nativeBinding.BindingPluginContext;
|
||||
module.exports.BindingRenderedChunk = nativeBinding.BindingRenderedChunk;
|
||||
module.exports.BindingRenderedChunkMeta = nativeBinding.BindingRenderedChunkMeta;
|
||||
module.exports.BindingRenderedModule = nativeBinding.BindingRenderedModule;
|
||||
module.exports.BindingSourceMap = nativeBinding.BindingSourceMap;
|
||||
module.exports.BindingTransformPluginContext = nativeBinding.BindingTransformPluginContext;
|
||||
module.exports.BindingWatcher = nativeBinding.BindingWatcher;
|
||||
module.exports.BindingWatcherBundler = nativeBinding.BindingWatcherBundler;
|
||||
module.exports.BindingWatcherChangeData = nativeBinding.BindingWatcherChangeData;
|
||||
module.exports.BindingWatcherEvent = nativeBinding.BindingWatcherEvent;
|
||||
module.exports.ParallelJsPluginRegistry = nativeBinding.ParallelJsPluginRegistry;
|
||||
module.exports.TraceSubscriberGuard = nativeBinding.TraceSubscriberGuard;
|
||||
module.exports.TsconfigCache = nativeBinding.TsconfigCache;
|
||||
module.exports.BindingAttachDebugInfo = nativeBinding.BindingAttachDebugInfo;
|
||||
module.exports.BindingBuiltinPluginName = nativeBinding.BindingBuiltinPluginName;
|
||||
module.exports.BindingChunkModuleOrderBy = nativeBinding.BindingChunkModuleOrderBy;
|
||||
module.exports.BindingErrorStage = nativeBinding.BindingErrorStage;
|
||||
module.exports.BindingLogLevel = nativeBinding.BindingLogLevel;
|
||||
module.exports.BindingPluginOrder = nativeBinding.BindingPluginOrder;
|
||||
module.exports.BindingPropertyReadSideEffects = nativeBinding.BindingPropertyReadSideEffects;
|
||||
module.exports.BindingPropertyWriteSideEffects = nativeBinding.BindingPropertyWriteSideEffects;
|
||||
module.exports.BindingRebuildStrategy = nativeBinding.BindingRebuildStrategy;
|
||||
module.exports.collapseSourcemaps = nativeBinding.collapseSourcemaps;
|
||||
module.exports.enhancedTransform = nativeBinding.enhancedTransform;
|
||||
module.exports.enhancedTransformSync = nativeBinding.enhancedTransformSync;
|
||||
module.exports.FilterTokenKind = nativeBinding.FilterTokenKind;
|
||||
module.exports.initTraceSubscriber = nativeBinding.initTraceSubscriber;
|
||||
module.exports.registerPlugins = nativeBinding.registerPlugins;
|
||||
module.exports.resolveTsconfig = nativeBinding.resolveTsconfig;
|
||||
module.exports.shutdownAsyncRuntime = nativeBinding.shutdownAsyncRuntime;
|
||||
module.exports.startAsyncRuntime = nativeBinding.startAsyncRuntime;
|
||||
}));
|
||||
//#endregion
|
||||
export { __toESM as n, require_binding as t };
|
||||
@@ -0,0 +1,5 @@
|
||||
export declare enum CommentDirectiveType {
|
||||
ExpectError = 0,
|
||||
Ignore = 1
|
||||
}
|
||||
//# sourceMappingURL=commentDirectiveType.enum.d.ts.map
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
||||
"description": "Meta-schema for $data reference (JSON Schema extension proposal)",
|
||||
"type": "object",
|
||||
"required": [ "$data" ],
|
||||
"properties": {
|
||||
"$data": {
|
||||
"type": "string",
|
||||
"anyOf": [
|
||||
{ "format": "relative-json-pointer" },
|
||||
{ "format": "json-pointer" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// @ts-ignore TS6133
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import * as z from "zod/v3";
|
||||
import { util } from "../helpers/util.js";
|
||||
|
||||
const fish = z.object({
|
||||
name: z.string(),
|
||||
age: z.number(),
|
||||
nested: z.object({}),
|
||||
});
|
||||
|
||||
test("pick type inference", () => {
|
||||
const nameonlyFish = fish.pick({ name: true });
|
||||
type nameonlyFish = z.infer<typeof nameonlyFish>;
|
||||
util.assertEqual<nameonlyFish, { name: string }>(true);
|
||||
});
|
||||
|
||||
test("pick parse - success", () => {
|
||||
const nameonlyFish = fish.pick({ name: true });
|
||||
nameonlyFish.parse({ name: "bob" });
|
||||
|
||||
// @ts-expect-error checking runtime picks `name` only.
|
||||
const anotherNameonlyFish = fish.pick({ name: true, age: false });
|
||||
anotherNameonlyFish.parse({ name: "bob" });
|
||||
});
|
||||
|
||||
test("pick parse - fail", () => {
|
||||
fish.pick({ name: true }).parse({ name: "12" } as any);
|
||||
fish.pick({ name: true }).parse({ name: "bob", age: 12 } as any);
|
||||
fish.pick({ age: true }).parse({ age: 12 } as any);
|
||||
|
||||
const nameonlyFish = fish.pick({ name: true }).strict();
|
||||
const bad1 = () => nameonlyFish.parse({ name: 12 } as any);
|
||||
const bad2 = () => nameonlyFish.parse({ name: "bob", age: 12 } as any);
|
||||
const bad3 = () => nameonlyFish.parse({ age: 12 } as any);
|
||||
|
||||
// @ts-expect-error checking runtime picks `name` only.
|
||||
const anotherNameonlyFish = fish.pick({ name: true, age: false }).strict();
|
||||
const bad4 = () => anotherNameonlyFish.parse({ name: "bob", age: 12 } as any);
|
||||
|
||||
expect(bad1).toThrow();
|
||||
expect(bad2).toThrow();
|
||||
expect(bad3).toThrow();
|
||||
expect(bad4).toThrow();
|
||||
});
|
||||
|
||||
test("omit type inference", () => {
|
||||
const nonameFish = fish.omit({ name: true });
|
||||
type nonameFish = z.infer<typeof nonameFish>;
|
||||
util.assertEqual<nonameFish, { age: number; nested: {} }>(true);
|
||||
});
|
||||
|
||||
test("omit parse - success", () => {
|
||||
const nonameFish = fish.omit({ name: true });
|
||||
nonameFish.parse({ age: 12, nested: {} });
|
||||
|
||||
// @ts-expect-error checking runtime omits `name` only.
|
||||
const anotherNonameFish = fish.omit({ name: true, age: false });
|
||||
anotherNonameFish.parse({ age: 12, nested: {} });
|
||||
});
|
||||
|
||||
test("omit parse - fail", () => {
|
||||
const nonameFish = fish.omit({ name: true });
|
||||
const bad1 = () => nonameFish.parse({ name: 12 } as any);
|
||||
const bad2 = () => nonameFish.parse({ age: 12 } as any);
|
||||
const bad3 = () => nonameFish.parse({} as any);
|
||||
|
||||
// @ts-expect-error checking runtime omits `name` only.
|
||||
const anotherNonameFish = fish.omit({ name: true, age: false });
|
||||
const bad4 = () => anotherNonameFish.parse({ nested: {} } as any);
|
||||
|
||||
expect(bad1).toThrow();
|
||||
expect(bad2).toThrow();
|
||||
expect(bad3).toThrow();
|
||||
expect(bad4).toThrow();
|
||||
});
|
||||
|
||||
test("nonstrict inference", () => {
|
||||
const laxfish = fish.pick({ name: true }).catchall(z.any());
|
||||
type laxfish = z.infer<typeof laxfish>;
|
||||
util.assertEqual<laxfish, { name: string } & { [k: string]: any }>(true);
|
||||
});
|
||||
|
||||
test("nonstrict parsing - pass", () => {
|
||||
const laxfish = fish.passthrough().pick({ name: true });
|
||||
laxfish.parse({ name: "asdf", whatever: "asdf" });
|
||||
laxfish.parse({ name: "asdf", age: 12, nested: {} });
|
||||
});
|
||||
|
||||
test("nonstrict parsing - fail", () => {
|
||||
const laxfish = fish.passthrough().pick({ name: true });
|
||||
const bad = () => laxfish.parse({ whatever: "asdf" } as any);
|
||||
expect(bad).toThrow();
|
||||
});
|
||||
|
||||
test("pick/omit/required/partial - do not allow unknown keys", () => {
|
||||
const schema = z.object({
|
||||
name: z.string(),
|
||||
age: z.number(),
|
||||
});
|
||||
|
||||
// @ts-expect-error
|
||||
schema.pick({ $unknown: true });
|
||||
// @ts-expect-error
|
||||
schema.omit({ $unknown: true });
|
||||
// @ts-expect-error
|
||||
schema.required({ $unknown: true });
|
||||
// @ts-expect-error
|
||||
schema.partial({ $unknown: true });
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* @fileoverview Rule to enforce a particular function style
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
defaultOptions: [
|
||||
"expression",
|
||||
{
|
||||
allowArrowFunctions: false,
|
||||
allowTypeAnnotation: false,
|
||||
overrides: {},
|
||||
},
|
||||
],
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Enforce the consistent use of either `function` declarations or expressions assigned to variables",
|
||||
dialects: ["JavaScript", "TypeScript"],
|
||||
recommended: false,
|
||||
frozen: true,
|
||||
url: "https://eslint.org/docs/latest/rules/func-style",
|
||||
},
|
||||
|
||||
schema: [
|
||||
{
|
||||
enum: ["declaration", "expression"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
allowArrowFunctions: {
|
||||
type: "boolean",
|
||||
},
|
||||
allowTypeAnnotation: {
|
||||
type: "boolean",
|
||||
},
|
||||
overrides: {
|
||||
type: "object",
|
||||
properties: {
|
||||
namedExports: {
|
||||
enum: ["declaration", "expression", "ignore"],
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
messages: {
|
||||
expression: "Expected a function expression.",
|
||||
declaration: "Expected a function declaration.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const [style, { allowArrowFunctions, allowTypeAnnotation, overrides }] =
|
||||
context.options;
|
||||
const enforceDeclarations = style === "declaration";
|
||||
const { namedExports: exportFunctionStyle } = overrides;
|
||||
const stack = [];
|
||||
|
||||
/**
|
||||
* Checks if a function declaration is part of an overloaded function
|
||||
* @param {ASTNode} node The function declaration node to check
|
||||
* @returns {boolean} True if the function is overloaded
|
||||
*/
|
||||
function isOverloadedFunction(node) {
|
||||
const functionName = node.id.name;
|
||||
|
||||
if (node.parent.type === "ExportNamedDeclaration") {
|
||||
return node.parent.parent.body.some(
|
||||
member =>
|
||||
member.type === "ExportNamedDeclaration" &&
|
||||
member.declaration?.type === "TSDeclareFunction" &&
|
||||
member.declaration.id.name === functionName,
|
||||
);
|
||||
}
|
||||
|
||||
if (node.parent.type === "SwitchCase") {
|
||||
return node.parent.parent.cases.some(switchCase =>
|
||||
switchCase.consequent.some(
|
||||
member =>
|
||||
member.type === "TSDeclareFunction" &&
|
||||
member.id.name === functionName,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
Array.isArray(node.parent.body) &&
|
||||
node.parent.body.some(
|
||||
member =>
|
||||
member.type === "TSDeclareFunction" &&
|
||||
member.id.name === functionName,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const nodesToCheck = {
|
||||
FunctionDeclaration(node) {
|
||||
stack.push(false);
|
||||
|
||||
if (
|
||||
!enforceDeclarations &&
|
||||
node.parent.type !== "ExportDefaultDeclaration" &&
|
||||
(typeof exportFunctionStyle === "undefined" ||
|
||||
node.parent.type !== "ExportNamedDeclaration") &&
|
||||
!isOverloadedFunction(node)
|
||||
) {
|
||||
context.report({ node, messageId: "expression" });
|
||||
}
|
||||
|
||||
if (
|
||||
node.parent.type === "ExportNamedDeclaration" &&
|
||||
exportFunctionStyle === "expression" &&
|
||||
!isOverloadedFunction(node)
|
||||
) {
|
||||
context.report({ node, messageId: "expression" });
|
||||
}
|
||||
},
|
||||
"FunctionDeclaration:exit"() {
|
||||
stack.pop();
|
||||
},
|
||||
|
||||
FunctionExpression(node) {
|
||||
stack.push(false);
|
||||
|
||||
if (
|
||||
enforceDeclarations &&
|
||||
node.parent.type === "VariableDeclarator" &&
|
||||
(typeof exportFunctionStyle === "undefined" ||
|
||||
node.parent.parent.parent.type !==
|
||||
"ExportNamedDeclaration") &&
|
||||
!(allowTypeAnnotation && node.parent.id.typeAnnotation)
|
||||
) {
|
||||
context.report({
|
||||
node: node.parent,
|
||||
messageId: "declaration",
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
node.parent.type === "VariableDeclarator" &&
|
||||
node.parent.parent.parent.type ===
|
||||
"ExportNamedDeclaration" &&
|
||||
exportFunctionStyle === "declaration" &&
|
||||
!(allowTypeAnnotation && node.parent.id.typeAnnotation)
|
||||
) {
|
||||
context.report({
|
||||
node: node.parent,
|
||||
messageId: "declaration",
|
||||
});
|
||||
}
|
||||
},
|
||||
"FunctionExpression:exit"() {
|
||||
stack.pop();
|
||||
},
|
||||
|
||||
"ThisExpression, Super"() {
|
||||
if (stack.length > 0) {
|
||||
stack[stack.length - 1] = true;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if (!allowArrowFunctions) {
|
||||
nodesToCheck.ArrowFunctionExpression = function () {
|
||||
stack.push(false);
|
||||
};
|
||||
|
||||
nodesToCheck["ArrowFunctionExpression:exit"] = function (node) {
|
||||
const hasThisOrSuperExpr = stack.pop();
|
||||
|
||||
if (
|
||||
!hasThisOrSuperExpr &&
|
||||
node.parent.type === "VariableDeclarator"
|
||||
) {
|
||||
if (
|
||||
enforceDeclarations &&
|
||||
(typeof exportFunctionStyle === "undefined" ||
|
||||
node.parent.parent.parent.type !==
|
||||
"ExportNamedDeclaration") &&
|
||||
!(allowTypeAnnotation && node.parent.id.typeAnnotation)
|
||||
) {
|
||||
context.report({
|
||||
node: node.parent,
|
||||
messageId: "declaration",
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
node.parent.parent.parent.type ===
|
||||
"ExportNamedDeclaration" &&
|
||||
exportFunctionStyle === "declaration" &&
|
||||
!(allowTypeAnnotation && node.parent.id.typeAnnotation)
|
||||
) {
|
||||
context.report({
|
||||
node: node.parent,
|
||||
messageId: "declaration",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return nodesToCheck;
|
||||
},
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* @fileoverview disallow unnecessary concatenation of template strings
|
||||
* @author Henry Zhu
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Checks whether or not a given node is a concatenation.
|
||||
* @param {ASTNode} node A node to check.
|
||||
* @returns {boolean} `true` if the node is a concatenation.
|
||||
*/
|
||||
function isConcatenation(node) {
|
||||
return node.type === "BinaryExpression" && node.operator === "+";
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a `+` token or not.
|
||||
* @param {Token} token The token to check.
|
||||
* @returns {boolean} `true` if the token is a `+` token.
|
||||
*/
|
||||
function isConcatOperatorToken(token) {
|
||||
return token.value === "+" && token.type === "Punctuator";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the right most node on the left side of a BinaryExpression with + operator.
|
||||
* @param {ASTNode} node A BinaryExpression node to check.
|
||||
* @returns {ASTNode} node
|
||||
*/
|
||||
function getLeft(node) {
|
||||
let left = node.left;
|
||||
|
||||
while (isConcatenation(left)) {
|
||||
left = left.right;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the left most node on the right side of a BinaryExpression with + operator.
|
||||
* @param {ASTNode} node A BinaryExpression node to check.
|
||||
* @returns {ASTNode} node
|
||||
*/
|
||||
function getRight(node) {
|
||||
let right = node.right;
|
||||
|
||||
while (isConcatenation(right)) {
|
||||
right = right.left;
|
||||
}
|
||||
return right;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Disallow unnecessary concatenation of literals or template literals",
|
||||
recommended: false,
|
||||
frozen: true,
|
||||
url: "https://eslint.org/docs/latest/rules/no-useless-concat",
|
||||
},
|
||||
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
unexpectedConcat: "Unexpected string concatenation of literals.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
return {
|
||||
BinaryExpression(node) {
|
||||
// check if not concatenation
|
||||
if (node.operator !== "+") {
|
||||
return;
|
||||
}
|
||||
|
||||
// account for the `foo + "a" + "b"` case
|
||||
const left = getLeft(node);
|
||||
const right = getRight(node);
|
||||
|
||||
if (
|
||||
astUtils.isStringLiteral(left) &&
|
||||
astUtils.isStringLiteral(right) &&
|
||||
astUtils.isTokenOnSameLine(left, right)
|
||||
) {
|
||||
const operatorToken = sourceCode.getFirstTokenBetween(
|
||||
left,
|
||||
right,
|
||||
isConcatOperatorToken,
|
||||
);
|
||||
|
||||
context.report({
|
||||
node,
|
||||
loc: operatorToken.loc,
|
||||
messageId: "unexpectedConcat",
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
var x=String;
|
||||
var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};
|
||||
module.exports=create();
|
||||
module.exports.createColors = create;
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { TSESTree } from '@typescript-eslint/utils';
|
||||
import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util';
|
||||
declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"exceed", ({
|
||||
countVoidThis?: boolean;
|
||||
max: number;
|
||||
} | {
|
||||
countVoidThis?: boolean;
|
||||
maximum: number;
|
||||
})[], unknown, {
|
||||
ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression): void;
|
||||
FunctionDeclaration(node: TSESTree.FunctionDeclaration | TSESTree.TSDeclareFunction | TSESTree.TSFunctionType): void;
|
||||
FunctionExpression(node: TSESTree.FunctionExpression): void;
|
||||
}>;
|
||||
export type Options = InferOptionsTypeFromRule<typeof baseRule>;
|
||||
export type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"exceed", ({
|
||||
countVoidThis?: boolean;
|
||||
max: number;
|
||||
} | {
|
||||
countVoidThis?: boolean;
|
||||
maximum: number;
|
||||
})[], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { TSESLint } from '@typescript-eslint/utils';
|
||||
declare const _default: TSESLint.RuleModule<"preferConstAssertion" | "variableConstAssertion" | "variableSuggest", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { expectType, expectNotType } from 'tsd'
|
||||
|
||||
import { createWriteStream } from 'node:fs'
|
||||
|
||||
import pino, { multistream } from '../../pino'
|
||||
|
||||
const streams = [
|
||||
{ stream: process.stdout },
|
||||
{ stream: createWriteStream('') },
|
||||
{ level: 'error' as const, stream: process.stderr },
|
||||
{ level: 'fatal' as const, stream: process.stderr },
|
||||
]
|
||||
|
||||
expectType<pino.MultiStreamRes>(pino.multistream(process.stdout))
|
||||
expectType<pino.MultiStreamRes>(pino.multistream([createWriteStream('')]))
|
||||
expectType<pino.MultiStreamRes<'error'>>(pino.multistream({ level: 'error' as const, stream: process.stderr }))
|
||||
expectType<pino.MultiStreamRes<'fatal'>>(pino.multistream([{ level: 'fatal' as const, stream: createWriteStream('') }]))
|
||||
|
||||
expectType<pino.MultiStreamRes<'error' | 'fatal'>>(pino.multistream(streams))
|
||||
expectType<pino.MultiStreamRes<'error' | 'fatal'>>(pino.multistream(streams, {}))
|
||||
expectType<pino.MultiStreamRes<'error' | 'fatal'>>(pino.multistream(streams, { levels: { info: 30 } }))
|
||||
expectType<pino.MultiStreamRes<'error' | 'fatal'>>(pino.multistream(streams, { dedupe: true }))
|
||||
expectType<pino.MultiStreamRes<'error' | 'fatal'>>(pino.multistream(streams[0]).add(streams[1]))
|
||||
expectType<pino.MultiStreamRes<'error' | 'fatal'>>(multistream(streams))
|
||||
expectType<pino.MultiStreamRes<'error'>>(multistream(streams).clone('error'))
|
||||
expectNotType<pino.MultiStreamRes<string>>(multistream(streams).clone('error'))
|
||||
|
||||
expectType<pino.MultiStreamRes>(multistream(process.stdout))
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { IndividualAndMetaSelectorsString, MetaSelectorsString, Selectors, SelectorsString } from './enums';
|
||||
import { MetaSelectors } from './enums';
|
||||
export declare function selectorTypeToMessageString(selectorType: SelectorsString): string;
|
||||
export declare function isMetaSelector(selector: IndividualAndMetaSelectorsString | MetaSelectors | Selectors): selector is MetaSelectorsString;
|
||||
export declare function isMethodOrPropertySelector(selector: IndividualAndMetaSelectorsString | MetaSelectors | Selectors): boolean;
|
||||
@@ -0,0 +1 @@
|
||||
export default 'ffffffff-ffff-ffff-ffff-ffffffffffff';
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* @fileoverview The main file for the hfs package.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
/** @typedef{import("@humanfs/types").HfsImpl} HfsImpl */
|
||||
/** @typedef{import("@humanfs/types").HfsDirectoryEntry} HfsDirectoryEntry */
|
||||
/**
|
||||
* Error to represent when a method is missing on an impl.
|
||||
*/
|
||||
export class NoSuchMethodError extends Error {
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} methodName The name of the method that was missing.
|
||||
*/
|
||||
constructor(methodName: string);
|
||||
}
|
||||
/**
|
||||
* Error to represent when an impl is already set.
|
||||
*/
|
||||
export class ImplAlreadySetError extends Error {
|
||||
/**
|
||||
* Creates a new instance.
|
||||
*/
|
||||
constructor();
|
||||
}
|
||||
/**
|
||||
* A class representing a log entry.
|
||||
*/
|
||||
export class LogEntry {
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} type The type of log entry.
|
||||
* @param {any} [data] The data associated with the log entry.
|
||||
*/
|
||||
constructor(type: string, data?: any);
|
||||
/**
|
||||
* The time at which the log entry was created.
|
||||
* @type {number}
|
||||
*/
|
||||
timestamp: number;
|
||||
methodName: string;
|
||||
data: any;
|
||||
#private;
|
||||
}
|
||||
/**
|
||||
* A class representing a file system utility library.
|
||||
* @implements {HfsImpl}
|
||||
*/
|
||||
export class Hfs implements HfsImpl {
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {object} options The options for the instance.
|
||||
* @param {HfsImpl} options.impl The implementation to use.
|
||||
*/
|
||||
constructor({ impl }: {
|
||||
impl: HfsImpl;
|
||||
});
|
||||
/**
|
||||
* Starts a new log with the given name.
|
||||
* @param {string} name The name of the log to start;
|
||||
* @returns {void}
|
||||
* @throws {Error} When the log already exists.
|
||||
* @throws {TypeError} When the name is not a non-empty string.
|
||||
*/
|
||||
logStart(name: string): void;
|
||||
/**
|
||||
* Ends a log with the given name and returns the entries.
|
||||
* @param {string} name The name of the log to end.
|
||||
* @returns {Array<LogEntry>} The entries in the log.
|
||||
* @throws {Error} When the log does not exist.
|
||||
*/
|
||||
logEnd(name: string): Array<LogEntry>;
|
||||
/**
|
||||
* Determines if the current implementation is the base implementation.
|
||||
* @returns {boolean} True if the current implementation is the base implementation.
|
||||
*/
|
||||
isBaseImpl(): boolean;
|
||||
/**
|
||||
* Sets the implementation for this instance.
|
||||
* @param {object} impl The implementation to use.
|
||||
* @returns {void}
|
||||
*/
|
||||
setImpl(impl: object): void;
|
||||
/**
|
||||
* Resets the implementation for this instance back to its original.
|
||||
* @returns {void}
|
||||
*/
|
||||
resetImpl(): void;
|
||||
/**
|
||||
* Reads the given file and returns the contents as text. Assumes UTF-8 encoding.
|
||||
* @param {string} filePath The file to read.
|
||||
* @returns {Promise<string|undefined>} The contents of the file.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the file path is not a non-empty string.
|
||||
*/
|
||||
text(filePath: string): Promise<string | undefined>;
|
||||
/**
|
||||
* Reads the given file and returns the contents as JSON. Assumes UTF-8 encoding.
|
||||
* @param {string} filePath The file to read.
|
||||
* @returns {Promise<any|undefined>} The contents of the file as JSON.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {SyntaxError} When the file contents are not valid JSON.
|
||||
* @throws {TypeError} When the file path is not a non-empty string.
|
||||
*/
|
||||
json(filePath: string): Promise<any | undefined>;
|
||||
/**
|
||||
* Reads the given file and returns the contents as an ArrayBuffer.
|
||||
* @param {string} filePath The file to read.
|
||||
* @returns {Promise<ArrayBuffer|undefined>} The contents of the file as an ArrayBuffer.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the file path is not a non-empty string.
|
||||
* @deprecated Use bytes() instead.
|
||||
*/
|
||||
arrayBuffer(filePath: string): Promise<ArrayBuffer | undefined>;
|
||||
/**
|
||||
* Reads the given file and returns the contents as an Uint8Array.
|
||||
* @param {string} filePath The file to read.
|
||||
* @returns {Promise<Uint8Array|undefined>} The contents of the file as an Uint8Array.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the file path is not a non-empty string.
|
||||
*/
|
||||
bytes(filePath: string): Promise<Uint8Array | undefined>;
|
||||
/**
|
||||
* Writes the given data to the given file. Creates any necessary directories along the way.
|
||||
* If the data is a string, UTF-8 encoding is used.
|
||||
* @param {string} filePath The file to write.
|
||||
* @param {any} contents The data to write.
|
||||
* @returns {Promise<void>} A promise that resolves when the file is written.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the file path is not a non-empty string.
|
||||
*/
|
||||
write(filePath: string, contents: any): Promise<void>;
|
||||
/**
|
||||
* Determines if the given file exists.
|
||||
* @param {string} filePath The file to check.
|
||||
* @returns {Promise<boolean>} True if the file exists.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the file path is not a non-empty string.
|
||||
*/
|
||||
isFile(filePath: string): Promise<boolean>;
|
||||
/**
|
||||
* Determines if the given directory exists.
|
||||
* @param {string} dirPath The directory to check.
|
||||
* @returns {Promise<boolean>} True if the directory exists.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the directory path is not a non-empty string.
|
||||
*/
|
||||
isDirectory(dirPath: string): Promise<boolean>;
|
||||
/**
|
||||
* Creates the given directory.
|
||||
* @param {string} dirPath The directory to create.
|
||||
* @returns {Promise<void>} A promise that resolves when the directory is created.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the directory path is not a non-empty string.
|
||||
*/
|
||||
createDirectory(dirPath: string): Promise<void>;
|
||||
/**
|
||||
* Deletes the given file.
|
||||
* @param {string} filePath The file to delete.
|
||||
* @returns {Promise<void>} A promise that resolves when the file is deleted.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the file path is not a non-empty string.
|
||||
*/
|
||||
delete(filePath: string): Promise<void>;
|
||||
/**
|
||||
* Deletes the given directory.
|
||||
* @param {string} dirPath The directory to delete.
|
||||
* @returns {Promise<void>} A promise that resolves when the directory is deleted.
|
||||
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
|
||||
* @throws {TypeError} When the directory path is not a non-empty string.
|
||||
*/
|
||||
deleteAll(dirPath: string): Promise<void>;
|
||||
/**
|
||||
* Returns a list of directory entries for the given path.
|
||||
* @param {string} dirPath The path to the directory to read.
|
||||
* @returns {AsyncIterable<HfsDirectoryEntry>} A promise that resolves with the
|
||||
* directory entries.
|
||||
* @throws {TypeError} If the directory path is not a string.
|
||||
* @throws {Error} If the directory cannot be read.
|
||||
*/
|
||||
list(dirPath: string): AsyncIterable<HfsDirectoryEntry>;
|
||||
/**
|
||||
* Returns the size of the given file.
|
||||
* @param {string} filePath The path to the file to read.
|
||||
* @returns {Promise<number>} A promise that resolves with the size of the file.
|
||||
* @throws {TypeError} If the file path is not a string.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
size(filePath: string): Promise<number>;
|
||||
#private;
|
||||
}
|
||||
export type HfsImpl = import("@humanfs/types").HfsImpl;
|
||||
export type HfsDirectoryEntry = import("@humanfs/types").HfsDirectoryEntry;
|
||||
@@ -0,0 +1,8 @@
|
||||
"use strict";
|
||||
/* eslint-disable @typescript-eslint/no-namespace, no-restricted-syntax */
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SourceCode = void 0;
|
||||
const eslint_1 = require("eslint");
|
||||
class SourceCode extends eslint_1.SourceCode {
|
||||
}
|
||||
exports.SourceCode = SourceCode;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"jsdoc.d.ts","sourceRoot":"","sources":["../../src/ast/jsdoc.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAER,YAAY,EAKZ,QAAQ,EAOX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAEH,KAAK,IAAI,EACT,KAAK,SAAS,EACd,UAAU,EACb,MAAM,UAAU,CAAC;AAalB,6EAA6E;AAC7E,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,QAAQ,EAAE,CAE5D;AAED,2DAA2D;AAC3D,wBAAgB,eAAe,CAAC,CAAC,SAAS,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,QAAQ,KAAK,GAAG,IAAI,CAAC,GAAG,SAAS,CAAC,EAAE,CAEpH;AAED,8CAA8C;AAC9C,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,UAAU,GAAG,SAAS,QAAQ,EAAE,CAEvF;AAED,wEAAwE;AACxE,wBAAgB,qBAAqB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,YAAY,CAAC,GAAG,MAAM,GAAG,SAAS,CAGpG"}
|
||||
@@ -0,0 +1,73 @@
|
||||
# 🛣️ pathe
|
||||
|
||||
> Universal filesystem path utils
|
||||
|
||||
[![version][npm-v-src]][npm-v-href]
|
||||
[![downloads][npm-d-src]][npm-d-href]
|
||||
[![size][size-src]][size-href]
|
||||
|
||||
## ❓ Why
|
||||
|
||||
For [historical reasons](https://docs.microsoft.com/en-us/archive/blogs/larryosterman/why-is-the-dos-path-character), windows followed MS-DOS and used backslash for separating paths rather than slash used for macOS, Linux, and other Posix operating systems. Nowadays, [Windows](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN) supports both Slash and Backslash for paths. [Node.js's built-in `path` module](https://nodejs.org/api/path.html) in the default operation of the path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the path module will assume that Windows-style paths are being used. **This makes inconsistent code behavior between Windows and POSIX.**
|
||||
|
||||
Compared to popular [upath](https://github.com/anodynos/upath), pathe provides **identical exports** of Node.js with normalization on **all operations** and is written in modern **ESM/TypeScript** and has **no dependency on Node.js**!
|
||||
|
||||
This package is a drop-in replacement of the Node.js's [path module](https://nodejs.org/api/path.html) module and ensures paths are normalized with slash `/` and work in environments including Node.js.
|
||||
|
||||
## 💿 Usage
|
||||
|
||||
Install using npm or yarn:
|
||||
|
||||
```bash
|
||||
# npm
|
||||
npm i pathe
|
||||
|
||||
# yarn
|
||||
yarn add pathe
|
||||
|
||||
# pnpm
|
||||
pnpm i pathe
|
||||
```
|
||||
|
||||
Import:
|
||||
|
||||
```js
|
||||
// ESM / Typescript
|
||||
import { resolve, matchesGlob } from "pathe";
|
||||
|
||||
// CommonJS
|
||||
const { resolve, matchesGlob } = require("pathe");
|
||||
```
|
||||
|
||||
Read more about path utils from [Node.js documentation](https://nodejs.org/api/path.html) and rest assured behavior is consistently like POSIX regardless of your input paths format and running platform (the only exception is `delimiter` constant export, it will be set to `;` on windows platform).
|
||||
|
||||
### Extra utilities
|
||||
|
||||
Pathe exports some extra utilities that do not exist in standard Node.js [path module](https://nodejs.org/api/path.html).
|
||||
In order to use them, you can import from `pathe/utils` subpath:
|
||||
|
||||
```js
|
||||
import {
|
||||
filename,
|
||||
normalizeAliases,
|
||||
resolveAlias,
|
||||
reverseResolveAlias,
|
||||
} from "pathe/utils";
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Made with 💛 Published under the [MIT](./LICENSE) license.
|
||||
|
||||
Some code was used from the Node.js project. Glob supported is powered by [zeptomatch](https://github.com/fabiospampinato/zeptomatch).
|
||||
|
||||
<!-- Refs -->
|
||||
|
||||
[npm-v-src]: https://img.shields.io/npm/v/pathe?style=flat-square
|
||||
[npm-v-href]: https://npmjs.com/package/pathe
|
||||
[npm-d-src]: https://img.shields.io/npm/dm/pathe?style=flat-square
|
||||
[npm-d-href]: https://npmjs.com/package/pathe
|
||||
[github-actions-src]: https://img.shields.io/github/workflow/status/unjs/pathe/ci/main?style=flat-square
|
||||
[github-actions-href]: https://github.com/unjs/pathe/actions?query=workflow%3Aci
|
||||
[size-src]: https://packagephobia.now.sh/badge?p=pathe
|
||||
[size-href]: https://packagephobia.now.sh/result?p=pathe
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"name": "tinyglobby",
|
||||
"version": "0.2.17",
|
||||
"description": "A fast and minimal alternative to globby and fast-glob",
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.cts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.cjs"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"author": "Superchupu",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"glob",
|
||||
"patterns",
|
||||
"tiny",
|
||||
"fast"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/SuperchupuDev/tinyglobby.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/SuperchupuDev/tinyglobby/issues"
|
||||
},
|
||||
"homepage": "https://superchupu.dev/tinyglobby",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
},
|
||||
"dependencies": {
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.4.16",
|
||||
"@types/node": "^25.9.1",
|
||||
"@types/picomatch": "^4.0.3",
|
||||
"fast-glob": "^3.3.3",
|
||||
"fs-fixture": "^2.14.0",
|
||||
"glob": "^13.0.6",
|
||||
"tinybench": "^6.0.2",
|
||||
"tsdown": "^0.22.1",
|
||||
"typescript": "^6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "node benchmark/bench.ts",
|
||||
"bench:setup": "node benchmark/setup.ts",
|
||||
"build": "tsdown",
|
||||
"check": "biome check",
|
||||
"check:fix": "biome check --write --unsafe",
|
||||
"format": "biome format --write",
|
||||
"lint": "biome lint",
|
||||
"test": "node --test \"test/**/*.ts\"",
|
||||
"test:coverage": "node --test --experimental-test-coverage \"test/**/*.ts\"",
|
||||
"test:only": "node --test --test-only \"test/**/*.ts\"",
|
||||
"typecheck": "tsc --noEmit"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
'use strict'
|
||||
|
||||
const build = require('../..')
|
||||
|
||||
module.exports = async function (threadStreamOpts) {
|
||||
const { port, opts = {} } = threadStreamOpts
|
||||
return build(
|
||||
function (source) {
|
||||
source.on('data', function (line) {
|
||||
port.postMessage({
|
||||
data: line,
|
||||
pinoConfig: {
|
||||
levels: source.levels,
|
||||
messageKey: source.messageKey,
|
||||
errorKey: source.errorKey
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
opts
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import * as util from "../core/util.js";
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: { unit: "tecken", verb: "att ha" },
|
||||
file: { unit: "bytes", verb: "att ha" },
|
||||
array: { unit: "objekt", verb: "att innehålla" },
|
||||
set: { unit: "objekt", verb: "att innehålla" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "reguljärt uttryck",
|
||||
email: "e-postadress",
|
||||
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-datum och tid",
|
||||
date: "ISO-datum",
|
||||
time: "ISO-tid",
|
||||
duration: "ISO-varaktighet",
|
||||
ipv4: "IPv4-intervall",
|
||||
ipv6: "IPv6-intervall",
|
||||
cidrv4: "IPv4-spektrum",
|
||||
cidrv6: "IPv6-spektrum",
|
||||
base64: "base64-kodad sträng",
|
||||
base64url: "base64url-kodad sträng",
|
||||
json_string: "JSON-sträng",
|
||||
e164: "E.164-nummer",
|
||||
jwt: "JWT",
|
||||
template_literal: "mall-literal",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "antal",
|
||||
array: "lista",
|
||||
};
|
||||
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 `Ogiltig inmatning: förväntat instanceof ${issue.expected}, fick ${received}`;
|
||||
}
|
||||
return `Ogiltig inmatning: förväntat ${expected}, fick ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Ogiltig inmatning: förväntat ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Ogiltigt val: förväntade en av ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `För stor(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`;
|
||||
}
|
||||
return `För stor(t): förväntat ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with") {
|
||||
return `Ogiltig sträng: måste börja med "${_issue.prefix}"`;
|
||||
}
|
||||
if (_issue.format === "ends_with")
|
||||
return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes")
|
||||
return `Ogiltig sträng: måste innehålla "${_issue.includes}"`;
|
||||
if (_issue.format === "regex")
|
||||
return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`;
|
||||
return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Ogiltigt tal: måste vara en multipel av ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `${issue.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Ogiltig nyckel i ${issue.origin ?? "värdet"}`;
|
||||
case "invalid_union":
|
||||
return "Ogiltig input";
|
||||
case "invalid_element":
|
||||
return `Ogiltigt värde i ${issue.origin ?? "värdet"}`;
|
||||
default:
|
||||
return `Ogiltig input`;
|
||||
}
|
||||
};
|
||||
};
|
||||
export default function () {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
"use strict";
|
||||
|
||||
var punycode = require("punycode");
|
||||
var mappingTable = require("./lib/mappingTable.json");
|
||||
|
||||
var PROCESSING_OPTIONS = {
|
||||
TRANSITIONAL: 0,
|
||||
NONTRANSITIONAL: 1
|
||||
};
|
||||
|
||||
function normalize(str) { // fix bug in v8
|
||||
return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000');
|
||||
}
|
||||
|
||||
function findStatus(val) {
|
||||
var start = 0;
|
||||
var end = mappingTable.length - 1;
|
||||
|
||||
while (start <= end) {
|
||||
var mid = Math.floor((start + end) / 2);
|
||||
|
||||
var target = mappingTable[mid];
|
||||
if (target[0][0] <= val && target[0][1] >= val) {
|
||||
return target;
|
||||
} else if (target[0][0] > val) {
|
||||
end = mid - 1;
|
||||
} else {
|
||||
start = mid + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
|
||||
|
||||
function countSymbols(string) {
|
||||
return string
|
||||
// replace every surrogate pair with a BMP symbol
|
||||
.replace(regexAstralSymbols, '_')
|
||||
// then get the length
|
||||
.length;
|
||||
}
|
||||
|
||||
function mapChars(domain_name, useSTD3, processing_option) {
|
||||
var hasError = false;
|
||||
var processed = "";
|
||||
|
||||
var len = countSymbols(domain_name);
|
||||
for (var i = 0; i < len; ++i) {
|
||||
var codePoint = domain_name.codePointAt(i);
|
||||
var status = findStatus(codePoint);
|
||||
|
||||
switch (status[1]) {
|
||||
case "disallowed":
|
||||
hasError = true;
|
||||
processed += String.fromCodePoint(codePoint);
|
||||
break;
|
||||
case "ignored":
|
||||
break;
|
||||
case "mapped":
|
||||
processed += String.fromCodePoint.apply(String, status[2]);
|
||||
break;
|
||||
case "deviation":
|
||||
if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {
|
||||
processed += String.fromCodePoint.apply(String, status[2]);
|
||||
} else {
|
||||
processed += String.fromCodePoint(codePoint);
|
||||
}
|
||||
break;
|
||||
case "valid":
|
||||
processed += String.fromCodePoint(codePoint);
|
||||
break;
|
||||
case "disallowed_STD3_mapped":
|
||||
if (useSTD3) {
|
||||
hasError = true;
|
||||
processed += String.fromCodePoint(codePoint);
|
||||
} else {
|
||||
processed += String.fromCodePoint.apply(String, status[2]);
|
||||
}
|
||||
break;
|
||||
case "disallowed_STD3_valid":
|
||||
if (useSTD3) {
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
processed += String.fromCodePoint(codePoint);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
string: processed,
|
||||
error: hasError
|
||||
};
|
||||
}
|
||||
|
||||
var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/;
|
||||
|
||||
function validateLabel(label, processing_option) {
|
||||
if (label.substr(0, 4) === "xn--") {
|
||||
label = punycode.toUnicode(label);
|
||||
processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;
|
||||
}
|
||||
|
||||
var error = false;
|
||||
|
||||
if (normalize(label) !== label ||
|
||||
(label[3] === "-" && label[4] === "-") ||
|
||||
label[0] === "-" || label[label.length - 1] === "-" ||
|
||||
label.indexOf(".") !== -1 ||
|
||||
label.search(combiningMarksRegex) === 0) {
|
||||
error = true;
|
||||
}
|
||||
|
||||
var len = countSymbols(label);
|
||||
for (var i = 0; i < len; ++i) {
|
||||
var status = findStatus(label.codePointAt(i));
|
||||
if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") ||
|
||||
(processing === PROCESSING_OPTIONS.NONTRANSITIONAL &&
|
||||
status[1] !== "valid" && status[1] !== "deviation")) {
|
||||
error = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
label: label,
|
||||
error: error
|
||||
};
|
||||
}
|
||||
|
||||
function processing(domain_name, useSTD3, processing_option) {
|
||||
var result = mapChars(domain_name, useSTD3, processing_option);
|
||||
result.string = normalize(result.string);
|
||||
|
||||
var labels = result.string.split(".");
|
||||
for (var i = 0; i < labels.length; ++i) {
|
||||
try {
|
||||
var validation = validateLabel(labels[i]);
|
||||
labels[i] = validation.label;
|
||||
result.error = result.error || validation.error;
|
||||
} catch(e) {
|
||||
result.error = true;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
string: labels.join("."),
|
||||
error: result.error
|
||||
};
|
||||
}
|
||||
|
||||
module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {
|
||||
var result = processing(domain_name, useSTD3, processing_option);
|
||||
var labels = result.string.split(".");
|
||||
labels = labels.map(function(l) {
|
||||
try {
|
||||
return punycode.toASCII(l);
|
||||
} catch(e) {
|
||||
result.error = true;
|
||||
return l;
|
||||
}
|
||||
});
|
||||
|
||||
if (verifyDnsLength) {
|
||||
var total = labels.slice(0, labels.length - 1).join(".").length;
|
||||
if (total.length > 253 || total.length === 0) {
|
||||
result.error = true;
|
||||
}
|
||||
|
||||
for (var i=0; i < labels.length; ++i) {
|
||||
if (labels.length > 63 || labels.length === 0) {
|
||||
result.error = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result.error) return null;
|
||||
return labels.join(".");
|
||||
};
|
||||
|
||||
module.exports.toUnicode = function(domain_name, useSTD3) {
|
||||
var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);
|
||||
|
||||
return {
|
||||
domain: result.string,
|
||||
error: result.error
|
||||
};
|
||||
};
|
||||
|
||||
module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;
|
||||
@@ -0,0 +1,108 @@
|
||||
# 1.2.1
|
||||
- fix version
|
||||
|
||||
# 1.2.0
|
||||
- add `List.remove`
|
||||
- build with LiveScript 1.6.0
|
||||
- update dependencies
|
||||
- remove coverage calculation
|
||||
|
||||
# 1.1.2
|
||||
- add `Func.memoize`
|
||||
- fix `zip-all` and `zip-with-all` corner case (no input)
|
||||
- build with LiveScript 1.4.0
|
||||
|
||||
# 1.1.1
|
||||
- curry `unique-by`, `minimum-by`
|
||||
|
||||
# 1.1.0
|
||||
- added `List` functions: `maximum-by`, `minimum-by`, `unique-by`
|
||||
- added `List` functions: `at`, `elem-index`, `elem-indices`, `find-index`, `find-indices`
|
||||
- added `Str` functions: `capitalize`, `camelize`, `dasherize`
|
||||
- added `Func` function: `over` - eg. ``same-length = (==) `over` (.length)``
|
||||
- exported `Str.repeat` through main `prelude` object
|
||||
- fixed definition of `foldr` and `foldr1`, the new correct definition is backwards incompatible with the old, incorrect one
|
||||
- fixed issue with `fix`
|
||||
- improved code coverage
|
||||
|
||||
# 1.0.3
|
||||
- build browser versions
|
||||
|
||||
# 1.0.2
|
||||
- bug fix for `flatten` - slight change with bug fix, flattens arrays only, not array-like objects
|
||||
|
||||
# 1.0.1
|
||||
- bug fixes for `drop-while` and `take-while`
|
||||
|
||||
# 1.0.0
|
||||
* massive update - separated functions into separate modules
|
||||
* functions do not accept multiple types anymore - use different versions in their respective modules in some cases (eg. `Obj.map`), or use `chars` or `values` in other cases to transform into a list
|
||||
* objects are no longer transformed into functions, simply use `(obj.)` in LiveScript to do that
|
||||
* browser version now using browserify - use `prelude = require('prelude-ls')`
|
||||
* added `compact`, `split`, `flatten`, `difference`, `intersection`, `union`, `count-by`, `group-by`, `chars`, `unchars`, `apply`
|
||||
* added `lists-to-obj` which takes a list of keys and list of values and zips them up into an object, and the converse `obj-to-lists`
|
||||
* added `pairs-to-obj` which takes a list of pairs (2 element lists) and creates an object, and the converse `obj-to-pairs`
|
||||
* removed `cons`, `append` - use the concat operator
|
||||
* removed `compose` - use the compose operator
|
||||
* removed `obj-to-func` - use partially applied access (eg. `(obj.)`)
|
||||
* removed `length` - use `(.length)`
|
||||
* `sort-by` renamed to `sort-with`
|
||||
* added new `sort-by`
|
||||
* removed `compare` - just use the new `sort-by`
|
||||
* `break-it` renamed `break-list`, (`Str.break-str` for the string version)
|
||||
* added `Str.repeat` which creates a new string by repeating the input n times
|
||||
* `unfold` as alias to `unfoldr` is no longer used
|
||||
* fixed up style and compiled with LiveScript 1.1.1
|
||||
* use Make instead of Slake
|
||||
* greatly improved tests
|
||||
|
||||
# 0.6.0
|
||||
* fixed various bugs
|
||||
* added `fix`, a fixpoint (Y combinator) for anonymous recursive functions
|
||||
* added `unfoldr` (alias `unfold`)
|
||||
* calling `replicate` with a string now returns a list of strings
|
||||
* removed `partial`, just use native partial application in LiveScript using the `_` placeholder, or currying
|
||||
* added `sort`, `sortBy`, and `compare`
|
||||
|
||||
# 0.5.0
|
||||
* removed `lookup` - use (.prop)
|
||||
* removed `call` - use (.func arg1, arg2)
|
||||
* removed `pluck` - use map (.prop), xs
|
||||
* fixed buys wtih `head` and `last`
|
||||
* added non-minifed browser version, as `prelude-browser.js`
|
||||
* renamed `prelude-min.js` to `prelude-browser-min.js`
|
||||
* renamed `zip` to `zipAll`
|
||||
* renamed `zipWith` to `zipAllWith`
|
||||
* added `zip`, a curried zip that takes only two arguments
|
||||
* added `zipWith`, a curried zipWith that takes only two arguments
|
||||
|
||||
# 0.4.0
|
||||
* added `parition` function
|
||||
* added `curry` function
|
||||
* removed `elem` function (use `in`)
|
||||
* removed `notElem` function (use `not in`)
|
||||
|
||||
# 0.3.0
|
||||
* added `listToObject`
|
||||
* added `unique`
|
||||
* added `objToFunc`
|
||||
* added support for using strings in map and the like
|
||||
* added support for using objects in map and the like
|
||||
* added ability to use objects instead of functions in certain cases
|
||||
* removed `error` (just use throw)
|
||||
* added `tau` constant
|
||||
* added `join`
|
||||
* added `values`
|
||||
* added `keys`
|
||||
* added `partial`
|
||||
* renamed `log` to `ln`
|
||||
* added alias to `head`: `first`
|
||||
* added `installPrelude` helper
|
||||
|
||||
# 0.2.0
|
||||
* removed functions that simply warp operators as you can now use operators as functions in LiveScript
|
||||
* `min/max` are now curried and take only 2 arguments
|
||||
* added `call`
|
||||
|
||||
# 0.1.0
|
||||
* initial public release
|
||||
@@ -0,0 +1,145 @@
|
||||
[![npm][npm-image]][npm-url]
|
||||
[![npm-downloads][npm-downloads-image]][npm-url]
|
||||
[![semantic-release][semantic-release-image]][semantic-release-url]
|
||||
<br />
|
||||
[![code-style-prettier][code-style-prettier-image]][code-style-prettier-url]
|
||||
|
||||
[code-style-prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square
|
||||
[code-style-prettier-url]: https://github.com/prettier/prettier
|
||||
[npm-downloads-image]: https://img.shields.io/npm/dm/@solana/web3.js.svg?style=flat
|
||||
[npm-image]: https://img.shields.io/npm/v/@solana/web3.js.svg?style=flat
|
||||
[npm-url]: https://www.npmjs.com/package/@solana/web3.js
|
||||
[semantic-release-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
|
||||
[semantic-release-url]: https://github.com/semantic-release/semantic-release
|
||||
|
||||
> [!NOTE]
|
||||
> This is the maintenance branch for the 1.x line of `@solana/web3.js`. You can find the successor to this library here: [`@solana/kit`](https://l.anza.xyz/s/js-sdk-repo).
|
||||
|
||||
# Solana JavaScript SDK (v1.x)
|
||||
|
||||
Use this to interact with accounts and programs on the Solana network through the Solana [JSON RPC API](https://solana.com/docs/rpc).
|
||||
|
||||
## Installation
|
||||
|
||||
### For use in Node.js or a web application
|
||||
|
||||
```
|
||||
$ npm install --save @solana/web3.js
|
||||
```
|
||||
|
||||
### For use in a browser, without a build system
|
||||
|
||||
```html
|
||||
<!-- Development (un-minified) -->
|
||||
<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>
|
||||
|
||||
<!-- Production (minified) -->
|
||||
<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.min.js"></script>
|
||||
```
|
||||
|
||||
## Documentation and examples
|
||||
|
||||
- [The Solana Cookbook](https://solanacookbook.com/) has extensive task-based documentation using this library.
|
||||
- For more detail on individual functions, see the [latest API Documentation](https://solana-foundation.github.io/solana-web3.js)
|
||||
|
||||
## Getting help
|
||||
|
||||
Have a question or a problem? Check the [Solana Stack Exchange](https://solana.stackexchange.com) to see if anyone else is having the same one. If not, [post a new question](https://solana.stackexchange.com/questions/ask).
|
||||
|
||||
Include:
|
||||
|
||||
- A detailed description of what you're trying to achieve
|
||||
- Source code, if possible
|
||||
- The text of any errors you encountered, with stacktraces if available
|
||||
|
||||
## Compatibility
|
||||
|
||||
This library requires a JavaScript runtime that supports [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) and the [exponentiation operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation). Both are supported in the following runtimes:
|
||||
|
||||
- Browsers, by [release date](https://caniuse.com/bigint):
|
||||
- Chrome: May 2018
|
||||
- Firefox: July 2019
|
||||
- Safari: September 2020
|
||||
- Mobile Safari: September 2020
|
||||
- Edge: January 2020
|
||||
- Opera: June 2018
|
||||
- Samsung Internet: April 2019
|
||||
- Runtimes, [by version](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt):
|
||||
- Deno: >=1.0
|
||||
- Node: >=10.4.0
|
||||
- React Native:
|
||||
- \>=0.7.0 using the [Hermes](https://reactnative.dev/blog/2022/07/08/hermes-as-the-default) engine ([integration guide](https://solanacookbook.com/integrations/react-native.html#how-to-use-solana-web3-js-in-a-react-native-app)):
|
||||
|
||||
## Development environment setup
|
||||
|
||||
### Testing
|
||||
|
||||
#### Unit tests
|
||||
|
||||
To run the full suite of unit tests, execute the following in the root:
|
||||
|
||||
```shell
|
||||
$ npm test
|
||||
```
|
||||
|
||||
#### Integration tests
|
||||
|
||||
Integration tests require a validator client running on your machine.
|
||||
|
||||
To install a test validator:
|
||||
|
||||
```shell
|
||||
$ npm run test:live-with-test-validator:setup
|
||||
```
|
||||
|
||||
To start the test validator and run all of the integration tests in live mode:
|
||||
|
||||
```shell
|
||||
$ cd packages/library-legacy
|
||||
$ npm run test:live-with-test-validator
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
If you found a bug or would like to request a feature, please [file an issue](https://github.com/solana-foundation/solana-web3.js/issues/new). If, based on the discussion on an issue you would like to offer a code change, please make a [pull request](https://github.com/solana-foundation/solana-web3.js/compare). If neither of these describes what you would like to contribute, read the [getting help](#getting-help) section above.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
All claims, content, designs, algorithms, estimates, roadmaps,
|
||||
specifications, and performance measurements described in this project
|
||||
are done with the Solana Foundation's ("SF") best efforts. It is up to
|
||||
the reader to check and validate their accuracy and truthfulness.
|
||||
Furthermore nothing in this project constitutes a solicitation for
|
||||
investment.
|
||||
|
||||
Any content produced by SF or developer resources that SF provides, are
|
||||
for educational and inspiration purposes only. SF does not encourage,
|
||||
induce or sanction the deployment, integration or use of any such
|
||||
applications (including the code comprising the Solana blockchain
|
||||
protocol) in violation of applicable laws or regulations and hereby
|
||||
prohibits any such deployment, integration or use. This includes use of
|
||||
any such applications by the reader (a) in violation of export control
|
||||
or sanctions laws of the United States or any other applicable
|
||||
jurisdiction, (b) if the reader is located in or ordinarily resident in
|
||||
a country or territory subject to comprehensive sanctions administered
|
||||
by the U.S. Office of Foreign Assets Control (OFAC), or (c) if the
|
||||
reader is or is working on behalf of a Specially Designated National
|
||||
(SDN) or a person subject to similar blocking or denied party
|
||||
prohibitions.
|
||||
|
||||
The reader should be aware that U.S. export control and sanctions laws
|
||||
prohibit U.S. persons (and other persons that are subject to such laws)
|
||||
from transacting with persons in certain countries and territories or
|
||||
that are on the SDN list. As a project based primarily on open-source
|
||||
software, it is possible that such sanctioned persons may nevertheless
|
||||
bypass prohibitions, obtain the code comprising the Solana blockchain
|
||||
protocol (or other project code or applications) and deploy, integrate,
|
||||
or otherwise use it. Accordingly, there is a risk to individuals that
|
||||
other persons using the Solana blockchain protocol may be sanctioned
|
||||
persons and that transactions with such persons would be a violation of
|
||||
U.S. export controls and sanctions law. This risk applies to
|
||||
individuals, organizations, and other ecosystem participants that
|
||||
deploy, integrate, or use the Solana blockchain protocol code directly
|
||||
(e.g., as a node operator), and individuals that transact on the Solana
|
||||
blockchain through light clients, third party interfaces, and/or wallet
|
||||
software.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
/*! *****************************************************************************
|
||||
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 ObjectConstructor {
|
||||
/**
|
||||
* Groups members of an iterable according to the return value of the passed callback.
|
||||
* @param items An iterable.
|
||||
* @param keySelector A callback which will be invoked for each item in items.
|
||||
*/
|
||||
groupBy<K extends PropertyKey, T>(
|
||||
items: Iterable<T>,
|
||||
keySelector: (item: T, index: number) => K,
|
||||
): Partial<Record<K, T[]>>;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,163 @@
|
||||
# detect-libc
|
||||
|
||||
Node.js module to detect details of the C standard library (libc)
|
||||
implementation provided by a given Linux system.
|
||||
|
||||
Currently supports detection of GNU glibc and MUSL libc.
|
||||
|
||||
Provides asychronous and synchronous functions for the
|
||||
family (e.g. `glibc`, `musl`) and version (e.g. `1.23`, `1.2.3`).
|
||||
|
||||
The version numbers of libc implementations
|
||||
are not guaranteed to be semver-compliant.
|
||||
|
||||
For previous v1.x releases, please see the
|
||||
[v1](https://github.com/lovell/detect-libc/tree/v1) branch.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
npm install detect-libc
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### GLIBC
|
||||
|
||||
```ts
|
||||
const GLIBC: string = 'glibc';
|
||||
```
|
||||
|
||||
A String constant containing the value `glibc`.
|
||||
|
||||
### MUSL
|
||||
|
||||
```ts
|
||||
const MUSL: string = 'musl';
|
||||
```
|
||||
|
||||
A String constant containing the value `musl`.
|
||||
|
||||
### family
|
||||
|
||||
```ts
|
||||
function family(): Promise<string | null>;
|
||||
```
|
||||
|
||||
Resolves asychronously with:
|
||||
|
||||
* `glibc` or `musl` when the libc family can be determined
|
||||
* `null` when the libc family cannot be determined
|
||||
* `null` when run on a non-Linux platform
|
||||
|
||||
```js
|
||||
const { family, GLIBC, MUSL } = require('detect-libc');
|
||||
|
||||
switch (await family()) {
|
||||
case GLIBC: ...
|
||||
case MUSL: ...
|
||||
case null: ...
|
||||
}
|
||||
```
|
||||
|
||||
### familySync
|
||||
|
||||
```ts
|
||||
function familySync(): string | null;
|
||||
```
|
||||
|
||||
Synchronous version of `family()`.
|
||||
|
||||
```js
|
||||
const { familySync, GLIBC, MUSL } = require('detect-libc');
|
||||
|
||||
switch (familySync()) {
|
||||
case GLIBC: ...
|
||||
case MUSL: ...
|
||||
case null: ...
|
||||
}
|
||||
```
|
||||
|
||||
### version
|
||||
|
||||
```ts
|
||||
function version(): Promise<string | null>;
|
||||
```
|
||||
|
||||
Resolves asychronously with:
|
||||
|
||||
* The version when it can be determined
|
||||
* `null` when the libc family cannot be determined
|
||||
* `null` when run on a non-Linux platform
|
||||
|
||||
```js
|
||||
const { version } = require('detect-libc');
|
||||
|
||||
const v = await version();
|
||||
if (v) {
|
||||
const [major, minor, patch] = v.split('.');
|
||||
}
|
||||
```
|
||||
|
||||
### versionSync
|
||||
|
||||
```ts
|
||||
function versionSync(): string | null;
|
||||
```
|
||||
|
||||
Synchronous version of `version()`.
|
||||
|
||||
```js
|
||||
const { versionSync } = require('detect-libc');
|
||||
|
||||
const v = versionSync();
|
||||
if (v) {
|
||||
const [major, minor, patch] = v.split('.');
|
||||
}
|
||||
```
|
||||
|
||||
### isNonGlibcLinux
|
||||
|
||||
```ts
|
||||
function isNonGlibcLinux(): Promise<boolean>;
|
||||
```
|
||||
|
||||
Resolves asychronously with:
|
||||
|
||||
* `false` when the libc family is `glibc`
|
||||
* `true` when the libc family is not `glibc`
|
||||
* `false` when run on a non-Linux platform
|
||||
|
||||
```js
|
||||
const { isNonGlibcLinux } = require('detect-libc');
|
||||
|
||||
if (await isNonGlibcLinux()) { ... }
|
||||
```
|
||||
|
||||
### isNonGlibcLinuxSync
|
||||
|
||||
```ts
|
||||
function isNonGlibcLinuxSync(): boolean;
|
||||
```
|
||||
|
||||
Synchronous version of `isNonGlibcLinux()`.
|
||||
|
||||
```js
|
||||
const { isNonGlibcLinuxSync } = require('detect-libc');
|
||||
|
||||
if (isNonGlibcLinuxSync()) { ... }
|
||||
```
|
||||
|
||||
## Licensing
|
||||
|
||||
Copyright 2017 Lovell Fuller and others.
|
||||
|
||||
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](http://www.apache.org/licenses/LICENSE-2.0.html)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = function () {
|
||||
throw new Error(
|
||||
'ws does not work in the browser. Browser clients must use the native ' +
|
||||
'WebSocket object'
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.string = string;
|
||||
exports.number = number;
|
||||
exports.boolean = boolean;
|
||||
exports.bigint = bigint;
|
||||
exports.date = date;
|
||||
const core = __importStar(require("../core/index.cjs"));
|
||||
const schemas = __importStar(require("./schemas.cjs"));
|
||||
// @__NO_SIDE_EFFECTS__
|
||||
function string(params) {
|
||||
return core._coercedString(schemas.ZodMiniString, params);
|
||||
}
|
||||
// @__NO_SIDE_EFFECTS__
|
||||
function number(params) {
|
||||
return core._coercedNumber(schemas.ZodMiniNumber, params);
|
||||
}
|
||||
// @__NO_SIDE_EFFECTS__
|
||||
function boolean(params) {
|
||||
return core._coercedBoolean(schemas.ZodMiniBoolean, params);
|
||||
}
|
||||
// @__NO_SIDE_EFFECTS__
|
||||
function bigint(params) {
|
||||
return core._coercedBigint(schemas.ZodMiniBigInt, params);
|
||||
}
|
||||
// @__NO_SIDE_EFFECTS__
|
||||
function date(params) {
|
||||
return core._coercedDate(schemas.ZodMiniDate, params);
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
|
||||
SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
|
||||
Don't use them in a new protocol. What "weak" means:
|
||||
|
||||
- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
|
||||
- No practical pre-image attacks (only theoretical, 2^123.4)
|
||||
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
|
||||
* @module
|
||||
*/
|
||||
import { Chi, HashMD, Maj } from './_md.ts';
|
||||
import { type CHash, clean, createHasher, rotl } from './utils.ts';
|
||||
|
||||
/** Initial SHA1 state */
|
||||
const SHA1_IV = /* @__PURE__ */ Uint32Array.from([
|
||||
0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,
|
||||
]);
|
||||
|
||||
// Reusable temporary buffer
|
||||
const SHA1_W = /* @__PURE__ */ new Uint32Array(80);
|
||||
|
||||
/** SHA1 legacy hash class. */
|
||||
export class SHA1 extends HashMD<SHA1> {
|
||||
private A = SHA1_IV[0] | 0;
|
||||
private B = SHA1_IV[1] | 0;
|
||||
private C = SHA1_IV[2] | 0;
|
||||
private D = SHA1_IV[3] | 0;
|
||||
private E = SHA1_IV[4] | 0;
|
||||
|
||||
constructor() {
|
||||
super(64, 20, 8, false);
|
||||
}
|
||||
protected get(): [number, number, number, number, number] {
|
||||
const { A, B, C, D, E } = this;
|
||||
return [A, B, C, D, E];
|
||||
}
|
||||
protected set(A: number, B: number, C: number, D: number, E: number): void {
|
||||
this.A = A | 0;
|
||||
this.B = B | 0;
|
||||
this.C = C | 0;
|
||||
this.D = D | 0;
|
||||
this.E = E | 0;
|
||||
}
|
||||
protected process(view: DataView, offset: number): void {
|
||||
for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);
|
||||
for (let i = 16; i < 80; i++)
|
||||
SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
|
||||
// Compression function main loop, 80 rounds
|
||||
let { A, B, C, D, E } = this;
|
||||
for (let i = 0; i < 80; i++) {
|
||||
let F, K;
|
||||
if (i < 20) {
|
||||
F = Chi(B, C, D);
|
||||
K = 0x5a827999;
|
||||
} else if (i < 40) {
|
||||
F = B ^ C ^ D;
|
||||
K = 0x6ed9eba1;
|
||||
} else if (i < 60) {
|
||||
F = Maj(B, C, D);
|
||||
K = 0x8f1bbcdc;
|
||||
} else {
|
||||
F = B ^ C ^ D;
|
||||
K = 0xca62c1d6;
|
||||
}
|
||||
const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;
|
||||
E = D;
|
||||
D = C;
|
||||
C = rotl(B, 30);
|
||||
B = A;
|
||||
A = T;
|
||||
}
|
||||
// Add the compressed chunk to the current hash value
|
||||
A = (A + this.A) | 0;
|
||||
B = (B + this.B) | 0;
|
||||
C = (C + this.C) | 0;
|
||||
D = (D + this.D) | 0;
|
||||
E = (E + this.E) | 0;
|
||||
this.set(A, B, C, D, E);
|
||||
}
|
||||
protected roundClean(): void {
|
||||
clean(SHA1_W);
|
||||
}
|
||||
destroy(): void {
|
||||
this.set(0, 0, 0, 0, 0);
|
||||
clean(this.buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */
|
||||
export const sha1: CHash = /* @__PURE__ */ createHasher(() => new SHA1());
|
||||
|
||||
/** Per-round constants */
|
||||
const p32 = /* @__PURE__ */ Math.pow(2, 32);
|
||||
const K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>
|
||||
Math.floor(p32 * Math.abs(Math.sin(i + 1)))
|
||||
);
|
||||
|
||||
/** md5 initial state: same as sha1, but 4 u32 instead of 5. */
|
||||
const MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);
|
||||
|
||||
// Reusable temporary buffer
|
||||
const MD5_W = /* @__PURE__ */ new Uint32Array(16);
|
||||
/** MD5 legacy hash class. */
|
||||
export class MD5 extends HashMD<MD5> {
|
||||
private A = MD5_IV[0] | 0;
|
||||
private B = MD5_IV[1] | 0;
|
||||
private C = MD5_IV[2] | 0;
|
||||
private D = MD5_IV[3] | 0;
|
||||
|
||||
constructor() {
|
||||
super(64, 16, 8, true);
|
||||
}
|
||||
protected get(): [number, number, number, number] {
|
||||
const { A, B, C, D } = this;
|
||||
return [A, B, C, D];
|
||||
}
|
||||
protected set(A: number, B: number, C: number, D: number): void {
|
||||
this.A = A | 0;
|
||||
this.B = B | 0;
|
||||
this.C = C | 0;
|
||||
this.D = D | 0;
|
||||
}
|
||||
protected process(view: DataView, offset: number): void {
|
||||
for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);
|
||||
// Compression function main loop, 64 rounds
|
||||
let { A, B, C, D } = this;
|
||||
for (let i = 0; i < 64; i++) {
|
||||
let F, g, s;
|
||||
if (i < 16) {
|
||||
F = Chi(B, C, D);
|
||||
g = i;
|
||||
s = [7, 12, 17, 22];
|
||||
} else if (i < 32) {
|
||||
F = Chi(D, B, C);
|
||||
g = (5 * i + 1) % 16;
|
||||
s = [5, 9, 14, 20];
|
||||
} else if (i < 48) {
|
||||
F = B ^ C ^ D;
|
||||
g = (3 * i + 5) % 16;
|
||||
s = [4, 11, 16, 23];
|
||||
} else {
|
||||
F = C ^ (B | ~D);
|
||||
g = (7 * i) % 16;
|
||||
s = [6, 10, 15, 21];
|
||||
}
|
||||
F = F + A + K[i] + MD5_W[g];
|
||||
A = D;
|
||||
D = C;
|
||||
C = B;
|
||||
B = B + rotl(F, s[i % 4]);
|
||||
}
|
||||
// Add the compressed chunk to the current hash value
|
||||
A = (A + this.A) | 0;
|
||||
B = (B + this.B) | 0;
|
||||
C = (C + this.C) | 0;
|
||||
D = (D + this.D) | 0;
|
||||
this.set(A, B, C, D);
|
||||
}
|
||||
protected roundClean(): void {
|
||||
clean(MD5_W);
|
||||
}
|
||||
destroy(): void {
|
||||
this.set(0, 0, 0, 0);
|
||||
clean(this.buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MD5 (RFC 1321) legacy hash function. It was cryptographically broken.
|
||||
* MD5 architecture is similar to SHA1, with some differences:
|
||||
* - Reduced output length: 16 bytes (128 bit) instead of 20
|
||||
* - 64 rounds, instead of 80
|
||||
* - Little-endian: could be faster, but will require more code
|
||||
* - Non-linear index selection: huge speed-up for unroll
|
||||
* - Per round constants: more memory accesses, additional speed-up for unroll
|
||||
*/
|
||||
export const md5: CHash = /* @__PURE__ */ createHasher(() => new MD5());
|
||||
|
||||
// RIPEMD-160
|
||||
|
||||
const Rho160 = /* @__PURE__ */ Uint8Array.from([
|
||||
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
|
||||
]);
|
||||
const Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
|
||||
const Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();
|
||||
const idxLR = /* @__PURE__ */ (() => {
|
||||
const L = [Id160];
|
||||
const R = [Pi160];
|
||||
const res = [L, R];
|
||||
for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));
|
||||
return res;
|
||||
})();
|
||||
const idxL = /* @__PURE__ */ (() => idxLR[0])();
|
||||
const idxR = /* @__PURE__ */ (() => idxLR[1])();
|
||||
// const [idxL, idxR] = idxLR;
|
||||
|
||||
const shifts160 = /* @__PURE__ */ [
|
||||
[11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
|
||||
[12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
|
||||
[13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
|
||||
[14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
|
||||
[15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
|
||||
].map((i) => Uint8Array.from(i));
|
||||
const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
|
||||
const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
|
||||
const Kl160 = /* @__PURE__ */ Uint32Array.from([
|
||||
0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
|
||||
]);
|
||||
const Kr160 = /* @__PURE__ */ Uint32Array.from([
|
||||
0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
|
||||
]);
|
||||
// It's called f() in spec.
|
||||
function ripemd_f(group: number, x: number, y: number, z: number): number {
|
||||
if (group === 0) return x ^ y ^ z;
|
||||
if (group === 1) return (x & y) | (~x & z);
|
||||
if (group === 2) return (x | ~y) ^ z;
|
||||
if (group === 3) return (x & z) | (y & ~z);
|
||||
return x ^ (y | ~z);
|
||||
}
|
||||
// Reusable temporary buffer
|
||||
const BUF_160 = /* @__PURE__ */ new Uint32Array(16);
|
||||
export class RIPEMD160 extends HashMD<RIPEMD160> {
|
||||
private h0 = 0x67452301 | 0;
|
||||
private h1 = 0xefcdab89 | 0;
|
||||
private h2 = 0x98badcfe | 0;
|
||||
private h3 = 0x10325476 | 0;
|
||||
private h4 = 0xc3d2e1f0 | 0;
|
||||
|
||||
constructor() {
|
||||
super(64, 20, 8, true);
|
||||
}
|
||||
protected get(): [number, number, number, number, number] {
|
||||
const { h0, h1, h2, h3, h4 } = this;
|
||||
return [h0, h1, h2, h3, h4];
|
||||
}
|
||||
protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {
|
||||
this.h0 = h0 | 0;
|
||||
this.h1 = h1 | 0;
|
||||
this.h2 = h2 | 0;
|
||||
this.h3 = h3 | 0;
|
||||
this.h4 = h4 | 0;
|
||||
}
|
||||
protected process(view: DataView, offset: number): void {
|
||||
for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);
|
||||
// prettier-ignore
|
||||
let al = this.h0 | 0, ar = al,
|
||||
bl = this.h1 | 0, br = bl,
|
||||
cl = this.h2 | 0, cr = cl,
|
||||
dl = this.h3 | 0, dr = dl,
|
||||
el = this.h4 | 0, er = el;
|
||||
|
||||
// Instead of iterating 0 to 80, we split it into 5 groups
|
||||
// And use the groups in constants, functions, etc. Much simpler
|
||||
for (let group = 0; group < 5; group++) {
|
||||
const rGroup = 4 - group;
|
||||
const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore
|
||||
const rl = idxL[group], rr = idxR[group]; // prettier-ignore
|
||||
const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;
|
||||
al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore
|
||||
}
|
||||
// 2 loops are 10% faster
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;
|
||||
ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore
|
||||
}
|
||||
}
|
||||
// Add the compressed chunk to the current hash value
|
||||
this.set(
|
||||
(this.h1 + cl + dr) | 0,
|
||||
(this.h2 + dl + er) | 0,
|
||||
(this.h3 + el + ar) | 0,
|
||||
(this.h4 + al + br) | 0,
|
||||
(this.h0 + bl + cr) | 0
|
||||
);
|
||||
}
|
||||
protected roundClean(): void {
|
||||
clean(BUF_160);
|
||||
}
|
||||
destroy(): void {
|
||||
this.destroyed = true;
|
||||
clean(this.buffer);
|
||||
this.set(0, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RIPEMD-160 - a legacy hash function from 1990s.
|
||||
* * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
|
||||
* * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
|
||||
*/
|
||||
export const ripemd160: CHash = /* @__PURE__ */ createHasher(() => new RIPEMD160());
|
||||
@@ -0,0 +1,152 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const tsutils = __importStar(require("ts-api-utils"));
|
||||
const ts = __importStar(require("typescript"));
|
||||
const util_1 = require("../util");
|
||||
const FUNCTION_CONSTRUCTOR = 'Function';
|
||||
const GLOBAL_CANDIDATES = new Set(['global', 'globalThis', 'window']);
|
||||
const EVAL_LIKE_FUNCTIONS = new Set([
|
||||
'execScript',
|
||||
'setImmediate',
|
||||
'setInterval',
|
||||
'setTimeout',
|
||||
]);
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-implied-eval',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Disallow the use of `eval()`-like functions',
|
||||
extendsBaseRule: true,
|
||||
recommended: 'recommended',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
messages: {
|
||||
noFunctionConstructor: 'Implied eval. Do not use the Function constructor to create functions.',
|
||||
noImpliedEvalError: 'Implied eval. Consider passing a function.',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
const checker = services.program.getTypeChecker();
|
||||
function getCalleeName(node) {
|
||||
if (node.type === utils_1.AST_NODE_TYPES.Identifier) {
|
||||
return node.name;
|
||||
}
|
||||
if (node.type === utils_1.AST_NODE_TYPES.MemberExpression &&
|
||||
node.object.type === utils_1.AST_NODE_TYPES.Identifier &&
|
||||
GLOBAL_CANDIDATES.has(node.object.name)) {
|
||||
if (node.property.type === utils_1.AST_NODE_TYPES.Identifier) {
|
||||
return node.property.name;
|
||||
}
|
||||
if (node.property.type === utils_1.AST_NODE_TYPES.Literal &&
|
||||
typeof node.property.value === 'string') {
|
||||
return node.property.value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function isFunctionType(node) {
|
||||
const type = services.getTypeAtLocation(node);
|
||||
const symbol = type.getSymbol();
|
||||
if (symbol &&
|
||||
tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Function | ts.SymbolFlags.Method)) {
|
||||
return true;
|
||||
}
|
||||
if ((0, util_1.isBuiltinSymbolLike)(services.program, type, FUNCTION_CONSTRUCTOR)) {
|
||||
return true;
|
||||
}
|
||||
const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call);
|
||||
return signatures.length > 0;
|
||||
}
|
||||
function isBind(node) {
|
||||
return node.type === utils_1.AST_NODE_TYPES.MemberExpression
|
||||
? isBind(node.property)
|
||||
: node.type === utils_1.AST_NODE_TYPES.Identifier && node.name === 'bind';
|
||||
}
|
||||
function isFunction(node) {
|
||||
switch (node.type) {
|
||||
case utils_1.AST_NODE_TYPES.ArrowFunctionExpression:
|
||||
case utils_1.AST_NODE_TYPES.FunctionDeclaration:
|
||||
case utils_1.AST_NODE_TYPES.FunctionExpression:
|
||||
return true;
|
||||
case utils_1.AST_NODE_TYPES.Literal:
|
||||
case utils_1.AST_NODE_TYPES.TemplateLiteral:
|
||||
return false;
|
||||
case utils_1.AST_NODE_TYPES.CallExpression:
|
||||
return isBind(node.callee) || isFunctionType(node);
|
||||
default:
|
||||
return isFunctionType(node);
|
||||
}
|
||||
}
|
||||
function checkImpliedEval(node) {
|
||||
const calleeName = getCalleeName(node.callee);
|
||||
if (calleeName == null) {
|
||||
return;
|
||||
}
|
||||
if (calleeName === FUNCTION_CONSTRUCTOR) {
|
||||
const type = services.getTypeAtLocation(node.callee);
|
||||
const symbol = type.getSymbol();
|
||||
if (symbol) {
|
||||
if ((0, util_1.isBuiltinSymbolLike)(services.program, type, 'FunctionConstructor')) {
|
||||
context.report({ node, messageId: 'noFunctionConstructor' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
else {
|
||||
context.report({ node, messageId: 'noFunctionConstructor' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (node.arguments.length === 0) {
|
||||
return;
|
||||
}
|
||||
const [handler] = node.arguments;
|
||||
if (EVAL_LIKE_FUNCTIONS.has(calleeName) &&
|
||||
!isFunction(handler) &&
|
||||
(0, util_1.isReferenceToGlobalFunction)(calleeName, node, context.sourceCode)) {
|
||||
context.report({ node: handler, messageId: 'noImpliedEvalError' });
|
||||
}
|
||||
}
|
||||
return {
|
||||
CallExpression: checkImpliedEval,
|
||||
NewExpression: checkImpliedEval,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isUndefinedIdentifier = isUndefinedIdentifier;
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
function isUndefinedIdentifier(i) {
|
||||
return i.type === utils_1.AST_NODE_TYPES.Identifier && i.name === 'undefined';
|
||||
}
|
||||
@@ -0,0 +1,703 @@
|
||||
import { describe, expect, expectTypeOf, test } from "vitest";
|
||||
import * as z from "zod/v4";
|
||||
|
||||
const isoDateCodec = z.codec(
|
||||
z.iso.datetime(), // Input: ISO string (validates to string)
|
||||
z.date(), // Output: Date object
|
||||
{
|
||||
decode: (isoString) => new Date(isoString), // Forward: ISO string → Date
|
||||
encode: (date) => date.toISOString(), // Backward: Date → ISO string
|
||||
}
|
||||
);
|
||||
|
||||
test("instanceof", () => {
|
||||
expect(isoDateCodec instanceof z.ZodCodec).toBe(true);
|
||||
expect(isoDateCodec instanceof z.ZodPipe).toBe(true);
|
||||
expect(isoDateCodec instanceof z.ZodType).toBe(true);
|
||||
expect(isoDateCodec instanceof z.core.$ZodCodec).toBe(true);
|
||||
expect(isoDateCodec instanceof z.core.$ZodPipe).toBe(true);
|
||||
expect(isoDateCodec instanceof z.core.$ZodType).toBe(true);
|
||||
|
||||
expectTypeOf(isoDateCodec.def).toEqualTypeOf<z.core.$ZodCodecDef<z.ZodISODateTime, z.ZodDate>>();
|
||||
});
|
||||
|
||||
test("codec basic functionality", () => {
|
||||
// ISO string -> Date codec using z.iso.datetime() for input validation
|
||||
|
||||
const testIsoString = "2024-01-15T10:30:00.000Z";
|
||||
const testDate = new Date("2024-01-15T10:30:00.000Z");
|
||||
|
||||
// Forward decoding (ISO string -> Date)
|
||||
const decodedResult = z.decode(isoDateCodec, testIsoString);
|
||||
expect(decodedResult).toBeInstanceOf(Date);
|
||||
expect(decodedResult.toISOString()).toMatchInlineSnapshot(`"2024-01-15T10:30:00.000Z"`);
|
||||
|
||||
// Backward encoding (Date -> ISO string)
|
||||
const encodedResult = z.encode(isoDateCodec, testDate);
|
||||
expect(typeof encodedResult).toBe("string");
|
||||
expect(encodedResult).toMatchInlineSnapshot(`"2024-01-15T10:30:00.000Z"`);
|
||||
});
|
||||
|
||||
test("codec round trip", () => {
|
||||
const isoDateCodec = z.codec(z.iso.datetime(), z.date(), {
|
||||
decode: (isoString) => new Date(isoString),
|
||||
encode: (date) => date.toISOString(),
|
||||
});
|
||||
|
||||
const original = "2024-12-25T15:45:30.123Z";
|
||||
const toDate = z.decode(isoDateCodec, original);
|
||||
const backToString = z.encode(isoDateCodec, toDate);
|
||||
|
||||
expect(backToString).toMatchInlineSnapshot(`"2024-12-25T15:45:30.123Z"`);
|
||||
expect(toDate).toBeInstanceOf(Date);
|
||||
expect(toDate.getTime()).toMatchInlineSnapshot(`1735141530123`);
|
||||
});
|
||||
|
||||
test("codec with refinement", () => {
|
||||
const isoDateCodec = z
|
||||
.codec(z.iso.datetime(), z.date(), {
|
||||
decode: (isoString) => new Date(isoString),
|
||||
encode: (date) => date.toISOString(),
|
||||
})
|
||||
.refine((val) => val.getFullYear() === 2024, { error: "Year must be 2024" });
|
||||
|
||||
// Valid 2024 date
|
||||
const validDate = z.decode(isoDateCodec, "2024-01-15T10:30:00.000Z");
|
||||
expect(validDate.getFullYear()).toMatchInlineSnapshot(`2024`);
|
||||
expect(validDate.getTime()).toMatchInlineSnapshot(`1705314600000`);
|
||||
|
||||
// Invalid year should fail safely
|
||||
const invalidYearResult = z.safeDecode(isoDateCodec, "2023-01-15T10:30:00.000Z");
|
||||
expect(invalidYearResult.success).toBe(false);
|
||||
if (!invalidYearResult.success) {
|
||||
expect(invalidYearResult.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "custom",
|
||||
"message": "Year must be 2024",
|
||||
"path": [],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
});
|
||||
|
||||
test("safe codec operations", () => {
|
||||
const isoDateCodec = z.codec(z.iso.datetime(), z.date(), {
|
||||
decode: (isoString) => new Date(isoString),
|
||||
encode: (date) => date.toISOString(),
|
||||
});
|
||||
|
||||
// Safe decode with invalid input
|
||||
const safeDecodeResult = z.safeDecode(isoDateCodec, "invalid-date");
|
||||
expect(safeDecodeResult.success).toBe(false);
|
||||
if (!safeDecodeResult.success) {
|
||||
expect(safeDecodeResult.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "invalid_format",
|
||||
"format": "datetime",
|
||||
"message": "Invalid ISO datetime",
|
||||
"origin": "string",
|
||||
"path": [],
|
||||
"pattern": "/^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$/",
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
|
||||
// Safe decode with valid input
|
||||
const safeDecodeValid = z.safeDecode(isoDateCodec, "2024-01-15T10:30:00.000Z");
|
||||
expect(safeDecodeValid.success).toBe(true);
|
||||
if (safeDecodeValid.success) {
|
||||
expect(safeDecodeValid.data).toBeInstanceOf(Date);
|
||||
expect(safeDecodeValid.data.getTime()).toMatchInlineSnapshot(`1705314600000`);
|
||||
}
|
||||
|
||||
// Safe encode with valid input
|
||||
const safeEncodeResult = z.safeEncode(isoDateCodec, new Date("2024-01-01"));
|
||||
expect(safeEncodeResult.success).toBe(true);
|
||||
if (safeEncodeResult.success) {
|
||||
expect(safeEncodeResult.data).toMatchInlineSnapshot(`"2024-01-01T00:00:00.000Z"`);
|
||||
}
|
||||
});
|
||||
|
||||
test("codec with different types", () => {
|
||||
// String -> Number codec
|
||||
const stringNumberCodec = z.codec(z.string(), z.number(), {
|
||||
decode: (str) => Number.parseFloat(str),
|
||||
encode: (num) => num.toString(),
|
||||
});
|
||||
|
||||
const decodedNumber = z.decode(stringNumberCodec, "42.5");
|
||||
expect(decodedNumber).toMatchInlineSnapshot(`42.5`);
|
||||
expect(typeof decodedNumber).toBe("number");
|
||||
|
||||
const encodedString = z.encode(stringNumberCodec, 42.5);
|
||||
expect(encodedString).toMatchInlineSnapshot(`"42.5"`);
|
||||
expect(typeof encodedString).toBe("string");
|
||||
});
|
||||
|
||||
test("async codec operations", async () => {
|
||||
const isoDateCodec = z.codec(z.iso.datetime(), z.date(), {
|
||||
decode: (isoString) => new Date(isoString),
|
||||
encode: (date) => date.toISOString(),
|
||||
});
|
||||
|
||||
// Async decode
|
||||
const decodedResult = await z.decodeAsync(isoDateCodec, "2024-01-15T10:30:00.000Z");
|
||||
expect(decodedResult).toBeInstanceOf(Date);
|
||||
expect(decodedResult.getTime()).toMatchInlineSnapshot(`1705314600000`);
|
||||
|
||||
// Async encode
|
||||
const encodedResult = await z.encodeAsync(isoDateCodec, new Date("2024-01-15T10:30:00.000Z"));
|
||||
expect(typeof encodedResult).toBe("string");
|
||||
expect(encodedResult).toMatchInlineSnapshot(`"2024-01-15T10:30:00.000Z"`);
|
||||
|
||||
// Safe async operations
|
||||
const safeDecodeResult = await z.safeDecodeAsync(isoDateCodec, "2024-01-15T10:30:00.000Z");
|
||||
expect(safeDecodeResult.success).toBe(true);
|
||||
if (safeDecodeResult.success) {
|
||||
expect(safeDecodeResult.data.getTime()).toMatchInlineSnapshot(`1705314600000`);
|
||||
}
|
||||
|
||||
const safeEncodeResult = await z.safeEncodeAsync(isoDateCodec, new Date("2024-01-15T10:30:00.000Z"));
|
||||
expect(safeEncodeResult.success).toBe(true);
|
||||
if (safeEncodeResult.success) {
|
||||
expect(safeEncodeResult.data).toMatchInlineSnapshot(`"2024-01-15T10:30:00.000Z"`);
|
||||
}
|
||||
});
|
||||
|
||||
test("codec type inference", () => {
|
||||
const codec = z.codec(z.string(), z.number(), {
|
||||
decode: (str) => Number.parseInt(str),
|
||||
encode: (num) => num.toString(),
|
||||
});
|
||||
|
||||
// These should compile without type errors
|
||||
const decoded: number = z.decode(codec, "123");
|
||||
const encoded: string = z.encode(codec, 123);
|
||||
|
||||
expect(decoded).toMatchInlineSnapshot(`123`);
|
||||
expect(encoded).toMatchInlineSnapshot(`"123"`);
|
||||
});
|
||||
|
||||
test("nested codec with object containing codec property", () => {
|
||||
// Nested schema: object containing a codec as one of its properties, with refinements at all levels
|
||||
const waypointSchema = z
|
||||
.object({
|
||||
name: z.string().min(1, "Waypoint name required"),
|
||||
difficulty: z.enum(["easy", "medium", "hard"]),
|
||||
coordinate: z
|
||||
.codec(
|
||||
z
|
||||
.string()
|
||||
.regex(/^-?\d+,-?\d+$/, "Must be 'x,y' format"), // Input: coordinate string
|
||||
z
|
||||
.object({ x: z.number(), y: z.number() })
|
||||
.refine((coord) => coord.x >= 0 && coord.y >= 0, { error: "Coordinates must be non-negative" }), // Output: coordinate object
|
||||
{
|
||||
decode: (coordString: string) => {
|
||||
const [x, y] = coordString.split(",").map(Number);
|
||||
return { x, y };
|
||||
},
|
||||
encode: (coord: { x: number; y: number }) => `${coord.x},${coord.y}`,
|
||||
}
|
||||
)
|
||||
.refine((coord) => coord.x <= 1000 && coord.y <= 1000, { error: "Coordinates must be within bounds" }),
|
||||
})
|
||||
.refine((waypoint) => waypoint.difficulty !== "hard" || waypoint.coordinate.x >= 100, {
|
||||
error: "Hard waypoints must be at least 100 units from origin",
|
||||
});
|
||||
|
||||
// Test data
|
||||
const inputWaypoint = {
|
||||
name: "Summit Point",
|
||||
difficulty: "medium" as const,
|
||||
coordinate: "150,200",
|
||||
};
|
||||
|
||||
// Forward decoding (object with string coordinate -> object with coordinate object)
|
||||
const decodedWaypoint = z.decode(waypointSchema, inputWaypoint);
|
||||
expect(decodedWaypoint).toMatchInlineSnapshot(`
|
||||
{
|
||||
"coordinate": {
|
||||
"x": 150,
|
||||
"y": 200,
|
||||
},
|
||||
"difficulty": "medium",
|
||||
"name": "Summit Point",
|
||||
}
|
||||
`);
|
||||
|
||||
// Backward encoding (object with coordinate object -> object with string coordinate)
|
||||
const encodedWaypoint = z.encode(waypointSchema, decodedWaypoint);
|
||||
expect(encodedWaypoint).toMatchInlineSnapshot(`
|
||||
{
|
||||
"coordinate": "150,200",
|
||||
"difficulty": "medium",
|
||||
"name": "Summit Point",
|
||||
}
|
||||
`);
|
||||
|
||||
// Test refinements at all levels
|
||||
// String validation (empty waypoint name)
|
||||
const emptyNameResult = z.safeDecode(waypointSchema, {
|
||||
name: "",
|
||||
difficulty: "easy",
|
||||
coordinate: "10,20",
|
||||
});
|
||||
expect(emptyNameResult.success).toBe(false);
|
||||
if (!emptyNameResult.success) {
|
||||
expect(emptyNameResult.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "too_small",
|
||||
"inclusive": true,
|
||||
"message": "Waypoint name required",
|
||||
"minimum": 1,
|
||||
"origin": "string",
|
||||
"path": [
|
||||
"name",
|
||||
],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
|
||||
// Enum validation (invalid difficulty)
|
||||
const invalidDifficultyResult = z.safeDecode(waypointSchema, {
|
||||
name: "Test Point",
|
||||
difficulty: "impossible" as any,
|
||||
coordinate: "10,20",
|
||||
});
|
||||
expect(invalidDifficultyResult.success).toBe(false);
|
||||
if (!invalidDifficultyResult.success) {
|
||||
expect(invalidDifficultyResult.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "invalid_value",
|
||||
"message": "Invalid option: expected one of "easy"|"medium"|"hard"",
|
||||
"path": [
|
||||
"difficulty",
|
||||
],
|
||||
"values": [
|
||||
"easy",
|
||||
"medium",
|
||||
"hard",
|
||||
],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
|
||||
// Codec string format validation (invalid coordinate format)
|
||||
const invalidFormatResult = z.safeDecode(waypointSchema, {
|
||||
name: "Test Point",
|
||||
difficulty: "easy",
|
||||
coordinate: "invalid",
|
||||
});
|
||||
expect(invalidFormatResult.success).toBe(false);
|
||||
if (!invalidFormatResult.success) {
|
||||
expect(invalidFormatResult.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "invalid_format",
|
||||
"format": "regex",
|
||||
"message": "Must be 'x,y' format",
|
||||
"origin": "string",
|
||||
"path": [
|
||||
"coordinate",
|
||||
],
|
||||
"pattern": "/^-?\\d+,-?\\d+$/",
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
|
||||
// Codec object refinement (negative coordinates)
|
||||
const negativeCoordResult = z.safeDecode(waypointSchema, {
|
||||
name: "Test Point",
|
||||
difficulty: "easy",
|
||||
coordinate: "-5,10",
|
||||
});
|
||||
expect(negativeCoordResult.success).toBe(false);
|
||||
if (!negativeCoordResult.success) {
|
||||
expect(negativeCoordResult.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "custom",
|
||||
"message": "Coordinates must be non-negative",
|
||||
"path": [
|
||||
"coordinate",
|
||||
],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
|
||||
// Codec-level refinement (coordinates out of bounds)
|
||||
const outOfBoundsResult = z.safeDecode(waypointSchema, {
|
||||
name: "Test Point",
|
||||
difficulty: "easy",
|
||||
coordinate: "1500,2000",
|
||||
});
|
||||
expect(outOfBoundsResult.success).toBe(false);
|
||||
if (!outOfBoundsResult.success) {
|
||||
expect(outOfBoundsResult.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "custom",
|
||||
"message": "Coordinates must be within bounds",
|
||||
"path": [
|
||||
"coordinate",
|
||||
],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
|
||||
// Object-level refinement (hard waypoint too close to origin)
|
||||
const hardWaypointResult = z.safeDecode(waypointSchema, {
|
||||
name: "Expert Point",
|
||||
difficulty: "hard",
|
||||
coordinate: "50,60", // x < 100, but hard waypoints need x >= 100
|
||||
});
|
||||
expect(hardWaypointResult.success).toBe(false);
|
||||
if (!hardWaypointResult.success) {
|
||||
expect(hardWaypointResult.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "custom",
|
||||
"message": "Hard waypoints must be at least 100 units from origin",
|
||||
"path": [],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
|
||||
// Round trip test
|
||||
const roundTripResult = z.encode(waypointSchema, z.decode(waypointSchema, inputWaypoint));
|
||||
expect(roundTripResult).toMatchInlineSnapshot(`
|
||||
{
|
||||
"coordinate": "150,200",
|
||||
"difficulty": "medium",
|
||||
"name": "Summit Point",
|
||||
}
|
||||
`);
|
||||
});
|
||||
|
||||
test("mutating refinements", () => {
|
||||
const A = z.codec(z.string(), z.string().trim(), {
|
||||
decode: (val) => val,
|
||||
encode: (val) => val,
|
||||
});
|
||||
|
||||
expect(z.decode(A, " asdf ")).toMatchInlineSnapshot(`"asdf"`);
|
||||
expect(z.encode(A, " asdf ")).toMatchInlineSnapshot(`"asdf"`);
|
||||
|
||||
const B = z
|
||||
.codec(z.string(), z.string(), {
|
||||
decode: (val) => val,
|
||||
encode: (val) => val,
|
||||
})
|
||||
.check(z.trim(), z.maxLength(4));
|
||||
|
||||
expect(z.decode(B, " asdf ")).toMatchInlineSnapshot(`"asdf"`);
|
||||
expect(z.encode(B, " asdf ")).toMatchInlineSnapshot(`"asdf"`);
|
||||
});
|
||||
|
||||
test("codec type enforcement - correct encode/decode signatures", () => {
|
||||
// Test that codec functions have correct type signatures
|
||||
const stringToNumberCodec = z.codec(z.string(), z.number(), {
|
||||
decode: (value: string) => Number(value), // core.output<A> -> core.input<B>
|
||||
encode: (value: number) => String(value), // core.input<B> -> core.output<A>
|
||||
});
|
||||
|
||||
// These should compile without errors - correct types (async support)
|
||||
expectTypeOf<(value: string, payload: z.core.ParsePayload<string>) => z.core.util.MaybeAsync<number>>(
|
||||
stringToNumberCodec.def.transform
|
||||
).toBeFunction();
|
||||
expectTypeOf<(value: number, payload: z.core.ParsePayload<number>) => z.core.util.MaybeAsync<string>>(
|
||||
stringToNumberCodec.def.reverseTransform
|
||||
).toBeFunction();
|
||||
|
||||
// Test that decode parameter type is core.output<A> (string)
|
||||
const validDecode = (value: string) => Number(value);
|
||||
expectTypeOf(validDecode).toMatchTypeOf<(value: string) => number>();
|
||||
|
||||
// Test that encode parameter type is core.input<B> (number)
|
||||
const validEncode = (value: number) => String(value);
|
||||
expectTypeOf(validEncode).toMatchTypeOf<(value: number) => string>();
|
||||
|
||||
z.codec(z.string(), z.number(), {
|
||||
// @ts-expect-error - decode should NOT accept core.input<A> as parameter
|
||||
decode: (value: never, _payload) => Number(value), // Wrong: should be string, not unknown
|
||||
encode: (value: number, _payload) => String(value),
|
||||
});
|
||||
|
||||
z.codec(z.string(), z.number(), {
|
||||
decode: (value: string) => Number(value),
|
||||
// @ts-expect-error - encode should NOT accept core.output<B> as parameter
|
||||
encode: (value: never) => String(value), // Wrong: should be number, not unknown
|
||||
});
|
||||
|
||||
z.codec(z.string(), z.number(), {
|
||||
// @ts-expect-error - decode return type should be core.input<B>
|
||||
decode: (value: string) => String(value), // Wrong: should return number, not string
|
||||
encode: (value: number) => String(value),
|
||||
});
|
||||
|
||||
z.codec(z.string(), z.number(), {
|
||||
decode: (value: string) => Number(value),
|
||||
// @ts-expect-error - encode return type should be core.output<A>
|
||||
encode: (value: number) => Number(value), // Wrong: should return string, not number
|
||||
});
|
||||
});
|
||||
|
||||
test("codec type enforcement - complex types", () => {
|
||||
type User = { id: number; name: string };
|
||||
type UserInput = { id: string; name: string };
|
||||
|
||||
const userCodec = z.codec(
|
||||
z.object({ id: z.string(), name: z.string() }),
|
||||
z.object({ id: z.number(), name: z.string() }),
|
||||
{
|
||||
decode: (input: UserInput) => ({ id: Number(input.id), name: input.name }),
|
||||
encode: (user: User) => ({ id: String(user.id), name: user.name }),
|
||||
}
|
||||
);
|
||||
|
||||
// Verify correct types are inferred (async support)
|
||||
expectTypeOf<(input: UserInput, payload: z.core.ParsePayload<UserInput>) => z.core.util.MaybeAsync<User>>(
|
||||
userCodec.def.transform
|
||||
).toBeFunction();
|
||||
expectTypeOf<(user: User, payload: z.core.ParsePayload<User>) => z.core.util.MaybeAsync<UserInput>>(
|
||||
userCodec.def.reverseTransform
|
||||
).toBeFunction();
|
||||
|
||||
z.codec(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
}),
|
||||
z.object({ id: z.number(), name: z.string() }),
|
||||
{
|
||||
// @ts-expect-error - decode parameter should be UserInput, not User
|
||||
decode: (input: User) => ({ id: Number(input.id), name: input.name }), // Wrong type
|
||||
encode: (user: User) => ({ id: String(user.id), name: user.name }),
|
||||
}
|
||||
);
|
||||
|
||||
z.codec(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
}),
|
||||
z.object({ id: z.number(), name: z.string() }),
|
||||
{
|
||||
decode: (input: UserInput) => ({ id: Number(input.id), name: input.name }),
|
||||
// @ts-expect-error - encode parameter should be User, not UserInput
|
||||
encode: (user: UserInput) => ({ id: String(user.id), name: user.name }), // Wrong type
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("codec with overwrites", () => {
|
||||
const stringPlusA = z.string().overwrite((val) => val + "a");
|
||||
const A = z
|
||||
.codec(stringPlusA, stringPlusA, {
|
||||
decode: (val) => val,
|
||||
encode: (val) => val,
|
||||
})
|
||||
.overwrite((val) => val + "a");
|
||||
|
||||
expect(z.decode(A, "")).toEqual("aaa");
|
||||
expect(z.encode(A, "")).toEqual("aaa");
|
||||
|
||||
// @ts-expect-error
|
||||
expect(z.safeEncode(A, Symbol("a"))).toMatchInlineSnapshot(`
|
||||
{
|
||||
"error": [ZodError: [
|
||||
{
|
||||
"expected": "string",
|
||||
"code": "invalid_type",
|
||||
"path": [],
|
||||
"message": "Invalid input: expected string, received symbol"
|
||||
}
|
||||
]],
|
||||
"success": false,
|
||||
}
|
||||
`);
|
||||
});
|
||||
|
||||
test("async codec functionality", async () => {
|
||||
// Test that async encode/decode functions work properly
|
||||
const asyncCodec = z.codec(z.string(), z.number(), {
|
||||
decode: async (str) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1)); // Simulate async work
|
||||
return Number.parseFloat(str);
|
||||
},
|
||||
encode: async (num) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1)); // Simulate async work
|
||||
return num.toString();
|
||||
},
|
||||
});
|
||||
|
||||
// Test async decode/encode
|
||||
const decoded = await z.decodeAsync(asyncCodec, "42.5");
|
||||
expect(decoded).toBe(42.5);
|
||||
|
||||
const encoded = await z.encodeAsync(asyncCodec, 42.5);
|
||||
expect(encoded).toBe("42.5");
|
||||
|
||||
// Test that both sync and async work
|
||||
const mixedCodec = z.codec(z.string(), z.number(), {
|
||||
decode: async (str) => Number.parseFloat(str),
|
||||
encode: (num) => num.toString(), // sync encode
|
||||
});
|
||||
|
||||
const mixedResult = await z.decodeAsync(mixedCodec, "123");
|
||||
expect(mixedResult).toBe(123);
|
||||
});
|
||||
|
||||
test("invertCodec basic", () => {
|
||||
const inverted = z.invertCodec(isoDateCodec);
|
||||
|
||||
const testDate = new Date("2024-01-15T10:30:00.000Z");
|
||||
const decoded = z.decode(inverted, testDate);
|
||||
expect(typeof decoded).toBe("string");
|
||||
expect(decoded).toBe("2024-01-15T10:30:00.000Z");
|
||||
|
||||
const encoded = z.encode(inverted, "2024-01-15T10:30:00.000Z");
|
||||
expect(encoded).toBeInstanceOf(Date);
|
||||
expect(encoded.toISOString()).toBe("2024-01-15T10:30:00.000Z");
|
||||
});
|
||||
|
||||
test("invertCodec round trip", () => {
|
||||
const inverted = z.invertCodec(isoDateCodec);
|
||||
const testDate = new Date("2024-06-01T12:00:00.000Z");
|
||||
|
||||
const toStr = z.decode(inverted, testDate);
|
||||
const backToDate = z.encode(inverted, toStr);
|
||||
expect(backToDate.toISOString()).toBe(testDate.toISOString());
|
||||
});
|
||||
|
||||
test("invertCodec types", () => {
|
||||
const inverted = z.invertCodec(isoDateCodec);
|
||||
|
||||
type InvIn = z.input<typeof inverted>;
|
||||
type InvOut = z.output<typeof inverted>;
|
||||
expectTypeOf<InvIn>().toEqualTypeOf<Date>();
|
||||
expectTypeOf<InvOut>().toEqualTypeOf<string>();
|
||||
});
|
||||
|
||||
test("invertCodec is its own inverse", () => {
|
||||
const doubleInverted = z.invertCodec(z.invertCodec(isoDateCodec));
|
||||
const testIsoString = "2024-03-10T08:00:00.000Z";
|
||||
|
||||
const decoded = z.decode(doubleInverted, testIsoString);
|
||||
expect(decoded).toBeInstanceOf(Date);
|
||||
expect(decoded.toISOString()).toBe(testIsoString);
|
||||
|
||||
const encoded = z.encode(doubleInverted, decoded);
|
||||
expect(encoded).toBe(testIsoString);
|
||||
});
|
||||
|
||||
test("invertCodec with custom codec", () => {
|
||||
const intToString = z.codec(z.int(), z.string().regex(/^\d+$/), {
|
||||
decode: (num) => num.toString(),
|
||||
encode: (str) => Number.parseInt(str, 10),
|
||||
});
|
||||
|
||||
const stringToInt = z.invertCodec(intToString);
|
||||
const result = z.decode(stringToInt, "42");
|
||||
expect(result).toBe(42);
|
||||
|
||||
const back = z.encode(stringToInt, 42);
|
||||
expect(back).toBe("42");
|
||||
});
|
||||
|
||||
describe("context immutability", () => {
|
||||
test("decode/encode", () => {
|
||||
const stringToDateCodec = z.codec(z.iso.datetime(), z.date(), {
|
||||
decode: (isoString) => new Date(isoString),
|
||||
encode: (date) => date.toISOString(),
|
||||
});
|
||||
|
||||
const ctx = { reportInput: true } as const;
|
||||
|
||||
const result1 = z.decode(stringToDateCodec, "2024-01-15T10:30:00.000Z", ctx);
|
||||
expect(result1).toBeInstanceOf(Date);
|
||||
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
expect("direction" in ctx).toBe(false);
|
||||
|
||||
const result2 = z.decode(stringToDateCodec, "2024-12-25T15:45:30.123Z", ctx);
|
||||
expect(result2).toBeInstanceOf(Date);
|
||||
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
expect("direction" in ctx).toBe(false);
|
||||
|
||||
z.encode(stringToDateCodec, new Date("2024-01-01T00:00:00.000Z"), ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("direction" in ctx).toBe(false);
|
||||
|
||||
z.safeEncode(stringToDateCodec, new Date("2024-01-01T00:00:00.000Z"), ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("direction" in ctx).toBe(false);
|
||||
});
|
||||
|
||||
test("parse functions", () => {
|
||||
const schema = z.string().min(1);
|
||||
const ctx = { reportInput: true } as const;
|
||||
|
||||
z.parse(schema, "asdf", ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
|
||||
z.safeParse(schema, "asdf", ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
});
|
||||
|
||||
test("async functions", async () => {
|
||||
const stringToDateCodec = z.codec(z.iso.datetime(), z.date(), {
|
||||
decode: (isoString) => new Date(isoString),
|
||||
encode: (date) => date.toISOString(),
|
||||
});
|
||||
|
||||
const ctx = { reportInput: true } as const;
|
||||
|
||||
const schema = z.string();
|
||||
await z.parseAsync(schema, "asdf", ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
|
||||
await z.safeParseAsync(schema, "asdf", ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
|
||||
await z.decodeAsync(stringToDateCodec, "2024-01-15T10:30:00.000Z", ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
expect("direction" in ctx).toBe(false);
|
||||
|
||||
await z.encodeAsync(stringToDateCodec, new Date("2024-01-01T00:00:00.000Z"), ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
expect("direction" in ctx).toBe(false);
|
||||
|
||||
await z.safeDecodeAsync(stringToDateCodec, "2024-01-15T10:30:00.000Z", ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
expect("direction" in ctx).toBe(false);
|
||||
|
||||
await z.safeEncodeAsync(stringToDateCodec, new Date("2024-01-01T00:00:00.000Z"), ctx);
|
||||
expect(ctx).toEqual({ reportInput: true });
|
||||
expect("async" in ctx).toBe(false);
|
||||
expect("direction" in ctx).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user