API Elements JavaScript Library

raw JSON →
0.3.2 verified Sun Apr 19 auth: no javascript

The `api-elements` package provides a JavaScript interface for working with API Elements, an abstract syntax tree (AST) for describing APIs. It acts as a core component within the larger API Elements ecosystem, enabling programmatic creation, manipulation, and serialization of API descriptions using a unified model, regardless of the original format (like OpenAPI or API Blueprint). The current stable version of this specific package is 0.3.2, though its sub-packages, like `@apielements/openapi3-parser` and `@apielements/openapi2-parser`, are more actively developed with frequent minor and patch releases, incorporating new OpenAPI specification features and bug fixes. This library differentiates itself by offering a language-agnostic, structured representation of API definitions, allowing for advanced tooling and transformations beyond simple parsing.

error TypeError: Cannot read properties of undefined (reading 'copy')
cause Attempting to access properties like `parseResult.api.copy` when `parseResult.api` is `null` or `undefined`, usually because the parsed API description lacks a main API category or a copy element within it.
fix
Always check for the existence of intermediate elements (e.g., if (parseResult.api && parseResult.api.copy)) before attempting to access their properties, especially when dealing with potentially incomplete or malformed API descriptions.
error Error: Not a Refract element: <value>
cause This error typically occurs when a function expecting an API Element (part of the Refract AST) receives a plain JavaScript object or a primitive value instead.
fix
Ensure that any arguments passed to API Elements functions or methods are instances of namespace.elements.SomeElement or other valid Refract elements. Convert plain data structures into appropriate minim or api-elements element types before use.
error JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
cause When deserializing API Elements from a JSON string, this error indicates that the input JSON is malformed or empty, preventing the serializer from correctly processing it.
fix
Verify that the JSON string passed to namespace.serialiser.deserialise is valid, complete, and represents a proper API Elements structure. Use a JSON linter or validator to check the input.
gotcha The `api-elements` package itself has a relatively low version (0.3.x) which can imply a less stable API compared to 1.0+ packages. While its underlying parsers are more active, direct usage of `api-elements` might involve more frequent adjustments.
fix Refer to the `api-elements.js` GitHub repository for the latest API documentation and examples. Consider pinning to exact patch versions if stability is critical.
breaking When consuming `Host URI metadata` from `openapi2-parser`, the default scheme changed from potentially undefined to `https` if `schemes` is not explicitly defined in the OpenAPI 2.0 specification. This might affect applications relying on an `http` default or a partial URI.
fix Ensure your OpenAPI 2.0 definitions explicitly define the `schemes` property (e.g., `schemes: ["http"]` or `schemes: ["https"]`) to control the generated host URI, or update your application logic to expect `https` by default for missing schemes.
gotcha Handling references to JSON paths that prefix the current path (e.g., `$ref: '#/definitions/User'` from a path inside `UserList`) was buggy in `openapi2-parser` when generating example JSON bodies. This could lead to incorrect or incomplete examples.
fix Upgrade to `@apielements/openapi2-parser@0.32.6` or newer to ensure correct generation of example JSON bodies from Swagger/OpenAPI 2.0 schemas with complex internal references.
gotcha Support for OpenAPI 3.1 features in `@apielements/openapi3-parser` is progressive. While basic `const` and array `type` support for 'Schema Object' is present, not all OpenAPI 3.1 features and fields are fully supported and may emit warnings.
fix Be aware of emitted 'unsupported warnings' when parsing OpenAPI 3.1 definitions. Test your specific 3.1 features with the parser and check its release notes for ongoing support and limitations. Provide feedback to the maintainers for missing features.
deprecated Older versions of `api-elements` might have unexpected behavior when generating values from elements, especially for objects with only undefined property values, or when handling headers without explicit values. These have been addressed in recent patches.
fix Update the `api-elements` package to at least `0.3.1` to benefit from fixes in value generation logic, and ensure `apib-serializer` is at `0.16.3` or newer for correct header handling.
npm install api-elements
yarn add api-elements
pnpm add api-elements

This quickstart demonstrates how to initialize the API Elements namespace and create or deserialize API Element ASTs. It shows both parsing a JSON representation and constructing elements programmatically, then accessing properties like the API title.

const apiElements = require('api-elements');
const namespace = new apiElements.Namespace();

// Parsing a JSON Representation of an API Elements tree
const parseResult = namespace.serialiser.deserialise({
  element: 'parseResult',
  content: [
    {
      element: 'category',
      meta: { classes: ['api'] },
      content: [
        { element: 'copy', content: 'My Awesome API' },
        { element: 'resource', content: [] }
      ]
    }
  ]
});

console.log('Deserialized ParseResult element:', parseResult.element);
console.log('API title:', parseResult.api.copy.toValue());

// Creating API Elements directly
const directParseResult = new namespace.elements.ParseResult();
const apiCategory = new namespace.elements.Category();
apiCategory.classes.push('api');
apiCategory.content.push(new namespace.elements.Copy('Another API'));
directParseResult.content.push(apiCategory);

console.log('Directly created ParseResult element:', directParseResult.element);
console.log('Another API title:', directParseResult.api.copy.toValue());