diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 00000000..bcd409ce --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,77 @@ +# Copilot Instructions for React Native Node-API + +This is a **monorepo** that brings Node-API support to React Native, enabling native addons written in C/C++/Rust to run on React Native across iOS and Android. + +## Package-Specific Instructions + +**IMPORTANT**: Before working on any package, always check for and read package-specific `copilot-instructions.md` files in the package directory. These contain critical preferences and patterns for that specific package. + +## Architecture Overview + +**Core Flow**: JS `require("./addon.node")` → Babel transform → `requireNodeAddon()` TurboModule call → native library loading → Node-API module initialization + +### Package Architecture + +See the [README.md](../README.md#packages) for detailed descriptions of each package and their roles in the system. Key packages include: + +- `packages/host` - Core Node-API runtime and Babel plugin +- `packages/cmake-rn` - CMake wrapper for native builds +- `packages/cmake-file-api` - TypeScript wrapper for CMake File API with Zod validation +- `packages/ferric` - Rust/Cargo wrapper with napi-rs integration +- `packages/gyp-to-cmake` - Legacy binding.gyp compatibility +- `apps/test-app` - Integration testing harness + +## Critical Build Dependencies + +- **Custom Hermes**: Currently depends on a patched Hermes with Node-API support (see [facebook/hermes#1377](https://github.com/facebook/hermes/pull/1377)) +- **Prebuilt Binary Spec**: All tools must output to the exact naming scheme: + - Android: `*.android.node/` with jniLibs structure + `react-native-node-api-module` marker file + - iOS: `*.apple.node` (XCFramework renamed) + marker file + +## Essential Workflows + +### Development Setup + +```bash +npm ci && npm run build # Install deps and build all packages +npm run bootstrap # Build native components (weak-node-api, examples) +``` + +### Package Development + +- **TypeScript project references**: Use `tsc --build` for incremental compilation +- **Workspace scripts**: Most build/test commands use npm workspaces (`--workspace` flag) +- **Focus on Node.js packages**: AI development primarily targets the Node.js tooling packages rather than native mobile code +- **No TypeScript type asserts**: You have to ask explicitly and justify if you want to add `as` type assertions. + +## Key Patterns + +### Babel Transformation + +The core magic happens in `packages/host/src/node/babel-plugin/plugin.ts`: + +```js +// Input: require("./addon.node") +// Output: require("react-native-node-api").requireNodeAddon("pkg-name--addon") +``` + +### CMake Integration + +For linking against Node-API in CMakeLists.txt: + +```cmake +include(${WEAK_NODE_API_CONFIG}) +target_link_libraries(addon PRIVATE weak-node-api) +``` + +### Cross-Platform Naming + +Library names use double-dash separation: `package-name--path-component--addon-name` + +### Testing + +- **Individual packages**: Some packages have VS Code test tasks and others have their own `npm test` scripts for focused iteration (e.g., `npm test --workspace cmake-rn`). Use the latter only if the former is missing. +- **Cross-package**: Use root-level `npm test` for cross-package testing once individual package tests pass +- **Mobile integration**: Available but not the primary AI development focus - ask the developer to run those tests as needed + +**Documentation**: Integration details, platform setup, and toolchain configuration are covered in existing repo documentation files. diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 00000000..f0c624e1 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,14 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Test cmake-file-api", + "command": "node", + "args": ["--run", "test"], + "options": { + "cwd": "${workspaceFolder}/packages/cmake-file-api" + }, + "group": "test" + } + ] +} diff --git a/configs/tsconfig.node-tests.json b/configs/tsconfig.node-tests.json new file mode 100644 index 00000000..642ba5ac --- /dev/null +++ b/configs/tsconfig.node-tests.json @@ -0,0 +1,17 @@ +{ + "extends": "./tsconfig.node.json", + "compilerOptions": { + "composite": true, + "emitDeclarationOnly": true, + "declarationMap": false + }, + "include": ["${configDir}/src/**/*.test.ts"], + "exclude": [] + /* + "references": [ + { + "path": "./tsconfig.json" + } + ] + */ +} diff --git a/configs/tsconfig.cli.json b/configs/tsconfig.node.json similarity index 73% rename from configs/tsconfig.cli.json rename to configs/tsconfig.node.json index 4e77cced..ff37e16c 100644 --- a/configs/tsconfig.cli.json +++ b/configs/tsconfig.node.json @@ -7,6 +7,6 @@ "rootDir": "${configDir}/src", "types": ["node"] }, - "include": ["${configDir}/src/*.ts"], - "exclude": ["${configDir}/**.test.ts"] + "include": ["${configDir}/src/"], + "exclude": ["${configDir}/**/*.test.ts"] } diff --git a/package-lock.json b/package-lock.json index 96a644fc..02024acc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,15 +7,16 @@ "name": "@react-native-node-api/root", "license": "MIT", "workspaces": [ - "apps/test-app", "packages/cli-utils", - "packages/gyp-to-cmake", + "packages/cmake-file-api", "packages/cmake-rn", "packages/ferric", + "packages/gyp-to-cmake", "packages/host", "packages/node-addon-examples", "packages/node-tests", - "packages/ferric-example" + "packages/ferric-example", + "apps/test-app" ], "devDependencies": { "@changesets/cli": "^2.29.5", @@ -7909,6 +7910,10 @@ "node": ">=0.8" } }, + "node_modules/cmake-file-api": { + "resolved": "packages/cmake-file-api", + "link": true + }, "node_modules/cmake-js": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/cmake-js/-/cmake-js-7.3.1.tgz", @@ -14784,11 +14789,26 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "packages/cmake-file-api": { + "version": "0.1.0", + "dependencies": { + "zod": "^4.1.11" + } + }, + "packages/cmake-file-api/node_modules/zod": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.11.tgz", + "integrity": "sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "packages/cmake-rn": { - "version": "0.3.2", + "version": "0.4.0", "dependencies": { "@react-native-node-api/cli-utils": "0.1.0", - "react-native-node-api": "0.5.0" + "react-native-node-api": "0.5.1" }, "bin": { "cmake-rn": "bin/cmake-rn.js" @@ -14800,11 +14820,11 @@ }, "packages/ferric": { "name": "ferric-cli", - "version": "0.3.2", + "version": "0.3.3", "dependencies": { "@napi-rs/cli": "~3.0.3", "@react-native-node-api/cli-utils": "0.1.0", - "react-native-node-api": "0.5.0" + "react-native-node-api": "0.5.1" }, "bin": { "ferric": "bin/ferric.js" @@ -14818,7 +14838,7 @@ } }, "packages/gyp-to-cmake": { - "version": "0.2.0", + "version": "0.3.0", "dependencies": { "@react-native-node-api/cli-utils": "0.1.0", "gyp-parser": "^1.0.4" @@ -14829,7 +14849,7 @@ }, "packages/host": { "name": "react-native-node-api", - "version": "0.5.0", + "version": "0.5.1", "license": "MIT", "dependencies": { "@react-native-node-api/cli-utils": "0.1.0", @@ -14869,7 +14889,7 @@ "cmake-rn": "*", "gyp-to-cmake": "*", "prebuildify": "^6.0.1", - "react-native-node-api": "^0.5.0", + "react-native-node-api": "^0.5.1", "read-pkg": "^9.0.1", "rolldown": "1.0.0-beta.29" } diff --git a/package.json b/package.json index c20b5813..699dbe3f 100644 --- a/package.json +++ b/package.json @@ -4,15 +4,16 @@ "type": "module", "private": true, "workspaces": [ - "apps/test-app", "packages/cli-utils", - "packages/gyp-to-cmake", + "packages/cmake-file-api", "packages/cmake-rn", "packages/ferric", + "packages/gyp-to-cmake", "packages/host", "packages/node-addon-examples", "packages/node-tests", - "packages/ferric-example" + "packages/ferric-example", + "apps/test-app" ], "homepage": "https://github.com/callstackincubator/react-native-node-api#readme", "scripts": { diff --git a/packages/cli-utils/tsconfig.json b/packages/cli-utils/tsconfig.json index aa43e9d9..f183b9a9 100644 --- a/packages/cli-utils/tsconfig.json +++ b/packages/cli-utils/tsconfig.json @@ -1,3 +1,3 @@ { - "extends": "../../configs/tsconfig.cli.json" + "extends": "../../configs/tsconfig.node.json" } diff --git a/packages/cmake-file-api/README.md b/packages/cmake-file-api/README.md new file mode 100644 index 00000000..50dce7ea --- /dev/null +++ b/packages/cmake-file-api/README.md @@ -0,0 +1,7 @@ +# CMake File API (unofficial) + +The CMake File API provides an interface for querying CMake's configuration and project information. + +The API is based on files, where queries are written by client tools and read by CMake and replies are then written by CMake and read by client tools. The API is versioned, and the current version is v1 and these files are located in a directory named `.cmake/api/v1` in the build directory. + +This package provides a TypeScript interface to create query files and read replies and is intended to serve the same purpose to the TypeScript community that the [`cmake-file-api` crate](https://crates.io/crates/cmake-file-api), serves to the Rust community. diff --git a/packages/cmake-file-api/copilot-instructions.md b/packages/cmake-file-api/copilot-instructions.md new file mode 100644 index 00000000..c6def984 --- /dev/null +++ b/packages/cmake-file-api/copilot-instructions.md @@ -0,0 +1,259 @@ +# Copilot Instructions for cmake-file-api Package + +This package provides a TypeScript wrapper around the CMake File API using Zod schemas for validation. + +## Code Style Preferences + +### Node.js Built-ins + +- **Always** use Node.js built-ins with the `node:` prefix (e.g., `node:fs`, `node:path`, `node:assert/strict`) +- Prefer async APIs where possible (e.g., `fs.promises.readFile`, `fs.promises.writeFile`) + +### Schema Validation + +- Use **Zod** for all schema validation with strict typing +- Follow the CMake File API v1 specification precisely - read the documentation in `docs/cmake-file-api.7.rst.txt` +- Use `z.enum()` instead of generic strings for known enumeration values +- Make record values optional when they might not exist (e.g., `z.record(key, value.optional())`) +- **Keep schema files clean** - avoid inline comments except when strictly necessary for clarity +- **Use `index = z.number().int().min(0)`** for all *Index and *Indexes fields (they are documented as "unsigned integer 0-based index" in the CMake File API) + +### TypeScript Patterns + +- **No TypeScript type assertions (`as`)** unless explicitly justified +- Use destructuring to extract values from objects instead of accessing object properties repeatedly +- Prefer explicit assertions with meaningful messages over implicit type assumptions + +### Testing + +- Use Node.js built-in test runner and run test using the "Test cmake-file-api" task in VS Code +- **Prefer `assert.deepStrictEqual(result, mockData)`** over individual field assertions for schema validation +- Create comprehensive test cases that validate the complete schema structure +- Use proper type guards with assertions when dealing with optional values +- Test both positive cases (valid data) and ensure schemas properly validate structure + +### Error Handling + +- Use `assert` from `node:assert/strict` for runtime validation +- Provide descriptive error messages that help with debugging +- Handle CMake File API error objects properly (they have an `error` field instead of the expected structure) + +## Architecture Patterns + +### Schema Organization + +- Export schemas with versioned names (e.g., `ReplyFileReferenceV1`, `IndexReplyV1`) +- Organize related schemas in dedicated files under `src/schemas/` +- Keep the main API functions in `src/reply.ts` and `src/query.ts` + +### Minor Version Schema Pattern + +When implementing schemas that support multiple minor versions (as documented in CMake File API), use this hierarchical extension pattern: + +1. **Base Version Schema**: Create the earliest version as the base (e.g., `DirectoryV2_0`) +2. **Extended Version Schemas**: Use `.extend()` to add new fields for later versions (e.g., `DirectoryV2_3 = DirectoryV2_0.extend({...})`) +3. **Hierarchical Composition**: Parent schemas should also follow this pattern (e.g., `ConfigurationV2_3 = ConfigurationV2_0.extend({...})`) +4. **Version Constraints**: Use `minor: z.number().max(X)` for earlier versions and `minor: z.number().min(X)` for later versions +5. **Union Export**: Combine all versions using `z.union([SchemaV2_0, SchemaV2_3])` and export as the main schema name + +This pattern ensures: + +- Type safety across different minor versions +- Proper validation based on version numbers +- Clear inheritance hierarchy +- Backward compatibility support + +### Context-Dependent Object Versioning + +For objects that don't contain version information themselves (like Target objects), use the versioned extension pattern and export a union of all versions. Keep it DRY by versioning nested schemas separately: + +```typescript +// Version nested schemas separately to avoid duplication +const SourceV2_0 = z.object({ + path: z.string(), + // ... base fields +}); + +const SourceV2_5 = SourceV2_0.extend({ + fileSetIndex: index.optional(), // Added in v2.5 +}); + +const CompileGroupV2_0 = z.object({ + sourceIndexes: z.array(index), + language: z.string(), + // ... base fields +}); + +const CompileGroupV2_1 = CompileGroupV2_0.extend({ + precompileHeaders: z.array(PrecompileHeader).optional(), // Added in v2.1 +}); + +// Build main object versions using versioned nested schemas +const TargetV2_0 = z.object({ + // ... base fields + sources: z.array(SourceV2_0).optional(), + compileGroups: z.array(CompileGroupV2_0).optional(), +}); + +const TargetV2_1 = TargetV2_0.extend({ + compileGroups: z.array(CompileGroupV2_1).optional(), // Use versioned nested schema +}); + +const TargetV2_5 = TargetV2_2.extend({ + fileSets: z.array(FileSet).optional(), + sources: z.array(SourceV2_5).optional(), // Use versioned nested schema +}); + +// Export union of all versions for flexible validation +export const TargetV2 = z.union([ + TargetV2_0, + TargetV2_1, + TargetV2_2, + TargetV2_5, + TargetV2_6, + TargetV2_7, + TargetV2_8, +]); + +// Also export individual versions for specific use cases +export { + TargetV2_0, + TargetV2_1, + TargetV2_2, + TargetV2_5, + TargetV2_6, + TargetV2_7, + TargetV2_8, +}; +``` + +Then, reader functions should accept an optional schema parameter defaulting to the latest version: + +```typescript +export async function readTarget( + filePath: string, + schema: z.ZodSchema = TargetV2_8, // Default to latest version +) { + // ... implementation +} +``` + +This approach provides flexibility while maintaining type safety, avoiding code duplication, and allowing callers to specify the exact version schema when needed. + +### Function Design + +- Functions should be async where file I/O is involved +- Use clear, descriptive function names that indicate their purpose +- Validate file paths and extensions before processing +- Parse and validate JSON using Zod schemas rather than manual type checking + +### Documentation References + +- Always refer to the official CMake File API documentation +- The specification is available in `docs/cmake-file-api.7.rst.txt` +- When implementing Object Kinds, check the docs for exact field requirements and optional properties. Pay attention to indention in the document as it indicates nested structures. + +## Example Patterns + +### Good Schema Pattern + +```typescript +const index = z.number().int().min(0); + +export const MySchemaV1 = z.object({ + kind: z.enum(["validValue1", "validValue2"]), + optionalField: z.string().optional(), + parentIndex: index.optional(), // For *Index fields + childIndexes: z.array(index).optional(), // For *Indexes fields + requiredNested: z.object({ + major: z.number(), + minor: z.number(), + }), +}); +``` + +### Good Minor Version Schema Pattern + +```typescript +// Base version schema (earliest version) +const ItemV2_0 = z.object({ + name: z.string(), + type: z.enum(["TYPE1", "TYPE2"]), + paths: z.object({ + source: z.string(), + build: z.string(), + }), +}); + +// Extended version schema (adds fields introduced in v2.3) +const ItemV2_3 = ItemV2_0.extend({ + jsonFile: z.string(), + metadata: z + .object({ + version: z.string(), + }) + .optional(), +}); + +// Parent schema versions +const ContainerV2_0 = z.object({ + kind: z.literal("container"), + version: z.object({ + major: z.literal(2), + minor: z.number().max(2), // Versions 2.0-2.2 + }), + items: z.array(ItemV2_0), +}); + +const ContainerV2_3 = ContainerV2_0.extend({ + version: z.object({ + major: z.literal(2), + minor: z.number().min(3), // Versions 2.3+ + }), + items: z.array(ItemV2_3), +}); + +// Union export for all versions +export const ContainerV2 = z.union([ContainerV2_0, ContainerV2_3]); +``` + +### Good Function Pattern + +```typescript +export async function readSomething(filePath: string) { + assert( + path.basename(filePath).startsWith("expected-") && + path.extname(filePath) === ".json", + "Expected a path to an expected-*.json file", + ); + const content = await fs.promises.readFile(filePath, "utf-8"); + const { field1, field2 } = MySchemaV1.parse(JSON.parse(content)); + // Use destructured values directly + return { field1, field2 }; +} +``` + +### Good Test Pattern + +```typescript +it("validates complete structure", async function (context) { + const mockData = { + // Complete, realistic test data based on CMake File API docs + field1: "expectedValue", + field2: { nested: "structure" }, + optionalField: "presentValue", + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["example-file.json", mockData], + ]); + const result = await readSomething(path.join(tmpPath, "example-file.json")); + + // Prefer deepStrictEqual for complete schema validation + assert.deepStrictEqual(result, mockData); + + // Only use individual assertions when testing specific edge cases + // const optionalValue = result.optionalField; + // assert(optionalValue, "Expected optional field to exist in this test case"); +}); +``` diff --git a/packages/cmake-file-api/docs/cmake-file-api.7.rst.txt b/packages/cmake-file-api/docs/cmake-file-api.7.rst.txt new file mode 100644 index 00000000..4211c572 --- /dev/null +++ b/packages/cmake-file-api/docs/cmake-file-api.7.rst.txt @@ -0,0 +1,1864 @@ +The following is a snapshot of https://cmake.org/cmake/help/latest/manual/cmake-file-api.7.html + +.. cmake-manual-description: CMake File-Based API + +cmake-file-api(7) +***************** + +.. only:: html + + .. contents:: + +Introduction +============ + +CMake provides a file-based API that clients may use to get semantic +information about the buildsystems CMake generates. Clients may use +the API by writing query files to a specific location in a build tree +to request zero or more `Object Kinds`_. When CMake generates the +buildsystem in that build tree it will read the query files and write +reply files for the client to read. + +The file-based API uses a ``/.cmake/api/`` directory at the top +of a build tree. The API is versioned to support changes to the layout +of files within the API directory. API file layout versioning is +orthogonal to the versioning of `Object Kinds`_ used in replies. +This version of CMake supports only one API version, `API v1`_. + +.. versionadded:: 3.27 + Projects may also submit queries for the current run using the + :command:`cmake_file_api` command. + +.. _`file-api v1`: + +API v1 +====== + +API v1 is housed in the ``/.cmake/api/v1/`` directory. +It has the following subdirectories: + +``query/`` + Holds query files written by clients. + These may be `v1 Shared Stateless Query Files`_, + `v1 Client Stateless Query Files`_, or `v1 Client Stateful Query Files`_. + +``reply/`` + Holds reply files written by CMake when it runs to generate a build system. + Clients may read reply files only when referenced by a reply index: + + ``index-*.json`` + A `v1 Reply Index File`_ written when CMake generates a build system. + + ``error-*.json`` + .. versionadded:: 4.1 + + A `v1 Reply Error Index`_ written when CMake fails to generate a build + system due to an error. + + Clients may look for and read a reply index at any time. + Clients may optionally create the ``reply/`` directory at any time + and monitor it for the appearance of a new reply index. + CMake owns all reply files. Clients must never remove them. + +.. versionadded:: 3.31 + Users can add query files to ``api/v1/query`` inside the + :envvar:`CMAKE_CONFIG_DIR` to create user-wide queries for all CMake projects. + +v1 Shared Stateless Query Files +------------------------------- + +Shared stateless query files allow clients to share requests for +major versions of the `Object Kinds`_ and get all requested versions +recognized by the CMake that runs. + +Clients may create shared requests by creating empty files in the +``v1/query/`` directory. The form is:: + + /.cmake/api/v1/query/-v + +where ```` is one of the `Object Kinds`_, ``-v`` is literal, +and ```` is the major version number. + +Files of this form are stateless shared queries not owned by any specific +client. Once created they should not be removed without external client +coordination or human intervention. + +v1 Client Stateless Query Files +------------------------------- + +Client stateless query files allow clients to create owned requests for +major versions of the `Object Kinds`_ and get all requested versions +recognized by the CMake that runs. + +Clients may create owned requests by creating empty files in +client-specific query subdirectories. The form is:: + + /.cmake/api/v1/query/client-/-v + +where ``client-`` is literal, ```` is a string uniquely +identifying the client, ```` is one of the `Object Kinds`_, +``-v`` is literal, and ```` is the major version number. +Each client must choose a unique ```` identifier via its +own means. + +Files of this form are stateless queries owned by the client ````. +The owning client may remove them at any time. + +v1 Client Stateful Query Files +------------------------------ + +Stateful query files allow clients to request a list of versions of +each of the `Object Kinds`_ and get only the most recent version +recognized by the CMake that runs. + +Clients may create owned stateful queries by creating ``query.json`` +files in client-specific query subdirectories. The form is:: + + /.cmake/api/v1/query/client-/query.json + +where ``client-`` is literal, ```` is a string uniquely +identifying the client, and ``query.json`` is literal. Each client +must choose a unique ```` identifier via its own means. + +``query.json`` files are stateful queries owned by the client ````. +The owning client may update or remove them at any time. When a +given client installation is updated it may then update the stateful +query it writes to build trees to request newer object versions. +This can be used to avoid asking CMake to generate multiple object +versions unnecessarily. + +A ``query.json`` file must contain a JSON object: + +.. code-block:: json + + { + "requests": [ + { "kind": "" , "version": 1 }, + { "kind": "" , "version": { "major": 1, "minor": 2 } }, + { "kind": "" , "version": [2, 1] }, + { "kind": "" , "version": [2, { "major": 1, "minor": 2 }] }, + { "kind": "" , "version": 1, "client": {} }, + { "kind": "..." } + ], + "client": {} + } + +The members are: + +``requests`` + A JSON array containing zero or more requests. Each request is + a JSON object with members: + + ``kind`` + Specifies one of the `Object Kinds`_ to be included in the reply. + + ``version`` + Indicates the version(s) of the object kind that the client + understands. Versions have major and minor components following + semantic version conventions. The value must be + + * a JSON integer specifying a (non-negative) major version number, or + * a JSON object containing ``major`` and (optionally) ``minor`` + members specifying non-negative integer version components, or + * a JSON array whose elements are each one of the above. + + ``client`` + Optional member reserved for use by the client. This value is + preserved in the reply written for the client in the + `v1 Reply Index File`_ but is otherwise ignored. Clients may use + this to pass custom information with a request through to its reply. + + For each requested object kind CMake will choose the *first* version + that it recognizes for that kind among those listed in the request. + The response will use the selected *major* version with the highest + *minor* version known to the running CMake for that major version. + Therefore clients should list all supported major versions in + preferred order along with the minimal minor version required + for each major version. + +``client`` + Optional member reserved for use by the client. This value is + preserved in the reply written for the client in the + `v1 Reply Index File`_ but is otherwise ignored. Clients may use + this to pass custom information with a query through to its reply. + +Other ``query.json`` top-level members are reserved for future use. +If present they are ignored for forward compatibility. + +v1 Reply Index File +------------------- + +CMake writes an ``index-*.json`` file to the ``v1/reply/`` directory +when it successfully generates a build system. Clients must read the +reply index file first and may read other `v1 Reply Files`_ only by +following references. The form of the reply index file name is:: + + /.cmake/api/v1/reply/index-.json + +where ``index-`` is literal and ```` is an unspecified +name selected by CMake. Whenever a new index file is generated it +is given a new name and any old one is deleted. During the short +time between these steps there may be multiple index files present; +the one with the largest name in lexicographic order is the current +index file. + +The reply index file contains a JSON object: + +.. code-block:: json + + { + "cmake": { + "version": { + "major": 3, "minor": 14, "patch": 0, "suffix": "", + "string": "3.14.0", "isDirty": false + }, + "paths": { + "cmake": "/prefix/bin/cmake", + "ctest": "/prefix/bin/ctest", + "cpack": "/prefix/bin/cpack", + "root": "/prefix/share/cmake-3.14" + }, + "generator": { + "multiConfig": false, + "name": "Unix Makefiles" + } + }, + "objects": [ + { "kind": "", + "version": { "major": 1, "minor": 0 }, + "jsonFile": "" }, + { "...": "..." } + ], + "reply": { + "-v": { "kind": "", + "version": { "major": 1, "minor": 0 }, + "jsonFile": "" }, + "": { "error": "unknown query file" }, + "...": {}, + "client-": { + "-v": { "kind": "", + "version": { "major": 1, "minor": 0 }, + "jsonFile": "" }, + "": { "error": "unknown query file" }, + "...": {}, + "query.json": { + "requests": [ {}, {}, {} ], + "responses": [ + { "kind": "", + "version": { "major": 1, "minor": 0 }, + "jsonFile": "" }, + { "error": "unknown query file" }, + { "...": {} } + ], + "client": {} + } + } + } + } + +The members are: + +``cmake`` + A JSON object containing information about the instance of CMake that + generated the reply. It contains members: + + ``version`` + A JSON object specifying the version of CMake with members: + + ``major``, ``minor``, ``patch`` + Integer values specifying the major, minor, and patch version components. + ``suffix`` + A string specifying the version suffix, if any, e.g. ``g0abc3``. + ``string`` + A string specifying the full version in the format + ``..[-]``. + ``isDirty`` + A boolean indicating whether the version was built from a version + controlled source tree with local modifications. + + ``paths`` + A JSON object specifying paths to things that come with CMake. + It has members for :program:`cmake`, :program:`ctest`, and :program:`cpack` + whose values are JSON strings specifying the absolute path to each tool, + represented with forward slashes. It also has a ``root`` member for + the absolute path to the directory containing CMake resources like the + ``Modules/`` directory (see :variable:`CMAKE_ROOT`). + + ``generator`` + A JSON object describing the CMake generator used for the build. + It has members: + + ``multiConfig`` + A boolean specifying whether the generator supports multiple output + configurations. + ``name`` + A string specifying the name of the generator. + ``platform`` + If the generator supports :variable:`CMAKE_GENERATOR_PLATFORM`, + this is a string specifying the generator platform name. + +``objects`` + A JSON array listing all versions of all `Object Kinds`_ generated + as part of the reply. Each array entry is a + `v1 Reply File Reference`_. + +``reply`` + A JSON object mirroring the content of the ``query/`` directory + that CMake loaded to produce the reply. The members are of the form + + ``-v`` + A member of this form appears for each of the + `v1 Shared Stateless Query Files`_ that CMake recognized as a + request for object kind ```` with major version ````. + The value is + + * a `v1 Reply File Reference`_ to the corresponding reply file for + that object kind and version, or + * in a `v1 Reply Error Index`_, a JSON object with a single ``error`` + member containing a string with an error message. + + ```` + A member of this form appears for each of the + `v1 Shared Stateless Query Files`_ that CMake did not recognize. + The value is a JSON object with a single ``error`` member + containing a string with an error message indicating that the + query file is unknown. + + ``client-`` + A member of this form appears for each client-owned directory + holding `v1 Client Stateless Query Files`_. + The value is a JSON object mirroring the content of the + ``query/client-/`` directory. The members are of the form: + + ``-v`` + A member of this form appears for each of the + `v1 Client Stateless Query Files`_ that CMake recognized as a + request for object kind ```` with major version ````. + The value is + + * a `v1 Reply File Reference`_ to the corresponding reply file for + that object kind and version, or + * in a `v1 Reply Error Index`_, a JSON object with a single ``error`` + member containing a string with an error message. + + ```` + A member of this form appears for each of the + `v1 Client Stateless Query Files`_ that CMake did not recognize. + The value is a JSON object with a single ``error`` member + containing a string with an error message indicating that the + query file is unknown. + + ``query.json`` + This member appears for clients using + `v1 Client Stateful Query Files`_. + If the ``query.json`` file failed to read or parse as a JSON object, + this member is a JSON object with a single ``error`` member + containing a string with an error message. Otherwise, this member + is a JSON object mirroring the content of the ``query.json`` file. + The members are: + + ``client`` + A copy of the ``query.json`` file ``client`` member, if it exists. + + ``requests`` + A copy of the ``query.json`` file ``requests`` member, if it exists. + + ``responses`` + If the ``query.json`` file ``requests`` member is missing or invalid, + this member is a JSON object with a single ``error`` member + containing a string with an error message. Otherwise, this member + contains a JSON array with a response for each entry of the + ``requests`` array, in the same order. Each response is + + * a `v1 Reply File Reference`_ to the corresponding reply file for + the requested object kind and selected version, or + * a JSON object with a single ``error`` member containing a string + with an error message. + +After reading the reply index file, clients may read the other +`v1 Reply Files`_ it references. + +v1 Reply File Reference +^^^^^^^^^^^^^^^^^^^^^^^ + +The reply index file represents each reference to another reply file +using a JSON object with members: + +``kind`` + A string specifying one of the `Object Kinds`_. +``version`` + A JSON object with members ``major`` and ``minor`` specifying + integer version components of the object kind. +``jsonFile`` + A JSON string specifying a path relative to the reply index file + to another JSON file containing the object. + +.. _`file-api reply error index`: + +v1 Reply Error Index +^^^^^^^^^^^^^^^^^^^^ + +.. versionadded:: 4.1 + +CMake writes an ``error-*.json`` file to the ``v1/reply/`` directory +when it fails to generate a build system. This reply error index +follows the same naming pattern, syntax, and semantics of a +`v1 Reply Index File`_, with the following exceptions: + +* The ``index-`` prefix is replaced by an ``error-`` prefix. + +* When a new error index is generated, old index files are *not* + deleted. If a `v1 Reply Index File`_ exists, it indexes replies + from the most recent successful run. If multiple ``index-*.json`` + and/or ``error-*.json`` files are present, the one with the largest + name in lexicographic order, excluding the ``index-`` or ``error-`` + prefix, is the current index. + +* Only a subset of `Object Kinds`_ are provided: + + `configureLog `_ + .. versionadded:: 4.1 + + Index entries for other object kinds contain an ``error`` message + instead of a `v1 Reply File Reference`_. + +v1 Reply Files +-------------- + +Reply files containing specific `Object Kinds`_ are written by CMake. +The names of these files are unspecified and must not be interpreted +by clients. Clients must first read the `v1 Reply Index File`_ and +follow references to the names of the desired response objects. + +Reply files (including the index file) will never be replaced by +files of the same name but different content. This allows a client +to read the files concurrently with a running CMake that may generate +a new reply. However, after generating a new reply CMake will attempt +to remove reply files from previous runs that it did not just write. +If a client attempts to read a reply file referenced by the index but +finds the file missing, that means a concurrent CMake has generated +a new reply. The client may simply start again by reading the new +reply index file. + +.. _`file-api object kinds`: + +Object Kinds +============ + +The CMake file-based API reports semantic information about the build +system using the following kinds of JSON objects. Each kind of object +is versioned independently using semantic versioning with major and +minor components. Every kind of object has the form: + +.. code-block:: json + + { + "kind": "", + "version": { "major": 1, "minor": 0 }, + "...": {} + } + +The ``kind`` member is a string specifying the object kind name. +The ``version`` member is a JSON object with ``major`` and ``minor`` +members specifying integer components of the object kind's version. +Additional top-level members are specific to each object kind. + +Object Kind "codemodel" +----------------------- + +The ``codemodel`` object kind describes the build system structure as +modeled by CMake. + +There is only one ``codemodel`` object major version, version 2. +Version 1 does not exist to avoid confusion with that from +:manual:`cmake-server(7)` mode. + +"codemodel" version 2 +^^^^^^^^^^^^^^^^^^^^^ + +``codemodel`` object version 2 is a JSON object: + +.. code-block:: json + + { + "kind": "codemodel", + "version": { "major": 2, "minor": 8 }, + "paths": { + "source": "/path/to/top-level-source-dir", + "build": "/path/to/top-level-build-dir" + }, + "configurations": [ + { + "name": "Debug", + "directories": [ + { + "source": ".", + "build": ".", + "childIndexes": [ 1 ], + "projectIndex": 0, + "targetIndexes": [ 0 ], + "hasInstallRule": true, + "minimumCMakeVersion": { + "string": "3.14" + }, + "jsonFile": "" + }, + { + "source": "sub", + "build": "sub", + "parentIndex": 0, + "projectIndex": 0, + "targetIndexes": [ 1 ], + "minimumCMakeVersion": { + "string": "3.14" + }, + "jsonFile": "" + } + ], + "projects": [ + { + "name": "MyProject", + "directoryIndexes": [ 0, 1 ], + "targetIndexes": [ 0, 1 ] + } + ], + "targets": [ + { + "name": "MyExecutable", + "directoryIndex": 0, + "projectIndex": 0, + "jsonFile": "" + }, + { + "name": "MyLibrary", + "directoryIndex": 1, + "projectIndex": 0, + "jsonFile": "" + } + ] + } + ] + } + +The members specific to ``codemodel`` objects are: + +``paths`` + A JSON object containing members: + + ``source`` + A string specifying the absolute path to the top-level source directory, + represented with forward slashes. + + ``build`` + A string specifying the absolute path to the top-level build directory, + represented with forward slashes. + +``configurations`` + A JSON array of entries corresponding to available build configurations. + On single-configuration generators there is one entry for the value + of the :variable:`CMAKE_BUILD_TYPE` variable. For multi-configuration + generators there is an entry for each configuration listed in the + :variable:`CMAKE_CONFIGURATION_TYPES` variable. + Each entry is a JSON object containing members: + + ``name`` + A string specifying the name of the configuration, e.g. ``Debug``. + + ``directories`` + A JSON array of entries each corresponding to a build system directory + whose source directory contains a ``CMakeLists.txt`` file. The first + entry corresponds to the top-level directory. Each entry is a + JSON object containing members: + + ``source`` + A string specifying the path to the source directory, represented + with forward slashes. If the directory is inside the top-level + source directory then the path is specified relative to that + directory (with ``.`` for the top-level source directory itself). + Otherwise the path is absolute. + + ``build`` + A string specifying the path to the build directory, represented + with forward slashes. If the directory is inside the top-level + build directory then the path is specified relative to that + directory (with ``.`` for the top-level build directory itself). + Otherwise the path is absolute. + + ``parentIndex`` + Optional member that is present when the directory is not top-level. + The value is an unsigned integer 0-based index of another entry in + the main ``directories`` array that corresponds to the parent + directory that added this directory as a subdirectory. + + ``childIndexes`` + Optional member that is present when the directory has subdirectories. + The value is a JSON array of entries corresponding to child directories + created by the :command:`add_subdirectory` or :command:`subdirs` + command. Each entry is an unsigned integer 0-based index of another + entry in the main ``directories`` array. + + ``projectIndex`` + An unsigned integer 0-based index into the main ``projects`` array + indicating the build system project to which the this directory belongs. + + ``targetIndexes`` + Optional member that is present when the directory itself has targets, + excluding those belonging to subdirectories. The value is a JSON + array of entries corresponding to the targets. Each entry is an + unsigned integer 0-based index into the main ``targets`` array. + + ``minimumCMakeVersion`` + Optional member present when a minimum required version of CMake is + known for the directory. This is the ```` version given to the + most local call to the :command:`cmake_minimum_required(VERSION)` + command in the directory itself or one of its ancestors. + The value is a JSON object with one member: + + ``string`` + A string specifying the minimum required version in the format:: + + .[.[.]][] + + Each component is an unsigned integer and the suffix may be an + arbitrary string. + + ``hasInstallRule`` + Optional member that is present with boolean value ``true`` when + the directory or one of its subdirectories contains any + :command:`install` rules, i.e. whether a ``make install`` + or equivalent rule is available. + + ``jsonFile`` + A JSON string specifying a path relative to the codemodel file + to another JSON file containing a + `"codemodel" version 2 "directory" object`_. + + This field was added in codemodel version 2.3. + + ``projects`` + A JSON array of entries corresponding to the top-level project + and sub-projects defined in the build system. Each (sub-)project + corresponds to a source directory whose ``CMakeLists.txt`` file + calls the :command:`project` command with a project name different + from its parent directory. The first entry corresponds to the + top-level project. + + Each entry is a JSON object containing members: + + ``name`` + A string specifying the name given to the :command:`project` command. + + ``parentIndex`` + Optional member that is present when the project is not top-level. + The value is an unsigned integer 0-based index of another entry in + the main ``projects`` array that corresponds to the parent project + that added this project as a sub-project. + + ``childIndexes`` + Optional member that is present when the project has sub-projects. + The value is a JSON array of entries corresponding to the sub-projects. + Each entry is an unsigned integer 0-based index of another + entry in the main ``projects`` array. + + ``directoryIndexes`` + A JSON array of entries corresponding to build system directories + that are part of the project. The first entry corresponds to the + top-level directory of the project. Each entry is an unsigned + integer 0-based index into the main ``directories`` array. + + ``targetIndexes`` + Optional member that is present when the project itself has targets, + excluding those belonging to sub-projects. The value is a JSON + array of entries corresponding to the targets. Each entry is an + unsigned integer 0-based index into the main ``targets`` array. + + ``targets`` + A JSON array of entries corresponding to the build system targets. + Such targets are created by calls to :command:`add_executable`, + :command:`add_library`, and :command:`add_custom_target`, excluding + imported targets and interface libraries (which do not generate any + build rules). Each entry is a JSON object containing members: + + ``name`` + A string specifying the target name. + + ``id`` + A string uniquely identifying the target. This matches the ``id`` + field in the file referenced by ``jsonFile``. + + ``directoryIndex`` + An unsigned integer 0-based index into the main ``directories`` array + indicating the build system directory in which the target is defined. + + ``projectIndex`` + An unsigned integer 0-based index into the main ``projects`` array + indicating the build system project in which the target is defined. + + ``jsonFile`` + A JSON string specifying a path relative to the codemodel file + to another JSON file containing a + `"codemodel" version 2 "target" object`_. + +"codemodel" version 2 "directory" object +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A codemodel "directory" object is referenced by a `"codemodel" version 2`_ +object's ``directories`` array. Each "directory" object is a JSON object +with members: + +``paths`` + A JSON object containing members: + + ``source`` + A string specifying the path to the source directory, represented + with forward slashes. If the directory is inside the top-level + source directory then the path is specified relative to that + directory (with ``.`` for the top-level source directory itself). + Otherwise the path is absolute. + + ``build`` + A string specifying the path to the build directory, represented + with forward slashes. If the directory is inside the top-level + build directory then the path is specified relative to that + directory (with ``.`` for the top-level build directory itself). + Otherwise the path is absolute. + +``installers`` + A JSON array of entries corresponding to :command:`install` rules. + Each entry is a JSON object containing members: + + ``component`` + A string specifying the component selected by the corresponding + :command:`install` command invocation. + + ``destination`` + Optional member that is present for specific ``type`` values below. + The value is a string specifying the install destination path. + The path may be absolute or relative to the install prefix. + + ``paths`` + Optional member that is present for specific ``type`` values below. + The value is a JSON array of entries corresponding to the paths + (files or directories) to be installed. Each entry is one of: + + * A string specifying the path from which a file or directory + is to be installed. The portion of the path not preceded by + a ``/`` also specifies the path (name) to which the file + or directory is to be installed under the destination. + + * A JSON object with members: + + ``from`` + A string specifying the path from which a file or directory + is to be installed. + + ``to`` + A string specifying the path to which the file or directory + is to be installed under the destination. + + In both cases the paths are represented with forward slashes. If + the "from" path is inside the top-level directory documented by the + corresponding ``type`` value, then the path is specified relative + to that directory. Otherwise the path is absolute. + + ``type`` + A string specifying the type of installation rule. The value is one + of the following, with some variants providing additional members: + + ``file`` + An :command:`install(FILES)` or :command:`install(PROGRAMS)` call. + The ``destination`` and ``paths`` members are populated, with paths + under the top-level *source* directory expressed relative to it. + The ``isOptional`` member may exist. + This type has no additional members. + + ``directory`` + An :command:`install(DIRECTORY)` call. + The ``destination`` and ``paths`` members are populated, with paths + under the top-level *source* directory expressed relative to it. + The ``isOptional`` member may exist. + This type has no additional members. + + ``target`` + An :command:`install(TARGETS)` call. + The ``destination`` and ``paths`` members are populated, with paths + under the top-level *build* directory expressed relative to it. + The ``isOptional`` member may exist. + This type has additional members ``targetId``, ``targetIndex``, + ``targetIsImportLibrary``, and ``targetInstallNamelink``. + + ``export`` + An :command:`install(EXPORT)` call. + The ``destination`` and ``paths`` members are populated, with paths + under the top-level *build* directory expressed relative to it. + The ``paths`` entries refer to files generated automatically by + CMake for installation, and their actual values are considered + private implementation details. + This type has additional members ``exportName`` and ``exportTargets``. + + ``script`` + An :command:`install(SCRIPT)` call. + This type has additional member ``scriptFile``. + + ``code`` + An :command:`install(CODE)` call. + This type has no additional members. + + ``importedRuntimeArtifacts`` + An :command:`install(IMPORTED_RUNTIME_ARTIFACTS)` call. + The ``destination`` member is populated. The ``isOptional`` member may + exist. This type has no additional members. + + ``runtimeDependencySet`` + An :command:`install(RUNTIME_DEPENDENCY_SET)` call or an + :command:`install(TARGETS)` call with ``RUNTIME_DEPENDENCIES``. The + ``destination`` member is populated. This type has additional members + ``runtimeDependencySetName`` and ``runtimeDependencySetType``. + + ``fileSet`` + An :command:`install(TARGETS)` call with ``FILE_SET``. + The ``destination`` and ``paths`` members are populated. + The ``isOptional`` member may exist. + This type has additional members ``fileSetName``, ``fileSetType``, + ``fileSetDirectories``, and ``fileSetTarget``. + + This type was added in codemodel version 2.4. + + ``cxxModuleBmi`` + An :command:`install(TARGETS)` call with ``CXX_MODULES_BMI``. + The ``destination`` member is populated and the ``isOptional`` member + may exist. This type has an additional ``cxxModuleBmiTarget`` member. + + This type was added in codemodel version 2.5. + + ``isExcludeFromAll`` + Optional member that is present with boolean value ``true`` when + :command:`install` is called with the ``EXCLUDE_FROM_ALL`` option. + + ``isForAllComponents`` + Optional member that is present with boolean value ``true`` when + :command:`install(SCRIPT|CODE)` is called with the + ``ALL_COMPONENTS`` option. + + ``isOptional`` + Optional member that is present with boolean value ``true`` when + :command:`install` is called with the ``OPTIONAL`` option. + This is allowed when ``type`` is ``file``, ``directory``, or ``target``. + + ``targetId`` + Optional member that is present when ``type`` is ``target``. + The value is a string uniquely identifying the target to be installed. + This matches the ``id`` member of the target in the main + "codemodel" object's ``targets`` array. + + ``targetIndex`` + Optional member that is present when ``type`` is ``target``. + The value is an unsigned integer 0-based index into the main "codemodel" + object's ``targets`` array for the target to be installed. + + ``targetIsImportLibrary`` + Optional member that is present when ``type`` is ``target`` and + the installer is for a Windows DLL import library file or for an + AIX linker import file. If present, it has boolean value ``true``. + + ``targetInstallNamelink`` + Optional member that is present when ``type`` is ``target`` and + the installer corresponds to a target that may use symbolic links + to implement the :prop_tgt:`VERSION` and :prop_tgt:`SOVERSION` + target properties. + The value is a string indicating how the installer is supposed to + handle the symlinks: ``skip`` means the installer should skip the + symlinks and install only the real file, and ``only`` means the + installer should install only the symlinks and not the real file. + In all cases the ``paths`` member lists what it actually installs. + + ``exportName`` + Optional member that is present when ``type`` is ``export``. + The value is a string specifying the name of the export. + + ``exportTargets`` + Optional member that is present when ``type`` is ``export``. + The value is a JSON array of entries corresponding to the targets + included in the export. Each entry is a JSON object with members: + + ``id`` + A string uniquely identifying the target. This matches + the ``id`` member of the target in the main "codemodel" + object's ``targets`` array. + + ``index`` + An unsigned integer 0-based index into the main "codemodel" + object's ``targets`` array for the target. + + ``runtimeDependencySetName`` + Optional member that is present when ``type`` is ``runtimeDependencySet`` + and the installer was created by an + :command:`install(RUNTIME_DEPENDENCY_SET)` call. The value is a string + specifying the name of the runtime dependency set that was installed. + + ``runtimeDependencySetType`` + Optional member that is present when ``type`` is ``runtimeDependencySet``. + The value is a string with one of the following values: + + ``library`` + Indicates that this installer installs dependencies that are not macOS + frameworks. + + ``framework`` + Indicates that this installer installs dependencies that are macOS + frameworks. + + ``fileSetName`` + Optional member that is present when ``type`` is ``fileSet``. The value is + a string with the name of the file set. + + This field was added in codemodel version 2.4. + + ``fileSetType`` + Optional member that is present when ``type`` is ``fileSet``. The value is + a string with the type of the file set. + + This field was added in codemodel version 2.4. + + ``fileSetDirectories`` + Optional member that is present when ``type`` is ``fileSet``. The value + is a list of strings with the file set's base directories (determined by + genex-evaluation of :prop_tgt:`HEADER_DIRS` or + :prop_tgt:`HEADER_DIRS_`). + + This field was added in codemodel version 2.4. + + ``fileSetTarget`` + Optional member that is present when ``type`` is ``fileSet``. The value + is a JSON object with members: + + ``id`` + A string uniquely identifying the target. This matches + the ``id`` member of the target in the main "codemodel" + object's ``targets`` array. + + ``index`` + An unsigned integer 0-based index into the main "codemodel" + object's ``targets`` array for the target. + + This field was added in codemodel version 2.4. + + ``cxxModuleBmiTarget`` + Optional member that is present when ``type`` is ``cxxModuleBmi``. + The value is a JSON object with members: + + ``id`` + A string uniquely identifying the target. This matches + the ``id`` member of the target in the main "codemodel" + object's ``targets`` array. + + ``index`` + An unsigned integer 0-based index into the main "codemodel" + object's ``targets`` array for the target. + + This field was added in codemodel version 2.5. + + ``scriptFile`` + Optional member that is present when ``type`` is ``script``. + The value is a string specifying the path to the script file on disk, + represented with forward slashes. If the file is inside the top-level + source directory then the path is specified relative to that directory. + Otherwise the path is absolute. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`install` or other command invocation that added this + installer is available. The value is an unsigned integer 0-based + index into the ``backtraceGraph`` member's ``nodes`` array. + +``backtraceGraph`` + A `"codemodel" version 2 "backtrace graph"`_ whose nodes are referenced + from ``backtrace`` members elsewhere in this "directory" object. + +"codemodel" version 2 "target" object +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A codemodel "target" object is referenced by a `"codemodel" version 2`_ +object's ``targets`` array. Each "target" object is a JSON object +with members: + +``name`` + A string specifying the logical name of the target. + +``id`` + A string uniquely identifying the target. The format is unspecified + and should not be interpreted by clients. + +``type`` + A string specifying the type of the target. The value is one of + ``EXECUTABLE``, ``STATIC_LIBRARY``, ``SHARED_LIBRARY``, + ``MODULE_LIBRARY``, ``OBJECT_LIBRARY``, ``INTERFACE_LIBRARY``, + or ``UTILITY``. + +``backtrace`` + Optional member that is present when a CMake language backtrace to + the command in the source code that created the target is available. + The value is an unsigned integer 0-based index into the + ``backtraceGraph`` member's ``nodes`` array. + +``folder`` + Optional member that is present when the :prop_tgt:`FOLDER` target + property is set. The value is a JSON object with one member: + + ``name`` + A string specifying the name of the target folder. + +``paths`` + A JSON object containing members: + + ``source`` + A string specifying the path to the target's source directory, + represented with forward slashes. If the directory is inside the + top-level source directory then the path is specified relative to + that directory (with ``.`` for the top-level source directory itself). + Otherwise the path is absolute. + + ``build`` + A string specifying the path to the target's build directory, + represented with forward slashes. If the directory is inside the + top-level build directory then the path is specified relative to + that directory (with ``.`` for the top-level build directory itself). + Otherwise the path is absolute. + +``nameOnDisk`` + Optional member that is present for executable and library targets + that are linked or archived into a single primary artifact. + The value is a string specifying the file name of that artifact on disk. + +``artifacts`` + Optional member that is present for executable and library targets + that produce artifacts on disk meant for consumption by dependents. + The value is a JSON array of entries corresponding to the artifacts. + Each entry is a JSON object containing one member: + + ``path`` + A string specifying the path to the file on disk, represented with + forward slashes. If the file is inside the top-level build directory + then the path is specified relative to that directory. + Otherwise the path is absolute. + +``isGeneratorProvided`` + Optional member that is present with boolean value ``true`` if the + target is provided by CMake's build system generator rather than by + a command in the source code. + +``install`` + Optional member that is present when the target has an :command:`install` + rule. The value is a JSON object with members: + + ``prefix`` + A JSON object specifying the installation prefix. It has one member: + + ``path`` + A string specifying the value of :variable:`CMAKE_INSTALL_PREFIX`. + + ``destinations`` + A JSON array of entries specifying an install destination path. + Each entry is a JSON object with members: + + ``path`` + A string specifying the install destination path. The path may + be absolute or relative to the install prefix. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`install` command invocation that specified this + destination is available. The value is an unsigned integer 0-based + index into the ``backtraceGraph`` member's ``nodes`` array. + +``launchers`` + Optional member that is present on executable targets that have + at least one launcher specified by the project. The value is a + JSON array of entries corresponding to the specified launchers. + Each entry is a JSON object with members: + + ``command`` + A string specifying the path to the launcher on disk, represented + with forward slashes. If the file is inside the top-level source + directory then the path is specified relative to that directory. + + ``arguments`` + Optional member that is present when the launcher command has + arguments preceding the executable to be launched. The value + is a JSON array of strings representing the arguments. + + ``type`` + A string specifying the type of launcher. The value is one of + the following: + + ``emulator`` + An emulator for the target platform when cross-compiling. + See the :prop_tgt:`CROSSCOMPILING_EMULATOR` target property. + + ``test`` + A start program for the execution of tests. + See the :prop_tgt:`TEST_LAUNCHER` target property. + + This field was added in codemodel version 2.7. + +``link`` + Optional member that is present for executables and shared library + targets that link into a runtime binary. The value is a JSON object + with members describing the link step: + + ``language`` + A string specifying the language (e.g. ``C``, ``CXX``, ``Fortran``) + of the toolchain is used to invoke the linker. + + ``commandFragments`` + Optional member that is present when fragments of the link command + line invocation are available. The value is a JSON array of entries + specifying ordered fragments. Each entry is a JSON object with members: + + ``fragment`` + A string specifying a fragment of the link command line invocation. + The value is encoded in the build system's native shell format. + + ``role`` + A string specifying the role of the fragment's content: + + * ``flags``: link flags. + * ``libraries``: link library file paths or flags. + * ``libraryPath``: library search path flags. + * ``frameworkPath``: macOS framework search path flags. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`target_link_libraries`, :command:`target_link_options`, + or other command invocation that added this link fragment is available. + The value is an unsigned integer 0-based index into the ``backtraceGraph`` + member's ``nodes`` array. + + ``lto`` + Optional member that is present with boolean value ``true`` + when link-time optimization (a.k.a. interprocedural optimization + or link-time code generation) is enabled. + + ``sysroot`` + Optional member that is present when the :variable:`CMAKE_SYSROOT_LINK` + or :variable:`CMAKE_SYSROOT` variable is defined. The value is a + JSON object with one member: + + ``path`` + A string specifying the absolute path to the sysroot, represented + with forward slashes. + +``archive`` + Optional member that is present for static library targets. The value + is a JSON object with members describing the archive step: + + ``commandFragments`` + Optional member that is present when fragments of the archiver command + line invocation are available. The value is a JSON array of entries + specifying the fragments. Each entry is a JSON object with members: + + ``fragment`` + A string specifying a fragment of the archiver command line invocation. + The value is encoded in the build system's native shell format. + + ``role`` + A string specifying the role of the fragment's content: + + * ``flags``: archiver flags. + + ``lto`` + Optional member that is present with boolean value ``true`` + when link-time optimization (a.k.a. interprocedural optimization + or link-time code generation) is enabled. + +``debugger`` + Optional member that is present when the target has one of the + following fields set. + The value is a JSON object of entries corresponding to + debugger specific values set. + + This field was added in codemodel version 2.8. + + ``workingDirectory`` + Optional member that is present when the + :prop_tgt:`DEBUGGER_WORKING_DIRECTORY` target property is set. + The member will also be present in :ref:`Visual Studio Generators` + when :prop_tgt:`VS_DEBUGGER_WORKING_DIRECTORY` is set. + + This field was added in codemodel version 2.8. + +``dependencies`` + Optional member that is present when the target depends on other targets. + The value is a JSON array of entries corresponding to the dependencies. + Each entry is a JSON object with members: + + ``id`` + A string uniquely identifying the target on which this target depends. + This matches the main ``id`` member of the other target. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`add_dependencies`, :command:`target_link_libraries`, + or other command invocation that created this dependency is + available. The value is an unsigned integer 0-based index into + the ``backtraceGraph`` member's ``nodes`` array. + +``fileSets`` + An optional member that is present when a target defines one or more + file sets. The value is a JSON array of entries corresponding to the + target's file sets. Each entry is a JSON object with members: + + ``name`` + A string specifying the name of the file set. + + ``type`` + A string specifying the type of the file set. See + :command:`target_sources` supported file set types. + + ``visibility`` + A string specifying the visibility of the file set; one of ``PUBLIC``, + ``PRIVATE``, or ``INTERFACE``. + + ``baseDirectories`` + A JSON array of strings, each specifying a base directory containing + sources in the file set. If the directory is inside the top-level source + directory then the path is specified relative to that directory. + Otherwise the path is absolute. + + This field was added in codemodel version 2.5. + +``sources`` + A JSON array of entries corresponding to the target's source files. + Each entry is a JSON object with members: + + ``path`` + A string specifying the path to the source file on disk, represented + with forward slashes. If the file is inside the top-level source + directory then the path is specified relative to that directory. + Otherwise the path is absolute. + + ``compileGroupIndex`` + Optional member that is present when the source is compiled. + The value is an unsigned integer 0-based index into the + ``compileGroups`` array. + + ``sourceGroupIndex`` + Optional member that is present when the source is part of a source + group either via the :command:`source_group` command or by default. + The value is an unsigned integer 0-based index into the + ``sourceGroups`` array. + + ``isGenerated`` + Optional member that is present with boolean value ``true`` if + the source is :prop_sf:`GENERATED`. + + ``fileSetIndex`` + Optional member that is present when the source is part of a file set. + The value is an unsigned integer 0-based index into the ``fileSets`` + array. + + This field was added in codemodel version 2.5. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`target_sources`, :command:`add_executable`, + :command:`add_library`, :command:`add_custom_target`, or other + command invocation that added this source to the target is + available. The value is an unsigned integer 0-based index into + the ``backtraceGraph`` member's ``nodes`` array. + +``sourceGroups`` + Optional member that is present when sources are grouped together by + the :command:`source_group` command or by default. The value is a + JSON array of entries corresponding to the groups. Each entry is + a JSON object with members: + + ``name`` + A string specifying the name of the source group. + + ``sourceIndexes`` + A JSON array listing the sources belonging to the group. + Each entry is an unsigned integer 0-based index into the + main ``sources`` array for the target. + +``compileGroups`` + Optional member that is present when the target has sources that compile. + The value is a JSON array of entries corresponding to groups of sources + that all compile with the same settings. Each entry is a JSON object + with members: + + ``sourceIndexes`` + A JSON array listing the sources belonging to the group. + Each entry is an unsigned integer 0-based index into the + main ``sources`` array for the target. + + ``language`` + A string specifying the language (e.g. ``C``, ``CXX``, ``Fortran``) + of the toolchain is used to compile the source file. + + ``languageStandard`` + Optional member that is present when the language standard is set + explicitly (e.g. via :prop_tgt:`CXX_STANDARD`) or implicitly by + compile features. Each entry is a JSON object with two members: + + ``backtraces`` + Optional member that is present when a CMake language backtrace to + the ``_STANDARD`` setting is available. If the language + standard was set implicitly by compile features those are used as + the backtrace(s). It's possible for multiple compile features to + require the same language standard so there could be multiple + backtraces. The value is a JSON array with each entry being an + unsigned integer 0-based index into the ``backtraceGraph`` + member's ``nodes`` array. + + ``standard`` + String representing the language standard. + + This field was added in codemodel version 2.2. + + ``compileCommandFragments`` + Optional member that is present when fragments of the compiler command + line invocation are available. The value is a JSON array of entries + specifying ordered fragments. Each entry is a JSON object with + one member: + + ``fragment`` + A string specifying a fragment of the compile command line invocation. + The value is encoded in the build system's native shell format. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the command invocation that added this fragment is available. + The value is an unsigned integer 0-based index into the + ``backtraceGraph`` member's ``nodes`` array. + + ``includes`` + Optional member that is present when there are include directories. + The value is a JSON array with an entry for each directory. Each + entry is a JSON object with members: + + ``path`` + A string specifying the path to the include directory, + represented with forward slashes. + + ``isSystem`` + Optional member that is present with boolean value ``true`` if + the include directory is marked as a system include directory. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`target_include_directories` or other command invocation + that added this include directory is available. The value is + an unsigned integer 0-based index into the ``backtraceGraph`` + member's ``nodes`` array. + + ``frameworks`` + Optional member that is present when, on Apple platforms, there are + frameworks. The value is a JSON array with an entry for each directory. + Each entry is a JSON object with members: + + ``path`` + A string specifying the path to the framework directory, + represented with forward slashes. + + ``isSystem`` + Optional member that is present with boolean value ``true`` if + the framework is marked as a system one. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`target_link_libraries` or other command invocation + that added this framework is available. The value is + an unsigned integer 0-based index into the ``backtraceGraph`` + member's ``nodes`` array. + + This field was added in codemodel version 2.6. + + ``precompileHeaders`` + Optional member that is present when :command:`target_precompile_headers` + or other command invocations set :prop_tgt:`PRECOMPILE_HEADERS` on the + target. The value is a JSON array with an entry for each header. Each + entry is a JSON object with members: + + ``header`` + Full path to the precompile header file. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`target_precompile_headers` or other command invocation + that added this precompiled header is available. The value is an + unsigned integer 0-based index into the ``backtraceGraph`` member's + ``nodes`` array. + + This field was added in codemodel version 2.1. + + ``defines`` + Optional member that is present when there are preprocessor definitions. + The value is a JSON array with an entry for each definition. Each + entry is a JSON object with members: + + ``define`` + A string specifying the preprocessor definition in the format + ``[=]``, e.g. ``DEF`` or ``DEF=1``. + + ``backtrace`` + Optional member that is present when a CMake language backtrace to + the :command:`target_compile_definitions` or other command invocation + that added this preprocessor definition is available. The value is + an unsigned integer 0-based index into the ``backtraceGraph`` + member's ``nodes`` array. + + ``sysroot`` + Optional member that is present when the + :variable:`CMAKE_SYSROOT_COMPILE` or :variable:`CMAKE_SYSROOT` + variable is defined. The value is a JSON object with one member: + + ``path`` + A string specifying the absolute path to the sysroot, represented + with forward slashes. + +``backtraceGraph`` + A `"codemodel" version 2 "backtrace graph"`_ whose nodes are referenced + from ``backtrace`` members elsewhere in this "target" object. + +"codemodel" version 2 "backtrace graph" +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``backtraceGraph`` member of a `"codemodel" version 2 "directory" object`_, +or `"codemodel" version 2 "target" object`_ is a JSON object describing a +graph of backtraces. Its nodes are referenced from ``backtrace`` members +elsewhere in the containing object. The backtrace graph object members are: + +``nodes`` + A JSON array listing nodes in the backtrace graph. Each entry + is a JSON object with members: + + ``file`` + An unsigned integer 0-based index into the backtrace ``files`` array. + + ``line`` + An optional member present when the node represents a line within + the file. The value is an unsigned integer 1-based line number. + + ``command`` + An optional member present when the node represents a command + invocation within the file. The value is an unsigned integer + 0-based index into the backtrace ``commands`` array. + + ``parent`` + An optional member present when the node is not the bottom of + the call stack. The value is an unsigned integer 0-based index + of another entry in the backtrace ``nodes`` array. + +``commands`` + A JSON array listing command names referenced by backtrace nodes. + Each entry is a string specifying a command name. + +``files`` + A JSON array listing CMake language files referenced by backtrace nodes. + Each entry is a string specifying the path to a file, represented + with forward slashes. If the file is inside the top-level source + directory then the path is specified relative to that directory. + Otherwise the path is absolute. + +.. _`file-api configureLog`: + +Object Kind "configureLog" +-------------------------- + +.. versionadded:: 3.26 + +The ``configureLog`` object kind describes the location and contents of +a :manual:`cmake-configure-log(7)` file. + +There is only one ``configureLog`` object major version, version 1. + +"configureLog" version 1 +^^^^^^^^^^^^^^^^^^^^^^^^ + +``configureLog`` object version 1 is a JSON object: + +.. code-block:: json + + { + "kind": "configureLog", + "version": { "major": 1, "minor": 0 }, + "path": "/path/to/top-level-build-dir/CMakeFiles/CMakeConfigureLog.yaml", + "eventKindNames": [ "try_compile-v1", "try_run-v1" ] + } + +The members specific to ``configureLog`` objects are: + +``path`` + A string specifying the path to the configure log file. + Clients must read the log file from this path, which may be + different than the path documented by :manual:`cmake-configure-log(7)`. + The log file may not exist if no events are logged. + +``eventKindNames`` + A JSON array whose entries are each a JSON string naming one + of the :manual:`cmake-configure-log(7)` versioned event kinds. + At most one version of each configure log event kind will be listed. + Although the configure log may contain other (versioned) event kinds, + clients must ignore those that are not listed in this field. + +Object Kind "cache" +------------------- + +The ``cache`` object kind lists cache entries. These are the +:ref:`CMake Language Variables` stored in the persistent cache +(``CMakeCache.txt``) for the build tree. + +There is only one ``cache`` object major version, version 2. +Version 1 does not exist to avoid confusion with that from +:manual:`cmake-server(7)` mode. + +"cache" version 2 +^^^^^^^^^^^^^^^^^ + +``cache`` object version 2 is a JSON object: + +.. code-block:: json + + { + "kind": "cache", + "version": { "major": 2, "minor": 0 }, + "entries": [ + { + "name": "BUILD_SHARED_LIBS", + "value": "ON", + "type": "BOOL", + "properties": [ + { + "name": "HELPSTRING", + "value": "Build shared libraries" + } + ] + }, + { + "name": "CMAKE_GENERATOR", + "value": "Unix Makefiles", + "type": "INTERNAL", + "properties": [ + { + "name": "HELPSTRING", + "value": "Name of generator." + } + ] + } + ] + } + +The members specific to ``cache`` objects are: + +``entries`` + A JSON array whose entries are each a JSON object specifying a + cache entry. The members of each entry are: + + ``name`` + A string specifying the name of the entry. + + ``value`` + A string specifying the value of the entry. + + ``type`` + A string specifying the type of the entry used by + :manual:`cmake-gui(1)` to choose a widget for editing. + + ``properties`` + A JSON array of entries specifying associated + :ref:`cache entry properties `. + Each entry is a JSON object containing members: + + ``name`` + A string specifying the name of the cache entry property. + + ``value`` + A string specifying the value of the cache entry property. + +Object Kind "cmakeFiles" +------------------------ + +The ``cmakeFiles`` object kind lists files used by CMake while +configuring and generating the build system. These include the +``CMakeLists.txt`` files as well as included ``.cmake`` files. + +There is only one ``cmakeFiles`` object major version, version 1. + +"cmakeFiles" version 1 +^^^^^^^^^^^^^^^^^^^^^^ + +``cmakeFiles`` object version 1 is a JSON object: + +.. code-block:: json + + { + "kind": "cmakeFiles", + "version": { "major": 1, "minor": 1 }, + "paths": { + "build": "/path/to/top-level-build-dir", + "source": "/path/to/top-level-source-dir" + }, + "inputs": [ + { + "path": "CMakeLists.txt" + }, + { + "isGenerated": true, + "path": "/path/to/top-level-build-dir/.../CMakeSystem.cmake" + }, + { + "isExternal": true, + "path": "/path/to/external/third-party/module.cmake" + }, + { + "isCMake": true, + "isExternal": true, + "path": "/path/to/cmake/Modules/CMakeGenericSystem.cmake" + } + ], + "globsDependent": [ + { + "expression": "src/*.cxx", + "recurse": true, + "files": [ + "src/foo.cxx", + "src/bar.cxx" + ] + } + ] + } + +The members specific to ``cmakeFiles`` objects are: + +``paths`` + A JSON object containing members: + + ``source`` + A string specifying the absolute path to the top-level source directory, + represented with forward slashes. + + ``build`` + A string specifying the absolute path to the top-level build directory, + represented with forward slashes. + +``inputs`` + A JSON array whose entries are each a JSON object specifying an input + file used by CMake when configuring and generating the build system. + The members of each entry are: + + ``path`` + A string specifying the path to an input file to CMake, represented + with forward slashes. If the file is inside the top-level source + directory then the path is specified relative to that directory. + Otherwise the path is absolute. + + ``isGenerated`` + Optional member that is present with boolean value ``true`` + if the path specifies a file that is under the top-level + build directory and the build is out-of-source. + This member is not available on in-source builds. + + ``isExternal`` + Optional member that is present with boolean value ``true`` + if the path specifies a file that is not under the top-level + source or build directories. + + ``isCMake`` + Optional member that is present with boolean value ``true`` + if the path specifies a file in the CMake installation. + +``globsDependent`` + Optional member that is present when the project calls :command:`file(GLOB)` + or :command:`file(GLOB_RECURSE)` with the ``CONFIGURE_DEPENDS`` option. + The value is a JSON array of JSON objects, each specifying a globbing + expression and the list of paths it matched. If the globbing expression + no longer matches the same list of paths, CMake considers the build system + to be out of date. + + This field was added in ``cmakeFiles`` version 1.1. + + The members of each entry are: + + ``expression`` + A string specifying the globbing expression. + + ``recurse`` + Optional member that is present with boolean value ``true`` + if the entry corresponds to a :command:`file(GLOB_RECURSE)` call. + Otherwise the entry corresponds to a :command:`file(GLOB)` call. + + ``listDirectories`` + Optional member that is present with boolean value ``true`` if + :command:`file(GLOB)` was called without ``LIST_DIRECTORIES false`` or + :command:`file(GLOB_RECURSE)` was called with ``LIST_DIRECTORIES true``. + + ``followSymlinks`` + Optional member that is present with boolean value ``true`` if + :command:`file(GLOB)` was called with the ``FOLLOW_SYMLINKS`` option. + + ``relative`` + Optional member that is present if :command:`file(GLOB)` was called + with the ``RELATIVE `` option. The value is a string containing + the ```` given. + + ``paths`` + A JSON array of strings specifying the paths matched by the call + to :command:`file(GLOB)` or :command:`file(GLOB_RECURSE)`. + +Object Kind "toolchains" +------------------------ + +The ``toolchains`` object kind lists properties of the toolchains used during +the build. These include the language, compiler path, ID, and version. + +There is only one ``toolchains`` object major version, version 1. + +"toolchains" version 1 +^^^^^^^^^^^^^^^^^^^^^^ + +``toolchains`` object version 1 is a JSON object: + +.. code-block:: json + + { + "kind": "toolchains", + "version": { "major": 1, "minor": 0 }, + "toolchains": [ + { + "language": "C", + "compiler": { + "path": "/usr/bin/cc", + "id": "GNU", + "version": "9.3.0", + "implicit": { + "includeDirectories": [ + "/usr/lib/gcc/x86_64-linux-gnu/9/include", + "/usr/local/include", + "/usr/include/x86_64-linux-gnu", + "/usr/include" + ], + "linkDirectories": [ + "/usr/lib/gcc/x86_64-linux-gnu/9", + "/usr/lib/x86_64-linux-gnu", + "/usr/lib", + "/lib/x86_64-linux-gnu", + "/lib" + ], + "linkFrameworkDirectories": [], + "linkLibraries": [ "gcc", "gcc_s", "c", "gcc", "gcc_s" ] + } + }, + "sourceFileExtensions": [ "c", "m" ] + }, + { + "language": "CXX", + "compiler": { + "path": "/usr/bin/c++", + "id": "GNU", + "version": "9.3.0", + "implicit": { + "includeDirectories": [ + "/usr/include/c++/9", + "/usr/include/x86_64-linux-gnu/c++/9", + "/usr/include/c++/9/backward", + "/usr/lib/gcc/x86_64-linux-gnu/9/include", + "/usr/local/include", + "/usr/include/x86_64-linux-gnu", + "/usr/include" + ], + "linkDirectories": [ + "/usr/lib/gcc/x86_64-linux-gnu/9", + "/usr/lib/x86_64-linux-gnu", + "/usr/lib", + "/lib/x86_64-linux-gnu", + "/lib" + ], + "linkFrameworkDirectories": [], + "linkLibraries": [ + "stdc++", "m", "gcc_s", "gcc", "c", "gcc_s", "gcc" + ] + } + }, + "sourceFileExtensions": [ + "C", "M", "c++", "cc", "cpp", "cxx", "mm", "CPP" + ] + } + ] + } + +The members specific to ``toolchains`` objects are: + +``toolchains`` + A JSON array whose entries are each a JSON object specifying a toolchain + associated with a particular language. The members of each entry are: + + ``language`` + A JSON string specifying the toolchain language, like C or CXX. Language + names are the same as language names that can be passed to the + :command:`project` command. Because CMake only supports a single toolchain + per language, this field can be used as a key. + + ``compiler`` + A JSON object containing members: + + ``path`` + Optional member that is present when the + :variable:`CMAKE__COMPILER` variable is defined for the current + language. Its value is a JSON string holding the path to the compiler. + + ``id`` + Optional member that is present when the + :variable:`CMAKE__COMPILER_ID` variable is defined for the current + language. Its value is a JSON string holding the ID (GNU, MSVC, etc.) of + the compiler. + + ``version`` + Optional member that is present when the + :variable:`CMAKE__COMPILER_VERSION` variable is defined for the + current language. Its value is a JSON string holding the version of the + compiler. + + ``target`` + Optional member that is present when the + :variable:`CMAKE__COMPILER_TARGET` variable is defined for the + current language. Its value is a JSON string holding the cross-compiling + target of the compiler. + + ``implicit`` + A JSON object containing members: + + ``includeDirectories`` + Optional member that is present when the + :variable:`CMAKE__IMPLICIT_INCLUDE_DIRECTORIES` variable is + defined for the current language. Its value is a JSON array of JSON + strings where each string holds a path to an implicit include + directory for the compiler. + + ``linkDirectories`` + Optional member that is present when the + :variable:`CMAKE__IMPLICIT_LINK_DIRECTORIES` variable is + defined for the current language. Its value is a JSON array of JSON + strings where each string holds a path to an implicit link directory + for the compiler. + + ``linkFrameworkDirectories`` + Optional member that is present when the + :variable:`CMAKE__IMPLICIT_LINK_FRAMEWORK_DIRECTORIES` variable + is defined for the current language. Its value is a JSON array of JSON + strings where each string holds a path to an implicit link framework + directory for the compiler. + + ``linkLibraries`` + Optional member that is present when the + :variable:`CMAKE__IMPLICIT_LINK_LIBRARIES` variable is defined + for the current language. Its value is a JSON array of JSON strings + where each string holds a path to an implicit link library for the + compiler. + + ``sourceFileExtensions`` + Optional member that is present when the + :variable:`CMAKE__SOURCE_FILE_EXTENSIONS` variable is defined for + the current language. Its value is a JSON array of JSON strings where + each string holds a file extension (without the leading dot) for the + language. diff --git a/packages/cmake-file-api/package.json b/packages/cmake-file-api/package.json new file mode 100644 index 00000000..b641dffc --- /dev/null +++ b/packages/cmake-file-api/package.json @@ -0,0 +1,33 @@ +{ + "name": "cmake-file-api", + "version": "0.1.0", + "type": "module", + "description": "TypeScript wrapper around the CMake File API", + "homepage": "https://cmake.org/cmake/help/latest/manual/cmake-file-api.7.html", + "scripts": { + "build": "tsc --build", + "lint": "eslint 'src/**/*.ts'", + "test": "tsx --test --test-reporter=@reporters/github --test-reporter-destination=stdout --test-reporter=spec --test-reporter-destination=stdout" + }, + "files": [ + "docs/", + "dist/", + "!*.test.d.ts", + "!*.test.d.ts.map" + ], + "exports": { + ".": "./dist/index.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/callstackincubator/react-native-node-api", + "directory": "packages/cmake-file-api" + }, + "author": { + "name": "Kræn Hansen", + "url": "https://github.com/kraenhansen" + }, + "dependencies": { + "zod": "^4.1.11" + } +} diff --git a/packages/cmake-file-api/src/index.ts b/packages/cmake-file-api/src/index.ts new file mode 100644 index 00000000..a0f3fa3a --- /dev/null +++ b/packages/cmake-file-api/src/index.ts @@ -0,0 +1,26 @@ +export { + createSharedStatelessQuery, + createClientStatelessQuery, + createClientStatefulQuery, + type VersionSpec, + type QueryRequest, + type StatefulQuery, +} from "./query.js"; + +export { + readReplyIndex, + isReplyErrorIndexPath, + readReplyErrorIndex, + readCodemodel, + readTarget, + readCache, + readCmakeFiles, + readToolchains, + readConfigureLog, + findCurrentReplyIndexPath, + readCurrentSharedCodemodel, + readCurrentTargets, + readCurrentTargetsDeep, +} from "./reply.js"; + +export * from "./schemas.js"; diff --git a/packages/cmake-file-api/src/query.test.ts b/packages/cmake-file-api/src/query.test.ts new file mode 100644 index 00000000..5995cd23 --- /dev/null +++ b/packages/cmake-file-api/src/query.test.ts @@ -0,0 +1,228 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, it, type TestContext } from "node:test"; + +import { + createSharedStatelessQuery, + createClientStatelessQuery, + createClientStatefulQuery, + type StatefulQuery, +} from "./query.js"; + +function createTempBuildDir(context: TestContext) { + const tmpPath = fs.mkdtempSync(path.join(os.tmpdir(), "cmake-api-test-")); + + context.after(() => { + fs.rmSync(tmpPath, { recursive: true, force: true }); + }); + + return tmpPath; +} + +describe("createSharedStatelessQuery", () => { + it("creates a shared stateless query file", async function (context) { + const buildPath = createTempBuildDir(context); + + await createSharedStatelessQuery(buildPath, "codemodel", "2"); + + const queryPath = path.join(buildPath, ".cmake/api/v1/query/codemodel-v2"); + assert(fs.existsSync(queryPath), "Query file should exist"); + + const content = fs.readFileSync(queryPath, "utf-8"); + assert.strictEqual(content, "", "Query file should be empty"); + }); + + it("creates directory structure recursively", async function (context) { + const buildPath = createTempBuildDir(context); + + await createSharedStatelessQuery(buildPath, "cache", "2"); + + const queryDir = path.join(buildPath, ".cmake/api/v1/query"); + assert(fs.existsSync(queryDir), "Query directory should exist"); + + const queryPath = path.join(queryDir, "cache-v2"); + assert(fs.existsSync(queryPath), "Query file should exist"); + }); + + it("supports all object kinds", async function (context) { + const buildPath = createTempBuildDir(context); + const kinds = [ + "codemodel", + "configureLog", + "cache", + "cmakeFiles", + "toolchains", + ] as const; + + for (const kind of kinds) { + await createSharedStatelessQuery(buildPath, kind, "1"); + + const queryPath = path.join(buildPath, `.cmake/api/v1/query/${kind}-v1`); + assert(fs.existsSync(queryPath), `Query file for ${kind} should exist`); + } + }); +}); + +describe("createClientStatelessQuery", () => { + it("creates a client stateless query file", async function (context) { + const buildPath = createTempBuildDir(context); + + await createClientStatelessQuery(buildPath, "my-client", "codemodel", "2"); + + const queryPath = path.join( + buildPath, + ".cmake/api/v1/query/client-my-client/codemodel-v2", + ); + assert(fs.existsSync(queryPath), "Client query file should exist"); + + const content = fs.readFileSync(queryPath, "utf-8"); + assert.strictEqual(content, "", "Client query file should be empty"); + }); + + it("creates client directory structure", async function (context) { + const buildPath = createTempBuildDir(context); + + await createClientStatelessQuery(buildPath, "test-client", "cache", "2"); + + const clientDir = path.join( + buildPath, + ".cmake/api/v1/query/client-test-client", + ); + assert(fs.existsSync(clientDir), "Client directory should exist"); + + const queryPath = path.join(clientDir, "cache-v2"); + assert(fs.existsSync(queryPath), "Client query file should exist"); + }); + + it("supports multiple clients", async function (context) { + const buildPath = createTempBuildDir(context); + + await createClientStatelessQuery(buildPath, "client-a", "codemodel", "2"); + await createClientStatelessQuery(buildPath, "client-b", "cache", "2"); + + const clientAPath = path.join( + buildPath, + ".cmake/api/v1/query/client-client-a/codemodel-v2", + ); + const clientBPath = path.join( + buildPath, + ".cmake/api/v1/query/client-client-b/cache-v2", + ); + + assert(fs.existsSync(clientAPath), "Client A query should exist"); + assert(fs.existsSync(clientBPath), "Client B query should exist"); + }); +}); + +describe("createClientStatefulQuery", () => { + it("creates a client stateful query file with simple request", async function (context) { + const buildPath = createTempBuildDir(context); + + const query: StatefulQuery = { + requests: [{ kind: "codemodel", version: 2 }], + }; + + await createClientStatefulQuery(buildPath, "my-client", query); + + const queryPath = path.join( + buildPath, + ".cmake/api/v1/query/client-my-client/query.json", + ); + assert(fs.existsSync(queryPath), "Stateful query file should exist"); + + const content = fs.readFileSync(queryPath, "utf-8"); + const parsed = JSON.parse(content) as StatefulQuery; + + assert.deepStrictEqual(parsed, query, "Parsed query should match input"); + }); + + it("creates stateful query with complex version specifications", async function (context) { + const buildPath = createTempBuildDir(context); + + const query: StatefulQuery = { + requests: [ + { + kind: "codemodel", + version: [2, { major: 1, minor: 5 }], + }, + { + kind: "cache", + version: { major: 2, minor: 0 }, + }, + { + kind: "toolchains", + }, + ], + client: { name: "test-tool", version: "1.0.0" }, + }; + + await createClientStatefulQuery(buildPath, "advanced-client", query); + + const queryPath = path.join( + buildPath, + ".cmake/api/v1/query/client-advanced-client/query.json", + ); + const content = fs.readFileSync(queryPath, "utf-8"); + const parsed = JSON.parse(content) as StatefulQuery; + + assert.deepStrictEqual(parsed, query, "Complex query should be preserved"); + }); + + it("creates well-formatted JSON", async function (context) { + const buildPath = createTempBuildDir(context); + + const query: StatefulQuery = { + requests: [ + { kind: "codemodel", version: 2 }, + { kind: "cache", version: 2 }, + ], + }; + + await createClientStatefulQuery(buildPath, "format-test", query); + + const queryPath = path.join( + buildPath, + ".cmake/api/v1/query/client-format-test/query.json", + ); + const content = fs.readFileSync(queryPath, "utf-8"); + + // Should be pretty-printed with 2-space indentation + assert(content.includes(" "), "JSON should be indented"); + assert(content.includes("\n"), "JSON should have newlines"); + + // Should be valid JSON + assert.doesNotThrow(() => JSON.parse(content), "Should be valid JSON"); + }); + + it("supports client-specific data in requests", async function (context) { + const buildPath = createTempBuildDir(context); + + const query: StatefulQuery = { + requests: [ + { + kind: "codemodel", + version: 2, + client: { requestId: "req-001", priority: "high" }, + }, + ], + client: { sessionId: "session-123" }, + }; + + await createClientStatefulQuery(buildPath, "custom-client", query); + + const queryPath = path.join( + buildPath, + ".cmake/api/v1/query/client-custom-client/query.json", + ); + const content = fs.readFileSync(queryPath, "utf-8"); + const parsed = JSON.parse(content) as StatefulQuery; + + assert.deepStrictEqual(parsed.requests[0]?.client, { + requestId: "req-001", + priority: "high", + }); + assert.deepStrictEqual(parsed.client, { sessionId: "session-123" }); + }); +}); diff --git a/packages/cmake-file-api/src/query.ts b/packages/cmake-file-api/src/query.ts new file mode 100644 index 00000000..ccb3a2d8 --- /dev/null +++ b/packages/cmake-file-api/src/query.ts @@ -0,0 +1,93 @@ +import fs from "node:fs"; +import path from "node:path"; + +/** + * Creates a shared stateless query file for the specified object kind and major version. + * These are stateless shared queries not owned by any specific client. + * + * @param buildPath Path to the build directory + * @param kind Object kind to query for + * @param majorVersion Major version number as string + */ +export async function createSharedStatelessQuery( + buildPath: string, + kind: "codemodel" | "configureLog" | "cache" | "cmakeFiles" | "toolchains", + majorVersion: string, +) { + const queryPath = path.join( + buildPath, + `.cmake/api/v1/query/${kind}-v${majorVersion}`, + ); + await fs.promises.mkdir(path.dirname(queryPath), { recursive: true }); + await fs.promises.writeFile(queryPath, ""); +} + +/** + * Creates a client stateless query file for the specified client, object kind and major version. + * These are stateless queries owned by the specified client. + * + * @param buildPath Path to the build directory + * @param clientName Unique identifier for the client + * @param kind Object kind to query for + * @param majorVersion Major version number as string + */ +export async function createClientStatelessQuery( + buildPath: string, + clientName: string, + kind: "codemodel" | "configureLog" | "cache" | "cmakeFiles" | "toolchains", + majorVersion: string, +) { + const queryPath = path.join( + buildPath, + `.cmake/api/v1/query/client-${clientName}/${kind}-v${majorVersion}`, + ); + await fs.promises.mkdir(path.dirname(queryPath), { recursive: true }); + await fs.promises.writeFile(queryPath, ""); +} + +/** + * Version specification for stateful queries + */ +export type VersionSpec = + | number // major version only + | { major: number; minor?: number } // major with optional minor + | (number | { major: number; minor?: number })[]; // array of version specs + +/** + * Request specification for stateful queries + */ +export interface QueryRequest { + kind: "codemodel" | "configureLog" | "cache" | "cmakeFiles" | "toolchains"; + version?: VersionSpec; + client?: unknown; // Reserved for client use +} + +/** + * Stateful query specification + */ +export interface StatefulQuery { + requests: QueryRequest[]; + client?: unknown; // Reserved for client use +} + +/** + * Creates a client stateful query file (query.json) for the specified client. + * These are stateful queries owned by the specified client that can request + * specific versions and get only the most recent version recognized by CMake. + * + * @param buildPath Path to the build directory + * @param clientName Unique identifier for the client + * @param query Stateful query specification + */ +export async function createClientStatefulQuery( + buildPath: string, + clientName: string, + query: StatefulQuery, +) { + const queryPath = path.join( + buildPath, + `.cmake/api/v1/query/client-${clientName}/query.json`, + ); + await fs.promises.mkdir(path.dirname(queryPath), { recursive: true }); + await fs.promises.writeFile(queryPath, JSON.stringify(query, null, 2)); +} diff --git a/packages/cmake-file-api/src/reply.test.ts b/packages/cmake-file-api/src/reply.test.ts new file mode 100644 index 00000000..87c1a7bd --- /dev/null +++ b/packages/cmake-file-api/src/reply.test.ts @@ -0,0 +1,1075 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, it, type TestContext } from "node:test"; + +import { + findCurrentReplyIndexPath, + readReplyIndex, + readCodemodel, + readCurrentSharedCodemodel, + readTarget, + readCache, + readCmakeFiles, + readToolchains, + readConfigureLog, + isReplyErrorIndexPath, + readReplyErrorIndex, +} from "./reply.js"; + +function createTempDir(context: TestContext, prefix = "test-") { + const tmpPath = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + + context.after(() => { + fs.rmSync(tmpPath, { recursive: true, force: true }); + }); + + return tmpPath; +} + +function createMockReplyDirectory( + context: TestContext, + replyFiles: [string, Record][], +) { + const tmpPath = createTempDir(context); + + for (const [fileName, content] of replyFiles) { + const filePath = path.join(tmpPath, fileName); + fs.writeFileSync(filePath, JSON.stringify(content), { + encoding: "utf-8", + }); + } + + return tmpPath; +} + +describe("findCurrentReplyIndexPath", () => { + it("returns the correct path when only index files are present", async function (context) { + const tmpPath = createMockReplyDirectory(context, [ + ["index-a.json", {}], + ["index-b.json", {}], + ]); + const result = await findCurrentReplyIndexPath(tmpPath); + assert.strictEqual(result, path.join(tmpPath, "index-b.json")); + }); + + it("returns the correct path when only error files are present", async function (context) { + const tmpPath = createMockReplyDirectory(context, [ + ["error-a.json", {}], + ["error-b.json", {}], + ]); + const result = await findCurrentReplyIndexPath(tmpPath); + assert.strictEqual(result, path.join(tmpPath, "error-b.json")); + }); + + it("returns the correct path when both index and error files are present", async function (context) { + const tmpPath = createMockReplyDirectory(context, [ + ["index-a.json", {}], + ["error-b.json", {}], + ]); + const result = await findCurrentReplyIndexPath(tmpPath); + assert.strictEqual(result, path.join(tmpPath, "error-b.json")); + }); + + it("returns the correct path when both index and error files are present (reversed)", async function (context) { + const tmpPath = createMockReplyDirectory(context, [ + ["error-a.json", {}], + ["index-b.json", {}], + ]); + const result = await findCurrentReplyIndexPath(tmpPath); + assert.strictEqual(result, path.join(tmpPath, "index-b.json")); + }); +}); + +describe("readIndex", () => { + it("reads a well-formed index file with complete structure", async function (context) { + const mockIndex = { + cmake: { + version: { + major: 3, + minor: 26, + patch: 0, + suffix: "", + string: "3.26.0", + isDirty: false, + }, + paths: { + cmake: "/usr/bin/cmake", + ctest: "/usr/bin/ctest", + cpack: "/usr/bin/cpack", + root: "/usr/share/cmake", + }, + generator: { + multiConfig: false, + name: "Unix Makefiles", + // Note: platform is optional according to docs - omitted here like in the example + }, + }, + objects: [ + { + kind: "codemodel", + version: { major: 2, minor: 0 }, + jsonFile: "codemodel-v2-12345.json", + }, + { + kind: "cache", + version: { major: 2, minor: 0 }, + jsonFile: "cache-v2-67890.json", + }, + ], + reply: { + "codemodel-v2": { + kind: "codemodel", + version: { major: 2, minor: 0 }, + jsonFile: "codemodel-v2-12345.json", + }, + "cache-v2": { + kind: "cache", + version: { major: 2, minor: 0 }, + jsonFile: "cache-v2-67890.json", + }, + "unknown-kind-v1": { + error: "unknown query file", + }, + "client-test-client": { + "codemodel-v2": { + kind: "codemodel", + version: { major: 2, minor: 0 }, + jsonFile: "codemodel-v2-12345.json", + }, + "unknown-v1": { + error: "unknown query file", + }, + }, + }, + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["index-a.json", mockIndex], + ]); + const result = await readReplyIndex(path.join(tmpPath, "index-a.json")); + + // Verify the entire structure matches our mock data + assert.deepStrictEqual(result, mockIndex); + }); + + it("reads index file with generator platform", async function (context) { + const mockIndexWithPlatform = { + cmake: { + version: { + major: 3, + minor: 26, + patch: 0, + suffix: "", + string: "3.26.0", + isDirty: false, + }, + paths: { + cmake: "/usr/bin/cmake", + ctest: "/usr/bin/ctest", + cpack: "/usr/bin/cpack", + root: "/usr/share/cmake", + }, + generator: { + multiConfig: true, + name: "Visual Studio 16 2019", + platform: "x64", // Present when generator supports CMAKE_GENERATOR_PLATFORM + }, + }, + objects: [], + reply: {}, + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["index-b.json", mockIndexWithPlatform], + ]); + const result = await readReplyIndex(path.join(tmpPath, "index-b.json")); + + // Verify the entire structure matches our mock data + assert.deepStrictEqual(result, mockIndexWithPlatform); + }); +}); + +describe("readCodeModel", () => { + it("reads a well-formed codemodel file", async function (context) { + const mockCodemodel = { + kind: "codemodel", + version: { major: 2, minor: 3 }, + paths: { + source: "/path/to/source", + build: "/path/to/build", + }, + configurations: [ + { + name: "Debug", + directories: [ + { + source: ".", + build: ".", + childIndexes: [], + projectIndex: 0, + targetIndexes: [0], + hasInstallRule: true, + minimumCMakeVersion: { + string: "3.14", + }, + jsonFile: "directory-debug.json", + }, + ], + projects: [ + { + name: "MyProject", + directoryIndexes: [0], + targetIndexes: [0], + }, + ], + targets: [ + { + name: "MyExecutable", + id: "MyExecutable::@6890a9b7b1a1a2e4d6b9", + directoryIndex: 0, + projectIndex: 0, + jsonFile: "target-MyExecutable.json", + }, + ], + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["codemodel-v2-12345.json", mockCodemodel], + ]); + const result = await readCodemodel( + path.join(tmpPath, "codemodel-v2-12345.json"), + ); + + // Verify the entire structure matches our mock data + assert.deepStrictEqual(result, mockCodemodel); + }); +}); + +describe("readTarget", () => { + // Base objects for reusable test data + const baseTarget = { + name: "MyTarget", + id: "MyTarget::@6890a9b7b1a1a2e4d6b9", + type: "EXECUTABLE" as const, + paths: { + source: ".", + build: ".", + }, + }; + + const baseCompileGroup = { + sourceIndexes: [0], + language: "CXX", + includes: [ + { + path: "/usr/include", + isSystem: true, + backtrace: 1, + }, + ], + defines: [ + { + define: "NDEBUG", + backtrace: 2, + }, + ], + }; + + const baseSource = { + path: "main.cpp", + compileGroupIndex: 0, + isGenerated: false, + backtrace: 1, + }; + + it("validates TargetV2_0 schema (base version)", async function (context) { + const targetV2_0 = { + ...baseTarget, + sources: [baseSource], + compileGroups: [baseCompileGroup], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["target-v2_0.json", targetV2_0], + ]); + const result = await readTarget( + path.join(tmpPath, "target-v2_0.json"), + "2.0", + ); + + assert.deepStrictEqual(result, targetV2_0); + }); + + it("validates TargetV2_1 schema (added precompileHeaders)", async function (context) { + const targetV2_1 = { + ...baseTarget, + sources: [baseSource], + compileGroups: [ + { + ...baseCompileGroup, + precompileHeaders: [ + { + header: "pch.h", + backtrace: 3, + }, + ], + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["target-v2_1.json", targetV2_1], + ]); + const result = await readTarget( + path.join(tmpPath, "target-v2_1.json"), + "2.1", + ); + + assert.deepStrictEqual(result, targetV2_1); + }); + + it("validates TargetV2_2 schema (added languageStandard)", async function (context) { + const targetV2_2 = { + ...baseTarget, + sources: [baseSource], + compileGroups: [ + { + ...baseCompileGroup, + precompileHeaders: [ + { + header: "pch.h", + backtrace: 3, + }, + ], + languageStandard: { + backtraces: [4], + standard: "17", + }, + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["target-v2_2.json", targetV2_2], + ]); + const result = await readTarget( + path.join(tmpPath, "target-v2_2.json"), + "2.2", + ); + + assert.deepStrictEqual(result, targetV2_2); + }); + + it("validates TargetV2_5 schema (added fileSets and fileSetIndex)", async function (context) { + const targetV2_5 = { + ...baseTarget, + fileSets: [ + { + name: "HEADERS", + type: "HEADERS", + visibility: "PUBLIC" as const, + baseDirectories: ["."], + }, + ], + sources: [ + { + ...baseSource, + fileSetIndex: 0, + }, + ], + compileGroups: [ + { + ...baseCompileGroup, + precompileHeaders: [ + { + header: "pch.h", + backtrace: 3, + }, + ], + languageStandard: { + backtraces: [4], + standard: "17", + }, + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["target-v2_5.json", targetV2_5], + ]); + const result = await readTarget( + path.join(tmpPath, "target-v2_5.json"), + "2.5", + ); + + assert.deepStrictEqual(result, targetV2_5); + }); + + it("validates TargetV2_6 schema (added frameworks)", async function (context) { + const targetV2_6 = { + ...baseTarget, + fileSets: [ + { + name: "HEADERS", + type: "HEADERS", + visibility: "PUBLIC" as const, + baseDirectories: ["."], + }, + ], + sources: [ + { + ...baseSource, + fileSetIndex: 0, + }, + ], + compileGroups: [ + { + ...baseCompileGroup, + precompileHeaders: [ + { + header: "pch.h", + backtrace: 3, + }, + ], + languageStandard: { + backtraces: [4], + standard: "17", + }, + frameworks: [ + { + path: "/System/Library/Frameworks/Foundation.framework", + isSystem: true, + backtrace: 5, + }, + ], + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["target-v2_6.json", targetV2_6], + ]); + const result = await readTarget( + path.join(tmpPath, "target-v2_6.json"), + "2.6", + ); + + assert.deepStrictEqual(result, targetV2_6); + }); + + it("validates TargetV2_7 schema (added launchers)", async function (context) { + const targetV2_7 = { + ...baseTarget, + launchers: [ + { + command: "/usr/bin/gdb", + arguments: ["--args"], + type: "test" as const, + }, + ], + fileSets: [ + { + name: "HEADERS", + type: "HEADERS", + visibility: "PUBLIC" as const, + baseDirectories: ["."], + }, + ], + sources: [ + { + ...baseSource, + fileSetIndex: 0, + }, + ], + compileGroups: [ + { + ...baseCompileGroup, + precompileHeaders: [ + { + header: "pch.h", + backtrace: 3, + }, + ], + languageStandard: { + backtraces: [4], + standard: "17", + }, + frameworks: [ + { + path: "/System/Library/Frameworks/Foundation.framework", + isSystem: true, + backtrace: 5, + }, + ], + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["target-v2_7.json", targetV2_7], + ]); + const result = await readTarget( + path.join(tmpPath, "target-v2_7.json"), + "2.7", + ); + + assert.deepStrictEqual(result, targetV2_7); + }); + + it("validates TargetV2_8 schema (added debugger)", async function (context) { + const targetV2_8 = { + ...baseTarget, + debugger: { + workingDirectory: "/path/to/debug", + }, + launchers: [ + { + command: "/usr/bin/gdb", + arguments: ["--args"], + type: "test" as const, + }, + ], + fileSets: [ + { + name: "HEADERS", + type: "HEADERS", + visibility: "PUBLIC" as const, + baseDirectories: ["."], + }, + ], + sources: [ + { + ...baseSource, + fileSetIndex: 0, + }, + ], + compileGroups: [ + { + ...baseCompileGroup, + precompileHeaders: [ + { + header: "pch.h", + backtrace: 3, + }, + ], + languageStandard: { + backtraces: [4], + standard: "17", + }, + frameworks: [ + { + path: "/System/Library/Frameworks/Foundation.framework", + isSystem: true, + backtrace: 5, + }, + ], + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["target-v2_8.json", targetV2_8], + ]); + const result = await readTarget( + path.join(tmpPath, "target-v2_8.json"), + "2.8", + ); + + assert.deepStrictEqual(result, targetV2_8); + }); +}); + +describe("readCache", () => { + it("reads a well-formed cache file", async function (context) { + const mockCache = { + kind: "cache", + version: { major: 2, minor: 0 }, + entries: [ + { + name: "BUILD_SHARED_LIBS", + value: "ON", + type: "BOOL", + properties: [ + { + name: "HELPSTRING", + value: "Build shared libraries", + }, + ], + }, + { + name: "CMAKE_GENERATOR", + value: "Unix Makefiles", + type: "INTERNAL", + properties: [ + { + name: "HELPSTRING", + value: "Name of generator.", + }, + ], + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["cache-v2.json", mockCache], + ]); + const result = await readCache(path.join(tmpPath, "cache-v2.json"), "2.0"); + + // Verify the entire structure matches our mock data + assert.deepStrictEqual(result, mockCache); + }); +}); + +describe("readCmakeFiles", () => { + // Base objects for reusable test data + const baseCmakeFiles = { + kind: "cmakeFiles" as const, + paths: { + build: "/path/to/top-level-build-dir", + source: "/path/to/top-level-source-dir", + }, + inputs: [ + { + path: "CMakeLists.txt", + }, + { + isExternal: true, + path: "/path/to/external/third-party/module.cmake", + }, + ], + }; + + it("validates CmakeFilesV1_0 schema (base version)", async function (context) { + const cmakeFilesV1_0 = { + ...baseCmakeFiles, + version: { major: 1, minor: 0 }, + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["cmakeFiles-v1_0.json", cmakeFilesV1_0], + ]); + const result = await readCmakeFiles( + path.join(tmpPath, "cmakeFiles-v1_0.json"), + "1.0", + ); + + assert.deepStrictEqual(result, cmakeFilesV1_0); + }); + + it("validates CmakeFilesV1_1 schema (added globsDependent)", async function (context) { + const cmakeFilesV1_1 = { + ...baseCmakeFiles, + version: { major: 1, minor: 1 }, + globsDependent: [ + { + expression: "src/*.cxx", + recurse: true, + paths: ["src/foo.cxx", "src/bar.cxx"], + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["cmakeFiles-v1_1.json", cmakeFilesV1_1], + ]); + const result = await readCmakeFiles( + path.join(tmpPath, "cmakeFiles-v1_1.json"), + "1.1", + ); + + assert.deepStrictEqual(result, cmakeFilesV1_1); + }); +}); + +describe("readToolchains", () => { + it("reads a well-formed toolchains file", async function (context) { + const mockToolchains = { + kind: "toolchains", + version: { major: 1, minor: 0 }, + toolchains: [ + { + language: "C", + compiler: { + path: "/usr/bin/cc", + id: "GNU", + version: "9.3.0", + implicit: { + includeDirectories: [ + "/usr/lib/gcc/x86_64-linux-gnu/9/include", + "/usr/local/include", + "/usr/include/x86_64-linux-gnu", + "/usr/include", + ], + linkDirectories: [ + "/usr/lib/gcc/x86_64-linux-gnu/9", + "/usr/lib/x86_64-linux-gnu", + "/usr/lib", + "/lib/x86_64-linux-gnu", + "/lib", + ], + linkFrameworkDirectories: [], + linkLibraries: ["gcc", "gcc_s", "c", "gcc", "gcc_s"], + }, + }, + sourceFileExtensions: ["c", "m"], + }, + { + language: "CXX", + compiler: { + path: "/usr/bin/c++", + id: "GNU", + version: "9.3.0", + implicit: { + includeDirectories: [ + "/usr/include/c++/9", + "/usr/include/x86_64-linux-gnu/c++/9", + "/usr/include/c++/9/backward", + "/usr/lib/gcc/x86_64-linux-gnu/9/include", + "/usr/local/include", + "/usr/include/x86_64-linux-gnu", + "/usr/include", + ], + linkDirectories: [ + "/usr/lib/gcc/x86_64-linux-gnu/9", + "/usr/lib/x86_64-linux-gnu", + "/usr/lib", + "/lib/x86_64-linux-gnu", + "/lib", + ], + linkFrameworkDirectories: [], + linkLibraries: [ + "stdc++", + "m", + "gcc_s", + "gcc", + "c", + "gcc_s", + "gcc", + ], + }, + }, + sourceFileExtensions: [ + "C", + "M", + "c++", + "cc", + "cpp", + "cxx", + "mm", + "CPP", + ], + }, + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["toolchains-v1.json", mockToolchains], + ]); + const result = await readToolchains( + path.join(tmpPath, "toolchains-v1.json"), + "1.0", + ); + + // Verify the entire structure matches our mock data + assert.deepStrictEqual(result, mockToolchains); + }); +}); + +describe("readConfigureLog", () => { + it("reads a well-formed configureLog file", async function (context) { + const mockConfigureLog = { + kind: "configureLog", + version: { major: 1, minor: 0 }, + path: "/path/to/build/dir/CMakeFiles/CMakeConfigureLog.yaml", + eventKindNames: [ + "message", + "try_compile-v1", + "try_run-v1", + "detect-c_compiler-v1", + "detect-cxx_compiler-v1", + ], + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["configureLog-v1.json", mockConfigureLog], + ]); + const result = await readConfigureLog( + path.join(tmpPath, "configureLog-v1.json"), + "1.0", + ); + assert.deepStrictEqual(result, mockConfigureLog); + }); +}); + +describe("Reply Error Index Support", () => { + describe("isReplyErrorIndexPath", () => { + it("identifies reply error index files correctly", function () { + assert.strictEqual( + isReplyErrorIndexPath("/path/to/error-12345.json"), + true, + ); + assert.strictEqual( + isReplyErrorIndexPath("/path/to/index-12345.json"), + false, + ); + assert.strictEqual(isReplyErrorIndexPath("error-abc.json"), true); + assert.strictEqual(isReplyErrorIndexPath("index-abc.json"), false); + }); + }); + + describe("readReplyErrorIndex", () => { + it("reads a well-formed reply error index file", async function (context) { + const mockReplyErrorIndex = { + cmake: { + version: { + major: 3, + minor: 26, + patch: 0, + suffix: "", + string: "3.26.0", + isDirty: false, + }, + paths: { + cmake: "/usr/bin/cmake", + ctest: "/usr/bin/ctest", + cpack: "/usr/bin/cpack", + root: "/usr/share/cmake", + }, + generator: { + multiConfig: false, + name: "Unix Makefiles", + }, + }, + objects: [ + { + kind: "configureLog", + version: { major: 1, minor: 0 }, + jsonFile: "configureLog-v1-12345.json", + }, + ], + reply: { + "configureLog-v1": { + kind: "configureLog", + version: { major: 1, minor: 0 }, + jsonFile: "configureLog-v1-12345.json", + }, + "codemodel-v2": { + error: "CMake failed to generate build system", + }, + "cache-v2": { + error: "CMake failed to generate build system", + }, + }, + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["error-12345.json", mockReplyErrorIndex], + ]); + const result = await readReplyErrorIndex( + path.join(tmpPath, "error-12345.json"), + ); + + assert.deepStrictEqual(result, mockReplyErrorIndex); + }); + + it("rejects non-reply error index files", async function (context) { + const tmpPath = createMockReplyDirectory(context, [ + ["index-12345.json", {}], + ]); + + await assert.rejects( + () => readReplyErrorIndex(path.join(tmpPath, "index-12345.json")), + /Expected a path to an error-\*\.json file/, + ); + }); + + it("rejects reply error index with unsupported object kind in objects array", async function (context) { + const invalidReplyErrorIndex = { + cmake: { + version: { + major: 3, + minor: 26, + patch: 0, + suffix: "", + string: "3.26.0", + isDirty: false, + }, + paths: { + cmake: "/usr/bin/cmake", + ctest: "/usr/bin/ctest", + cpack: "/usr/bin/cpack", + root: "/usr/share/cmake", + }, + generator: { + multiConfig: false, + name: "Unix Makefiles", + }, + }, + objects: [ + { + kind: "codemodel", // Invalid: only configureLog is supported + version: { major: 2, minor: 0 }, + jsonFile: "codemodel-v2-12345.json", + }, + ], + reply: {}, + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["error-12345.json", invalidReplyErrorIndex], + ]); + + await assert.rejects( + () => readReplyErrorIndex(path.join(tmpPath, "error-12345.json")), + (error: Error) => { + return error.message.includes( + 'Invalid input: expected \\"configureLog\\"', + ); + }, + ); + }); + + it("rejects reply error index with unsupported object kind in client stateful query responses", async function (context) { + const invalidReplyErrorIndex = { + cmake: { + version: { + major: 3, + minor: 26, + patch: 0, + suffix: "", + string: "3.26.0", + isDirty: false, + }, + paths: { + cmake: "/usr/bin/cmake", + ctest: "/usr/bin/ctest", + cpack: "/usr/bin/cpack", + root: "/usr/share/cmake", + }, + generator: { + multiConfig: false, + name: "Unix Makefiles", + }, + }, + objects: [], + reply: { + "client-test": { + "query.json": { + client: {}, + requests: [ + { + kind: "codemodel", + version: { major: 2, minor: 0 }, + }, + ], + responses: [ + { + kind: "codemodel", // Invalid: only configureLog is supported in error index + version: { major: 2, minor: 0 }, + jsonFile: "codemodel-v2-12345.json", + }, + ], + }, + }, + }, + }; + + const tmpPath = createMockReplyDirectory(context, [ + ["error-12345.json", invalidReplyErrorIndex], + ]); + + await assert.rejects( + () => readReplyErrorIndex(path.join(tmpPath, "error-12345.json")), + (error: Error) => { + return error.message.includes( + 'Invalid input: expected \\"configureLog\\"', + ); + }, + ); + }); + }); + + describe("readCurrentCodemodel with error index handling", () => { + it("throws descriptive error when current index is a reply error index", async function (context) { + const mockReplyErrorIndex = { + cmake: { + version: { + major: 3, + minor: 26, + patch: 0, + suffix: "", + string: "3.26.0", + isDirty: false, + }, + paths: { + cmake: "/usr/bin/cmake", + ctest: "/usr/bin/ctest", + cpack: "/usr/bin/cpack", + root: "/usr/share/cmake", + }, + generator: { multiConfig: false, name: "Unix Makefiles" }, + }, + objects: [], + reply: { + "codemodel-v2": { error: "Build system generation failed" }, + }, + }; + + const buildPath = createTempDir(context, "build-test-"); + const replyPath = path.join(buildPath, ".cmake/api/v1/reply"); + await fs.promises.mkdir(replyPath, { recursive: true }); + + fs.writeFileSync( + path.join(replyPath, "error-12345.json"), + JSON.stringify(mockReplyErrorIndex), + ); + + await assert.rejects( + () => readCurrentSharedCodemodel(buildPath), + /CMake failed to generate build system\. Error in codemodel: Build system generation failed/, + ); + }); + + it("throws generic error when reply error index has no codemodel entry", async function (context) { + const mockReplyErrorIndex = { + cmake: { + version: { + major: 3, + minor: 26, + patch: 0, + suffix: "", + string: "3.26.0", + isDirty: false, + }, + paths: { + cmake: "/usr/bin/cmake", + ctest: "/usr/bin/ctest", + cpack: "/usr/bin/cpack", + root: "/usr/share/cmake", + }, + generator: { multiConfig: false, name: "Unix Makefiles" }, + }, + objects: [], + reply: {}, + }; + + const buildPath = createTempDir(context, "build-test-"); + const replyPath = path.join(buildPath, ".cmake/api/v1/reply"); + await fs.promises.mkdir(replyPath, { recursive: true }); + + fs.writeFileSync( + path.join(replyPath, "error-12345.json"), + JSON.stringify(mockReplyErrorIndex), + ); + + await assert.rejects( + () => readCurrentSharedCodemodel(buildPath), + /CMake failed to generate build system\. No codemodel available in error index\./, + ); + }); + }); +}); diff --git a/packages/cmake-file-api/src/reply.ts b/packages/cmake-file-api/src/reply.ts new file mode 100644 index 00000000..0a8a1a02 --- /dev/null +++ b/packages/cmake-file-api/src/reply.ts @@ -0,0 +1,240 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; + +import * as z from "zod"; + +import * as schemas from "./schemas.js"; + +/** + * As per https://cmake.org/cmake/help/latest/manual/cmake-file-api.7.html#v1-reply-error-index + */ +export async function findCurrentReplyIndexPath(replyPath: string) { + // If multiple index-*.json and/or error-*.json files are present, + // the one with the largest name in lexicographic order, + // excluding the index- or error- prefix, is the current index. + + const fileNames = ( + await Promise.all([ + Array.fromAsync( + fs.promises.glob("error-*.json", { + withFileTypes: false, + cwd: replyPath, + }), + ), + Array.fromAsync( + fs.promises.glob("index-*.json", { + withFileTypes: false, + cwd: replyPath, + }), + ), + ]) + ).flat(); + + const [currentIndexFileName] = fileNames + .sort((a, b) => { + const strippedA = a.replace(/^(error|index)-/, ""); + const strippedB = b.replace(/^(error|index)-/, ""); + return strippedA.localeCompare(strippedB); + }) + .reverse(); + + assert( + currentIndexFileName, + `No index-*.json or error-*.json files found in ${replyPath}`, + ); + + return path.join(replyPath, currentIndexFileName); +} + +export async function readReplyIndex(filePath: string) { + assert( + path.basename(filePath).startsWith("index-") && + path.extname(filePath) === ".json", + "Expected a path to a index-*.json file", + ); + const content = await fs.promises.readFile(filePath, "utf-8"); + return schemas.IndexReplyV1.parse(JSON.parse(content)); +} + +export function isReplyErrorIndexPath(filePath: string): boolean { + return ( + path.basename(filePath).startsWith("error-") && + path.extname(filePath) === ".json" + ); +} + +export async function readReplyErrorIndex(filePath: string) { + assert( + isReplyErrorIndexPath(filePath), + "Expected a path to an error-*.json file", + ); + const content = await fs.promises.readFile(filePath, "utf-8"); + return schemas.ReplyErrorIndex.parse(JSON.parse(content)); +} + +export async function readCodemodel(filePath: string) { + assert( + path.basename(filePath).startsWith("codemodel-") && + path.extname(filePath) === ".json", + "Expected a path to a codemodel-*.json file", + ); + const content = await fs.promises.readFile(filePath, "utf-8"); + return schemas.CodemodelV2.parse(JSON.parse(content)); +} + +/** + * Call {@link createSharedStatelessQuery} to create a shared codemodel query before reading the current shared codemodel. + */ +export async function readCurrentSharedCodemodel(buildPath: string) { + const replyPath = path.join(buildPath, `.cmake/api/v1/reply`); + const replyIndexPath = await findCurrentReplyIndexPath(replyPath); + + // Check if this is an error index - they don't contain codemodel data + if (isReplyErrorIndexPath(replyIndexPath)) { + const errorIndex = await readReplyErrorIndex(replyIndexPath); + const { reply } = errorIndex; + const codemodelFile = reply["codemodel-v2"]; + + if ( + codemodelFile && + "error" in codemodelFile && + typeof codemodelFile.error === "string" + ) { + throw new Error( + `CMake failed to generate build system. Error in codemodel: ${codemodelFile.error}`, + ); + } + + throw new Error( + "CMake failed to generate build system. No codemodel available in error index.", + ); + } + + const index = await readReplyIndex(replyIndexPath); + const { reply } = index; + const { "codemodel-v2": codemodelFile } = reply; + assert( + codemodelFile, + "Expected a codemodel-v2 reply file - was a query created?", + ); + if ("error" in codemodelFile && typeof codemodelFile.error === "string") { + throw new Error( + `Error reading codemodel-v2 reply file: ${codemodelFile.error}`, + ); + } + + // Use ReplyFileReference schema to validate and parse the codemodel file + const { kind, jsonFile } = schemas.ReplyFileReferenceV1.parse(codemodelFile); + assert(kind === "codemodel", "Expected a codemodel file reference"); + + const codemodelPath = path.join(buildPath, `.cmake/api/v1/reply`, jsonFile); + return readCodemodel(codemodelPath); +} + +export async function readCurrentTargets( + buildPath: string, + configuration: string, +) { + const { configurations } = await readCurrentSharedCodemodel(buildPath); + const relevantConfig = + configurations.length === 1 + ? configurations[0] + : configurations.find((config) => config.name === configuration); + assert( + relevantConfig, + `Unable to locate "${configuration}" configuration found`, + ); + return relevantConfig.targets; +} + +export async function readTarget( + targetPath: string, + version: keyof typeof schemas.targetSchemaPerVersion, +): Promise> { + assert( + path.basename(targetPath).startsWith("target-") && + path.extname(targetPath) === ".json", + "Expected a path to a target-*.json file", + ); + const content = await fs.promises.readFile(targetPath, "utf-8"); + return schemas.targetSchemaPerVersion[version].parse(JSON.parse(content)); +} + +export async function readCurrentTargetsDeep( + buildPath: string, + configuration: string, + version: keyof typeof schemas.targetSchemaPerVersion, +): Promise[]> { + const targets = await readCurrentTargets(buildPath, configuration); + return Promise.all( + targets.map((target) => { + const targetPath = path.join( + buildPath, + `.cmake/api/v1/reply`, + target.jsonFile, + ); + return readTarget(targetPath, version); + }), + ); +} + +export async function readCache( + cachePath: string, + version: keyof typeof schemas.cacheSchemaPerVersion, +): Promise> { + assert( + path.basename(cachePath).startsWith("cache-") && + path.extname(cachePath) === ".json", + "Expected a path to a cache-*.json file", + ); + const content = await fs.promises.readFile(cachePath, "utf-8"); + return schemas.cacheSchemaPerVersion[version].parse(JSON.parse(content)); +} + +export async function readCmakeFiles( + cmakeFilesPath: string, + version: keyof typeof schemas.cmakeFilesSchemaPerVersion, +): Promise< + z.infer<(typeof schemas.cmakeFilesSchemaPerVersion)[typeof version]> +> { + assert( + path.basename(cmakeFilesPath).startsWith("cmakeFiles-") && + path.extname(cmakeFilesPath) === ".json", + "Expected a path to a cmakeFiles-*.json file", + ); + const content = await fs.promises.readFile(cmakeFilesPath, "utf-8"); + return schemas.cmakeFilesSchemaPerVersion[version].parse(JSON.parse(content)); +} + +export async function readToolchains( + toolchainsPath: string, + version: keyof typeof schemas.toolchainsSchemaPerVersion, +): Promise< + z.infer<(typeof schemas.toolchainsSchemaPerVersion)[typeof version]> +> { + assert( + path.basename(toolchainsPath).startsWith("toolchains-") && + path.extname(toolchainsPath) === ".json", + "Expected a path to a toolchains-*.json file", + ); + const content = await fs.promises.readFile(toolchainsPath, "utf-8"); + return schemas.toolchainsSchemaPerVersion[version].parse(JSON.parse(content)); +} + +export async function readConfigureLog( + configureLogPath: string, + version: keyof typeof schemas.configureLogSchemaPerVersion, +): Promise< + z.infer<(typeof schemas.configureLogSchemaPerVersion)[typeof version]> +> { + assert( + path.basename(configureLogPath).startsWith("configureLog-") && + path.extname(configureLogPath) === ".json", + "Expected a path to a configureLog-*.json file", + ); + const content = await fs.promises.readFile(configureLogPath, "utf-8"); + return schemas.configureLogSchemaPerVersion[version].parse( + JSON.parse(content), + ); +} diff --git a/packages/cmake-file-api/src/schemas.ts b/packages/cmake-file-api/src/schemas.ts new file mode 100644 index 00000000..3984bee5 --- /dev/null +++ b/packages/cmake-file-api/src/schemas.ts @@ -0,0 +1,7 @@ +export * from "./schemas/ReplyIndexV1.js"; +export * from "./schemas/objects/CodemodelV2.js"; +export * from "./schemas/objects/TargetV2.js"; +export * from "./schemas/objects/CacheV2.js"; +export * from "./schemas/objects/CmakeFilesV1.js"; +export * from "./schemas/objects/ToolchainsV1.js"; +export * from "./schemas/objects/ConfigureLogV1.js"; diff --git a/packages/cmake-file-api/src/schemas/ReplyIndexV1.ts b/packages/cmake-file-api/src/schemas/ReplyIndexV1.ts new file mode 100644 index 00000000..272ba4ce --- /dev/null +++ b/packages/cmake-file-api/src/schemas/ReplyIndexV1.ts @@ -0,0 +1,116 @@ +import * as z from "zod"; + +export const ReplyFileReferenceV1 = z.object({ + kind: z.enum([ + "codemodel", + "configureLog", + "cache", + "cmakeFiles", + "toolchains", + ]), + version: z.object({ + major: z.number(), + minor: z.number(), + }), + jsonFile: z.string(), +}); + +const ReplyErrorObject = z.object({ + error: z.string(), +}); + +const VersionNumber = z.number(); + +const VersionObject = z.object({ + major: z.number(), + minor: z.number().optional(), +}); + +const VersionSpec = z.union([ + VersionNumber, + VersionObject, + z.array(z.union([VersionNumber, VersionObject])), +]); + +const QueryRequest = z.object({ + kind: z.string(), + version: VersionSpec.optional(), + client: z.unknown().optional(), +}); + +const ClientStatefulQueryReply = z.object({ + client: z.unknown().optional(), + requests: z.array(QueryRequest).optional(), + responses: z.array(ReplyFileReferenceV1).optional(), +}); + +export const IndexReplyV1 = z.object({ + cmake: z.object({ + version: z.object({ + major: z.number(), + minor: z.number(), + patch: z.number(), + suffix: z.string(), + string: z.string(), + isDirty: z.boolean(), + }), + paths: z.object({ + cmake: z.string(), + ctest: z.string(), + cpack: z.string(), + root: z.string(), + }), + generator: z.object({ + multiConfig: z.boolean(), + name: z.string(), + platform: z.string().optional(), + }), + }), + objects: z.array(ReplyFileReferenceV1), + reply: z.record( + z.string(), + z + .union([ + ReplyFileReferenceV1, + ReplyErrorObject, + z.record( + z.string(), + z.union([ + ReplyFileReferenceV1, + ReplyErrorObject, + ClientStatefulQueryReply, + ]), + ), + ]) + .optional(), + ), +}); + +const ReplyErrorIndexFileReference = ReplyFileReferenceV1.extend({ + kind: z.enum(["configureLog"]), +}); + +const ClientStatefulQueryReplyForErrorIndex = ClientStatefulQueryReply.extend({ + responses: z.array(ReplyErrorIndexFileReference).optional(), +}); + +export const ReplyErrorIndex = IndexReplyV1.extend({ + objects: z.array(ReplyErrorIndexFileReference), + reply: z.record( + z.string(), + z + .union([ + ReplyErrorIndexFileReference, + ReplyErrorObject, + z.record( + z.string(), + z.union([ + ReplyErrorIndexFileReference, + ReplyErrorObject, + ClientStatefulQueryReplyForErrorIndex, + ]), + ), + ]) + .optional(), + ), +}); diff --git a/packages/cmake-file-api/src/schemas/objects/CacheV2.ts b/packages/cmake-file-api/src/schemas/objects/CacheV2.ts new file mode 100644 index 00000000..a85d6caf --- /dev/null +++ b/packages/cmake-file-api/src/schemas/objects/CacheV2.ts @@ -0,0 +1,28 @@ +import * as z from "zod"; + +const CacheEntryProperty = z.object({ + name: z.string(), + value: z.string(), +}); + +const CacheEntry = z.object({ + name: z.string(), + value: z.string(), + type: z.string(), + properties: z.array(CacheEntryProperty), +}); + +export const CacheV2_0 = z.object({ + kind: z.literal("cache"), + version: z.object({ + major: z.literal(2), + minor: z.number().int().nonnegative(), + }), + entries: z.array(CacheEntry), +}); + +export const CacheV2 = z.union([CacheV2_0]); + +export const cacheSchemaPerVersion = { + "2.0": CacheV2_0, +} as const satisfies Record; diff --git a/packages/cmake-file-api/src/schemas/objects/CmakeFilesV1.ts b/packages/cmake-file-api/src/schemas/objects/CmakeFilesV1.ts new file mode 100644 index 00000000..f23bd999 --- /dev/null +++ b/packages/cmake-file-api/src/schemas/objects/CmakeFilesV1.ts @@ -0,0 +1,45 @@ +import * as z from "zod"; + +const CmakeFilesInput = z.object({ + path: z.string(), + isGenerated: z.boolean().optional(), + isExternal: z.boolean().optional(), + isCMake: z.boolean().optional(), +}); + +const CmakeFilesGlobDependent = z.object({ + expression: z.string(), + recurse: z.boolean().optional(), + listDirectories: z.boolean().optional(), + followSymlinks: z.boolean().optional(), + relative: z.string().optional(), + paths: z.array(z.string()), +}); + +export const CmakeFilesV1_0 = z.object({ + kind: z.literal("cmakeFiles"), + version: z.object({ + major: z.literal(1), + minor: z.number().max(0), + }), + paths: z.object({ + source: z.string(), + build: z.string(), + }), + inputs: z.array(CmakeFilesInput), +}); + +export const CmakeFilesV1_1 = CmakeFilesV1_0.extend({ + version: z.object({ + major: z.literal(1), + minor: z.number().min(1), + }), + globsDependent: z.array(CmakeFilesGlobDependent).optional(), +}); + +export const CmakeFilesV1 = z.union([CmakeFilesV1_0, CmakeFilesV1_1]); + +export const cmakeFilesSchemaPerVersion = { + "1.0": CmakeFilesV1_0, + "1.1": CmakeFilesV1_1, +} as const satisfies Record; diff --git a/packages/cmake-file-api/src/schemas/objects/CodemodelV2.ts b/packages/cmake-file-api/src/schemas/objects/CodemodelV2.ts new file mode 100644 index 00000000..17fc202f --- /dev/null +++ b/packages/cmake-file-api/src/schemas/objects/CodemodelV2.ts @@ -0,0 +1,77 @@ +import * as z from "zod"; + +const index = z.number().int().nonnegative(); + +const MinimumCMakeVersion = z.object({ + string: z.string(), +}); + +const DirectoryV2_0 = z.object({ + source: z.string(), + build: z.string(), + parentIndex: index.optional(), + childIndexes: z.array(index).optional(), + projectIndex: index, + targetIndexes: z.array(index).optional(), + minimumCMakeVersion: MinimumCMakeVersion.optional(), + hasInstallRule: z.boolean().optional(), +}); + +const DirectoryV2_3 = DirectoryV2_0.extend({ + jsonFile: z.string(), +}); + +const Project = z.object({ + name: z.string(), + parentIndex: index.optional(), + childIndexes: z.array(index).optional(), + directoryIndexes: z.array(index), + targetIndexes: z.array(index).optional(), +}); + +const Target = z.object({ + name: z.string(), + id: z.string(), + directoryIndex: index, + projectIndex: index, + jsonFile: z.string(), +}); + +const ConfigurationV2_0 = z.object({ + name: z.string(), + directories: z.array(DirectoryV2_0), + projects: z.array(Project), + targets: z.array(Target), +}); + +const ConfigurationV2_3 = ConfigurationV2_0.extend({ + directories: z.array(DirectoryV2_3), +}); + +export const CodemodelV2_0 = z.object({ + kind: z.literal("codemodel"), + version: z.object({ + major: z.literal(2), + minor: z.number().max(2), + }), + paths: z.object({ + source: z.string(), + build: z.string(), + }), + configurations: z.array(ConfigurationV2_0), +}); + +export const CodemodelV2_3 = CodemodelV2_0.extend({ + version: z.object({ + major: z.literal(2), + minor: z.number().min(3), + }), + configurations: z.array(ConfigurationV2_3), +}); + +export const CodemodelV2 = z.union([CodemodelV2_0, CodemodelV2_3]); + +export const codemodelFilesSchemaPerVersion = { + "2.0": CodemodelV2_0, + "2.3": CodemodelV2_3, +} as const satisfies Record; diff --git a/packages/cmake-file-api/src/schemas/objects/ConfigureLogV1.ts b/packages/cmake-file-api/src/schemas/objects/ConfigureLogV1.ts new file mode 100644 index 00000000..6f6688ef --- /dev/null +++ b/packages/cmake-file-api/src/schemas/objects/ConfigureLogV1.ts @@ -0,0 +1,17 @@ +import { z } from "zod"; + +export const ConfigureLogV1_0 = z.object({ + kind: z.literal("configureLog"), + version: z.object({ + major: z.literal(1), + minor: z.literal(0), + }), + path: z.string(), + eventKindNames: z.array(z.string()), +}); + +export const ConfigureLogV1 = z.union([ConfigureLogV1_0]); + +export const configureLogSchemaPerVersion = { + "1.0": ConfigureLogV1_0, +} as const satisfies Record; diff --git a/packages/cmake-file-api/src/schemas/objects/TargetV2.ts b/packages/cmake-file-api/src/schemas/objects/TargetV2.ts new file mode 100644 index 00000000..da34e479 --- /dev/null +++ b/packages/cmake-file-api/src/schemas/objects/TargetV2.ts @@ -0,0 +1,253 @@ +import * as z from "zod"; + +const index = z.number().int().nonnegative(); + +const Artifact = z.object({ + path: z.string(), +}); + +const Folder = z.object({ + name: z.string(), +}); + +const InstallPrefix = z.object({ + path: z.string(), +}); + +const InstallDestination = z.object({ + path: z.string(), + backtrace: index.optional(), +}); + +const Install = z.object({ + prefix: InstallPrefix, + destinations: z.array(InstallDestination), +}); + +const Launcher = z.object({ + command: z.string(), + arguments: z.array(z.string()).optional(), + type: z.enum(["emulator", "test"]), +}); + +const LinkCommandFragment = z.object({ + fragment: z.string(), + role: z.enum(["flags", "libraries", "libraryPath", "frameworkPath"]), + backtrace: index.optional(), +}); + +const Sysroot = z.object({ + path: z.string(), +}); + +const Link = z.object({ + language: z.string(), + commandFragments: z.array(LinkCommandFragment).optional(), + lto: z.boolean().optional(), + sysroot: Sysroot.optional(), +}); + +const ArchiveCommandFragment = z.object({ + fragment: z.string(), + role: z.enum(["flags"]), +}); + +const Archive = z.object({ + commandFragments: z.array(ArchiveCommandFragment).optional(), + lto: z.boolean().optional(), +}); + +const Debugger = z.object({ + workingDirectory: z.string().optional(), +}); + +const Dependency = z.object({ + id: z.string(), + backtrace: index.optional(), +}); + +const FileSet = z.object({ + name: z.string(), + type: z.string(), + visibility: z.enum(["PUBLIC", "PRIVATE", "INTERFACE"]), + baseDirectories: z.array(z.string()), +}); + +const SourceGroup = z.object({ + name: z.string(), + sourceIndexes: z.array(index), +}); + +const LanguageStandard = z.object({ + backtraces: z.array(index).optional(), + standard: z.string(), +}); + +const CompileCommandFragment = z.object({ + fragment: z.string(), + backtrace: index.optional(), +}); + +const Include = z.object({ + path: z.string(), + isSystem: z.boolean().optional(), + backtrace: index.optional(), +}); + +const Framework = z.object({ + path: z.string(), + isSystem: z.boolean().optional(), + backtrace: index.optional(), +}); + +const PrecompileHeader = z.object({ + header: z.string(), + backtrace: index.optional(), +}); + +const Define = z.object({ + define: z.string(), + backtrace: index.optional(), +}); + +const BacktraceNode = z.object({ + file: index, + line: z.number().int().positive().optional(), + command: index.optional(), + parent: index.optional(), +}); + +const BacktraceGraph = z.object({ + nodes: z.array(BacktraceNode), + commands: z.array(z.string()), + files: z.array(z.string()), +}); + +// Versioned nested schemas +const SourceV2_0 = z.object({ + path: z.string(), + compileGroupIndex: index.optional(), + sourceGroupIndex: index.optional(), + isGenerated: z.boolean().optional(), + backtrace: index.optional(), +}); + +const SourceV2_5 = SourceV2_0.extend({ + fileSetIndex: index.optional(), +}); + +const CompileGroupV2_0 = z.object({ + sourceIndexes: z.array(index), + language: z.string(), + compileCommandFragments: z.array(CompileCommandFragment).optional(), + includes: z.array(Include).optional(), + defines: z.array(Define).optional(), + sysroot: Sysroot.optional(), +}); + +const CompileGroupV2_1 = CompileGroupV2_0.extend({ + precompileHeaders: z.array(PrecompileHeader).optional(), +}); + +const CompileGroupV2_2 = CompileGroupV2_1.extend({ + languageStandard: LanguageStandard.optional(), +}); + +const CompileGroupV2_6 = CompileGroupV2_2.extend({ + frameworks: z.array(Framework).optional(), +}); + +// Base version (v2.0) - Original target fields +const TargetV2_0 = z.object({ + name: z.string(), + id: z.string(), + type: z.enum([ + "EXECUTABLE", + "STATIC_LIBRARY", + "SHARED_LIBRARY", + "MODULE_LIBRARY", + "OBJECT_LIBRARY", + "INTERFACE_LIBRARY", + "UTILITY", + ]), + backtrace: index.optional(), + folder: Folder.optional(), + paths: z.object({ + source: z.string(), + build: z.string(), + }), + nameOnDisk: z.string().optional(), + artifacts: z.array(Artifact).optional(), + isGeneratorProvided: z.boolean().optional(), + install: Install.optional(), + link: Link.optional(), + archive: Archive.optional(), + dependencies: z.array(Dependency).optional(), + sources: z.array(SourceV2_0).optional(), + sourceGroups: z.array(SourceGroup).optional(), + compileGroups: z.array(CompileGroupV2_0).optional(), + backtraceGraph: BacktraceGraph.optional(), +}); + +// v2.1+ - Added precompileHeaders +const TargetV2_1 = TargetV2_0.extend({ + compileGroups: z.array(CompileGroupV2_1).optional(), +}); + +// v2.2+ - Added languageStandard +const TargetV2_2 = TargetV2_1.extend({ + compileGroups: z.array(CompileGroupV2_2).optional(), +}); + +// v2.5+ - Added fileSets and fileSetIndex in sources +const TargetV2_5 = TargetV2_2.extend({ + fileSets: z.array(FileSet).optional(), + sources: z.array(SourceV2_5).optional(), +}); + +// v2.6+ - Added frameworks +const TargetV2_6 = TargetV2_5.extend({ + compileGroups: z.array(CompileGroupV2_6).optional(), +}); + +// v2.7+ - Added launchers +const TargetV2_7 = TargetV2_6.extend({ + launchers: z.array(Launcher).optional(), +}); + +// v2.8+ - Added debugger +const TargetV2_8 = TargetV2_7.extend({ + debugger: Debugger.optional(), +}); + +// Export union of all versions for flexible validation +export const TargetV2 = z.union([ + TargetV2_0, + TargetV2_1, + TargetV2_2, + TargetV2_5, + TargetV2_6, + TargetV2_7, + TargetV2_8, +]); + +// Also export individual versions for specific use cases +export { + TargetV2_0, + TargetV2_1, + TargetV2_2, + TargetV2_5, + TargetV2_6, + TargetV2_7, + TargetV2_8, +}; + +export const targetSchemaPerVersion = { + "2.0": TargetV2_0, + "2.1": TargetV2_1, + "2.2": TargetV2_2, + "2.5": TargetV2_5, + "2.6": TargetV2_6, + "2.7": TargetV2_7, + "2.8": TargetV2_8, +} as const satisfies Record; diff --git a/packages/cmake-file-api/src/schemas/objects/ToolchainsV1.ts b/packages/cmake-file-api/src/schemas/objects/ToolchainsV1.ts new file mode 100644 index 00000000..1e3f79c2 --- /dev/null +++ b/packages/cmake-file-api/src/schemas/objects/ToolchainsV1.ts @@ -0,0 +1,37 @@ +import * as z from "zod"; + +const ToolchainCompilerImplicit = z.object({ + includeDirectories: z.array(z.string()).optional(), + linkDirectories: z.array(z.string()).optional(), + linkFrameworkDirectories: z.array(z.string()).optional(), + linkLibraries: z.array(z.string()).optional(), +}); + +const ToolchainCompiler = z.object({ + path: z.string().optional(), + id: z.string().optional(), + version: z.string().optional(), + target: z.string().optional(), + implicit: ToolchainCompilerImplicit, +}); + +const Toolchain = z.object({ + language: z.string(), + compiler: ToolchainCompiler, + sourceFileExtensions: z.array(z.string()).optional(), +}); + +export const ToolchainsV1_0 = z.object({ + kind: z.literal("toolchains"), + version: z.object({ + major: z.literal(1), + minor: z.number().int().nonnegative(), + }), + toolchains: z.array(Toolchain), +}); + +export const ToolchainsV1 = z.union([ToolchainsV1_0]); + +export const toolchainsSchemaPerVersion = { + "1.0": ToolchainsV1_0, +} as const satisfies Record; diff --git a/packages/cmake-file-api/tsconfig.json b/packages/cmake-file-api/tsconfig.json new file mode 100644 index 00000000..f183b9a9 --- /dev/null +++ b/packages/cmake-file-api/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "../../configs/tsconfig.node.json" +} diff --git a/packages/cmake-file-api/tsconfig.tests.json b/packages/cmake-file-api/tsconfig.tests.json new file mode 100644 index 00000000..c203a437 --- /dev/null +++ b/packages/cmake-file-api/tsconfig.tests.json @@ -0,0 +1,8 @@ +{ + "extends": "../../configs/tsconfig.node-tests.json", + "references": [ + { + "path": "./tsconfig.json" + } + ] +} diff --git a/tsconfig.json b/tsconfig.json index cde11ae1..a733c3ff 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,6 +7,8 @@ "files": ["prettier.config.js", "eslint.config.js"], "references": [ { "path": "./packages/cli-utils/tsconfig.json" }, + { "path": "./packages/cmake-file-api/tsconfig.json" }, + { "path": "./packages/cmake-file-api/tsconfig.tests.json" }, { "path": "./packages/host/tsconfig.json" }, { "path": "./packages/gyp-to-cmake/tsconfig.json" }, { "path": "./packages/cmake-rn/tsconfig.json" },