> For the complete documentation index, see [llms.txt](https://infinitode-docs.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://infinitode-docs.gitbook.io/documentation/package-documentation/cloakjs-package-documentation/cloakjs-usage-examples.md).

# CloakJS Usage Examples

Usage examples for CloakJS 1.3.0: obfuscate code in the browser, in Node.js and in a build step, choose presets and options, use seeds for reproducible builds, measure size, and verify the generated o

## 1. Load CloakJS

**In a browser**, drop one script tag in your page — minified for production, the readable file while developing:

```html
<script src="https://cdn.jsdelivr.net/gh/Infinitode/CloakJS@main/cloakjs.min.js"></script>
```

The tag registers a global `CloakJS`. For reproducible deployments, pin a tag or commit hash instead of `@main`.

**In Node.js**, require the file directly — it's UMD, with no dependencies and no manifest to install:

```js
const CloakJS = require('./cloakjs.js');
```

## 2. Obfuscate your first snippet (browser)

This page obfuscates a snippet and then runs the result, so you can see the whole round trip. CloakJS never executes the code it produces — the `new Function` call below is your script doing that on purpose.

```html
<script src="https://cdn.jsdelivr.net/gh/Infinitode/CloakJS@main/cloakjs.min.js"></script>
<script>
  const source = 'var greeting = "Hello, world!"; console.log(greeting);';

  const result = CloakJS.obfuscateWithStats(source, 'extreme');

  console.log(result.code);                       // the obfuscated source, as a string
  console.log(result.stats.techniques);           // what was actually applied
  console.log(result.stats.ratio);                // how much bigger it got
  console.log(result.warnings);                   // read these before shipping

  // Run the generated code (your choice — CloakJS never does this for you).
  new Function(result.code)();
</script>
```

You'll see `Hello, world!` in the console. The generated code is self-contained: it needs no `atob`, no `Uint8Array` and no `TextDecoder` — it uses those APIs only if the host happens to provide them.

## 3. Use a seed for reproducible builds

Output is randomised on purpose, so two builds of the same file differ. When you need a repeatable artefact — CI, a cached CDN file, a diff you can review — pass a `seed`:

```js
const options = { seed: process.env.BUILD_ID ?? "local-dev" };

const a = CloakJS.obfuscate(source, options);
const b = CloakJS.obfuscate(source, options);

console.log(a === b); // true — same input, same options, same seed, same bytes
```

Leave `seed` at its default (`null`) for a release build where you *want* fresh randomness, and record `stats.seed` in your build log when you do set one.

## 4. Obfuscate a file in a build step (Node)

CloakJS has no file I/O: read the source yourself, transform the text, write the result. This script is verified end to end — it produced reproducible output and ran correctly in a bare sandbox:

```js
// build/obfuscate.js
const fs = require('node:fs');
const path = require('node:path');
const CloakJS = require('../vendor/cloakjs.js');

const inputPath = process.argv[2] ?? 'src/app.js';
const outputPath = process.argv[3] ?? 'dist/app.obfuscated.js';
const preset = process.argv[4] ?? 'high';

const source = fs.readFileSync(inputPath, 'utf8');

const result = CloakJS.obfuscateWithStats(source, {
  ...CloakJS.resolveOptions(preset),   // start from a validated preset
  seed: process.env.BUILD_ID ?? null,  // reproducible when BUILD_ID is set
  selfDefending: false,                // the bundle is minified again later
});

for (const warning of result.warnings) {
  console.warn(`[CloakJS] ${warning}`);
}

if (result.warnings.some((w) => /failed to parse/i.test(w))) {
  console.error('[CloakJS] Output did not parse — refusing to write it.');
  process.exit(1);
}

fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, result.code, 'utf8');

console.log(
  `[CloakJS] ${preset} (seed ${result.stats.seed}): ` +
  `${result.stats.originalBytes} → ${result.stats.obfuscatedBytes} bytes ` +
  `(ratio ${result.stats.ratio.toFixed(2)}), techniques: ${result.stats.techniques.join(', ')}`
);
```

```bash
BUILD_ID=build-42 node build/obfuscate.js src/app.js dist/app.obfuscated.js high
# [CloakJS] high (seed build-42): 124 → 2562 bytes (ratio 20.66),
#   techniques: identifierMangling, opaquePredicates, stringEncryption, stringCipher
```

Two things worth copying from this script: it **fails the build** on a parse warning instead of writing broken output, and it turns `selfDefending` off because the bundle is minified again downstream (a minifier rewrites the generated functions and trips the guard).

## 5. Tune the settings

Start from a preset and override what you need:

```js
// Full preset
const a = CloakJS.obfuscate(source, 'high');

// Defaults (the high settings) with no dispatcher, decoys or guard
const b = CloakJS.obfuscate(source, {
  controlFlowFlattening: false,
  deadCodeInjection: false,
  selfDefending: false,
});

// Encoded strings only — no runtime guard, no flattening
const c = CloakJS.obfuscate(source, { stringEncryption: true, controlFlowFlattening: false, selfDefending: false });

// Keep names readable for code that reads Function#name
const d = CloakJS.obfuscate(source, { preserveFunctionNames: true });

// Randomise how much of a big file gets flattened, for a less uniform build
const e = CloakJS.obfuscate(source, { controlFlowThreshold: 0.5 });

// Readable output while you debug a transform problem
const f = CloakJS.obfuscate(source, { compactOutput: false, deadCodeInjection: false, selfDefending: false });

// Log the effective settings, exactly as the transform sees them
console.log(CloakJS.resolveOptions('extreme'));
```

`resolveOptions` returns a validated copy, so logging or editing it won't change `CloakJS.presets` or `CloakJS.defaultOptions`.

{% hint style="warning" %}
A misspelled option is now an error rather than a silent no-op — `{ stringEncrypton: true }` throws `TypeError: CloakJS: unknown option "stringEncrypton"`. See [Option validation](/documentation/package-documentation/cloakjs-package-documentation/cloakjs-reference/cloakjs-options.md#option-validation).
{% endhint %}

## 6. Check the size before you ship

```js
const size = CloakJS.measure(source, 'high');

console.log(`${size.originalBytes} → ${size.obfuscatedBytes} bytes (ratio ${size.ratio.toFixed(2)})`);
```

`measure` generates its own random sample, so its numbers describe that run rather than any earlier `obfuscate` call. Growth depends on content as much as size — string-dense and function-dense files grow much more than numeric ones, because every eligible literal and statement run can attract encoding, splitting, decoys and dispatchers. Measured examples are in the [API reference](/documentation/package-documentation/cloakjs-package-documentation/cloakjs-reference.md#size-measurement).

If the ratio is a problem, try `low`, or drop `deadCodeInjection` and `stringArrayDecoys` first — they are the biggest contributors.

## 7. Verify the generated code

CloakJS can't promise that transformed code behaves like the original, so make verification part of your pipeline. The test suite does exactly what you should do: run the original and the obfuscated version and compare observable output.

```js
const vm = require('node:vm');
const CloakJS = require('./vendor/cloakjs.js');

const source = 'function add(a, b) { return a + b; } console.log(add(2, 3));';

function evaluate(code, sandbox = {}) {
  const logs = [];
  const scope = Object.assign({ console: { log: (...v) => logs.push(v) } }, sandbox);
  new vm.Script(code).runInNewContext(scope);
  return logs;
}

const expected = evaluate(source);

for (const preset of ['off', 'low', 'medium', 'high', 'extreme']) {
  const { code, warnings, stats } = CloakJS.obfuscateWithStats(source, { seed: preset });

  // an empty sandbox proves the decoder needs no host helpers
  const actual = evaluate(code);

  console.log(preset, JSON.stringify(actual), 'warnings:', warnings.length, 'techniques:', stats.techniques.length);

  if (JSON.stringify(actual) !== JSON.stringify(expected)) {
    throw new Error(`${preset} changed behaviour`);
  }
}
```

The cases that deserve the most attention in your own suite:

* **Strict mode.** A leading `"use strict";` stays a directive and is emitted in front of the generated code.
* **String edge cases.** Escapes, non-ASCII text, emoji and long strings — splitting never cuts a surrogate pair.
* **Templates.** Identifiers inside `` `${…}` `` are renamed, and static templates are encoded.
* **Public names.** Anything another script looks up by spelling — turn off `identifierMangling` for that file, or keep those names out of top-level declarations.
* **Dynamic access.** `eval`, `with` and `new Function("…")` disable mangling and escaping for that call by design; the reason appears in `warnings`.
* **Minified input.** CloakJS is a lexer, not a parser: it preserves what it doesn't rewrite and skips what it can't prove safe.

## 8. What not to do

* **Don't obfuscate secrets.** API keys, tokens, credentials and licence checks in client-side JavaScript are readable no matter what the file looks like. The decoder ships with the key.
* **Don't minify obfuscated output while `selfDefending` is on.** The guard throws `Error("Unexpected token")` at runtime. Disable it, or obfuscate after minifying.
* **Don't obfuscate twice.** Re-obfuscating `high` or `extreme` output rewrites the guarded generated functions and throws. Output from `off`, `low` or `medium` can be obfuscated again.
* **Don't feed it ES modules, JSX or TypeScript.** CloakJS targets classic scripts; module syntax triggers a warning and skips mangling. Compile or bundle to a script first.
* **Don't turn on `disableConsoleOutput` or `wrapInIife` casually.** Both change what your program does — console silencing applies to the whole page or process, and the IIFE wrapper changes globals and the script's completion value.
* **Don't treat `'off'` as a guaranteed no-op.** It still applies `compactOutput`, so whitespace in the output can differ from your input.
* **Don't rely on `selfDefending` or `debugProtection` as protection.** They raise the cost of casual tampering; they don't stop a determined analyst, and neither is a security boundary.

## Related pages

* [CloakJS package documentation](/documentation/package-documentation/cloakjs-package-documentation.md) — overview, installation, presets and limitations.
* [API reference](/documentation/package-documentation/cloakjs-package-documentation/cloakjs-reference.md) — methods, `stats`, `warnings`, seeds and limits.
* [Options and presets](/documentation/package-documentation/cloakjs-package-documentation/cloakjs-reference/cloakjs-options.md) — every setting in detail.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://infinitode-docs.gitbook.io/documentation/package-documentation/cloakjs-package-documentation/cloakjs-usage-examples.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
