Skip to content

Dynamic style access (kleur[style]) fails silently when style is undefined #62

@fatkobra

Description

@fatkobra

Invalid style usage in kleur does not consistently result in runtime errors. I found that out after testing both direct and dynamic style access patterns. I observed that direct calls (example: kleur.reed()) throw generic JavaScript errors, dynamic access (example: kleur[style]) can fail silently when the style is undefined and guarded in user code.

When invalid styles do not surface any feedback this leads to silent loss of formatting and making bugs difficult to detect. Some of the current abstractions assume valid style input which is not always true.

The design ought to be updated to acknowledge that style resolution may fail, and introduce optional mechanisms (e.g., validation helpers or debug warnings) to improve developer feedback without breaking existing behavior.

I found that out using the following:

❯ node test.js
This should be red
Error caught: TypeError: kleur.reed is not a function
    at Object.<anonymous> (/homes/kleur-test/test.js:8:21)
    at Module._compile (node:internal/modules/cjs/loader:1761:14)
    at Object..js (node:internal/modules/cjs/loader:1893:10)
    at Module.load (node:internal/modules/cjs/loader:1481:32)
    at Module._load (node:internal/modules/cjs/loader:1300:12)
    at TracingChannel.traceSync (node:diagnostics_channel:328:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:245:24)
    at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:154:5)
    at node:internal/main/run_main_module:33:47
Error caught: TypeError: kleur.red(...).bold(...).notAStyle is not a function
    at Object.<anonymous> (/homes/kleur-test/test.js:15:34)
    at Module._compile (node:internal/modules/cjs/loader:1761:14)
    at Object..js (node:internal/modules/cjs/loader:1893:10)
    at Module.load (node:internal/modules/cjs/loader:1481:32)
    at Module._load (node:internal/modules/cjs/loader:1300:12)
    at TracingChannel.traceSync (node:diagnostics_channel:328:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:245:24)
    at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:154:5)
    at node:internal/main/run_main_module:33:47
❯
❯ node -e "
const k = require('kleur');
const style = 'reed'; // imagine user input
if (k[style]) {
  console.log(k[style]('Hello'));
} else {
  console.log('No style applied');
}
"
No style applied
```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions