{"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,"search_vec":"'4.0.1':15 'abstract':34 'also':78 'analysi':69 'analyz':47 'ast':37,114 'babel':43 'babylon':39 'build':65 'caus':75 'conserv':54 'constant':2,27,72,89,98,113 'constantinopl':1,5 'could':74 'current':11 'definit':105 'design':16 'detect':73 'determin':18 'develop':107 'enhanc':106 'ensur':62 'error':92 'evalu':4,24,85 'experi':108 'express':3,23,31,86,95 'fals':56 'function':82 'given':21 'identifi':87 'incorrect':71 'issu':76 'javascript':8,22,112 'librari':51 'packag':10,100 'pars':29 'parser':45 'part':41 'predict':49 'priorit':52 'provid':79 'reliabl':63 'return':55 'safe':84 'safeti':53 'ship':101 'stabl':13 'static':68 'syntax':35 'throw':90 'toconst':81 'tool':66,115 'tree':36 'type':104 'typescript':103,110,116 'uncertainti':61 'use':38 'user':111 'util':9 'version':14","created_at":"2026-04-19T13:33:58.986500+00:00","updated_at":"2026-04-19T13:33:58.986500+00:00","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","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/ForbesLindesay/constantinople","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/constantinople","openapi_spec":null,"status_page":null,"smithery":null,"categories":["serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}