Socket
Socket
Sign inDemoInstall

@hyrious/dts

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@hyrious/dts - npm Package Compare versions

Comparing version 0.2.1 to 0.2.2

49

cli.js

@@ -49,6 +49,28 @@ #!/usr/bin/env node

// node_modules/.pnpm/yoctocolors@1.0.0/node_modules/yoctocolors/index.js
// node_modules/.pnpm/yoctocolors@2.0.2/node_modules/yoctocolors/index.js
import tty from "node:tty";
var hasColors = tty.WriteStream.prototype.hasColors();
var format = (startCode, endCode) => hasColors ? (string) => "\x1B[" + startCode + "m" + string + "\x1B[" + endCode + "m" : (string) => string;
var format = (open, close) => {
if (!hasColors) {
return (input) => input;
}
const openCode = `\x1B[${open}m`;
const closeCode = `\x1B[${close}m`;
return (input) => {
const string = input + "";
let index = string.indexOf(closeCode);
if (index === -1) {
return openCode + string + closeCode;
}
let result = openCode;
let lastIndex = 0;
while (index !== -1) {
result += string.slice(lastIndex, index) + openCode;
lastIndex = index + closeCode.length;
index = string.indexOf(closeCode, lastIndex);
}
result += string.slice(lastIndex) + closeCode;
return result;
};
};
var black = /* @__PURE__ */ format(30, 39);

@@ -62,3 +84,3 @@ var bgBlue = /* @__PURE__ */ format(44, 49);

// package.json
var version = "0.2.1";
var version = "0.2.2";

@@ -72,18 +94,13 @@ // src/cli.ts

