# C library contracts

Maligator 0.1.0-alpha.35 · Experimental
Source revision: 7a9e60fb1f282e577871ac66f8715e30c2dfcf37
Canonical: https://maligator.ddv.tools/api/library

Import `defineLibrary` from `@maligator/cli` to declare the headers and facts that Maligator uses to bind a C library. Point the [`ffi` build option](/api/build#ffi) at the contract file. The CLI loads and validates that file as trusted project code.

Use `find` to describe how to locate the library. Paths in the contract resolve from the contract file's directory. Set `find` in the build configuration's library entry to replace the contract's discovery alternatives on a particular machine.

Follow [Bind a library](/guides/c-libraries) to call C code from an application. Use [`maligator ffi inspect`](/api/cli#ffi-inspect) to see which declarations bind and which need more facts.

<a id="MaligatorFfiFind"></a>

## MaligatorFfiFind

How the build finds a C library's headers and binaries. Relative paths resolve
against the file that declares them. Name at least `pkgConfig`, `libraries`, or
`sources`; the other fields add to what those provide.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiFind {
	/** A pkg-config package that supplies include directories and linker inputs. */
	pkgConfig?: string;
	/** Header search directories. */
	includeDirs?: Array<string>;
	/** Preprocessor definitions for the headers and sources. */
	defines?: Record<string, string>;
	/** Directories searched for `libraries`. */
	libraryDirs?: Array<string>;
	/** Libraries linked by name, as with `-lname`. */
	libraries?: Array<string>;
	/** macOS frameworks to link, such as `Cocoa`. */
	frameworks?: Array<string>;
	/** C sources compiled into the program instead of a prebuilt library. */
	sources?: Array<string>;
}
```

</details>


<a id="MaligatorFfiFind.pkgConfig"></a>

### MaligatorFfiFind.pkgConfig

A pkg-config package that supplies include directories and linker inputs.

```typescript
pkgConfig?: string;
```


<a id="MaligatorFfiFind.includeDirs"></a>

### MaligatorFfiFind.includeDirs

Header search directories.

```typescript
includeDirs?: Array<string>;
```


<a id="MaligatorFfiFind.defines"></a>

### MaligatorFfiFind.defines

Preprocessor definitions for the headers and sources.

```typescript
defines?: Record<string, string>;
```


<a id="MaligatorFfiFind.libraryDirs"></a>

### MaligatorFfiFind.libraryDirs

Directories searched for `libraries`.

```typescript
libraryDirs?: Array<string>;
```


<a id="MaligatorFfiFind.libraries"></a>

### MaligatorFfiFind.libraries

Libraries linked by name, as with `-lname`.

```typescript
libraries?: Array<string>;
```


<a id="MaligatorFfiFind.frameworks"></a>

### MaligatorFfiFind.frameworks

macOS frameworks to link, such as `Cocoa`.

```typescript
frameworks?: Array<string>;
```


<a id="MaligatorFfiFind.sources"></a>

### MaligatorFfiFind.sources

C sources compiled into the program instead of a prebuilt library.

```typescript
sources?: Array<string>;
```


<a id="MaligatorFfiHandle"></a>

## MaligatorFfiHandle

A C resource or caller-owned state struct. Its handles
close on `[Symbol.dispose]()` or when passed to `destroy`; a closed handle throws
instead of reaching C.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiHandle {
	/** Export a factory named by the type fact. It allocates aligned,
	 * zeroed caller-owned storage. C initialization and cleanup
	 * remain explicit. With a collecting destructor, an `initializes` function arms
	 * cleanup; before initialization, disposal frees only the outer storage.
	 */
	storage?: "caller";
	/** A final flexible or zero-length array field in caller storage. The factory
	 * takes its element count as a bigint; without this fact it takes no arguments.
	 * Allocation does not initialize a C count field.
	 */
	trailing?: string;
	/** Native size and alignment queries for an incomplete struct. Both functions
	 * take no arguments and return unsigned integers up to 64 bits. The factory
	 * calls them for each allocation, checking size and alignment before allocating.
	 */
	layout?: { size: string; alignment: string };
	/** Other handle types whose pointers accept this resource without adjustment.
	 * Compatibility is directed and preserves the resource's identity and owner.
	 */
	views?: Array<string>;
	/** The function that releases the resource, taking it as its only parameter.
	 * A name asserts unconditional release. With `success`, release occurs only when
	 * its integer or boolean result equals the C identifier or integer literal.
	 */
	destroy?: string | { function: string; success: string };
	/** Release a collected handle once its native result borrowers finish. The last lease
	 * may retire on a foreign thread. Off unless
	 * set; leave it off for resources that must be released on one thread or before the
	 * library shuts down. Conditional cleanup requires explicit disposal and retry.
	 */
	collect?: boolean;
}
```

</details>


<a id="MaligatorFfiHandle.storage"></a>

### MaligatorFfiHandle.storage

Export a factory named by the type fact. It allocates aligned,
zeroed caller-owned storage. C initialization and cleanup
remain explicit. With a collecting destructor, an `initializes` function arms
cleanup; before initialization, disposal frees only the outer storage.

```typescript
storage?: "caller";
```


<a id="MaligatorFfiHandle.trailing"></a>

### MaligatorFfiHandle.trailing

A final flexible or zero-length array field in caller storage. The factory
takes its element count as a bigint; without this fact it takes no arguments.
Allocation does not initialize a C count field.

```typescript
trailing?: string;
```


<a id="MaligatorFfiHandle.layout"></a>

### MaligatorFfiHandle.layout

Native size and alignment queries for an incomplete struct. Both functions
take no arguments and return unsigned integers up to 64 bits. The factory
calls them for each allocation, checking size and alignment before allocating.
<details><summary>Full TypeScript declaration</summary>


```typescript
layout?: { size: string; alignment: string };
```

</details>


<a id="MaligatorFfiHandle.layout.size"></a>

### MaligatorFfiHandle.layout.size



```typescript
size: string;
```


<a id="MaligatorFfiHandle.layout.alignment"></a>

### MaligatorFfiHandle.layout.alignment



```typescript
alignment: string
```


<a id="MaligatorFfiHandle.views"></a>

### MaligatorFfiHandle.views

Other handle types whose pointers accept this resource without adjustment.
Compatibility is directed and preserves the resource's identity and owner.

```typescript
views?: Array<string>;
```


<a id="MaligatorFfiHandle.destroy"></a>

### MaligatorFfiHandle.destroy

The function that releases the resource, taking it as its only parameter.
A name asserts unconditional release. With `success`, release occurs only when
its integer or boolean result equals the C identifier or integer literal.
<details><summary>Full TypeScript declaration</summary>


```typescript
destroy?: string | { function: string; success: string };
```

</details>


<a id="MaligatorFfiHandle.destroy.function"></a>

### MaligatorFfiHandle.destroy.function



```typescript
function: string;
```


<a id="MaligatorFfiHandle.destroy.success"></a>

### MaligatorFfiHandle.destroy.success



```typescript
success: string
```


<a id="MaligatorFfiHandle.collect"></a>

### MaligatorFfiHandle.collect

Release a collected handle once its native result borrowers finish. The last lease
may retire on a foreign thread. Off unless
set; leave it off for resources that must be released on one thread or before the
library shuts down. Conditional cleanup requires explicit disposal and retry.

```typescript
collect?: boolean;
```


<a id="MaligatorFfiTypeFacts"></a>

## MaligatorFfiTypeFacts

Facts about one C type, keyed by its typedef or tag.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiTypeFacts {
	/** Preserve an arithmetic typedef exactly in a nominal native value box. */
	representation?: "native";
	handle?: MaligatorFfiHandle;
	/** Select active union storage explicitly or from a record's discriminator. */
	shape?: MaligatorFfiShape;
	/** Owned resource fields in value records, borrowed fields on handles, or retained ranges.
	 * Range assignment writes the pointer and count together; C may advance them only
	 * within the assigned range.
	 */
	fields?: Record<string, MaligatorFfiFieldFacts>;
	/** Header documentation that `ffi check` watches when reviewing these facts. */
	evidence?: Array<MaligatorFfiEvidence>;
}
```

Types: [`MaligatorFfiHandle`](/api/library#MaligatorFfiHandle), [`MaligatorFfiFieldFacts`](/api/library#MaligatorFfiFieldFacts), [`MaligatorFfiEvidence`](/api/library#MaligatorFfiEvidence), [`MaligatorFfiShape`](/api/library#MaligatorFfiShape)


</details>


<a id="MaligatorFfiTypeFacts.representation"></a>

### MaligatorFfiTypeFacts.representation

Preserve an arithmetic typedef exactly in a nominal native value box.

```typescript
representation?: "native";
```


<a id="MaligatorFfiTypeFacts.handle"></a>

### MaligatorFfiTypeFacts.handle



```typescript
handle?: MaligatorFfiHandle;
```

Types: [`MaligatorFfiHandle`](/api/library#MaligatorFfiHandle)



<a id="MaligatorFfiTypeFacts.shape"></a>

### MaligatorFfiTypeFacts.shape

Select active union storage explicitly or from a record's discriminator.

```typescript
shape?: MaligatorFfiShape;
```

Types: [`MaligatorFfiShape`](/api/library#MaligatorFfiShape)



<a id="MaligatorFfiTypeFacts.fields"></a>

### MaligatorFfiTypeFacts.fields

Owned resource fields in value records, borrowed fields on handles, or retained ranges.
Range assignment writes the pointer and count together; C may advance them only
within the assigned range.

```typescript
fields?: Record<string, MaligatorFfiFieldFacts>;
```

Types: [`MaligatorFfiFieldFacts`](/api/library#MaligatorFfiFieldFacts)



<a id="MaligatorFfiTypeFacts.evidence"></a>

### MaligatorFfiTypeFacts.evidence

Header documentation that `ffi check` watches when reviewing these facts.

```typescript
evidence?: Array<MaligatorFfiEvidence>;
```

Types: [`MaligatorFfiEvidence`](/api/library#MaligatorFfiEvidence)



<a id="MaligatorFfiFieldFacts"></a>

## MaligatorFfiFieldFacts

A resource, callable or counted array field, or a range retained by caller-owned state.

```typescript
export type MaligatorFfiFieldFacts =
	| {
			bytes: {
				/** The C integer field holding the remaining byte count. */
				length: string;
				/** Whether C writes these bytes; defaults to true for a non-const pointee. */
				writable?: boolean;
			};
			string?: never;
			callable?: never;
			handle?: never;
			array?: never;
			value?: never;
	  }
	| {
			/** UTF-8 text kept in a private encoding, with a C field holding its byte count. */
			string: MaligatorFfiCount;
			bytes?: never;
			callable?: never;
			handle?: never;
			array?: never;
			value?: never;
	  }
	| {
			callable: MaligatorFfiCallable;
			bytes?: never;
			string?: never;
			handle?: never;
			array?: never;
			value?: never;
	  }
	| {
			/** Owned fields transfer from value results; record inputs borrow their handles.
			 * Borrowed accessor lifetime follows its owner or the C library's process storage.
			 */
			handle:
				| { lifetime: "owner" | "library"; owned?: never; fresh?: never }
				| { owned: true; fresh?: boolean; lifetime?: never };
			bytes?: never;
			string?: never;
			callable?: never;
			array?: never;
			value?: never;
	  }
	| {
			/**
			 * A pointer to values on any handle, read as a fresh array of as many elements as
			 * the C integer field `length` holds; `null` for a null pointer.
			 */
			array: MaligatorFfiCount;
			bytes?: never;
			string?: never;
			callable?: never;
			handle?: never;
			value?: never;
	  }
	| {
			/**
			 * Expose this value member as a read-only property on any handle, including a
			 * library-owned pointer handle whose other members stay hidden.
			 */
			value: true;
			bytes?: never;
			string?: never;
			callable?: never;
			handle?: never;
			array?: never;
	  };
```

Types: [`MaligatorFfiCount`](/api/library#MaligatorFfiCount), [`MaligatorFfiCallable`](/api/library#MaligatorFfiCallable)



<a id="MaligatorFfiEvidence"></a>

## MaligatorFfiEvidence

A declaration whose documentation supports a fact, independent of its source location.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiEvidence {
	kind: "function" | "global" | "typedef" | "struct" | "union" | "enum" | "macro";
	name: string;
}
```

</details>


<a id="MaligatorFfiEvidence.kind"></a>

### MaligatorFfiEvidence.kind



```typescript
kind: "function" | "global" | "typedef" | "struct" | "union" | "enum" | "macro";
```


<a id="MaligatorFfiEvidence.name"></a>

### MaligatorFfiEvidence.name



```typescript
name: string;
```


<a id="MaligatorFfiCount"></a>

## MaligatorFfiCount

The C parameter or state field carrying a byte or element count.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiCount {
	/**
	 * The parameter's C name, or its 1-based position. For a result, the count comes
	 * from an integer parameter or from an integer the function writes through a pointer.
	 * Callback counts use 1-based positions.
	 * State counts use C field names; global counts use C object names.
	 * An input buffer or array of a function can instead require a minimum length, a
	 * product of integer parameters and literals such as `"width * height * 4"`; those
	 * parameters stay in the JavaScript signature.
	 */
	length: string;
}
```

</details>


<a id="MaligatorFfiCount.length"></a>

### MaligatorFfiCount.length

The parameter's C name, or its 1-based position. For a result, the count comes
from an integer parameter or from an integer the function writes through a pointer.
Callback counts use 1-based positions.
State counts use C field names; global counts use C object names.
An input buffer or array of a function can instead require a minimum length, a
product of integer parameters and literals such as `"width * height * 4"`; those
parameters stay in the JavaScript signature.

```typescript
length: string;
```


<a id="MaligatorFfiShape"></a>

## MaligatorFfiShape

Select active C union storage explicitly or through an integer discriminator.

```typescript
export type MaligatorFfiShape =
	| { member: string }
	| {
			/** A direct or anonymously promoted C integer field. */
			tag: string;
			/** Integer constants map to paths naming the active C union members. */
			cases: Readonly<Record<string, ReadonlyArray<string>>>;
	  };
```


<a id="MaligatorFfiValueFacts"></a>

## MaligatorFfiValueFacts

Facts about a parameter or a result.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiValueFacts {
	/** Override the active union shape for this value or array element. */
	shape?: MaligatorFfiShape;
	/** Accept `null` for a pointer parameter and pass `NULL`. */
	nullable?: boolean;
	/** A returned/output handle or flat pointer array whose pointees the library keeps
	 * owning. Closing a borrowed wrapper does not release its resource. Caller pointer
	 * buffers require an explicit choice: `false` transfers pointee ownership.
	 */
	borrowed?: boolean;
	/** A pointer result starts a new resource lifetime, rather than aliasing an
	 * existing handle. This distinguishes a reused address during worker cleanup.
	 */
	fresh?: boolean;
	/** The function writes a value through this pointer; it returns beside the result. */
	out?: boolean;
	/** The function reads and updates the value behind this pointer; the new value returns beside the result. */
	inout?: boolean;
	/** UTF-8 text in a char pointer. `true` uses NUL termination; a length names
	 * its byte count and permits embedded NUL bytes. Out strings use a count pointer C
	 * fills. Inout strings borrow an encoding through conversion of the updated value.
	 * Queued notifications copy the counted bytes; waiting callbacks borrow them.
	 */
	string?: boolean | MaligatorFfiCount;
	/** Bytes passed as an `ArrayBuffer` or a view, or returned as a new `Uint8Array`. */
	bytes?: MaligatorFfiCount;
	/** Elements passed or returned as an array. For an out buffer, `capacity` names
	 * an integer input that bounds caller-owned storage; it stays in the JS signature.
	 */
	array?: MaligatorFfiCount & {
		capacity?: string;
		/** Decode fixed character rows as bounded UTF-8 text or exact byte views. */
		element?: { string: true; bytes?: never } | { bytes: true; string?: never };
		/**
		 * Lend a matching typed array, such as a `Float64Array` for `double *`, for C
		 * to write in place during a synchronous call. Ordinary arrays still pass a copy.
		 */
		writable?: true;
	};
	/** Release a copied string, buffer, or array result with this function. */
	free?: string;
	/** A function pointer the library calls during the call with a JavaScript function. */
	callback?: MaligatorFfiCallback;
	/** A returned C function pointer, callable with its declared header signature. */
	callable?: MaligatorFfiCallable;
	/**
	 * Pass this C macro, enumerator, or integer, such as `SQLITE_TRANSIENT` or `0`, and
	 * drop the parameter from the JavaScript signature. The C compiler checks its type.
	 */
	constant?: string;
	/** Pass the C compiler's `sizeof` for this complete struct or union type and
	 * omit the parameter from JavaScript. Its size must fit the integer parameter.
	 */
	sizeof?: string;
	/**
	 * The C type a `void *` or `const void *` parameter points at, such as `double`, when
	 * another argument selects it at runtime. The parameter then binds as a pointer to
	 * that type, keeping its constness; pair it with per-type `variants`.
	 */
	pointee?: string;
	/**
	 * Pass the address of the terminator of the NUL-terminated string that this
	 * parameter, named by C name or 1-based position, passes, and omit this parameter
	 * from JavaScript. C then reads that text as a `[start, end)` range.
	 */
	end?: string;
}
```

Types: [`MaligatorFfiCount`](/api/library#MaligatorFfiCount), [`MaligatorFfiShape`](/api/library#MaligatorFfiShape), [`MaligatorFfiCallable`](/api/library#MaligatorFfiCallable), [`MaligatorFfiCallback`](/api/library#MaligatorFfiCallback)


</details>


<a id="MaligatorFfiValueFacts.shape"></a>

### MaligatorFfiValueFacts.shape

Override the active union shape for this value or array element.

```typescript
shape?: MaligatorFfiShape;
```

Types: [`MaligatorFfiShape`](/api/library#MaligatorFfiShape)



<a id="MaligatorFfiValueFacts.nullable"></a>

### MaligatorFfiValueFacts.nullable

Accept `null` for a pointer parameter and pass `NULL`.

```typescript
nullable?: boolean;
```


<a id="MaligatorFfiValueFacts.borrowed"></a>

### MaligatorFfiValueFacts.borrowed

A returned/output handle or flat pointer array whose pointees the library keeps
owning. Closing a borrowed wrapper does not release its resource. Caller pointer
buffers require an explicit choice: `false` transfers pointee ownership.

```typescript
borrowed?: boolean;
```


<a id="MaligatorFfiValueFacts.fresh"></a>

### MaligatorFfiValueFacts.fresh

A pointer result starts a new resource lifetime, rather than aliasing an
existing handle. This distinguishes a reused address during worker cleanup.

```typescript
fresh?: boolean;
```


<a id="MaligatorFfiValueFacts.out"></a>

### MaligatorFfiValueFacts.out

The function writes a value through this pointer; it returns beside the result.

```typescript
out?: boolean;
```


<a id="MaligatorFfiValueFacts.inout"></a>

### MaligatorFfiValueFacts.inout

The function reads and updates the value behind this pointer; the new value returns beside the result.

```typescript
inout?: boolean;
```


<a id="MaligatorFfiValueFacts.string"></a>

### MaligatorFfiValueFacts.string

UTF-8 text in a char pointer. `true` uses NUL termination; a length names
its byte count and permits embedded NUL bytes. Out strings use a count pointer C
fills. Inout strings borrow an encoding through conversion of the updated value.
Queued notifications copy the counted bytes; waiting callbacks borrow them.

```typescript
string?: boolean | MaligatorFfiCount;
```

Types: [`MaligatorFfiCount`](/api/library#MaligatorFfiCount)



<a id="MaligatorFfiValueFacts.bytes"></a>

### MaligatorFfiValueFacts.bytes

Bytes passed as an `ArrayBuffer` or a view, or returned as a new `Uint8Array`.

```typescript
bytes?: MaligatorFfiCount;
```

Types: [`MaligatorFfiCount`](/api/library#MaligatorFfiCount)



<a id="MaligatorFfiValueFacts.array"></a>

### MaligatorFfiValueFacts.array

Elements passed or returned as an array. For an out buffer, `capacity` names
an integer input that bounds caller-owned storage; it stays in the JS signature.
<details><summary>Full TypeScript declaration</summary>


```typescript
array?: MaligatorFfiCount & {
		capacity?: string;
		/** Decode fixed character rows as bounded UTF-8 text or exact byte views. */
		element?: { string: true; bytes?: never } | { bytes: true; string?: never };
		/**
		 * Lend a matching typed array, such as a `Float64Array` for `double *`, for C
		 * to write in place during a synchronous call. Ordinary arrays still pass a copy.
		 */
		writable?: true;
	};
```

Types: [`MaligatorFfiCount`](/api/library#MaligatorFfiCount)


</details>


<a id="MaligatorFfiValueFacts.array.capacity"></a>

### MaligatorFfiValueFacts.array.capacity



```typescript
capacity?: string;
```


<a id="MaligatorFfiValueFacts.array.element"></a>

### MaligatorFfiValueFacts.array.element

Decode fixed character rows as bounded UTF-8 text or exact byte views.
<details><summary>Full TypeScript declaration</summary>


```typescript
element?: { string: true; bytes?: never } | { bytes: true; string?: never };
```

</details>


<a id="MaligatorFfiValueFacts.array.element.string"></a>

### MaligatorFfiValueFacts.array.element.string



```typescript
string: true;
```


<a id="MaligatorFfiValueFacts.array.element.bytes"></a>

### MaligatorFfiValueFacts.array.element.bytes



```typescript
bytes?: never
```


<a id="MaligatorFfiValueFacts.array.writable"></a>

### MaligatorFfiValueFacts.array.writable

Lend a matching typed array, such as a `Float64Array` for `double *`, for C
to write in place during a synchronous call. Ordinary arrays still pass a copy.

```typescript
writable?: true;
```


<a id="MaligatorFfiValueFacts.free"></a>

### MaligatorFfiValueFacts.free

Release a copied string, buffer, or array result with this function.

```typescript
free?: string;
```


<a id="MaligatorFfiValueFacts.callback"></a>

### MaligatorFfiValueFacts.callback

A function pointer the library calls during the call with a JavaScript function.

```typescript
callback?: MaligatorFfiCallback;
```

Types: [`MaligatorFfiCallback`](/api/library#MaligatorFfiCallback)



<a id="MaligatorFfiValueFacts.callable"></a>

### MaligatorFfiValueFacts.callable

A returned C function pointer, callable with its declared header signature.

```typescript
callable?: MaligatorFfiCallable;
```

Types: [`MaligatorFfiCallable`](/api/library#MaligatorFfiCallable)



<a id="MaligatorFfiValueFacts.constant"></a>

### MaligatorFfiValueFacts.constant

Pass this C macro, enumerator, or integer, such as `SQLITE_TRANSIENT` or `0`, and
drop the parameter from the JavaScript signature. The C compiler checks its type.

```typescript
constant?: string;
```


<a id="MaligatorFfiValueFacts.sizeof"></a>

### MaligatorFfiValueFacts.sizeof

Pass the C compiler's `sizeof` for this complete struct or union type and
omit the parameter from JavaScript. Its size must fit the integer parameter.

```typescript
sizeof?: string;
```


<a id="MaligatorFfiValueFacts.pointee"></a>

### MaligatorFfiValueFacts.pointee

The C type a `void *` or `const void *` parameter points at, such as `double`, when
another argument selects it at runtime. The parameter then binds as a pointer to
that type, keeping its constness; pair it with per-type `variants`.

```typescript
pointee?: string;
```


<a id="MaligatorFfiValueFacts.end"></a>

### MaligatorFfiValueFacts.end

Pass the address of the terminator of the NUL-terminated string that this
parameter, named by C name or 1-based position, passes, and omit this parameter
from JavaScript. C then reads that text as a `[start, end)` range.

```typescript
end?: string;
```


<a id="MaligatorFfiCallable"></a>

## MaligatorFfiCallable

A C function whose code and referenced state remain valid for its lifetime.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiCallable {
	/** Owner lifetime captures the handle whose function-table field was read. */
	lifetime: "library" | "owner";
	/** Facts keyed by the signature's 1-based parameter positions. */
	params?: Record<string, MaligatorFfiValueFacts>;
	returns?: MaligatorFfiValueFacts;
}
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)


</details>


<a id="MaligatorFfiCallable.lifetime"></a>

### MaligatorFfiCallable.lifetime

Owner lifetime captures the handle whose function-table field was read.

```typescript
lifetime: "library" | "owner";
```


<a id="MaligatorFfiCallable.params"></a>

### MaligatorFfiCallable.params

Facts keyed by the signature's 1-based parameter positions.

```typescript
params?: Record<string, MaligatorFfiValueFacts>;
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)



<a id="MaligatorFfiCallable.returns"></a>

### MaligatorFfiCallable.returns



```typescript
returns?: MaligatorFfiValueFacts;
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)



<a id="MaligatorFfiCallback"></a>

## MaligatorFfiCallback

A callback the library calls before the function returns, such as an iteration or
comparison function, until it releases the callback, until the next call
replaces it, or to complete a handle's close. An exception it throws skips later
calls and rethrows when the C function the library runs in returns.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiCallback {
	/**
	 * The input handle whose destruction root owns the registration, by C name or
	 * 1-based position, for a callback kept through `release` or `replaced`.
	 * Destruction must stop the callback and all its consumers before returning. Its closure and borrowed inputs share that root's lifetime. The root
	 * must be an independently owned library allocation with a destructor.
	 */
	owner?: string;
	/** Native copies or resource leases remain valid for the declared lifetime. */
	returns?: MaligatorFfiCallbackResult;
	/**
	 * The `void *` parameter the library passes back to the callback, by C name or
	 * 1-based position. Without it, a callback the library calls only during the
	 * function, such as `qsort`'s comparator, still binds, as does a `replaced` one.
	 */
	data?: string;
	/**
	 * The `void (*)(void *)` parameter that takes the destructor for `data`, by C name or
	 * 1-based position. The library may then keep calling the callback after the
	 * function returns, until it calls the destructor.
	 */
	release?: string;
	/**
	 * The library keeps the callback until the next call of the function replaces it,
	 * as setters such as `glfwSetErrorCallback` do. When the first parameter is a
	 * handle, each handle keeps its own callback until its resource is destroyed.
	 * Another setter for the same key throws while its setter is pending.
	 */
	replaced?: boolean;
	/**
	 * The input handle whose lifetime ends when this one-shot completion runs, by C
	 * name or 1-based position. Its storage and retained buffers survive until then.
	 * The wrapper is closed before JavaScript runs; foreign completions queue for it.
	 * An async twin settles at C return and requires a handle the program already holds.
	 */
	closes?: string;
	/**
	 * For a callback without a `void *` parameter: the function that returns `data`
	 * from the callback's parameter at 1-based position `param`, such as
	 * `sqlite3_user_data` for SQLite's `sqlite3_context *`.
	 */
	lookup?: { function: string; param: string };
	/**
	 * The library may call the kept callback from other threads. `true` copies arguments
	 * and queues for the program's thread, letting C continue with a void result.
	 * `"wait"` borrows pointed-to arguments while blocking C until JavaScript returns
	 * a result. Pointer results need an explicit lifetime. Handles are lent only for that
	 * callback. The program needs an event loop, which waits while the callback is kept. Stop or join the
	 * producer asynchronously; the program's thread must remain free to run callbacks.
	 */
	queued?: boolean | "wait";
	/**
	 * Facts per callback parameter, keyed by 1-based position: `string`, `bytes`, or
	 * `array` with a `length` naming another callback parameter, `nullable`, and `shape`.
	 */
	params?: Record<string, MaligatorFfiValueFacts>;
	/**
	 * The library calls the callback exactly once, during or after the function, and
	 * then drops it, as WebGPU's request functions do. Needs `data` or `lookup`.
	 */
	once?: boolean;
	/**
	 * On a struct parameter passed by value, such as WebGPU's callback info records: the
	 * function pointer member that receives the callback. `data` then names the `void *`
	 * member for the registration, and the parameter takes a JavaScript function.
	 */
	field?: string;
	/** C identifiers or integer literals for other members of a `field` record; the rest start zeroed. */
	constants?: Record<string, string>;
}
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts), [`MaligatorFfiCallbackResult`](/api/library#MaligatorFfiCallbackResult)


</details>


<a id="MaligatorFfiCallback.owner"></a>

### MaligatorFfiCallback.owner

The input handle whose destruction root owns the registration, by C name or
1-based position, for a callback kept through `release` or `replaced`.
Destruction must stop the callback and all its consumers before returning. Its closure and borrowed inputs share that root's lifetime. The root
must be an independently owned library allocation with a destructor.

```typescript
owner?: string;
```


<a id="MaligatorFfiCallback.returns"></a>

### MaligatorFfiCallback.returns

Native copies or resource leases remain valid for the declared lifetime.

```typescript
returns?: MaligatorFfiCallbackResult;
```

Types: [`MaligatorFfiCallbackResult`](/api/library#MaligatorFfiCallbackResult)



<a id="MaligatorFfiCallback.data"></a>

### MaligatorFfiCallback.data

The `void *` parameter the library passes back to the callback, by C name or
1-based position. Without it, a callback the library calls only during the
function, such as `qsort`'s comparator, still binds, as does a `replaced` one.

```typescript
data?: string;
```


<a id="MaligatorFfiCallback.release"></a>

### MaligatorFfiCallback.release

The `void (*)(void *)` parameter that takes the destructor for `data`, by C name or
1-based position. The library may then keep calling the callback after the
function returns, until it calls the destructor.

```typescript
release?: string;
```


<a id="MaligatorFfiCallback.replaced"></a>

### MaligatorFfiCallback.replaced

The library keeps the callback until the next call of the function replaces it,
as setters such as `glfwSetErrorCallback` do. When the first parameter is a
handle, each handle keeps its own callback until its resource is destroyed.
Another setter for the same key throws while its setter is pending.

```typescript
replaced?: boolean;
```


<a id="MaligatorFfiCallback.closes"></a>

### MaligatorFfiCallback.closes

The input handle whose lifetime ends when this one-shot completion runs, by C
name or 1-based position. Its storage and retained buffers survive until then.
The wrapper is closed before JavaScript runs; foreign completions queue for it.
An async twin settles at C return and requires a handle the program already holds.

```typescript
closes?: string;
```


<a id="MaligatorFfiCallback.lookup"></a>

### MaligatorFfiCallback.lookup

For a callback without a `void *` parameter: the function that returns `data`
from the callback's parameter at 1-based position `param`, such as
`sqlite3_user_data` for SQLite's `sqlite3_context *`.
<details><summary>Full TypeScript declaration</summary>


```typescript
lookup?: { function: string; param: string };
```

</details>


<a id="MaligatorFfiCallback.lookup.function"></a>

### MaligatorFfiCallback.lookup.function



```typescript
function: string;
```


<a id="MaligatorFfiCallback.lookup.param"></a>

### MaligatorFfiCallback.lookup.param



```typescript
param: string
```


<a id="MaligatorFfiCallback.queued"></a>

### MaligatorFfiCallback.queued

The library may call the kept callback from other threads. `true` copies arguments
and queues for the program's thread, letting C continue with a void result.
`"wait"` borrows pointed-to arguments while blocking C until JavaScript returns
a result. Pointer results need an explicit lifetime. Handles are lent only for that
callback. The program needs an event loop, which waits while the callback is kept. Stop or join the
producer asynchronously; the program's thread must remain free to run callbacks.

```typescript
queued?: boolean | "wait";
```


<a id="MaligatorFfiCallback.params"></a>

### MaligatorFfiCallback.params

Facts per callback parameter, keyed by 1-based position: `string`, `bytes`, or
`array` with a `length` naming another callback parameter, `nullable`, and `shape`.

```typescript
params?: Record<string, MaligatorFfiValueFacts>;
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)



<a id="MaligatorFfiCallback.once"></a>

### MaligatorFfiCallback.once

The library calls the callback exactly once, during or after the function, and
then drops it, as WebGPU's request functions do. Needs `data` or `lookup`.

```typescript
once?: boolean;
```


<a id="MaligatorFfiCallback.field"></a>

### MaligatorFfiCallback.field

On a struct parameter passed by value, such as WebGPU's callback info records: the
function pointer member that receives the callback. `data` then names the `void *`
member for the registration, and the parameter takes a JavaScript function.

```typescript
field?: string;
```


<a id="MaligatorFfiCallback.constants"></a>

### MaligatorFfiCallback.constants

C identifiers or integer literals for other members of a `field` record; the rest start zeroed.

```typescript
constants?: Record<string, string>;
```


<a id="MaligatorFfiCallbackResult"></a>

## MaligatorFfiCallbackResult

A callback result's value shape, or the lifetime of a returned pointer.

```typescript
export type MaligatorFfiCallbackResult =
	| {
			shape: MaligatorFfiShape;
			lifetime?: never;
			string?: never;
			bytes?: never;
			nullable?: never;
	  }
	| (Pick<MaligatorFfiValueFacts, "string" | "bytes" | "nullable"> & {
			/** C stops using every result before the call returns or the registration ends,
			 * including pointers held by pending consumers. Self-release forbids another non-null result. */
			lifetime: "call" | "registration";
			shape?: never;
	  });
```

Types: [`MaligatorFfiShape`](/api/library#MaligatorFfiShape), [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)



<a id="MaligatorFfiFunctionFacts"></a>

## MaligatorFfiFunctionFacts

Facts about one C function, keyed by its name.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiFunctionFacts {
	/**
	 * Audited fact that native execution never enters JavaScript, including through
	 * earlier callback registrations or shared C dependencies. Input getters and
	 * result cleanup retain their own effects. Omit this to keep conservative callbacks.
	 */
	callsJavaScript?: false;
	/** Header documentation that `ffi check` watches when reviewing these facts. */
	evidence?: Array<MaligatorFfiEvidence>;
	/** Facts per parameter, keyed by C name or by 1-based position for unnamed ones. */
	params?: Record<string, MaligatorFfiValueFacts>;
	returns?: MaligatorFfiValueFacts;
	/** Arm caller-storage cleanup after C returns successfully. An omitted success
	 * condition means every native return acquires cleanup responsibility. A failed
	 * initialization must leave storage safe to free without calling the destructor.
	 */
	initializes?: { param: string; success?: string };
	/**
	 * Functions that call a variadic function with fixed argument types, keyed by the
	 * name each is exported as. The function's own facts apply to every variant.
	 */
	variants?: Record<string, MaligatorFfiVariant>;
	/** Export a runtime selector over these variants. Its first argument is a variant
	 * export name, followed by that variant's JavaScript arguments.
	 */
	dispatch?: string;
	/**
	 * Also export the function under this name as one that runs the C call on a worker
	 * thread and returns a promise of its result. Only for functions the library allows
	 * on any thread while other calls run. Call-scoped callbacks run on the program's
	 * thread while C waits; their unhandled errors reject this promise. A destroy
	 * function keeps its handle closing until the worker retires; conditional cleanup
	 * failure leaves it open for retry.
	 */
	async?: string;
}
```

Types: [`MaligatorFfiEvidence`](/api/library#MaligatorFfiEvidence), [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts), [`MaligatorFfiVariant`](/api/library#MaligatorFfiVariant)


</details>


<a id="MaligatorFfiFunctionFacts.callsJavaScript"></a>

### MaligatorFfiFunctionFacts.callsJavaScript

Audited fact that native execution never enters JavaScript, including through
earlier callback registrations or shared C dependencies. Input getters and
result cleanup retain their own effects. Omit this to keep conservative callbacks.

```typescript
callsJavaScript?: false;
```


<a id="MaligatorFfiFunctionFacts.evidence"></a>

### MaligatorFfiFunctionFacts.evidence

Header documentation that `ffi check` watches when reviewing these facts.

```typescript
evidence?: Array<MaligatorFfiEvidence>;
```

Types: [`MaligatorFfiEvidence`](/api/library#MaligatorFfiEvidence)



<a id="MaligatorFfiFunctionFacts.params"></a>

### MaligatorFfiFunctionFacts.params

Facts per parameter, keyed by C name or by 1-based position for unnamed ones.

```typescript
params?: Record<string, MaligatorFfiValueFacts>;
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)



<a id="MaligatorFfiFunctionFacts.returns"></a>

### MaligatorFfiFunctionFacts.returns



```typescript
returns?: MaligatorFfiValueFacts;
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)



<a id="MaligatorFfiFunctionFacts.initializes"></a>

### MaligatorFfiFunctionFacts.initializes

Arm caller-storage cleanup after C returns successfully. An omitted success
condition means every native return acquires cleanup responsibility. A failed
initialization must leave storage safe to free without calling the destructor.
<details><summary>Full TypeScript declaration</summary>


```typescript
initializes?: { param: string; success?: string };
```

</details>


<a id="MaligatorFfiFunctionFacts.initializes.param"></a>

### MaligatorFfiFunctionFacts.initializes.param



```typescript
param: string;
```


<a id="MaligatorFfiFunctionFacts.initializes.success"></a>

### MaligatorFfiFunctionFacts.initializes.success



```typescript
success?: string
```


<a id="MaligatorFfiFunctionFacts.variants"></a>

### MaligatorFfiFunctionFacts.variants

Functions that call a variadic function with fixed argument types, keyed by the
name each is exported as. The function's own facts apply to every variant.

```typescript
variants?: Record<string, MaligatorFfiVariant>;
```

Types: [`MaligatorFfiVariant`](/api/library#MaligatorFfiVariant)



<a id="MaligatorFfiFunctionFacts.dispatch"></a>

### MaligatorFfiFunctionFacts.dispatch

Export a runtime selector over these variants. Its first argument is a variant
export name, followed by that variant's JavaScript arguments.

```typescript
dispatch?: string;
```


<a id="MaligatorFfiFunctionFacts.async"></a>

### MaligatorFfiFunctionFacts.async

Also export the function under this name as one that runs the C call on a worker
thread and returns a promise of its result. Only for functions the library allows
on any thread while other calls run. Call-scoped callbacks run on the program's
thread while C waits; their unhandled errors reject this promise. A destroy
function keeps its handle closing until the worker retires; conditional cleanup
failure leaves it open for retry.

```typescript
async?: string;
```


<a id="MaligatorFfiVariant"></a>

## MaligatorFfiVariant

One way to call a variadic function: the C types of the arguments after the fixed ones.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiVariant {
	/**
	 * For a variadic function, the C type spellings of the arguments after the fixed
	 * ones, such as `int` or `const char *`; arguments are named `arg<position>`.
	 * Variants of other functions have no `args`.
	 */
	args?: Array<string>;
	/**
	 * Facts for the variadic arguments, keyed by `arg<position>` or by 1-based position.
	 * Variants of other functions state facts for any parameter, by C name or position,
	 * replacing the function's own facts for that parameter.
	 */
	params?: Record<string, MaligatorFfiValueFacts>;
}
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)


</details>


<a id="MaligatorFfiVariant.args"></a>

### MaligatorFfiVariant.args

For a variadic function, the C type spellings of the arguments after the fixed
ones, such as `int` or `const char *`; arguments are named `arg<position>`.
Variants of other functions have no `args`.

```typescript
args?: Array<string>;
```


<a id="MaligatorFfiVariant.params"></a>

### MaligatorFfiVariant.params

Facts for the variadic arguments, keyed by `arg<position>` or by 1-based position.
Variants of other functions state facts for any parameter, by C name or position,
replacing the function's own facts for that parameter.

```typescript
params?: Record<string, MaligatorFfiValueFacts>;
```

Types: [`MaligatorFfiValueFacts`](/api/library#MaligatorFfiValueFacts)



<a id="MaligatorFfiGlobalValueFacts"></a>

## MaligatorFfiGlobalValueFacts

Representation of a library-owned global, shared by its read and write accessors.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiGlobalValueFacts {
	shape?: MaligatorFfiShape;
	/** A returned handle stays owned by the library. */
	borrowed?: boolean;
	callable?: MaligatorFfiCallable;
	/** UTF-8 text; a fixed array must contain a NUL within its declared bound. */
	string?: true;
	/** Fixed array bytes, or a pointer whose byte count is another C global. */
	bytes?: true | MaligatorFfiCount;
	/** Keep a native copy until replacement or clearing. C must stop retaining the
	 * previous allocation before either operation. The library's synchronization
	 * contract still applies to its own readers and mutations.
	 */
	lifetime?: "replacement";
}
```

Types: [`MaligatorFfiCount`](/api/library#MaligatorFfiCount), [`MaligatorFfiShape`](/api/library#MaligatorFfiShape), [`MaligatorFfiCallable`](/api/library#MaligatorFfiCallable)


</details>


<a id="MaligatorFfiGlobalValueFacts.shape"></a>

### MaligatorFfiGlobalValueFacts.shape



```typescript
shape?: MaligatorFfiShape;
```

Types: [`MaligatorFfiShape`](/api/library#MaligatorFfiShape)



<a id="MaligatorFfiGlobalValueFacts.borrowed"></a>

### MaligatorFfiGlobalValueFacts.borrowed

A returned handle stays owned by the library.

```typescript
borrowed?: boolean;
```


<a id="MaligatorFfiGlobalValueFacts.callable"></a>

### MaligatorFfiGlobalValueFacts.callable



```typescript
callable?: MaligatorFfiCallable;
```

Types: [`MaligatorFfiCallable`](/api/library#MaligatorFfiCallable)



<a id="MaligatorFfiGlobalValueFacts.string"></a>

### MaligatorFfiGlobalValueFacts.string

UTF-8 text; a fixed array must contain a NUL within its declared bound.

```typescript
string?: true;
```


<a id="MaligatorFfiGlobalValueFacts.bytes"></a>

### MaligatorFfiGlobalValueFacts.bytes

Fixed array bytes, or a pointer whose byte count is another C global.

```typescript
bytes?: true | MaligatorFfiCount;
```

Types: [`MaligatorFfiCount`](/api/library#MaligatorFfiCount)



<a id="MaligatorFfiGlobalValueFacts.lifetime"></a>

### MaligatorFfiGlobalValueFacts.lifetime

Keep a native copy until replacement or clearing. C must stop retaining the
previous allocation before either operation. The library's synchronization
contract still applies to its own readers and mutations.

```typescript
lifetime?: "replacement";
```


<a id="MaligatorFfiGlobalFacts"></a>

## MaligatorFfiGlobalFacts

Explicit access to a library-owned C object. Accessors run on the calling thread.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorFfiGlobalFacts {
	/** Export a function that reads the current C value. Pointer results need lifetime facts. */
	get?: string;
	/** Export a function that assigns a value without retaining JavaScript storage. */
	set?: string;
	/** Conversion facts; retained pointer copies require an explicit lifetime. */
	value?: MaligatorFfiGlobalValueFacts;
	/** Header documentation that `ffi check` watches when reviewing these facts. */
	evidence?: Array<MaligatorFfiEvidence>;
}
```

Types: [`MaligatorFfiEvidence`](/api/library#MaligatorFfiEvidence), [`MaligatorFfiGlobalValueFacts`](/api/library#MaligatorFfiGlobalValueFacts)


</details>


<a id="MaligatorFfiGlobalFacts.get"></a>

### MaligatorFfiGlobalFacts.get

Export a function that reads the current C value. Pointer results need lifetime facts.

```typescript
get?: string;
```


<a id="MaligatorFfiGlobalFacts.set"></a>

### MaligatorFfiGlobalFacts.set

Export a function that assigns a value without retaining JavaScript storage.

```typescript
set?: string;
```


<a id="MaligatorFfiGlobalFacts.value"></a>

### MaligatorFfiGlobalFacts.value

Conversion facts; retained pointer copies require an explicit lifetime.

```typescript
value?: MaligatorFfiGlobalValueFacts;
```

Types: [`MaligatorFfiGlobalValueFacts`](/api/library#MaligatorFfiGlobalValueFacts)



<a id="MaligatorFfiGlobalFacts.evidence"></a>

### MaligatorFfiGlobalFacts.evidence

Header documentation that `ffi check` watches when reviewing these facts.

```typescript
evidence?: Array<MaligatorFfiEvidence>;
```

Types: [`MaligatorFfiEvidence`](/api/library#MaligatorFfiEvidence)



<a id="MaligatorLibraryContract"></a>

## MaligatorLibraryContract

Facts about a C library that hold wherever it is installed. The binding comes from
the headers plus these facts.
<details><summary>Full TypeScript declaration</summary>


```typescript
export interface MaligatorLibraryContract {
	/** Headers to bind, spelled as C code includes them, such as `raylib.h` or `curl/curl.h`. */
	headers: Array<string>;
	/** Discovery alternatives, tried in order. A build config `find` replaces them. */
	find?: Array<MaligatorFfiFind>;
	/** Facts about types, keyed by typedef or tag. */
	types?: Record<string, MaligatorFfiTypeFacts>;
	/** Facts about functions, keyed by name. */
	functions?: Record<string, MaligatorFfiFunctionFacts>;
	/** Getter and setter exports for file-scope C objects, keyed by their C names. */
	globals?: Record<string, MaligatorFfiGlobalFacts>;
}
```

Types: [`MaligatorFfiFind`](/api/library#MaligatorFfiFind), [`MaligatorFfiTypeFacts`](/api/library#MaligatorFfiTypeFacts), [`MaligatorFfiFunctionFacts`](/api/library#MaligatorFfiFunctionFacts), [`MaligatorFfiGlobalFacts`](/api/library#MaligatorFfiGlobalFacts)


</details>


<a id="MaligatorLibraryContract.headers"></a>

### MaligatorLibraryContract.headers

Headers to bind, spelled as C code includes them, such as `raylib.h` or `curl/curl.h`.

```typescript
headers: Array<string>;
```


<a id="MaligatorLibraryContract.find"></a>

### MaligatorLibraryContract.find

Discovery alternatives, tried in order. A build config `find` replaces them.

```typescript
find?: Array<MaligatorFfiFind>;
```

Types: [`MaligatorFfiFind`](/api/library#MaligatorFfiFind)



<a id="MaligatorLibraryContract.types"></a>

### MaligatorLibraryContract.types

Facts about types, keyed by typedef or tag.

```typescript
types?: Record<string, MaligatorFfiTypeFacts>;
```

Types: [`MaligatorFfiTypeFacts`](/api/library#MaligatorFfiTypeFacts)



<a id="MaligatorLibraryContract.functions"></a>

### MaligatorLibraryContract.functions

Facts about functions, keyed by name.

```typescript
functions?: Record<string, MaligatorFfiFunctionFacts>;
```

Types: [`MaligatorFfiFunctionFacts`](/api/library#MaligatorFfiFunctionFacts)



<a id="MaligatorLibraryContract.globals"></a>

### MaligatorLibraryContract.globals

Getter and setter exports for file-scope C objects, keyed by their C names.

```typescript
globals?: Record<string, MaligatorFfiGlobalFacts>;
```

Types: [`MaligatorFfiGlobalFacts`](/api/library#MaligatorFfiGlobalFacts)



<a id="defineLibrary"></a>

## defineLibrary

Preserve the inferred contract type. Validation happens when the CLI loads the contract.

```typescript
import { defineLibrary } from "@maligator/cli";
export default defineLibrary({ headers: ["raylib.h"], find: [{ pkgConfig: "raylib" }] });
```

```typescript
export declare function defineLibrary<const Contract extends MaligatorLibraryContract>(
	contract: Contract,
): Contract;
```

Types: [`MaligatorLibraryContract`](/api/library#MaligatorLibraryContract)


