omni-obfuscator 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Omni Obfuscator contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # Omni Obfuscator
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Framework-independent JavaScript source protection for websites, desktop apps and server-side applications. Powered by the open-source [javascript-obfuscator](https://github.com/javascript-obfuscator/javascript-obfuscator) engine. Runs locally. Requires Node.js 20+ as a build tool, not necessarily in your deployed application.
4
+
5
+ ## Install
6
+ ```sh
7
+ npm install -D omni-obfuscator
8
+ ```
9
+
10
+ ## CLI
11
+ ```sh
12
+ npx omni-obfuscator protect public --output protected --mode medium
13
+ npx omni-obfuscator protect dist --in-place --mode high
14
+ npx omni-obfuscator protect dist --in-place --dry-run
15
+ ```
16
+ Output must not exist or overlap the input. Directory output copies non-JS assets and excluded scripts, but skips node_modules, VCS directories and symlinks. Only process your own code. In-place mode changes files explicitly; use it on disposable compiled artifacts only. Default excludes minified, vendor-directory, config and common test files; use a dedicated input containing your own build output. Associated .js.map files are removed by default, but unrelated maps and inline HTML scripts are not processed. Disable source maps in your compiler too.
17
+
18
+ ## Modes
19
+ - light: lower overhead, basic identifier and string transformations.
20
+ - medium: balanced string encoding and control-flow transformations.
21
+ - high: higher overhead, stronger transformations; test performance and compatibility.
22
+
23
+ ## Build orchestration
24
+ Add to package.json scripts:
25
+ ```json
26
+ {"build:obfuscated":"omni-obfuscator build","build:obfuscated:high":"omni-obfuscator build --mode high"}
27
+ ```
28
+ Create omni-obfuscator.config.json:
29
+ ```json
30
+ {
31
+ "before":"build:web",
32
+ "defaults":{"mode":"medium"},
33
+ "targets":[{"input":"dist","inPlace":true}],
34
+ "after":"package:app"
35
+ }
36
+ ```
37
+ The before/after values are optional existing npm script names. Targets run sequentially; errors stop the pipeline. Dry run skips scripts and previews existing artifacts. For Electron, compile main/preload and renderer into staging folders, protect those outputs, then run electron-builder or Forge as the after script, configured to package the staging files. Use target node for main-process output, and test preload/renderer with browser-no-eval. Do not point inPlace at your original source. There is no automatic ASAR unpack/repack.
38
+
39
+ ## Vite / Rollup
40
+ ```js
41
+ import omniObfuscator from 'omni-obfuscator/vite';
42
+ export default {
43
+ plugins: [omniObfuscator({ mode: 'medium' })],
44
+ build: { sourcemap: false }
45
+ };
46
+ ```
47
+ Use omni-obfuscator/rollup for Rollup, with output.sourcemap disabled. The plugin transforms emitted JS chunks; code bundled from third-party packages may also be transformed, so configure separate vendor chunks and exclusions. For React, Vue, Svelte, Angular, TypeScript, PHP/Laravel, Django, ASP.NET and other stacks, use the CLI on your own compiled/emitted JavaScript. For Next.js and other hashed/manifest-driven builds, prefer a compatible bundler integration; post-build modifications can invalidate integrity hashes or manifests. This package does not obfuscate PHP, Python, C#, native binaries, CSS, HTML or uncompiled TypeScript.
48
+
49
+ ## JavaScript API
50
+ ```js
51
+ import { obfuscate, protect } from 'omni-obfuscator';
52
+ const result = obfuscate('function add(a,b){return a+b}', {mode:'light'});
53
+ await protect('dist', {output:'protected', target:'node'});
54
+ ```
55
+ CommonJS require is also supported. Options include include/exclude glob arrays, target, mode, removeSourceMaps, dryRun and engine options. Global/property renaming is disabled by default for compatibility. Browser-no-eval is the default target. Custom engine options are advanced and can break compatibility.
56
+
57
+ ## Limitations
58
+ Obfuscation is not encryption, and cannot guarantee against reverse engineering. Never ship secrets in client code. Test production builds. Vendor files can become larger or slower. The CLI is framework-independent, but integrations and specific frameworks must be tested individually. In-place writes are not transactional in case of disk or permission failures.
59
+
60
+ ## Development
61
+ npm ci; npm test; npm pack --dry-run; npm pack.
62
+
63
+ MIT license for this wrapper. Upstream dependencies retain their respective licenses.
64
+
65
+ ## Automatic setup (v1.1.0)
66
+
67
+ ```sh
68
+ npm install -D omni-obfuscator
69
+ npx omni-obfuscator init
70
+ npm run build:obfuscated
71
+ npm run build:obfuscated:high
72
+ ```
73
+
74
+ `init` adds four build scripts without replacing existing custom commands. `detect` identifies the project, `doctor` reports basic compatibility, and `reset` removes matching generated scripts. An existing JSON configuration takes precedence. No configuration is needed for supported conventional layouts.
75
+
76
+ Electron Builder: requires an inline package.json build configuration with explicit simple files globs, no custom packaging hooks or custom app directory. Copies application files into a temporary app directory, obfuscates JavaScript, installs production dependencies there, runs Electron Builder, and removes staging in a finally block. Package output uses the existing output directory. Common Windows NSIS and portable build scripts are recognized; other custom script flags are not automatically reproduced. Full installer compatibility must be tested per application. Keep omni-obfuscator in devDependencies.
77
+
78
+ Vite, Vue CLI and Create React App: runs the existing build script and transforms the conventional dist or build directory. Custom output paths, integrity hashes, service worker manifests and source maps may require explicit integration. Prefer the Vite/Rollup plugin for hash-sensitive builds. Next.js, Angular, Electron Forge and unknown layouts are detected or require explicit configuration rather than guessing paths. The existing protect command and config-based pipeline remain supported. Dry run skips the actual packaging/build; it requires existing frontend output and may temporarily stage Electron files. Automatic cleanup is limited to the current run's own staging directory.
package/bin/cli.cjs ADDED
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ const fs=require('node:fs/promises');
4
+ const {parseArgs}=require('node:util');
5
+ const {spawnSync}=require('node:child_process');
6
+ const {protect}=require('../src/index.cjs');
7
+ const auto=require('../src/auto.cjs');
8
+ const help=`Omni Obfuscator
9
+ omni-obfuscator protect <file|directory> --output <path> [--mode light|medium|high]
10
+ omni-obfuscator protect <compiled-dir> --in-place [--dry-run]
11
+ omni-obfuscator build [--config omni-obfuscator.config.json] [--mode medium]
12
+ Options: --target node|browser|browser-no-eval, --include <glob>, --exclude <glob>,
13
+ --keep-source-maps, --dry-run, --help, --version
14
+ init | detect | doctor | reset
15
+ build uses optional JSON configuration or automatic project detection.
16
+ `;
17
+ function script(name){
18
+ if(!name)return;
19
+ if(typeof name!=='string'||!/^[a-zA-Z0-9:_-]+$/.test(name))throw new Error('Invalid npm script name');
20
+ const r=spawnSync(process.platform==='win32'?'npm.cmd':'npm',['run',name],{stdio:'inherit',shell:process.platform==='win32'});
21
+ if(r.error)throw r.error;
22
+ if(r.status!==0)throw new Error('Script failed: '+name);
23
+ }
24
+ (async()=>{
25
+ const {values:v,positionals:p}=parseArgs({allowPositionals:true,options:{help:{type:'boolean',short:'h'},version:{type:'boolean'},mode:{type:'string'},target:{type:'string'},output:{type:'string',short:'o'},'in-place':{type:'boolean'},'dry-run':{type:'boolean'},'keep-source-maps':{type:'boolean'},include:{type:'string',multiple:true},exclude:{type:'string',multiple:true},config:{type:'string'}}});
26
+ if(v.version){console.log(require('../package.json').version);return;}
27
+ if(v.help||!p.length){console.log(help);return;}
28
+ const overrides={};for(const k of ['mode','target','include','exclude'])if(v[k]!==undefined)overrides[k]=v[k];
29
+ if(v['dry-run'])overrides.dryRun=true;
30
+ if(v['keep-source-maps'])overrides.removeSourceMaps=false;
31
+ const report=r=>console.log(JSON.stringify(r,null,2));
32
+ if(p[0]==='protect'&&p.length===2){report(await protect(p[1],{...overrides,output:v.output,inPlace:v['in-place']}));return;}
33
+ if(p.length===1&&['init','detect','doctor','reset'].includes(p[0])){ const result=await auto[p[0]](); if(p[0]==='detect')delete result.pkg; report(result);return; }
34
+ if(p[0]==='build'&&p.length===1){
35
+ if(!v.config&&!await auto.exists('omni-obfuscator.config.json')){report(await auto.autoBuild(process.cwd(),overrides));return;}
36
+ const cfg=JSON.parse(await fs.readFile(v.config||'omni-obfuscator.config.json','utf8'));
37
+ if(!Array.isArray(cfg.targets)||!cfg.targets.length)throw new Error('Config requires targets');
38
+ if(!v['dry-run'])script(cfg.before);
39
+ for(const t of cfg.targets){const {input,...opts}=t;report(await protect(input,{...cfg.defaults,...opts,...overrides}));}
40
+ if(!v['dry-run'])script(cfg.after);
41
+ return;
42
+ }
43
+ throw new Error('Invalid command; use --help');
44
+ })().catch(e=>{console.error('Omni Obfuscator: '+e.message);process.exitCode=1;});
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "omni-obfuscator",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Framework-independent JavaScript obfuscation CLI, API and build integrations",
5
+ "license": "MIT",
6
+ "main": "src/index.cjs",
7
+ "types": "src/index.d.ts",
8
+ "bin": {
9
+ "omni-obfuscator": "bin/cli.cjs"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./src/index.d.ts",
14
+ "require": "./src/index.cjs",
15
+ "import": "./src/index.mjs"
16
+ },
17
+ "./vite": "./src/plugin.cjs",
18
+ "./rollup": "./src/plugin.cjs"
19
+ },
20
+ "files": [
21
+ "bin",
22
+ "src",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "scripts": {
30
+ "test": "node --test test/*.test.cjs",
31
+ "prepublishOnly": "npm test"
32
+ },
33
+ "dependencies": {
34
+ "javascript-obfuscator": "^4.1.1",
35
+ "picomatch": "^4.0.2"
36
+ },
37
+ "keywords": [
38
+ "javascript",
39
+ "obfuscator",
40
+ "electron",
41
+ "vite",
42
+ "rollup",
43
+ "react",
44
+ "vue",
45
+ "cli",
46
+ "build"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
package/src/auto.cjs ADDED
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+ const fs=require('node:fs/promises');
3
+ const path=require('node:path');
4
+ const {spawnSync}=require('node:child_process');
5
+ const {protect}=require('./index.cjs');
6
+ const CONFIG='omni-obfuscator.config.json';
7
+ const commands=Object.fromEntries(['','light','medium','high'].map(m=>['build:obfuscated'+(m?':'+m:''),'omni-obfuscator build'+(m?' --mode '+m:'')]));
8
+ async function exists(p){try{await fs.access(p);return true;}catch(e){if(e.code==='ENOENT')return false;throw e;}}
9
+ async function read(p){return JSON.parse(await fs.readFile(p,'utf8'));}
10
+ async function detect(root=process.cwd()){
11
+ const pkg=await read(path.join(root,'package.json'));
12
+ const deps={...pkg.dependencies,...pkg.devDependencies};
13
+ const scripts=pkg.scripts||{};
14
+ const build=scripts.build||'';
15
+ let kind='generic',output=null;
16
+ if(deps['electron-builder']||/electron-builder/.test(build))kind='electron-builder';
17
+ else if(deps['@electron-forge/cli'])kind='electron-forge';
18
+ else if(deps.next)kind='next';
19
+ else if(deps.vite){kind='vite';output='dist';}
20
+ else if(deps['react-scripts']){kind='react';output='build';}
21
+ else if(deps['@angular/core'])kind='angular';
22
+ else if(deps['@vue/cli-service']){kind='vue';output='dist';}
23
+ return {kind,output,hasBuild:!!scripts.build,pkg};
24
+ }
25
+ async function init(root=process.cwd()){
26
+ const d=await detect(root);
27
+ const pkg=d.pkg;pkg.scripts||={};
28
+ for(const [k,v] of Object.entries(commands))if(pkg.scripts[k]&&pkg.scripts[k]!==v)throw new Error('Existing script conflicts: '+k);
29
+ Object.assign(pkg.scripts,commands);
30
+ await fs.writeFile(path.join(root,'package.json'),JSON.stringify(pkg,null,2)+'\n');
31
+ return {framework:d.kind,scripts:commands,customConfig:await exists(path.join(root,CONFIG)),note:'Automatic build supports conventional Electron Builder and frontend outputs; custom layouts may require configuration.'};
32
+ }
33
+ function npmScript(root,name){
34
+ if(!/^[a-zA-Z0-9:_-]+$/.test(name))throw new Error('Invalid script');
35
+ const r=spawnSync(process.platform==='win32'?'npm.cmd':'npm',['run',name],{cwd:root,stdio:'inherit',shell:process.platform==='win32'});
36
+ if(r.error)throw r.error;if(r.status!==0)throw new Error('Build script failed: '+name);
37
+ }
38
+ async function electronBuild(root,d,opts){
39
+ // Electron Builder afterPack is too late: use beforePack to stage via appDir.
40
+ // Build API accepts separate projectDir and directories.app; project config stays at root.
41
+ const pkg=d.pkg;
42
+ if(!pkg.build||typeof pkg.build!=='object'||Array.isArray(pkg.build))throw new Error('Automatic Electron requires package.json build configuration');
43
+ const cfg=pkg.build;
44
+ if(cfg.directories?.app&&cfg.directories.app!=='.')throw new Error('Custom directories.app requires explicit configuration');
45
+ if(cfg.extends||cfg.beforePack||cfg.afterPack||cfg.afterSign)throw new Error('Custom builder hooks/extends require explicit integration');
46
+ if(!Array.isArray(cfg.files)||!cfg.files.length||cfg.files.some(f=>typeof f!=='string'||f.startsWith('!')||path.isAbsolute(f)||f.includes('..')))throw new Error('Automatic Electron requires explicit simple build.files globs');
47
+ const dirs=[...new Set(cfg.files.map(f=>f.split('/')[0]))];
48
+ if(dirs.some(f=>/[*?{}\[\]]/.test(f)||['node_modules','.git','dist','.'].includes(f) || f.includes('\\') || f.includes(':')))throw new Error('Unsupported broad build.files; use explicit top-level paths');
49
+ const main=pkg.main||'index.js';
50
+ if(!dirs.includes(main.split('/')[0]))throw new Error('Main entry not covered by build.files');
51
+ const stage=await fs.mkdtemp(path.join(root,'.omni-stage-'));
52
+ try{
53
+ for(const dir of dirs){
54
+ const source=path.join(root,dir);if(!await exists(source))continue;
55
+ await fs.cp(source,path.join(stage,dir),{recursive:true,filter:async s=>{const st=await fs.lstat(s);return !st.isSymbolicLink()&&!['node_modules','.git'].includes(path.basename(s));}});
56
+ }
57
+ const stagedPkg={...pkg};delete stagedPkg.build;
58
+ await fs.writeFile(path.join(stage,'package.json'),JSON.stringify(stagedPkg,null,2));
59
+ const results=[];
60
+ for(const dir of dirs){
61
+ const input=path.join(stage,dir);if(!await exists(input))continue;
62
+ try{results.push(await protect(input,{target:'browser-no-eval',...opts,inPlace:true}));}
63
+ catch(e){if(e.message!=='No matching JavaScript files')throw e;}
64
+ }
65
+ if(!results.length)throw new Error('No application JavaScript found');
66
+ if(opts.dryRun)return {framework:d.kind,results,dryRun:true};
67
+ // Install production dependencies in the staging app, avoiding modification of original node_modules.
68
+ const lock=path.join(root,'package-lock.json');
69
+ if(await exists(lock))await fs.copyFile(lock,path.join(stage,'package-lock.json'));
70
+ const npm=process.platform==='win32'?'npm.cmd':'npm';
71
+ const install=spawnSync(npm,[await exists(lock)?'ci':'install','--omit=dev','--no-audit','--no-fund'],{cwd:stage,stdio:'inherit',shell:process.platform==='win32'});
72
+ if(install.error)throw install.error;if(install.status!==0)throw new Error('Staging dependency installation failed');
73
+ const builder=require(require.resolve('electron-builder',{paths:[root]}));
74
+ const config={...cfg,directories:{...cfg.directories,app:stage,output:path.resolve(root,cfg.directories?.output||'dist')},publish:null};
75
+ if(cfg.electronDist)config.electronDist=path.resolve(root,cfg.electronDist);
76
+ const command=pkg.scripts?.build||'';
77
+ const winScript=pkg.scripts?.['build:win']||'';
78
+ const effective=/npm run build:win/.test(command)?winScript:command;
79
+ const target=/--win\s+nsis\b/.test(effective)?builder.Platform.WINDOWS.createTarget('nsis'):/--win\s+portable\b/.test(effective)?builder.Platform.WINDOWS.createTarget('portable'):undefined;
80
+ const artifacts=await builder.build({projectDir:root,config,...(target?{targets:target}:{}),publish:'never'});
81
+ return {framework:d.kind,results,artifacts};
82
+ }finally{await fs.rm(stage,{recursive:true,force:true});}
83
+ }
84
+ async function autoBuild(root=process.cwd(),opts={}){
85
+ const d=await detect(root);
86
+ if(d.kind==='electron-builder')return electronBuild(root,d,opts);
87
+ if(['electron-forge','next','angular'].includes(d.kind))throw new Error(d.kind+' requires an explicit build configuration in this release');
88
+ if(!d.hasBuild)throw new Error('No build script; use protect or provide explicit configuration');
89
+ if(!d.output)throw new Error('Unknown build output; provide omni-obfuscator.config.json');
90
+ const output=path.join(root,d.output);
91
+ if(!opts.dryRun)npmScript(root,'build');
92
+ if((await fs.lstat(output)).isSymbolicLink())throw new Error('Build output must not be a symlink');
93
+ return {framework:d.kind,result:await protect(output,{...opts,inPlace:true})};
94
+ }
95
+ async function doctor(root=process.cwd()){
96
+ const d=await detect(root);
97
+ return {framework:d.kind,hasBuild:d.hasBuild,output:d.output,customConfig:await exists(path.join(root,CONFIG)),automatic:['electron-builder','vite','react','vue'].includes(d.kind)};
98
+ }
99
+ async function reset(root=process.cwd()){
100
+ const pkg=await read(path.join(root,'package.json'));let removed=[];
101
+ for(const [k,v] of Object.entries(commands))if(pkg.scripts?.[k]===v){delete pkg.scripts[k];removed.push(k);}
102
+ await fs.writeFile(path.join(root,'package.json'),JSON.stringify(pkg,null,2)+'\n');return {removed};
103
+ }
104
+ module.exports={detect,init,autoBuild,doctor,reset,exists};
package/src/index.cjs ADDED
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+ const fs = require('node:fs/promises');
3
+ const path = require('node:path');
4
+ const Obfuscator = require('javascript-obfuscator');
5
+ const match = require('picomatch');
6
+ const presets = Object.freeze({
7
+ light: Object.freeze({compact:true,stringArray:true,stringArrayThreshold:0.5}),
8
+ medium: Object.freeze({compact:true,stringArray:true,stringArrayEncoding:['base64'],controlFlowFlattening:true,controlFlowFlatteningThreshold:0.25}),
9
+ high: Object.freeze({compact:true,stringArray:true,stringArrayEncoding:['rc4'],controlFlowFlattening:true,controlFlowFlatteningThreshold:0.6,deadCodeInjection:true,deadCodeInjectionThreshold:0.15,splitStrings:true})
10
+ });
11
+ function obfuscate(code, opts={}) {
12
+ const {mode='medium',target='browser-no-eval',options={}}=opts;
13
+ if (!Object.hasOwn(presets,mode)) throw new Error('Unknown mode: '+mode);
14
+ return Obfuscator.obfuscate(code,{...presets[mode],target,renameGlobals:false,renameProperties:false,sourceMap:false,...options}).getObfuscatedCode();
15
+ }
16
+ const blocked = new Set(['node_modules','.git','.svn','.hg']);
17
+ const defaultExclude=['**/*.min.js','**/*.config.js','**/*.config.cjs','**/*.config.mjs','**/*.test.js','**/*.spec.js','**/vendor/**'];
18
+ const isJs = p => /\.(?:js|cjs|mjs)$/i.test(p);
19
+ function within(a,b) { const r=path.relative(a,b); return r==='' || (!r.startsWith('..'+path.sep)&&r!=='..'&&!path.isAbsolute(r)); }
20
+ async function protect(input, opts={}) {
21
+ const src=await fs.realpath(input);
22
+ const stat=await fs.stat(src);
23
+ if(!stat.isFile()&&!stat.isDirectory()) throw new Error('Unsupported input');
24
+ if (Boolean(opts.inPlace)===Boolean(opts.output)) throw new Error('Specify exactly one of output or inPlace');
25
+ const dest=opts.inPlace?src:path.resolve(opts.output);
26
+ if(!opts.inPlace) {
27
+ if(within(src,dest)||within(dest,src)) throw new Error('Input/output must not overlap');
28
+ try { await fs.lstat(dest); throw new Error('Output already exists: '+dest); } catch(e) {if(e.code!=='ENOENT') throw e;}
29
+ // Resolve existing ancestors to prevent symlink aliasing.
30
+ let parent=path.dirname(dest);
31
+ while(true){try {const real=await fs.realpath(parent); if(within(src,path.resolve(real,path.relative(parent,dest)))) throw new Error('Output resolves inside input'); break;} catch(e){if(e.code!=='ENOENT') throw e; const next=path.dirname(parent);if(next===parent)throw e;parent=next;}}
32
+ }
33
+ const include=match(opts.include||['**/*.js','**/*.cjs','**/*.mjs'],{dot:true});
34
+ const exclude=match([...defaultExclude,...(opts.exclude||[])],{dot:true});
35
+ const files=[];
36
+ async function walk(abs,rel) {
37
+ const s=await fs.lstat(abs);
38
+ if(s.isSymbolicLink()) return;
39
+ if(s.isDirectory()){for(const name of (await fs.readdir(abs)).sort()){if(!blocked.has(name))await walk(path.join(abs,name),rel?rel+'/'+name:name);}return;}
40
+ if(s.isFile()) files.push({abs,rel:rel||path.basename(abs)});
41
+ }
42
+ await walk(src,'');
43
+ const selected=files.filter(f=>isJs(f.rel)&&include(f.rel)&&!exclude(f.rel));
44
+ if(!selected.length) throw new Error('No matching JavaScript files');
45
+ const transformed=new Map();
46
+ for(const f of selected){
47
+ const code=await fs.readFile(f.abs,'utf8');
48
+ try {transformed.set(f.abs,obfuscate(code,opts));} catch(e){throw new Error(f.rel+': '+e.message,{cause:e});}
49
+ }
50
+ const maps=new Set(selected.map(f=>f.abs+'.map'));
51
+ if(opts.dryRun)return {obfuscated:selected.length,files:selected.map(f=>f.rel),dryRun:true};
52
+ if(opts.inPlace){
53
+ // Transform everything before writing so parser failures leave sources intact.
54
+ for(const [file,code] of transformed)await fs.writeFile(file,code);
55
+ if(opts.removeSourceMaps!==false)for(const f of files)if(maps.has(f.abs))await fs.unlink(f.abs);
56
+ }else{
57
+ if(stat.isDirectory())await fs.mkdir(dest,{recursive:true});
58
+ for(const f of files){
59
+ if(opts.removeSourceMaps!==false&&maps.has(f.abs))continue;
60
+ const out=stat.isDirectory()?path.join(dest,f.rel):dest;
61
+ await fs.mkdir(path.dirname(out),{recursive:true});
62
+ if(transformed.has(f.abs))await fs.writeFile(out,transformed.get(f.abs),{flag:'wx'});
63
+ else await fs.copyFile(f.abs,out,require('node:fs').constants.COPYFILE_EXCL);
64
+ await fs.chmod(out,(await fs.stat(f.abs)).mode);
65
+ }
66
+ }
67
+ return {obfuscated:selected.length,files:selected.map(f=>f.rel),output:dest};
68
+ }
69
+ module.exports={obfuscate,protect,presets};
package/src/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export type Mode = 'light' | 'medium' | 'high';
2
+ export interface ObfuscateOptions { mode?: Mode; target?: 'browser'|'browser-no-eval'|'node'; options?: Record<string, unknown>; }
3
+ export interface ProtectOptions extends ObfuscateOptions { output?: string; inPlace?: boolean; include?: string[]; exclude?: string[]; dryRun?: boolean; removeSourceMaps?: boolean; }
4
+ export function obfuscate(code: string, options?: ObfuscateOptions): string;
5
+ export function protect(input: string, options: ProtectOptions): Promise<{obfuscated:number;files:string[];output?:string;dryRun?:boolean}>;
6
+ export const presets: Readonly<Record<Mode, Readonly<Record<string, unknown>>>>;
7
+ declare const api: {obfuscate:typeof obfuscate;protect:typeof protect;presets:typeof presets};
8
+ export default api;
package/src/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import api from './index.cjs';
2
+ export const {obfuscate,protect,presets}=api;
3
+ export default api;
package/src/plugin.cjs ADDED
@@ -0,0 +1,11 @@
1
+ const {obfuscate}=require('./index.cjs');
2
+ const match=require('picomatch');
3
+ function omniObfuscator(opts={}){
4
+ const exclude=match(opts.exclude||['**/vendor*.js','**/polyfills*.js']);
5
+ return {name:'omni-obfuscator',apply:'build',enforce:'post',renderChunk(code,chunk){
6
+ if(exclude(chunk.fileName))return null;
7
+ return {code:obfuscate(code,opts),map:null};
8
+ }};
9
+ }
10
+ module.exports=omniObfuscator;
11
+ module.exports.default=omniObfuscator;