function guess_entry(cwd) {
if (existsSync(join(cwd, "index.ts")))
return "index.ts";
if (existsSync(join(cwd, "src/index.ts")))
return "src/index.ts";
if (existsSync(join(cwd, "src/index.tsx")))
return "src/index.tsx";
if (existsSync(join(cwd, "index.ts"))) return "index.ts";
if (existsSync(join(cwd, "src/index.ts"))) return "src/index.ts";
if (existsSync(join(cwd, "src/index.tsx"))) return "src/index.tsx";
error_exit(new Error("Cannot find entry file, guessing src/index.ts"));
}
function to_array(e) {
if (Array.isArray(e))
return e;
if (typeof e === "string")
return [e];
if (Array.isArray(e)) return e;
if (typeof e === "string") return [e];
return void 0;
}
sade("dts").version(version).describe("Invoke rollup-plugin-dts to generate bundled .d.ts file").command("build [index.ts]", "Build a .d.ts file from a .ts file", { default: true }).option("-o, --outfile", "Output file").option("-i, --include", "Force include a module in the bundle").option("-e, --exclude", "Force exclude a module from the bundle").option("--expand-star", "Expand namespace imports to named imports (experimental)").example("src/index.ts dist/index.d.ts").action(async (entry, options) => {
sade("dts").version(version).describe("Invoke rollup-plugin-dts to generate bundled .d.ts file").command("build [index.ts]", "Build a .d.ts file from a .ts file", { default: true }).option("-o, --outfile", "Output file").option("-i, --include", "Force include a module in the bundle").option("-e, --exclude", "Force exclude a module from the bundle").example("src/index.ts -o dist/index.d.ts").action(async (entry, options) => {
entry ||= guess_entry(process.cwd());

@@ -93,3 +110,2 @@ const outfile = options.outfile && String(options.outfile) || entry.replace(/\.tsx?$/, ".d.ts");

const exclude = to_array(options.exclude);
const expandStar = !!options["expand-star"];
try {

@@ -101,4 +117,3 @@ if (include?.some((e) => exclude?.includes(e))) {

include,
exclude,
experimental: { expandStar }
exclude
});

@@ -105,0 +120,0 @@ const output_files = output.map((e) => e.fileName).join(", ");

import { RollupOutput } from 'rollup';
import { Options } from 'rollup-plugin-dts';
declare const version = "0.2.1";
declare const version = "0.2.2";

@@ -10,6 +10,2 @@ interface BuildOptions {

exclude?: string[];
experimental?: {
/** Post process the result and replace all `* as` to `{...names}` */
expandStar?: boolean;
};
}

@@ -16,0 +12,0 @@ interface BuildResult {

// src/index.ts
import json from "@rollup/plugin-json";
// node_modules/.pnpm/escalade@3.1.1/node_modules/escalade/sync/index.mjs
// node_modules/.pnpm/escalade@3.1.2/node_modules/escalade/sync/index.mjs
import { dirname, resolve } from "path";

@@ -15,7 +15,5 @@ import { readdirSync, statSync } from "fs";

tmp = callback(dir, readdirSync(dir));
if (tmp)
return resolve(dir, tmp);
if (tmp) return resolve(dir, tmp);
dir = dirname(tmp = dir);
if (tmp === dir)
break;
if (tmp === dir) break;
}

@@ -26,13 +24,50 @@ }

import { readFileSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join, relative } from "path";
import { rollup } from "rollup";
import dts from "rollup-plugin-dts";
import { tmpdir } from "os";
import { join, relative } from "path";
// package.json
var version = "0.2.1";
var version = "0.2.2";
// src/index.ts
var CommonExts = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|png|jpe?g|gif|svg|ico|webp|avif|mp4|webm|ogg|mp3|wav|flac|aac|woff2?|eot|ttf|otf|wasm)$/;
var _options = {
var CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
var KNOWN_ASSET_TYPES = [
// images
"apng",
"png",
"jpe?g",
"jfif",
"pjpeg",
"pjp",
"gif",
"svg",
"ico",
"webp",
"avif",
// media
"mp4",
"webm",
"ogg",
"mp3",
"wav",
"flac",
"aac",
"opus",
"mov",
"m4a",
"vtt",
// fonts
"woff2?",
"eot",
"ttf",
"otf",
// other
"webmanifest",
"pdf",
"txt"
];
var DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`);
var suppress_codes = /* @__PURE__ */ new Set(["UNRESOLVED_IMPORT", "CIRCULAR_DEPENDENCY", "EMPTY_BUNDLE"]);
var default_compiler_options = {
noEmit: false,

@@ -50,8 +85,11 @@ declaration: true,

async function build(entry, outfile, options = {}) {
const compilerOptions = Object.assign({}, options.dts?.compilerOptions, _options);
const compilerOptions = Object.assign({}, options.dts?.compilerOptions, default_compiler_options);
const include = options.include || [];
const exclude = options.exclude || [];
const expandStar = options.experimental?.expandStar;
const start = Date.now();
const dts_ = dts({
const pwd = process.cwd();
const json_plugin = json({
preferConst: true
});
const dts_plugin = dts({
respectExternal: true,

@@ -64,8 +102,28 @@ ...options.dts,

onwarn(warning, warn) {
if (warning.code === "UNRESOLVED_IMPORT" || warning.code === "CIRCULAR_DEPENDENCY" || warning.code === "EMPTY_BUNDLE") {
return;
}
if (suppress_codes.has(warning.code)) return;
return warn(warning);
},
plugins: [ignore(CommonExts, dts_), wrap(json, dts_), dts_, expandStar && expand_star()],
plugins: [
// import "./style.css" = nothing
ignore(CSS_LANGS_RE),
// import "./a.jpg" = nothing
ignore(DEFAULT_ASSETS_RE),
// import "./package.json" handled by the json plugin
custom("json", dts_plugin, void 0, void 0, function(code, id, tmpfiles) {
const result2 = json_plugin.transform.call(this, code, id);
if (!result2 || typeof result2 === "string") return result2;
const tmpfile = join(tmpdir(), relative(pwd, id).replace(/[\/\\]/g, "+") + ".ts");
writeFileSync(tmpfile, result2.code);
tmpfiles.push(tmpfile);
return dts_plugin.transform.call(this, result2.code, tmpfile);
}),
// import "./foo?inline" = export default string
custom(
"inline",
dts_plugin,
(id) => id.endsWith("?inline"),
"declare const __inline: string; export default __inline"
),
dts_plugin
],
external: [...get_external(entry, new Set(include)), ...exclude]

@@ -81,26 +139,2 @@ });

}
function wrap(json2, dts2) {
const pwd = process.cwd();
const jsonPlugin = json2({
preferConst: true
});
const tempfiles = [];
return {
name: "wrap(json)",
transform(code, id) {
const result = jsonPlugin.transform.call(this, code, id);
if (!result || typeof result === "string")
return result;
const tempfile = join(tmpdir(), relative(pwd, id).replace(/[\/\\]/g, "+") + ".ts");
writeFileSync(tempfile, result.code);
tempfiles.push(tempfile);
return dts2.transform.call(this, result.code, tempfile);
},
generateBundle() {
for (const file of tempfiles)
rmSync(file);
tempfiles.length = 0;
}
};
}
function get_external(file, reject) {

@@ -120,77 +154,44 @@ const pkg = sync_default(file, (_, names) => {

}
function ignore(re, dts2) {
const pwd = process.cwd();
const tempfiles = [];
const id2tempfile = /* @__PURE__ */ Object.create(null);
function ignore(re) {
return {
name: "ignore",
resolveId(id) {
if (re.test(id) || id.endsWith("?inline")) {
return id;
}
if (re.test(id)) return id;
},
load(id) {
if (re.test(id)) {
return "";
}
if (id.endsWith("?inline")) {
const tempfile = join(tmpdir(), relative(pwd, id).replace(/[\/\\]/g, "+") + ".ts");
const code = `declare const __inline: string; export default __inline`;
writeFileSync(tempfile, code);
tempfiles.push(tempfile);
id2tempfile[id] = tempfile;
if (re.test(id)) return "";
}
};
}
function custom(name, dts2, test, code, transform) {
const pwd = process.cwd();
const tmpfiles = [];
const id2tmpfile = /* @__PURE__ */ Object.create(null);
return {
name,
resolveId(id) {
if (test && test(id)) return id;
},
load(id) {
if (test && test(id) && code) {
const tmpfile = join(tmpdir(), relative(pwd, id).replace(/[\/\\]/g, "+") + ".ts");
writeFileSync(tmpfile, code);
tmpfiles.push(tmpfile);
id2tmpfile[id] = tmpfile;
return code;
}
},
transform(code, id) {
if (id.endsWith("?inline")) {
return dts2.transform.call(this, code, id2tempfile[id]);
transform(code2, id) {
if (!test && transform) {
return transform.call(this, code2, id, tmpfiles);
} else if (test && test(id)) {
return dts2.transform.call(this, code2, id2tmpfile[id]);
}
},
generateBundle() {
for (const file of tempfiles)
rmSync(file);
tempfiles.length = 0;
for (const file of tmpfiles) rmSync(file);
tmpfiles.length = 0;
}
};
}
function expand_star() {
return {
name: "expand-star",
renderChunk(code) {
const namespaces = [];
code.replace(/^import \* as (\S+) from ['"]([-@\w]+)/gm, (_, ns, external) => {
namespaces.push([ns, external]);
return "";
});
if (namespaces.length) {
const names = {};
for (const [ns, module] of namespaces) {
names[ns] ||= {};
const re = new RegExp(`^import {(.+)} from ['"]${module}['"];$`, "gm");
code = code.replace(re, (_, imports) => {
for (let name of imports.split(",")) {
name = name.trim();
if (name)
names[ns][name] = true;
}
return "";
});
}
for (const [ns] of namespaces) {
names[ns] ||= {};
const re = new RegExp(`\\b${ns.replace(/\$/g, "\\$")}\\.(\\w+)\\b`, "g");
code = code.replace(re, (_, name) => {
names[ns][name] = true;
return name;
});
}
code = code.replace(/^import \* as (\S+) from\b/gm, (_, ns) => {
return `import { ${Object.keys(names[ns]).join(", ")} } from`;
});
return code;
}
}
};
}
export {

@@ -197,0 +198,0 @@ build,

{
"name": "@hyrious/dts",
"version": "0.2.1",
"version": "0.2.2",
"description": "Invoke rollup-plugin-dts to generate bundled .d.ts file",

@@ -24,20 +24,20 @@ "keywords": [

],
"scripts": {
"build": "esbuild-dev scripts/build.ts"
},
"dependencies": {
"@rollup/plugin-json": "^6.1.0",
"rollup": "^4.9.5",
"rollup-plugin-dts": "^6.1.0",
"rollup": "^4.17.2",
"rollup-plugin-dts": "^6.1.1",
"sade": "^1.8.1",
"typescript": "^5.3.3"
"typescript": "^5.4.5"
},
"devDependencies": {
"@hyrious/esbuild-dev": "^0.10.5",
"@types/node": "^20.11.5",
"@types/node": "^20.12.12",
"clean-stack": "^5.2.0",
"esbuild": "^0.19.11",
"escalade": "^3.1.1",
"yoctocolors": "^1.0.0"
"esbuild": "^0.21.3",
"escalade": "^3.1.2",
"yoctocolors": "^2.0.2"
},
"scripts": {
"build": "esbuild-dev scripts/build.ts"
}
}
}

@@ -42,5 +42,4 @@ import cleanStack from 'clean-stack'

.option('-e, --exclude', 'Force exclude a module from the bundle')
.option('--expand-star', 'Expand namespace imports to named imports (experimental)')
.example('src/index.ts dist/index.d.ts')
.action(<SadeHandler1<'outfile' | 'include' | 'exclude' | 'expand-star'>>(async (entry, options) => {
.example('src/index.ts -o dist/index.d.ts')
.action(<SadeHandler1<'outfile' | 'include' | 'exclude'>>(async (entry, options) => {
entry ||= guess_entry(process.cwd())

@@ -50,3 +49,2 @@ const outfile = (options.outfile && String(options.outfile)) || entry.replace(/\.tsx?$/, '.d.ts')

const exclude = to_array(options.exclude)
const expandStar = !!options['expand-star']
try {

@@ -59,3 +57,2 @@ if (include?.some(e => exclude?.includes(e))) {

exclude,
experimental: { expandStar },
})

@@ -62,0 +59,0 @@ const output_files = output.map(e => e.fileName).join(', ')

import type ts from 'typescript'
import json, { RollupJsonOptions } from '@rollup/plugin-json'
import json from '@rollup/plugin-json'
import escalade from 'escalade/sync'
import { readFileSync, rmSync, writeFileSync } from 'fs'
import { Plugin, rollup, RollupOutput, TransformHook } from 'rollup'
import dts, { Options } from 'rollup-plugin-dts'
import { tmpdir } from 'os'
import { join, relative } from 'path'
import { Plugin, RollupOutput, TransformHook, TransformResult, rollup } from 'rollup'
import dts, { Options } from 'rollup-plugin-dts'
export { version } from '../package.json'
const CommonExts =
/\.(css|less|sass|scss|styl|stylus|pcss|postcss|png|jpe?g|gif|svg|ico|webp|avif|mp4|webm|ogg|mp3|wav|flac|aac|woff2?|eot|ttf|otf|wasm)$/
// https://github.com/vitejs/vite/blob/-/packages/vite/src/node/constants.ts
const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/
const _options: ts.CompilerOptions = {
const KNOWN_ASSET_TYPES = [
// images
'apng',
'png',
'jpe?g',
'jfif',
'pjpeg',
'pjp',
'gif',
'svg',
'ico',
'webp',
'avif',
// media
'mp4',
'webm',
'ogg',
'mp3',
'wav',
'flac',
'aac',
'opus',
'mov',
'm4a',
'vtt',
// fonts
'woff2?',
'eot',
'ttf',
'otf',
// other
'webmanifest',
'pdf',
'txt',
]
const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`)
const suppress_codes = new Set(['UNRESOLVED_IMPORT', 'CIRCULAR_DEPENDENCY', 'EMPTY_BUNDLE'])
const default_compiler_options: ts.CompilerOptions = {
noEmit: false,

@@ -33,6 +76,2 @@ declaration: true,

exclude?: string[]
experimental?: {
/** Post process the result and replace all `* as` to `{...names}` */
expandStar?: boolean
}
}

@@ -50,10 +89,15 @@

): Promise<BuildResult> {
const compilerOptions = Object.assign({}, options.dts?.compilerOptions, _options)
const compilerOptions = Object.assign({}, options.dts?.compilerOptions, default_compiler_options)
const include = options.include || []
const exclude = options.exclude || []
const expandStar = options.experimental?.expandStar
const start = Date.now()
const dts_ = dts({
const pwd = process.cwd()
const json_plugin = json({
preferConst: true,
})
const dts_plugin = dts({
respectExternal: true,

@@ -63,15 +107,32 @@ ...options.dts,

})
const bundle = await rollup({
input: entry,
onwarn(warning, warn) {
if (
warning.code === 'UNRESOLVED_IMPORT' ||
warning.code === 'CIRCULAR_DEPENDENCY' ||
warning.code === 'EMPTY_BUNDLE'
) {
return
}
if (suppress_codes.has(warning.code!)) return
return warn(warning)
},
plugins: [ignore(CommonExts, dts_), wrap(json, dts_), dts_, expandStar && expand_star()],
plugins: [
// import "./style.css" = nothing
ignore(CSS_LANGS_RE),
// import "./a.jpg" = nothing
ignore(DEFAULT_ASSETS_RE),
// import "./package.json" handled by the json plugin
custom('json', dts_plugin, void 0, void 0, function (this: any, code, id, tmpfiles) {
const result = (json_plugin.transform as TransformHook).call(this, code, id)
if (!result || typeof result === 'string') return result
const tmpfile = join(tmpdir(), relative(pwd, id).replace(/[\/\\]/g, '+') + '.ts')
writeFileSync(tmpfile, result.code!)
tmpfiles.push(tmpfile)
return (dts_plugin.transform as TransformHook).call(this, result.code!, tmpfile)
}),
// import "./foo?inline" = export default string
custom(
'inline',
dts_plugin,
id => id.endsWith('?inline'),
'declare const __inline: string; export default __inline',
),
dts_plugin,
],
external: [...get_external(entry, new Set(include)), ...exclude],

@@ -91,30 +152,2 @@ })

function wrap(json: (options?: RollupJsonOptions) => Plugin, dts: Plugin): Plugin {
const pwd = process.cwd()
const jsonPlugin = json({
preferConst: true,
})
const tempfiles: string[] = []
return {
name: 'wrap(json)',
transform(code, id) {
const result = (jsonPlugin.transform as TransformHook).call(this, code, id)
if (!result || typeof result === 'string') return result
const tempfile = join(tmpdir(), relative(pwd, id).replace(/[\/\\]/g, '+') + '.ts')
// rollup-plugin-dts uses `ts.sys.readFile` to create a new program for this file
// so we have to write this "virtual" file to disk -- becomes real
writeFileSync(tempfile, result.code!)
tempfiles.push(tempfile)
return (dts.transform as TransformHook).call(this, result.code!, tempfile)
},
generateBundle() {
for (const file of tempfiles) rmSync(file)
tempfiles.length = 0
},
}
}
function get_external(file: string, reject: Set<string>) {

@@ -137,27 +170,37 @@ const pkg = escalade(file, (_, names) => {

function ignore(re: RegExp, dts: Plugin): Plugin {
function ignore(re: RegExp): Plugin {
return {
name: 'ignore',
resolveId(id) {
if (re.test(id)) return id
},
load(id) {
if (re.test(id)) return ''
},
}
}
function custom(
name: string,
dts: Plugin,
test?: (id: string) => boolean,
code?: string,
transform?: (code: string, id: string, tmpfiles: string[]) => TransformResult,
): Plugin {
const pwd = process.cwd()
const tempfiles: string[] = []
const id2tempfile: Record<string, string> = Object.create(null)
const tmpfiles: string[] = []
const id2tmpfile = Object.create(null)
return {
name: 'ignore',
name,
resolveId(id) {
if (re.test(id) || id.endsWith('?inline')) {
return id
}
if (test && test(id)) return id
},
load(id) {
if (re.test(id)) {
return ''
}
if (id.endsWith('?inline')) {
const tempfile = join(tmpdir(), relative(pwd, id).replace(/[\/\\]/g, '+') + '.ts')
// rollup-plugin-dts uses `ts.sys.readFile` to create a new program for this file
// so we have to write this "virtual" file to disk -- becomes real
const code = `declare const __inline: string; export default __inline`
writeFileSync(tempfile, code)
tempfiles.push(tempfile)
id2tempfile[id] = tempfile
if (test && test(id) && code) {
const tmpfile = join(tmpdir(), relative(pwd, id).replace(/[\/\\]/g, '+') + '.ts')
writeFileSync(tmpfile, code)
tmpfiles.push(tmpfile)
id2tmpfile[id] = tmpfile
return code

@@ -167,50 +210,13 @@ }

transform(code, id) {
if (id.endsWith('?inline')) {
return (dts.transform as TransformHook).call(this, code, id2tempfile[id])
if (!test && transform) {
return transform.call(this, code, id, tmpfiles)
} else if (test && test(id)) {
return (dts.transform as TransformHook).call(this, code, id2tmpfile[id])
}
},
generateBundle() {
for (const file of tempfiles) rmSync(file)
tempfiles.length = 0
for (const file of tmpfiles) rmSync(file)
tmpfiles.length = 0
},
}
}
function expand_star(): Plugin {
return {
name: 'expand-star',
renderChunk(code) {
const namespaces: [variable: string, module: string][] = []
code.replace(/^import \* as (\S+) from ['"]([-@\w]+)/gm, (_, ns, external) => {
namespaces.push([ns, external])
return ''
})
if (namespaces.length) {
const names: Record<string, Record<string, true>> = {}
for (const [ns, module] of namespaces) {
names[ns] ||= {}
const re = new RegExp(`^import {(.+)} from ['"]${module}['"];$`, 'gm')
code = code.replace(re, (_, imports: string) => {
for (let name of imports.split(',')) {
name = name.trim()
if (name) names[ns][name] = true
}
return ''
})
}
for (const [ns] of namespaces) {
names[ns] ||= {}
const re = new RegExp(`\\b${ns.replace(/\$/g, '\\$')}\\.(\\w+)\\b`, 'g')
code = code.replace(re, (_, name) => {
names[ns][name] = true
return name
})
}
code = code.replace(/^import \* as (\S+) from\b/gm, (_, ns) => {
return `import { ${Object.keys(names[ns]).join(', ')} } from`
})
return code
}
},
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc