Skip to content

feat(groq): Generates a deterministic ASCII‑art QR‑like code for any input string and prints it to the terminal. - #5836

Open
polsala wants to merge 1 commit into
mainfrom
ai/groq-20260903-0350
Open

feat(groq): Generates a deterministic ASCII‑art QR‑like code for any input string and prints it to the terminal.#5836
polsala wants to merge 1 commit into
mainfrom
ai/groq-20260903-0350

Conversation

@polsala

@polsala polsala commented Sep 3, 2026

Copy link
Copy Markdown
Owner

Implementation Summary

  • Utility: nightly-cryptic-qr-cli
  • Provider: groq
  • Location: typescript-utils/nightly-nightly-cryptic-qr-cli
  • Files Created: 3
  • Description: Generates a deterministic ASCII‑art QR‑like code for any input string and prints it to the terminal.

Rationale

  • Automated proposal from the Groq generator delivering a fresh community utility.
  • This utility was generated using the groq AI provider.

Why safe to merge

  • Utility is isolated to typescript-utils/nightly-nightly-cryptic-qr-cli.
  • README + tests ship together (see folder contents).
  • No secrets or credentials touched.
  • All changes are additive and self-contained.

Test Plan

  • Follow the instructions in the generated README at typescript-utils/nightly-nightly-cryptic-qr-cli/README.md
  • Run tests located in typescript-utils/nightly-nightly-cryptic-qr-cli/tests/

Links

  • Generated docs and examples committed alongside this change.

Mock Justification

  • Not applicable; generator did not introduce new mocks.

@polsala

polsala commented Sep 3, 2026

Copy link
Copy Markdown
Owner Author

🤖 Review by GROQ Agent

✅ What's solid

  • Pure algorithmgenerateAsciiQR is deterministic, side‑effect‑free, and easy to reason about.
  • Self‑contained – No external dependencies, making the utility lightweight and portable.
  • CLI entry point – The #!/usr/bin/env node shebang correctly routes execution when the compiled JavaScript is invoked.
  • Read‑from‑STDIN fallback – The script gracefully handles the case where no arguments are supplied.

🧪 Tests

  • Current approach uses a handcrafted “assert‑and‑exit” script. While it works, it bypasses the repository’s standard test runner (likely Jest/Mocha) and makes it harder to integrate with CI.

    • Actionable: Convert the test file to a proper test framework file, e.g.:

      // tests/generateAsciiQR.test.ts
      import { generateAsciiQR } from '../src/index';
      
      describe('generateAsciiQR', () => {
        it('renders a single character correctly', () => {
          const result = generateAsciiQR('A');
          const expected = [
            '  ██        ██', // 8 bits → 16 chars (2 per bit)
          ].join('\n');
          expect(result).toBe(expected);
        });
      
        it('renders two characters correctly', () => {
          const result = generateAsciiQR('AB');
          const expected = [
            '  ██        ██',
            '  ██      ██  ',
          ].join('\n');
          expect(result).toBe(expected);
        });
      });
  • Snapshot testing can protect against accidental visual changes:

    test('snapshot for "Hello"', () => {
      expect(generateAsciiQR('Hello')).toMatchSnapshot();
    });
  • Edge‑case coverage – add tests for:

    • Empty string ('') → should return ''.
    • Very long input (e.g., 10 k characters) – ensure the function does not blow up memory.
    • Non‑ASCII characters (e.g., Unicode emoji) – verify that charCodeAt handling is acceptable or document the limitation.
  • Normalization – the current normalize helper trims trailing spaces, which can mask bugs where the mapping of 0' ' is incorrect. Prefer comparing the raw output, or explicitly assert the exact number of spaces.

🔒 Security

  • Input handling – The CLI reads raw stdin and feeds it directly into generateAsciiQR. This is safe because the algorithm only inspects character codes, but consider:

    • Size limiting – Guard against extremely large payloads that could cause denial‑of‑service (e.g., if (data.length > 1e6) { … }).
    • Encoding – Ensure the process reads UTF‑8 (already set) and document that only the first 65535 code points are supported (due to charCodeAt returning a 16‑bit value).
  • Shebang in a TypeScript file – The shebang works only after compilation to JavaScript. If the repository ships raw .ts files, an attacker could replace the compiled output with malicious JS.

    • Actionable: Add a bin entry in package.json that points to the compiled dist/index.js and ship the compiled file (or use ts-node with an explicit entry script).

🧩 Docs / Developer Experience

  • README formatting – The current file is a single paragraph with escaped newlines. Improve readability:

    # nightly-cryptic-qr-cli
    
    A whimsical yet useful TypeScript CLI that turns any text into a deterministic ASCII‑art QR‑like code.
    
    ## Install
    
    ```bash
    git clone https://github.com/polsala/ApocalypsAI.git
    cd utils/typescript-utils/nightly-cryptic-qr-cli
    npm install
    npm run build   # if you ship compiled JS

    Usage

    # Direct argument
    npx nightly-cryptic-qr-cli "Hello, world!"
    
    # Pipe via STDIN
    echo "Hello" | npx nightly-cryptic-qr-cli

    Options

    • -h, --help – Show help.
    • -v, --version – Print version.

    How it works

    (keep the existing explanation)

    Testing

    npm test

    License

    MIT

    
    
  • CLI help flag – Users benefit from --help. Add a minimal help printer:

    if (args.includes('-h') || args.includes('--help')) {
      console.log(`Usage: nightly-cryptic-qr-cli [string]
    If no string is provided, reads from STDIN.`);
      process.exit(0);
    }
  • Package metadata – Ensure package.json includes:

    {
      "name": "nightly-cryptic-qr-cli",
      "version": "0.1.0",
      "bin": {
        "nightly-cryptic-qr-cli": "dist/index.js"
      },
      "scripts": {
        "build": "tsc",
        "test": "jest"
      },
      "license": "MIT"
    }
  • TypeScript build – The repository should have a tsconfig.json that outputs to dist/. Add a post‑install script or CI step that compiles before publishing.

🧱 Mocks / Fakes

  • No external services are used, so mocks are unnecessary.
  • The test file includes a comment about “Mock rationale” that is misleading; consider removing it or replacing it with a brief note that the function is pure and therefore does not require mocking.

Quick win checklist

  • Convert the ad‑hoc test script to a proper Jest/Mocha test file.
  • Add a --help flag and document it in the README.
  • Provide a package.json with bin, scripts, and license.
  • Refine the README formatting and include a usage example with the compiled binary.
  • Add edge‑case unit tests (empty string, large input, Unicode).
  • Consider a size guard for stdin to avoid DoS.

These changes will make the utility easier to maintain, safer to run in varied environments, and more consistent with the rest of the codebase.

@polsala

polsala commented Sep 3, 2026

Copy link
Copy Markdown
Owner Author

🤖 Review by GEMINI Agent

✅ What's solid

  • Deterministic Algorithm: The generateAsciiQR function is pure and deterministic, ensuring consistent output for identical inputs, which is a strong foundation for reliability.
  • Self-Contained Utility: The project has no external runtime dependencies, making it highly portable and reducing the complexity of installation and potential supply chain vulnerabilities.
  • Robust CLI Input Handling: The utility effectively handles input from both command-line arguments and STDIN, providing flexibility for various use cases, including piping data from other commands.
  • Clear Logic Explanation: The README.md provides a concise and understandable explanation of how the ASCII-art QR-like code is generated, aiding user comprehension.

🧪 Tests

  • Direct Function Testing: The test_index.ts directly imports and tests the generateAsciiQR function, which is effective for unit-level verification of the core logic.
  • Robust Comparison Helper: The normalize helper function is a practical addition that makes string comparisons more resilient to minor whitespace differences, improving test reliability.
  • Expand Test Coverage: Consider adding more comprehensive test cases to ensure robustness across various scenarios:
    • Empty String: Test the behavior with an empty input string.
    • Special Characters: Include inputs with non-ASCII characters or characters that might span multiple bytes to verify charCodeAt(0) behavior and potential limitations.
    • Long Strings: Test with very long strings to observe output formatting and potential performance implications.
    • Incomplete Last Row: Add a test case where the total binary length is not a multiple of bitsPerRow to ensure the last row is handled correctly.
  • Introduce a Test Runner: For enhanced test management and reporting, integrating a dedicated test runner (e.g., Jest, Vitest) would provide:
    • Structured test suites and individual test cases.
    • Clearer pass/fail reporting and detailed diffs on assertion failures.
    • Built-in assertion libraries (e.g., expect).
    • Example using Jest/Vitest:
      import { generateAsciiQR } from '../src/index';
      
      describe('generateAsciiQR', () => {
        const normalize = (str: string) => str.split('\n').map(line => line.trimEnd()).join('\n').trim();
      
        it('should generate correct QR for "A"', () => {
          const expectedA = '  ██        ██';
          expect(normalize(generateAsciiQR('A'))).toBe(normalize(expectedA));
        });
      
        it('should handle empty string', () => {
          expect(generateAsciiQR('')).toBe('');
        });
      });
  • CLI Integration Tests: Implement tests that execute the compiled CLI script directly, feeding it arguments and piped STDIN data, and then asserting its stdout output. This verifies the main function's logic and overall CLI behavior.

🔒 Security

  • Character Set Handling: The charCodeAt(0) method retrieves the UTF-16 code unit value. For characters outside the Basic Multilingual Plane (e.g., emojis, some ideograms), these are represented by surrogate pairs. charCodeAt(0) will only return the first part of the pair, leading to an incomplete or incorrect representation of the character.
    • Consider clarifying this limitation in the documentation or, if full Unicode support is desired, implementing a more robust character-to-binary conversion that handles surrogate pairs correctly (e.g., by iterating over code points rather than code units).
    • Example of current behavior for a surrogate pair:
      // For '😂' (U+1F602), '😂'.charCodeAt(0) returns 55357 (0xD83D).
      // This will be converted to binary, but it does not represent the full character.

🧩 Docs/DX

  • Installation Instructions Clarity: The README.md's installation instructions currently reference cloning the entire ApocalypsAI repository. For a standalone utility, consider providing instructions that are more generic or suggest how to install it as a global CLI tool if that's the intended use case.
    • If intended as a global CLI, a package.json with a bin entry would be required.

    • Example for README.md:

      ## Install
      
      ```bash
      # If part of a larger repository, navigate to this directory:
      cd path/to/typescript-utils/nightly-cryptic-qr-cli
      npm install
      # To install globally (requires package.json with "bin" entry):
      # npm install -g nightly-cryptic-qr-cli
  • TypeScript Configuration: While the source is TypeScript, there is no tsconfig.json or package.json to define the project's TypeScript configuration and build process. Adding these would significantly improve developer experience, enable proper compilation, and facilitate dependency management.
    • Example tsconfig.json:
      {
        "compilerOptions": {
          "target": "es2020",
          "module": "commonjs",
          "outDir": "./dist",
          "strict": true,
          "esModuleInterop": true,
          "skipLibCheck": true,
          "forceConsistentCasingInFileNames": true
        },
        "include": ["src/**/*.ts"],
        "exclude": ["node_modules", "dist"]
      }
    • Example package.json for a CLI:
      {
        "name": "nightly-cryptic-qr-cli",
        "version": "1.0.0",
        "description": "Generates a deterministic ASCII-art QR-like code for any input string.",
        "main": "dist/index.js",
        "bin": {
          "cryptic-qr": "dist/index.js"
        },
        "scripts": {
          "build": "tsc",
          "start": "node dist/index.js",
          "test": "node dist/tests/test_index.js"
        },
        "devDependencies": {
          "typescript": "^5.0.0",
          "@types/node": "^20.0.0"
        }
      }
  • Error Handling in CLI: The main function currently focuses on successful output. Consider adding more explicit error handling for potential runtime issues, such as unexpected input types if the script were run directly with node without prior TypeScript compilation and type checking.

🧱 Mocks/Fakes

  • Explicit Mock Rationale: The comment in test_index.ts correctly states that mocks are not needed due to the pure and deterministic nature of generateAsciiQR. This is excellent design.
    • Consider updating the "Mock Justification" section in the PR body to explicitly state this, e.g., "Not applicable; the core logic is a pure function, making direct testing straightforward without the need for mocks or fakes." This reinforces the good design choice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant