# How the HKUDS/CLI-Anything Builder Handles JSONC-Style Comments in Spec Files

> Learn how the HKUDS CLI-Anything builder handles JSONC comments. It strips // style comments via regex, allowing JSONC-compatible spec files without extra dependencies.

- Repository: [✨Data Intelligence Lab@HKU✨/CLI-Anything](https://github.com/HKUDS/CLI-Anything)
- Tags: how-to-guide
- Published: 2026-08-16

---

**The CLI-Anything builder strips `//`-style comments using a simple regex before parsing, enabling JSONC-compatible spec files without external dependencies.**

The CLI-Anything toolkit allows developers to generate Sketch files from JSON specifications. A practical challenge with JSON-based configs is the inability to include comments for documentation. The project's Sketch builder solves this by preprocessing spec files to remove JSONC-style comments before standard JSON parsing.

## Where JSONC Comment Handling Occurs

The comment-stripping logic resides in [`sketch/agent-harness/src/builder.js`](https://github.com/HKUDS/CLI-Anything/blob/main/sketch/agent-harness/src/builder.js), specifically lines 27–30. This core builder file orchestrates the entire spec-to-Sketch pipeline, starting with reading the raw specification and sanitizing it for valid JSON consumption.

## The Three-Step Comment Removal Process

The builder implements a lightweight, regex-based approach that runs immediately after file read:

1. **Load the spec file** – `fs.readFileSync` reads the entire file as a UTF-8 string.
2. **Strip `//` comments** – a global, multiline regex removes everything from `//` to each line's end.
3. **Parse clean JSON** – `JSON.parse` processes the comment-free string into a specification object.

This sequence enables human-readable specs with inline documentation while maintaining strict JSON compatibility downstream.

## The Comment-Stripping Regex Explained

The critical transformation occurs in this single line (builder.js, lines 27–30):

```javascript
const specClean = specRaw.replace(/\/\/.*$/gm, '');

```

**Pattern breakdown:**

- `\/\/` – matches literal `//` (forward slashes escaped)
- `.*` – matches any characters following the slashes
- `$` – anchors to end of line (prevents over-matching across lines)
- `gm` flags – **g**lobal (all matches), **m**ultiline (`$` matches each line end)

This approach handles both standalone comment lines and trailing comments on JSON property lines.

## Complete Working Example

### JSONC Spec File with Comments

```json
{
  // Token definitions (optional)
  "tokens": "./tokens.json",

  // Pages array
  "pages": [
    {
      "name": "Home",
      "artboards": [
        {
          // Artboard dimensions
          "width": 375,
          "height": 812,
          // Layers on the artboard
          "layers": [
            {
              "type": "text",
              "content": "Hello World"
            }
          ]
        }
      ]
    }
  ]
}

```

Save this as [`example.spec.json`](https://github.com/HKUDS/CLI-Anything/blob/main/example.spec.json) — the builder accepts it despite the multiple `//` comments.

### Programmatic Usage

```javascript
const { build } = require('./sketch/agent-harness/src/builder');

(async () => {
  const input = 'example.spec.json';
  const output = 'out/myDesign.sketch';

  // The builder automatically strips the // comments above
  await build(input, output);
  console.log('Sketch file created at', output);
})();

```

### Direct CLI Invocation

```bash
node ./sketch/agent-harness/src/builder.js path/to/spec.json path/to/result.sketch

```

Both methods apply identical comment-stripping logic internally.

## Key Source Files in the Builder Pipeline

| File | Role |
|------|------|
| [`builder.js`](https://github.com/HKUDS/CLI-Anything/blob/main/builder.js) | Core orchestrator: reads spec, removes JSONC comments, parses JSON, constructs Sketch document |
| [`Sketch.js`](https://github.com/HKUDS/CLI-Anything/blob/main/Sketch.js) | Sketch document model imported by builder for file generation |
| [`Page.js`](https://github.com/HKUDS/CLI-Anything/blob/main/Page.js), [`Artboard.js`](https://github.com/HKUDS/CLI-Anything/blob/main/Artboard.js), [`Layer.js`](https://github.com/HKUDS/CLI-Anything/blob/main/Layer.js) | Helper classes that assemble hierarchy from parsed spec |

All files reside under `sketch/agent-harness/src/` or its subdirectories according to the HKUDS/CLI-Anything repository structure.

## Why This Approach Over Dedicated JSONC Parsers

The regex-based implementation in CLI-Anything trades full JSONC spec compliance (which includes `/* */` block comments) for **zero-dependency simplicity** and **performance**. Most developer documentation needs are satisfied by `//` line comments, making this a pragmatic engineering choice for the project's scope.

## Summary

- The CLI-Anything builder accepts JSONC-style comments through preprocessing in [`builder.js`](https://github.com/HKUDS/CLI-Anything/blob/main/builder.js)
- A single regex `/\/\/.*$/gm` removes all `//` line comments before `JSON.parse`
- This enables self-documenting spec files without adding external parser dependencies
- Both programmatic and CLI usage paths apply identical comment handling

## Frequently Asked Questions

### Does the builder support `/* */` block comments?

No. The implementation at [`sketch/agent-harness/src/builder.js`](https://github.com/HKUDS/CLI-Anything/blob/main/sketch/agent-harness/src/builder.js) only strips `//` line comments. Block comments pass through to `JSON.parse` and will cause parsing errors. Use `//` for all documentation needs.

### What happens if a JSON string value contains `//`?

The regex is line-based and unselective — it removes `//` anywhere on a line, including inside string values. Avoid `//` sequences in your actual data values; place documentation comments on separate lines to minimize collision risk.

### Is this approach safe for multi-megabyte spec files?

Yes. The regex replace operates on the full string in memory, which is efficient for typical configuration files. For extremely large specs (hundreds of MB), streaming parsers would be preferable, but such scale is atypical for UI specifications.

### Can I use this comment-stripping logic in my own projects?

The pattern is simple and portable. The CLI-Anything implementation uses: `specRaw.replace(/\/\/.*$/gm, '')`. Adapt this for any Node.js or JavaScript project requiring lightweight JSONC support without adding dependencies like `json5` or `comment-json`.