{"id":10664,"library":"constantinople","title":"Constantinople Constant Expression Evaluator","description":"Constantinople is a JavaScript utility package, currently at stable version 4.0.1, designed to determine if a given JavaScript expression evaluates to a constant. It parses the expression into an Abstract Syntax Tree (AST) using Babylon (now part of Babel's parser) to analyze its predictability. The library prioritizes safety, conservatively returning `false` if there's any uncertainty, ensuring reliability for build tools and static analysis where incorrect constant detection could cause issues. It also provides a `toConstant` function to safely evaluate expressions identified as constant, throwing an error if the expression is not constant. The package ships with TypeScript type definitions, enhancing developer experience for TypeScript users.","status":"active","version":"4.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/ForbesLindesay/constantinople","tags":["javascript","constant","ast","tooling","typescript"],"install":[{"cmd":"npm install constantinople","lang":"bash","label":"npm"},{"cmd":"yarn add constantinople","lang":"bash","label":"yarn"},{"cmd":"pnpm add constantinople","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary function `isConstant` is the default export of the package for ESM usage.","wrong":"import { isConstant } from 'constantinople';","symbol":"isConstant","correct":"import isConstant from 'constantinople';"},{"note":"For CommonJS environments, `isConstant` is the default export, meaning the entire module exports the function directly.","wrong":"const { isConstant } = require('constantinople');","symbol":"isConstant (CJS)","correct":"const isConstant = require('constantinople');"},{"note":"`toConstant` is a named property of the default `isConstant` export, not a top-level named export. Access it via the default imported `isConstant` object.","wrong":"import { toConstant } from 'constantinople';","symbol":"toConstant","correct":"import isConstant from 'constantinople';\nconst result = isConstant.toConstant('some_expression');"}],"quickstart":{"code":"import isConstant from 'constantinople';\n\nconst expression1 = '\"foo\" + 5';\nconst expression2 = 'Math.floor(10.5)';\nconst expression3 = 'Date.now()'; // Example of a non-constant\n\n// Check and evaluate a simple constant string concatenation\nif (isConstant(expression1)) {\n  console.log(`'${expression1}' is constant.`);\n  try {\n    const result = isConstant.toConstant(expression1);\n    console.log(`Value: ${result}`); // Expected: \"foo5\"\n  } catch (error: any) {\n    console.error(`Error evaluating '${expression1}':`, error.message);\n  }\n} else {\n  console.log(`'${expression1}' is not constant.`);\n}\n\nconsole.log('---\\n');\n\n// Check and evaluate with provided constants (e.g., Math object)\n// WARNING: Providing global objects like Math might lead to unexpected behavior if they contain non-constant functions like Math.random\nif (isConstant(expression2, { Math: Math })) {\n  console.log(`'${expression2}' is constant with Math context.`);\n  try {\n    const result = isConstant.toConstant(expression2, { Math: Math });\n    console.log(`Value: ${result}`); // Expected: 10\n  } catch (error: any) {\n    console.error(`Error evaluating '${expression2}':`, error.message);\n  }\n} else {\n  console.log(`'${expression2}' is not constant with Math context.`);\n}\n\nconsole.log('---\\n');\n\n// Demonstrate a non-constant expression\nif (isConstant(expression3)) {\n  console.log(`'${expression3}' is constant.`);\n} else {\n  console.log(`'${expression3}' is not constant.`);\n  try {\n    isConstant.toConstant(expression3); // This will throw an error\n  } catch (error: any) {\n    console.error(`Attempting to evaluate non-constant '${expression3}' throws: ${error.message}`);\n  }\n}","lang":"typescript","description":"This quickstart demonstrates how to use `isConstant` to check if an expression is constant and `toConstant` to evaluate its value, including handling non-constant expressions and custom constant contexts."},"warnings":[{"fix":"Carefully curate the `constants` object, ensuring it only contains truly static values or functions without side effects. Avoid passing global objects that include non-constant methods if the expression might call them.","message":"Providing volatile objects like `Math` or `Date` to the optional `constants` parameter can lead to incorrect `isConstant` evaluations or unexpected `toConstant` results if methods like `Math.random()` or `Date.now()` are present in the expression. The library aims to safely *underestimate* constancy, but user-provided contexts can unintentionally override this safety.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Always wrap calls to `isConstant.toConstant()` in a `try...catch` block, or, preferably, ensure you call `isConstant()` first and only invoke `toConstant()` if `isConstant()` returns `true`.","message":"The `toConstant` function will throw an error if the provided expression is determined not to be constant. This behavior is by design, ensuring that only truly constant expressions are evaluated to a direct value.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"If differentiating between non-constant and syntax errors is crucial, consider pre-validating syntax with a linter or a dedicated parser, or rely on `toConstant`'s error throwing behavior for invalid syntax when precise error types are needed.","message":"The `isConstant` function returns `false` for expressions with syntax errors rather than throwing an exception. While safe, this means a `false` return could indicate either a non-constant expression or a malformed one. `toConstant` *will* throw on syntax errors when attempting to parse and evaluate.","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `isConstant()` returns `true` for an expression before calling `isConstant.toConstant()`, or wrap `isConstant.toConstant()` calls in a `try...catch` block to handle this expected error.","cause":"You attempted to call `isConstant.toConstant()` on an expression that the library determined was not constant.","error":"Expression is not constant"},{"fix":"Review and correct the syntax of the input expression string. `isConstant()` will return `false` for syntax errors, while `isConstant.toConstant()` will throw a `SyntaxError`.","cause":"The input string provided to `isConstant` or `isConstant.toConstant` contained a JavaScript syntax error, preventing successful parsing.","error":"SyntaxError: Unexpected token ..."},{"fix":"Import `isConstant` as a default export (`import isConstant from 'constantinople';`) and access `toConstant` as a property of the imported object (`isConstant.toConstant`). For CommonJS, use `const isConstant = require('constantinople');`.","cause":"You attempted to import `isConstant` as a named export (`{ isConstant }`) or `toConstant` as a top-level named export. However, `isConstant` is the default export and `toConstant` is a property of that default export.","error":"TypeError: isConstant_1.toConstant is not a function"}],"ecosystem":"npm"}